id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_938_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP N N M M %
% P P NN N MM MM %
% PPPP N N N M M M %
% P N NN M M %
% P N N M M %
% %
% %
% Read/Write PBMPlus Portable Anymap Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
/*
Typedef declarations.
*/
typedef struct _CommentInfo
{
char
*comment;
size_t
extent;
} CommentInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P N M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPNM() returns MagickTrue if the image format type, identified by the
% magick string, is PNM.
%
% The format of the IsPNM method is:
%
% MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o extent: Specifies the extent of the magick string.
%
*/
static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent)
{
if (extent < 2)
return(MagickFalse);
if ((*magick == (unsigned char) 'P') &&
((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') ||
(magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') ||
(magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f')))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPNMImage() reads a Portable Anymap image file and returns it.
% It allocates the memory necessary for the new Image structure and returns
% a pointer to the new image.
%
% The format of the ReadPNMImage method is:
%
% Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static int PNMComment(Image *image,CommentInfo *comment_info,
ExceptionInfo *exception)
{
int
c;
register char
*p;
/*
Read comment.
*/
p=comment_info->comment+strlen(comment_info->comment);
for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++)
{
if ((size_t) (p-comment_info->comment+1) >= comment_info->extent)
{
comment_info->extent<<=1;
comment_info->comment=(char *) ResizeQuantumMemory(
comment_info->comment,comment_info->extent,
sizeof(*comment_info->comment));
if (comment_info->comment == (char *) NULL)
return(-1);
p=comment_info->comment+strlen(comment_info->comment);
}
c=ReadBlobByte(image);
if (c != EOF)
{
*p=(char) c;
*(p+1)='\0';
}
}
return(c);
}
static unsigned int PNMInteger(Image *image,CommentInfo *comment_info,
const unsigned int base,ExceptionInfo *exception)
{
int
c;
unsigned int
value;
/*
Skip any leading whitespace.
*/
do
{
c=ReadBlobByte(image);
if (c == EOF)
return(0);
if (c == (int) '#')
c=PNMComment(image,comment_info,exception);
} while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'));
if (base == 2)
return((unsigned int) (c-(int) '0'));
/*
Evaluate number.
*/
value=0;
while (isdigit(c) != 0)
{
if (value <= (unsigned int) (INT_MAX/10))
{
value*=10;
if (value <= (unsigned int) (INT_MAX-(c-(int) '0')))
value+=c-(int) '0';
}
c=ReadBlobByte(image);
if (c == EOF)
return(0);
}
if (c == (int) '#')
c=PNMComment(image,comment_info,exception);
return(value);
}
static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPNMException(exception,message) \
{ \
if (comment_info.comment != (char *) NULL) \
comment_info.comment=DestroyString(comment_info.comment); \
ThrowReaderException((exception),(message)); \
}
char
format;
CommentInfo
comment_info;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
comment_info.comment=AcquireString(NULL);
comment_info.extent=MagickPathExtent;
if ((count != 1) || (format != 'P'))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=(size_t) PNMInteger(image,&comment_info,10,exception);
image->rows=(size_t) PNMInteger(image,&comment_info,10,exception);
if ((format == 'f') || (format == 'F'))
{
char
scale[MagickPathExtent];
if (ReadBlobString(image,scale) != (char *) NULL)
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=(QuantumAny) PNMInteger(image,&comment_info,10,
exception);
}
}
else
{
char
keyword[MagickPathExtent],
value[MagickPathExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,&comment_info,exception);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
quantum_type=GrayQuantum;
(void) SetImageColorspace(image,GRAYColorspace,exception);
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
image->alpha_trait=BlendPixelTrait;
quantum_type=RGBAQuantum;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295UL))
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image))
ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile");
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
comment_info.comment=DestroyString(comment_info.comment); \
return(DestroyImageList(image));
}
(void) ResetImagePixels(image,exception);
/*
Convert PNM pixels to runextent-encoded MIFF packets.
*/
row=0;
y=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) ==
0 ? QuantumRange : 0,q);
if (EOFBlob(image) != MagickFalse)
break;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
Quantum
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGray(image,intensity,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
SetPixelGreen(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10,
exception),max_value);
SetPixelBlue(image,pixel,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
channels++;
extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)*
image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
offset;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
else
SetPixelAlpha(image,QuantumRange-
ScaleAnyToQuantum(pixel,max_value),q);
}
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
break;
}
default:
{
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
else
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
break;
}
}
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
offset;
size_t
length;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
break;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
break;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowPNMException(CorruptImageError,"ImproperImageHeader");
}
if (*comment_info.comment != '\0')
(void) SetImageProperty(image,"comment",comment_info.comment,exception);
comment_info.comment=DestroyString(comment_info.comment);
if (y < (ssize_t) image->rows)
ThrowPNMException(CorruptImageError,"UnableToReadImageData");
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPNMImage() adds properties for the PNM image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPNMImage method is:
%
% size_t RegisterPNMImage(void)
%
*/
ModuleExport size_t RegisterPNMImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PBM",
"Portable bitmap format (black and white)");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-bitmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PFM","Portable float format");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->flags|=CoderEndianSupportFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-greymap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PNM","Portable anymap");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->magick=(IsImageFormatHandler *) IsPNM;
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)");
entry->decoder=(DecodeImageHandler *) ReadPNMImage;
entry->encoder=(EncodeImageHandler *) WritePNMImage;
entry->mime_type=ConstantString("image/x-portable-pixmap");
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPNMImage() removes format registrations made by the
% PNM module from the list of supported formats.
%
% The format of the UnregisterPNMImage method is:
%
% UnregisterPNMImage(void)
%
*/
ModuleExport void UnregisterPNMImage(void)
{
(void) UnregisterMagickInfo("PAM");
(void) UnregisterMagickInfo("PBM");
(void) UnregisterMagickInfo("PGM");
(void) UnregisterMagickInfo("PNM");
(void) UnregisterMagickInfo("PPM");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P N M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePNMImage() writes an image to a file in the PNM rasterfile format.
%
% The format of the WritePNMImage method is:
%
% MagickBooleanType WritePNMImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+1) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_938_0 |
crossvul-cpp_data_good_1611_5 | /* t1mac
*
* This program converts Type 1 fonts in PFA or PFB format into Macintosh Type
* 1 fonts stored in MacBinary (I or II), AppleSingle, AppleDouble, BinHex, or
* raw resource fork format.
*
* Copyright (c) 2000-2013 Eddie Kohler
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, subject to the
* conditions listed in the Click LICENSE file, which is available in full at
* http://github.com/kohler/click/blob/master/LICENSE. The conditions
* include: you must preserve this copyright notice, and you cannot mention
* the copyright holders in advertising related to the Software without
* their permission. The Software is provided WITHOUT ANY WARRANTY, EXPRESS
* OR IMPLIED. This notice is a summary of the Click LICENSE file; the
* license in that file is binding.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#if defined(_MSDOS) || defined(_WIN32)
# include <fcntl.h>
# include <io.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <lcdf/clp.h>
#include "t1lib.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned char byte;
/* resource fork layout */
#define RFORK_HEADERLEN 256
#define RFORK_MAP_RESERVEDLEN 22
#define RFORK_MAP_HEADERLEN 28
#define RFORK_RTYPE_LEN 8
#define RFORK_RSRC_LEN 12
/* Macintosh times are # seconds since 1/1/1904, not 1/1/1970 */
#define MAC_TIME_DELTA 2082844800
/* POST resource information */
#define POST_ASCII 1
#define POST_BINARY 2
#define POST_END 5
/* Adobe font file information */
#define T1_FILETYPE 0x4C57464E /* LWFN */
#define T1_FILECREATOR 0x54315554 /* T1UT */
#define T1_FINDERFLAGS 33 /* Bundle + Inited */
#define MAX_RSRC_LEN 2048
static byte rbuf[MAX_RSRC_LEN];
static int rbufpos;
static int blocktyp;
static char *font_name;
/* information about the resources being built */
typedef struct Rsrc {
int32_t type;
int id;
int attrs;
int data_offset;
uint32_t data_len;
int next_in_type;
int next_type;
} Rsrc;
static Rsrc *rsrc = 0;
static int nrsrc = 0;
static int rsrc_cap = 0;
static int cur_post_id = 0;
/* output resource fork */
static FILE *rfork_f = 0;
/* ICN# data */
static const unsigned char icon_bw_data[] = {
0,0,0,0,255,255,255,255,128,0,0,1,128,0,0,1,128,0,0,1,
128,0,0,1,128,0,0,1,128,0,0,1,128,0,0,1,128,0,0,33,
128,0,0,97,128,0,0,225,128,0,1,225,128,0,3,225,128,0,7,225,
128,0,15,225,128,0,31,225,128,0,55,225,159,128,103,249,144,128,199,9,
240,129,135,15,0,131,7,0,0,134,7,0,15,140,7,240,8,31,255,240,
8,63,255,240,8,96,7,240,8,192,7,240,9,192,15,240,11,224,31,240,
15,240,63,240,15,255,255,240,0,0,0,0,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,240,255,255,15,240,255,255,15,0,255,255,0,0,255,255,0,
15,255,255,240,15,255,255,240,15,255,255,240,15,255,255,240,15,255,255,240,
15,255,255,240,15,255,255,240,15,255,255,240,15,255,255,240,};
static const unsigned char small_icon_bw_data[] = {
255,255,128,1,128,1,128,1,128,5,128,13,128,29,128,61,128,125,184,253,
201,179,59,60,39,252,44,60,60,124,63,252,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,207,243,63,252,63,252,63,252,
63,252,63,252,};
static const unsigned char icon_8_data[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,105,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,105,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,105,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,105,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,5,92,92,92,92,105,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,5,5,92,92,92,92,105,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,5,5,5,92,
92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,5,5,5,5,92,92,92,92,105,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,5,5,
5,5,5,92,92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,5,5,5,5,5,5,92,92,92,92,105,
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
5,5,5,5,5,5,5,92,92,92,92,105,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,5,5,5,5,5,5,5,5,92,
92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,5,5,92,5,5,5,5,5,5,92,92,92,92,105,92,92,92,105,
105,105,105,105,92,92,92,92,92,92,92,92,92,5,5,92,92,5,5,105,
105,105,105,105,92,92,92,105,92,92,92,105,0,0,0,0,92,92,92,92,
92,92,92,92,5,5,92,92,92,5,5,105,0,0,0,0,92,92,92,105,
105,105,105,105,0,0,0,0,92,92,92,92,92,92,92,5,5,92,92,92,
92,5,5,105,0,0,0,0,105,105,105,105,0,0,0,0,0,0,0,0,
92,92,92,92,92,92,5,5,92,92,92,92,92,5,5,105,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,92,92,92,92,92,5,5,92,
92,92,92,92,92,5,5,105,0,0,0,0,0,0,0,0,0,0,0,0,
92,92,92,92,92,92,92,92,5,5,92,92,92,92,92,92,92,5,5,5,
5,5,5,92,0,0,0,0,0,0,0,0,92,92,92,92,92,92,92,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,105,0,0,0,0,
0,0,0,0,92,92,92,92,92,92,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,105,0,0,0,0,0,0,0,0,92,92,92,92,
92,5,5,92,92,92,92,92,92,92,92,92,92,5,5,5,5,5,5,105,
0,0,0,0,0,0,0,0,92,92,92,92,5,5,92,92,92,92,92,92,
92,92,92,92,92,5,5,5,5,5,5,105,0,0,0,0,0,0,0,0,
92,92,92,5,5,5,92,92,92,92,92,92,92,92,92,92,5,5,5,5,
5,5,5,105,0,0,0,0,0,0,0,0,92,92,5,5,5,5,5,92,
92,92,92,92,92,92,92,5,5,5,5,5,5,5,5,105,0,0,0,0,
0,0,0,0,92,5,5,5,5,5,5,5,92,92,92,92,92,92,5,5,
5,5,5,5,5,5,5,105,0,0,0,0,0,0,0,0,92,105,105,105,
105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,105,
0,0,0,0,};
static const unsigned char small_icon_8_data[] = {
92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,92,92,92,92,105,92,92,92,92,92,92,92,92,
92,92,92,92,92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,
92,92,92,105,92,92,92,92,92,92,92,92,92,92,92,92,92,5,92,105,
92,92,92,92,92,92,92,92,92,92,92,92,5,5,92,105,92,92,92,92,
92,92,92,92,92,92,92,5,5,5,92,105,92,92,92,92,92,92,92,92,
92,92,5,5,5,5,92,105,92,92,92,92,92,92,92,92,92,5,92,5,
5,5,92,105,92,105,105,105,92,92,92,92,5,92,92,5,105,105,92,105,
92,105,0,0,92,92,92,5,92,92,92,5,0,0,105,105,0,0,92,92,
92,92,5,92,92,92,92,5,5,5,0,0,0,0,92,92,92,5,5,5,
5,5,5,5,5,5,0,0,0,0,92,92,5,92,92,92,92,92,92,5,
5,5,0,0,0,0,92,5,5,92,92,92,92,92,5,5,5,5,0,0,
0,0,5,5,5,5,105,105,105,5,5,5,5,5,0,0,};
static const unsigned char icon_4_data[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,69,69,69,69,
69,69,69,69,69,69,69,69,69,69,69,69,84,84,84,84,84,84,84,84,
84,84,84,84,84,84,84,85,69,69,69,69,69,69,69,69,69,69,69,69,
69,69,69,69,84,84,84,84,84,84,84,84,84,84,84,84,84,84,84,85,
69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,69,84,84,84,84,
84,84,84,84,84,84,84,84,84,84,84,85,69,69,69,69,69,69,69,69,
69,69,69,69,69,69,69,69,84,84,84,84,84,84,84,84,84,84,84,84,
84,84,84,85,69,69,69,69,69,69,69,69,69,69,69,69,69,21,69,69,
84,84,84,84,84,84,84,84,84,84,84,84,81,20,84,85,69,69,69,69,
69,69,69,69,69,69,69,69,17,21,69,69,84,84,84,84,84,84,84,84,
84,84,84,81,17,20,84,85,69,69,69,69,69,69,69,69,69,69,69,17,
17,21,69,69,84,84,84,84,84,84,84,84,84,84,81,17,17,20,84,85,
69,69,69,69,69,69,69,69,69,69,17,17,17,21,69,69,84,84,84,84,
84,84,84,84,84,81,17,17,17,20,84,85,69,69,69,69,69,69,69,69,
69,17,65,17,17,21,69,69,84,85,85,85,84,84,84,84,81,20,81,21,
85,85,84,85,69,69,0,0,69,69,69,69,17,69,65,21,0,0,69,69,
85,85,0,0,84,84,84,81,20,84,81,21,0,0,85,85,0,0,0,0,
69,69,69,17,69,69,65,21,0,0,0,0,0,0,0,0,84,84,81,20,
84,84,81,21,0,0,0,0,0,0,69,69,69,69,17,69,69,69,65,17,
17,30,0,0,0,0,84,84,84,81,17,17,17,17,17,17,17,21,0,0,
0,0,69,69,69,17,17,17,17,17,17,17,17,21,0,0,0,0,84,84,
81,20,84,84,84,84,81,17,17,21,0,0,0,0,69,69,17,69,69,69,
69,69,65,17,17,21,0,0,0,0,84,81,17,84,84,84,84,84,17,17,
17,21,0,0,0,0,69,17,17,21,69,69,69,65,17,17,17,21,0,0,
0,0,81,17,17,17,84,84,84,17,17,17,17,21,0,0,0,0,229,85,
85,85,85,85,85,85,85,85,85,85,0,0,};
static const unsigned char small_icon_4_data[] = {
84,84,84,84,84,84,84,85,69,69,69,69,69,69,69,69,84,84,84,84,
84,84,84,85,69,69,69,69,69,69,69,69,84,84,84,84,84,84,81,85,
69,69,69,69,69,69,17,69,84,84,84,84,84,81,17,85,69,69,69,69,
69,17,17,69,84,84,84,84,81,81,17,85,69,85,69,69,21,65,85,69,
85,0,84,81,84,81,0,85,0,69,69,21,69,65,17,0,0,84,81,17,
17,17,17,0,0,69,21,69,69,65,17,0,0,81,20,84,84,17,17,0,
0,17,17,85,81,17,17,0,};
/* fseek with fatal_error */
static void
reposition(FILE *fi, int32_t absolute)
{
if (fseek(fi, absolute, 0) == -1)
fatal_error("can't seek to position %d", absolute);
}
/* Some functions to write one, two, three, and four byte integers in 68000
byte order (most significant byte first). */
static void
write_one(int c, FILE *f)
{
putc(c, f);
}
static void
write_two(int c, FILE *f)
{
putc((c >> 8) & 255, f);
putc(c & 255, f);
}
static void
write_three(int32_t c, FILE *f)
{
putc((c >> 16) & 255, f);
putc((c >> 8) & 255, f);
putc(c & 255, f);
}
static void
write_four(int32_t c, FILE *f)
{
putc((c >> 24) & 255, f);
putc((c >> 16) & 255, f);
putc((c >> 8) & 255, f);
putc(c & 255, f);
}
/* Some functions to store one, two, three, and four byte integers in 68000
byte order (most significant byte first). */
static void
store_one(int c, char *s)
{
s[0] = (char)(c & 255);
}
static void
store_two(int c, char *s)
{
s[0] = (char)((c >> 8) & 255);
s[1] = (char)(c & 255);
}
static void
store_four(int32_t c, char *s)
{
s[0] = (char)((c >> 24) & 255);
s[1] = (char)((c >> 16) & 255);
s[2] = (char)((c >> 8) & 255);
s[3] = (char)(c & 255);
}
static void
output_new_rsrc(const char *rtype, int rid, int attrs,
const char *data, uint32_t len)
{
Rsrc *r;
if (nrsrc >= rsrc_cap) {
rsrc_cap = (rsrc_cap ? rsrc_cap * 2 : 256);
r = (Rsrc *)malloc(sizeof(Rsrc) * rsrc_cap);
if (!r)
fatal_error("out of memory");
memcpy(r, rsrc, sizeof(Rsrc) * nrsrc);
free(rsrc);
rsrc = r;
}
r = &rsrc[nrsrc];
nrsrc++;
/* prepare resource record */
{
const unsigned char *b = (const unsigned char *)rtype;
r->type = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
}
r->id = rid;
r->attrs = attrs;
if (nrsrc == 1)
r->data_offset = 0;
else
r->data_offset = rsrc[nrsrc-2].data_offset + rsrc[nrsrc-2].data_len + 4;
r->data_len = len;
r->next_in_type = r->next_type = -2;
/* resource consists of length, then data */
write_four(r->data_len, rfork_f);
fwrite(data, 1, len, rfork_f);
}
static void
init_current_post(void)
{
rbufpos = 2;
cur_post_id = 501;
blocktyp = POST_ASCII;
}
static void
output_current_post(void)
{
if (blocktyp != POST_END && rbufpos <= 2)
return;
rbuf[0] = blocktyp;
rbuf[1] = 0;
output_new_rsrc("POST", cur_post_id, 0, (char *)rbuf, rbufpos);
rbufpos = 2;
cur_post_id++;
}
/* font_reader functions */
static void
t1mac_output_data(byte *s, int len)
{
while (len > 0) {
int n;
/* In some Mac fonts, the ASCII sections terminate with a line-end */
if (rbufpos >= MAX_RSRC_LEN
|| (blocktyp == POST_ASCII && len + rbufpos > MAX_RSRC_LEN && rbufpos))
output_current_post();
n = (len + rbufpos <= MAX_RSRC_LEN ? len : MAX_RSRC_LEN - rbufpos);
memcpy(rbuf + rbufpos, s, n);
rbufpos += n;
s += n;
len -= n;
}
}
static void
t1mac_output_ascii(char *s, int len)
{
if (blocktyp == POST_BINARY) {
output_current_post();
blocktyp = POST_ASCII;
}
/* Mac line endings */
if (len > 0 && s[len-1] == '\n')
s[len-1] = '\r';
t1mac_output_data((byte *)s, len);
if (strncmp(s, "/FontName", 9) == 0) {
for (s += 9; isspace((unsigned char) *s); s++)
/* skip */;
if (*s == '/') {
const char *t = ++s;
while (*t && !isspace((unsigned char) *t)) t++;
free(font_name);
font_name = (char *)malloc(t - s + 1);
memcpy(font_name, s, t - s);
font_name[t - s] = 0;
}
}
}
static void
t1mac_output_binary(unsigned char *s, int len)
{
if (blocktyp == POST_ASCII) {
output_current_post();
blocktyp = POST_BINARY;
}
t1mac_output_data(s, len);
}
static void
t1mac_output_end(void)
{
output_current_post();
blocktyp = POST_END;
output_current_post();
}
/* finish off the resource fork */
static uint32_t
complete_rfork(void)
{
uint32_t reflist_offset, total_data_len;
uint32_t typelist_len;
int i, j, ntypes;
/* analyze resources */
{
int last_type = -1;
ntypes = 0;
for (i = 0; i < nrsrc; i++)
if (rsrc[i].next_in_type == -2) {
int last = -1;
if (last_type >= 0)
rsrc[last_type].next_type = i;
for (j = i; j < nrsrc; j++)
if (rsrc[j].type == rsrc[i].type) {
if (last >= 0)
rsrc[last].next_in_type = j;
last = j;
}
rsrc[last].next_in_type = -1;
last_type = i;
ntypes++;
}
}
/* have just finished writing data */
/* now write resource map */
for (i = 0; i < RFORK_MAP_RESERVEDLEN; i++)
putc(0, rfork_f); /* reserved */
write_two(0, rfork_f); /* resource fork attributes */
typelist_len = ntypes * RFORK_RTYPE_LEN + 2;
write_two(RFORK_MAP_HEADERLEN, rfork_f); /* offset from start of map to typelist */
write_two(RFORK_MAP_HEADERLEN + typelist_len + nrsrc * RFORK_RSRC_LEN, rfork_f); /* offset from start of map to namelist */
/* output type map */
write_two(ntypes - 1, rfork_f);/* number of types - 1 */
reflist_offset = typelist_len;
for (i = 0; i >= 0; i = rsrc[i].next_type) {
int n_in_type = 0;
for (j = i; j >= 0; j = rsrc[j].next_in_type)
n_in_type++;
write_four(rsrc[i].type, rfork_f); /* resource type */
write_two(n_in_type - 1, rfork_f); /* number in type - 1 */
write_two(reflist_offset, rfork_f); /* offset to reflist from start of typelist */
reflist_offset += n_in_type * RFORK_RSRC_LEN;
}
/* output reference list */
for (i = 0; i >= 0; i = rsrc[i].next_type)
for (j = i; j >= 0; j = rsrc[j].next_in_type) {
write_two(rsrc[j].id, rfork_f); /* ID */
write_two(-1, rfork_f); /* offset to name */
write_one(rsrc[j].attrs, rfork_f); /* attributes */
write_three(rsrc[j].data_offset, rfork_f); /* offset to data from start of data */
write_four(0, rfork_f); /* reserved */
}
/* finally, patch up resource fork header */
{
total_data_len = rsrc[nrsrc-1].data_offset + rsrc[nrsrc-1].data_len + 4;
reposition(rfork_f, 0);
write_four(RFORK_HEADERLEN, rfork_f); /* offset from rfork to data */
write_four(RFORK_HEADERLEN + total_data_len, rfork_f); /* offset from rfork to map */
write_four(total_data_len, rfork_f); /* length of data */
write_four(RFORK_MAP_HEADERLEN + reflist_offset, rfork_f); /* length of map */
}
return RFORK_HEADERLEN + total_data_len + RFORK_MAP_HEADERLEN + reflist_offset;
}
/* write a MacBinary II file */
static void
output_raw(FILE *rf, int32_t len, FILE *f)
{
char buf[2048];
reposition(rf, 0);
while (len > 0) {
int n = (len < 2048 ? len : 2048);
fread(buf, 1, n, rf);
fwrite(buf, 1, n, f);
len -= n;
}
}
static void
output_macbinary(FILE *rf, int32_t rf_len, const char *filename, FILE *f)
{
int i, len = strlen(filename);
char buf[128];
if (len < 1 || len > 63)
fatal_error("filename length must be between 1 and 63");
store_one(0, buf+0); /* old version number */
store_one(len, buf+1); /* filename length */
memset(buf+2, 0, 63); /* filename padding */
memcpy(buf+2, filename, len); /* filename */
store_four(T1_FILETYPE, buf+65); /* file type */
store_four(T1_FILECREATOR, buf+69); /* file creator */
store_one(T1_FINDERFLAGS, buf+73); /* finder flags */
store_one(0, buf+74); /* zero byte */
store_two(0, buf+75); /* vertical position in window */
store_two(0, buf+77); /* horizontal position in window */
store_two(0, buf+79); /* window or folder ID */
store_one(0, buf+81); /* protected flag */
store_one(0, buf+82); /* zero byte */
store_four(0, buf+83); /* data fork length */
store_four(rf_len, buf+87); /* resource fork length */
{
time_t t = time(0) + MAC_TIME_DELTA;
store_four(t, buf+91); /* creation date */
store_four(t, buf+95); /* modification date */
}
store_two(0, buf+99); /* GetInfo comment length */
store_one(0, buf+101); /* finder flags part 2 */
memset(buf+102, 0, 116 - 102); /* padding */
store_four(0, buf+116); /* total length when unpacked */
store_two(0, buf+120); /* length of secondary header */
store_one(129, buf+122); /* version number */
store_one(129, buf+123); /* minimum acceptable version number */
store_two(crcbuf(0, 124, buf), buf+124); /* CRC */
store_two(0, buf+126); /* padding to 128 bytes */
/* write out the header */
fwrite(buf, 1, 128, f);
/* now write resource fork */
output_raw(rf, rf_len, f);
for (i = rf_len % 128; i && i < 128; i++)
putc(0, f);
}
/* write an AppleSingle file */
#define APPLESINGLE_MAGIC 0x00051600
#define APPLEDOUBLE_MAGIC 0x00051607
#define APPLESINGLE_VERSION 0x00020000
#define APPLESINGLE_TIME_DELTA 883612800
#define APPLESINGLE_HEADERLEN 26
#define APPLESINGLE_ENTRYLEN 12
#define APPLESINGLE_DFORK_ENTRY 1
#define APPLESINGLE_RFORK_ENTRY 2
#define APPLESINGLE_DATES_ENTRY 8
#define APPLESINGLE_DATES_LEN 16
#define APPLESINGLE_FINDERINFO_ENTRY 9
#define APPLESINGLE_FINDERINFO_LEN 32
#define APPLESINGLE_REALNAME_ENTRY 3
static void
output_applesingle(FILE *rf, int32_t rf_len, const char *filename, FILE *f,
int appledouble)
{
uint32_t offset;
int i, nentries, len = strlen(filename);
if (appledouble) /* magic number */
write_four(APPLEDOUBLE_MAGIC, f);
else
write_four(APPLESINGLE_MAGIC, f);
write_four(APPLESINGLE_VERSION, f); /* version number */
for (i = 0; i < 4; i++)
write_four(0, f); /* filler */
nentries = (appledouble ? 4 : 5);
write_two(nentries, f); /* number of entries */
/* real name entry */
offset = APPLESINGLE_HEADERLEN + nentries * APPLESINGLE_ENTRYLEN;
write_four(APPLESINGLE_REALNAME_ENTRY, f);
write_four(offset, f);
write_four(len, f);
offset += len;
/* time entry */
write_four(APPLESINGLE_DATES_ENTRY, f);
write_four(offset, f);
write_four(APPLESINGLE_DATES_LEN, f);
offset += APPLESINGLE_DATES_LEN;
/* finder info entry */
write_four(APPLESINGLE_FINDERINFO_ENTRY, f);
write_four(offset, f);
write_four(APPLESINGLE_FINDERINFO_LEN, f);
offset += APPLESINGLE_FINDERINFO_LEN;
/* resource fork entry */
write_four(APPLESINGLE_RFORK_ENTRY, f);
write_four(offset, f);
write_four(rf_len, f);
offset += rf_len;
/* data fork entry */
if (!appledouble) {
write_four(APPLESINGLE_DFORK_ENTRY, f);
write_four(offset, f);
write_four(0, f);
}
/* real name data */
fwrite(filename, 1, len, f);
/* time data */
i = time(0) - APPLESINGLE_TIME_DELTA;
write_four(i, f); /* creation date */
write_four(i, f); /* modification date */
write_four(0x80000000, f); /* backup date */
write_four(0, f); /* access date */
/* finder info data */
write_four(T1_FILETYPE, f); /* file type */
write_four(T1_FILECREATOR, f); /* file creator */
write_one(T1_FINDERFLAGS, f); /* finder flags */
write_one(0, f); /* extended finder flags */
write_two(0, f); /* vertical position in window */
write_two(0, f); /* horizontal position in window */
write_two(0, f); /* window or folder ID */
write_four(0, f); /* icon ID and reserved */
write_four(0, f); /* reserved */
write_one(0, f); /* script flag */
write_one(0, f); /* reserved */
write_two(0, f); /* comment ID */
write_four(0, f); /* put away */
/* resource fork data */
output_raw(rf, rf_len, f);
}
/* write a BinHex file */
static void
binhex_buffer(const byte *s, int len, FILE *f)
{
static int col = 1;
static int bits = 0;
static int bitspos = 2;
static const char *table = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr";
byte buf[5];
int c, i, left;
if (!s && bitspos > 2) { /* output the remaining bits */
s = (const byte *)"\0";
len = 1;
}
for (left = len; left > 0; left--, s++) {
int pos;
if (s[0] == 0x90) {
buf[0] = 0x90;
buf[1] = 0x00;
pos = 2;
} else {
buf[0] = s[0];
pos = 1;
}
/* find a run */
if (left > 2 && s[0] == s[1] && s[0] == s[2]) {
for (i = 3; i < left && i < 255; i++)
if (s[i] != s[0])
break;
buf[pos] = 0x90;
buf[pos+1] = i;
pos += 2;
s += i - 1;
left -= i - 1;
}
/* store those characters */
for (i = 0; i < pos; i++) {
bits |= buf[i];
while (bitspos >= 0) {
c = (bits >> bitspos) & 0x3F;
putc(table[c], f);
if (++col == 63) {
putc('\n', f);
col = 0;
}
bitspos -= 6;
}
bits <<= 8;
bitspos += 8;
}
}
}
static void
output_binhex(FILE *rf, int32_t rf_len, const char *filename, FILE *f)
{
int crc, len = strlen(filename);
char buf[2048];
if (len < 1 || len > 63)
fatal_error("filename length must be between 1 and 63");
store_one(len, buf+0); /* filename length */
memcpy(buf+1, filename, len); /* filename */
store_one(0, buf+1+len); /* version */
store_four(T1_FILETYPE, buf+2+len); /* file type */
store_four(T1_FILECREATOR, buf+6+len); /* file creator */
store_one(T1_FINDERFLAGS, buf+10+len); /* finder flags */
store_one(0, buf+11+len); /* extended finder flags */
store_four(0, buf+12+len); /* length of data fork */
store_four(rf_len, buf+16+len); /* length of resource fork */
store_two(crcbuf(0, 20+len, buf), buf+20+len); /* CRC */
store_two(0, buf+22+len); /* data fork CRC */
/* output BinHex comment */
fputs("(This file must be converted with BinHex 4.0)\n:", f);
/* BinHex the header */
binhex_buffer((const byte *)buf, 24+len, f);
/* resource fork data */
reposition(rf, 0);
crc = 0;
while (rf_len > 0) {
int n = (rf_len < 2048 ? rf_len : 2048);
fread(buf, 1, n, rf);
crc = crcbuf(crc, n, buf); /* update CRC */
binhex_buffer((const byte *)buf, n, f);
rf_len -= n;
}
store_two(crc, buf); /* resource fork CRC */
binhex_buffer((const byte *)buf, 2, f);
binhex_buffer(0, 0, f); /* get rid of any remaining bits */
fputs(":\n", f); /* trailer */
}
/*****
* command line
**/
#define OUTPUT_OPT 301
#define VERSION_OPT 302
#define HELP_OPT 303
#define MACBINARY_OPT 304
#define RAW_OPT 305
#define APPLESINGLE_OPT 306
#define APPLEDOUBLE_OPT 307
#define BINHEX_OPT 308
#define FILENAME_OPT 309
static Clp_Option options[] = {
{ "appledouble", 0, APPLEDOUBLE_OPT, 0, 0 },
{ "applesingle", 0, APPLESINGLE_OPT, 0, 0 },
{ "binhex", 0, BINHEX_OPT, 0, 0 },
{ "help", 0, HELP_OPT, 0, 0 },
{ "macbinary", 0, MACBINARY_OPT, 0, 0 },
{ "filename", 'n', FILENAME_OPT, Clp_ValString, 0 },
{ "output", 'o', OUTPUT_OPT, Clp_ValString, 0 },
{ "raw", 'r', RAW_OPT, 0, 0 },
{ "version", 0, VERSION_OPT, 0, 0 },
};
static const char *program_name;
void
fatal_error(const char *message, ...)
{
va_list val;
va_start(val, message);
fprintf(stderr, "%s: ", program_name);
vfprintf(stderr, message, val);
putc('\n', stderr);
va_end(val);
exit(1);
}
void
error(const char *message, ...)
{
va_list val;
va_start(val, message);
fprintf(stderr, "%s: ", program_name);
vfprintf(stderr, message, val);
putc('\n', stderr);
va_end(val);
}
static void
short_usage(void)
{
fprintf(stderr, "Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\
Try `%s --help' for more information.\n",
program_name, program_name);
}
static void
usage(void)
{
printf("\
`T1mac' translates a PostScript Type 1 font from PFA or PFB format into\n\
Macintosh Type 1 format. The result can be written in MacBinary II format (the\n\
default), AppleSingle format, AppleDouble format, or BinHex format, or as a\n\
raw resource fork. It is sent to the standard output unless an OUTPUT file is\n\
given.\n\
\n\
Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\
\n\
Options:\n\
-r, --raw Output is a raw Macintosh resource fork.\n\
--macbinary Output is in MacBinary format (default).\n\
--applesingle Output is in AppleSingle format.\n\
--appledouble Output is in AppleDouble format.\n\
--binhex Output is in BinHex format.\n\
-n, --filename NAME Macintosh font filename will be NAME.\n\
-o, --output FILE Write output to FILE.\n\
-h, --help Print this message and exit.\n\
--version Print version number and warranty and exit.\n\
\n\
Report bugs to <ekohler@gmail.com>.\n", program_name);
}
#ifdef __cplusplus
}
#endif
int
main(int argc, char *argv[])
{
int i, c;
FILE *ifp = 0, *ofp = 0;
const char *ifp_filename = "<stdin>";
const char *ofp_filename = "<stdout>";
const char *set_font_name = 0;
struct font_reader fr;
uint32_t rfork_len;
int raw = 0, macbinary = 1, applesingle = 0, appledouble = 0, binhex = 0;
Clp_Parser *clp =
Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options);
program_name = Clp_ProgramName(clp);
/* interpret command line arguments using CLP */
while (1) {
int opt = Clp_Next(clp);
switch (opt) {
case RAW_OPT:
raw = 1;
macbinary = applesingle = appledouble = binhex = 0;
break;
case MACBINARY_OPT:
macbinary = 1;
raw = applesingle = appledouble = binhex = 0;
break;
case APPLESINGLE_OPT:
applesingle = 1;
raw = macbinary = appledouble = binhex = 0;
break;
case APPLEDOUBLE_OPT:
appledouble = 1;
raw = macbinary = applesingle = binhex = 0;
break;
case BINHEX_OPT:
binhex = 1;
raw = macbinary = applesingle = appledouble = 0;
break;
output_file:
case OUTPUT_OPT:
if (ofp)
fatal_error("output file already specified");
if (strcmp(clp->vstr, "-") == 0)
ofp = stdout;
else {
ofp_filename = clp->vstr;
ofp = fopen(ofp_filename, "wb");
if (!ofp) fatal_error("%s: %s", ofp_filename, strerror(errno));
}
break;
case FILENAME_OPT:
if (set_font_name)
fatal_error("Macintosh font filename already specified");
set_font_name = clp->vstr;
break;
case HELP_OPT:
usage();
exit(0);
break;
case VERSION_OPT:
printf("t1mac (LCDF t1utils) %s\n", VERSION);
printf("Copyright (C) 2000-2010 Eddie Kohler et al.\n\
This is free software; see the source for copying conditions.\n\
There is NO warranty, not even for merchantability or fitness for a\n\
particular purpose.\n");
exit(0);
break;
case Clp_NotOption:
if (ifp && ofp)
fatal_error("too many arguments");
else if (ifp)
goto output_file;
if (strcmp(clp->vstr, "-") == 0)
ifp = stdin;
else {
ifp_filename = clp->vstr;
ifp = fopen(clp->vstr, "r");
if (!ifp) fatal_error("%s: %s", clp->vstr, strerror(errno));
}
break;
case Clp_Done:
goto done;
case Clp_BadOption:
short_usage();
exit(1);
break;
}
}
done:
if (!ifp) ifp = stdin;
if (!ofp) ofp = stdout;
#if defined(_MSDOS) || defined(_WIN32)
/* As we are processing a PFB (binary) output */
/* file, we must set its file mode to binary. */
_setmode(_fileno(ofp), _O_BINARY);
#endif
/* prepare font reader */
fr.output_ascii = t1mac_output_ascii;
fr.output_binary = t1mac_output_binary;
fr.output_end = t1mac_output_end;
/* prepare resource fork file */
rfork_f = tmpfile();
if (!rfork_f)
fatal_error("cannot open temorary file: %s", strerror(errno));
for (i = 0; i < RFORK_HEADERLEN; i++)
putc(0, rfork_f);
init_current_post();
/* peek at first byte to see if it is the PFB marker 0x80 */
c = getc(ifp);
ungetc(c, ifp);
/* do the file */
if (c == PFB_MARKER)
process_pfb(ifp, ifp_filename, &fr);
else if (c == '%')
process_pfa(ifp, ifp_filename, &fr);
else
fatal_error("%s does not start with font marker (`%%' or 0x80)", ifp_filename);
if (ifp != stdin)
fclose(ifp);
/* check if anything was read */
if (nrsrc == 0)
error("no POST resources written -- are you sure this was a font?");
/* output large B/W icon */
output_new_rsrc("ICN#", 256, 32, (const char *)icon_bw_data, 256);
/* output FREF */
output_new_rsrc("FREF", 256, 32, "LWFN\0\0\0", 7);
/* output BNDL */
output_new_rsrc("BNDL", 256, 32, "T1UT\0\0\0\1FREF\0\0\0\0\1\0ICN#\0\0\0\0\1\0", 28);
/* output other icons */
output_new_rsrc("icl8", 256, 32, (const char *)icon_8_data, 1024);
output_new_rsrc("icl4", 256, 32, (const char *)icon_4_data, 512);
output_new_rsrc("ics#", 256, 32, (const char *)small_icon_bw_data, 64);
output_new_rsrc("ics8", 256, 32, (const char *)small_icon_8_data, 256);
output_new_rsrc("ics4", 256, 32, (const char *)small_icon_4_data, 128);
/* output T1UT (signature) */
output_new_rsrc("T1UT", 0, 0, "DConverted by t1mac (t1utils) \251Eddie Kohler http://www.lcdf.org/type/", 69);
/* finish off resource file */
rfork_len = complete_rfork();
/* prepare font name */
if (!set_font_name && font_name) {
int part = 0, len = 0;
char *x, *s;
for (x = s = font_name; *s; s++)
if (isupper((unsigned char) *s) || isdigit((unsigned char) *s)) {
*x++ = *s;
part++;
len = 1;
} else if (islower((unsigned char) *s)) {
if (len < (part <= 1 ? 5 : 3))
*x++ = *s;
len++;
}
*x++ = 0;
set_font_name = font_name;
} else if (!set_font_name)
set_font_name = "Unknown Font";
/* now, output the file */
if (macbinary)
output_macbinary(rfork_f, rfork_len, set_font_name, ofp);
else if (raw)
output_raw(rfork_f, rfork_len, ofp);
else if (applesingle || appledouble)
output_applesingle(rfork_f, rfork_len, set_font_name, ofp, appledouble);
else if (binhex)
output_binhex(rfork_f, rfork_len, set_font_name, ofp);
else
fatal_error("strange output format");
fclose(rfork_f);
if (ofp != stdout)
fclose(ofp);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1611_5 |
crossvul-cpp_data_good_3087_1 | /* $Id$ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Revised: 2/18/01 BAR -- added syntax for extracting single images from
* multi-image TIFF files.
*
* New syntax is: sourceFileName,image#
*
* image# ranges from 0..<n-1> where n is the # of images in the file.
* There may be no white space between the comma and the filename or
* image number.
*
* Example: tiffcp source.tif,1 destination.tif
*
* Copies the 2nd image in source.tif to the destination.
*
*****
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include "tif_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "tiffio.h"
#ifndef HAVE_GETOPT
extern int getopt(int, char**, char*);
#endif
#if defined(VMS)
# define unlink delete
#endif
#define streq(a,b) (strcmp(a,b) == 0)
#define strneq(a,b,n) (strncmp(a,b,n) == 0)
#define TRUE 1
#define FALSE 0
static int outtiled = -1;
static uint32 tilewidth;
static uint32 tilelength;
static uint16 config;
static uint16 compression;
static uint16 predictor;
static int preset;
static uint16 fillorder;
static uint16 orientation;
static uint32 rowsperstrip;
static uint32 g3opts;
static int ignore = FALSE; /* if true, ignore read errors */
static uint32 defg3opts = (uint32) -1;
static int quality = 75; /* JPEG quality */
static int jpegcolormode = JPEGCOLORMODE_RGB;
static uint16 defcompression = (uint16) -1;
static uint16 defpredictor = (uint16) -1;
static int defpreset = -1;
static int tiffcp(TIFF*, TIFF*);
static int processCompressOptions(char*);
static void usage(void);
static char comma = ','; /* (default) comma separator character */
static TIFF* bias = NULL;
static int pageNum = 0;
static int pageInSeq = 0;
static int nextSrcImage (TIFF *tif, char **imageSpec)
/*
seek to the next image specified in *imageSpec
returns 1 if success, 0 if no more images to process
*imageSpec=NULL if subsequent images should be processed in sequence
*/
{
if (**imageSpec == comma) { /* if not @comma, we've done all images */
char *start = *imageSpec + 1;
tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0);
if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif);
if (**imageSpec)
{
if (**imageSpec == comma) {
/* a trailing comma denotes remaining images in sequence */
if ((*imageSpec)[1] == '\0') *imageSpec = NULL;
}else{
fprintf (stderr,
"Expected a %c separated image # list after %s\n",
comma, TIFFFileName (tif));
exit (-4); /* syntax error */
}
}
if (TIFFSetDirectory (tif, nextImage)) return 1;
fprintf (stderr, "%s%c%d not found!\n",
TIFFFileName(tif), comma, (int) nextImage);
}
return 0;
}
static TIFF* openSrcImage (char **imageSpec)
/*
imageSpec points to a pointer to a filename followed by optional ,image#'s
Open the TIFF file and assign *imageSpec to either NULL if there are
no images specified, or a pointer to the next image number text
*/
{
TIFF *tif;
char *fn = *imageSpec;
*imageSpec = strchr (fn, comma);
if (*imageSpec) { /* there is at least one image number specifier */
**imageSpec = '\0';
tif = TIFFOpen (fn, "r");
/* but, ignore any single trailing comma */
if (!(*imageSpec)[1]) {*imageSpec = NULL; return tif;}
if (tif) {
**imageSpec = comma; /* replace the comma */
if (!nextSrcImage(tif, imageSpec)) {
TIFFClose (tif);
tif = NULL;
}
}
}else
tif = TIFFOpen (fn, "r");
return tif;
}
int
main(int argc, char* argv[])
{
uint16 defconfig = (uint16) -1;
uint16 deffillorder = 0;
uint32 deftilewidth = (uint32) -1;
uint32 deftilelength = (uint32) -1;
uint32 defrowsperstrip = (uint32) 0;
uint64 diroff = 0;
TIFF* in;
TIFF* out;
char mode[10];
char* mp = mode;
int c;
#if !HAVE_DECL_OPTARG
extern int optind;
extern char* optarg;
#endif
*mp++ = 'w';
*mp = '\0';
while ((c = getopt(argc, argv, ",:b:c:f:l:o:p:r:w:aistBLMC8x")) != -1)
switch (c) {
case ',':
if (optarg[0] != '=') usage();
comma = optarg[1];
break;
case 'b': /* this file is bias image subtracted from others */
if (bias) {
fputs ("Only 1 bias image may be specified\n", stderr);
exit (-2);
}
{
uint16 samples = (uint16) -1;
char **biasFn = &optarg;
bias = openSrcImage (biasFn);
if (!bias) exit (-5);
if (TIFFIsTiled (bias)) {
fputs ("Bias image must be organized in strips\n", stderr);
exit (-7);
}
TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples);
if (samples != 1) {
fputs ("Bias image must be monochrome\n", stderr);
exit (-7);
}
}
break;
case 'a': /* append to output */
mode[0] = 'a';
break;
case 'c': /* compression scheme */
if (!processCompressOptions(optarg))
usage();
break;
case 'f': /* fill order */
if (streq(optarg, "lsb2msb"))
deffillorder = FILLORDER_LSB2MSB;
else if (streq(optarg, "msb2lsb"))
deffillorder = FILLORDER_MSB2LSB;
else
usage();
break;
case 'i': /* ignore errors */
ignore = TRUE;
break;
case 'l': /* tile length */
outtiled = TRUE;
deftilelength = atoi(optarg);
break;
case 'o': /* initial directory offset */
diroff = strtoul(optarg, NULL, 0);
break;
case 'p': /* planar configuration */
if (streq(optarg, "separate"))
defconfig = PLANARCONFIG_SEPARATE;
else if (streq(optarg, "contig"))
defconfig = PLANARCONFIG_CONTIG;
else
usage();
break;
case 'r': /* rows/strip */
defrowsperstrip = atol(optarg);
break;
case 's': /* generate stripped output */
outtiled = FALSE;
break;
case 't': /* generate tiled output */
outtiled = TRUE;
break;
case 'w': /* tile width */
outtiled = TRUE;
deftilewidth = atoi(optarg);
break;
case 'B':
*mp++ = 'b'; *mp = '\0';
break;
case 'L':
*mp++ = 'l'; *mp = '\0';
break;
case 'M':
*mp++ = 'm'; *mp = '\0';
break;
case 'C':
*mp++ = 'c'; *mp = '\0';
break;
case '8':
*mp++ = '8'; *mp = '\0';
break;
case 'x':
pageInSeq = 1;
break;
case '?':
usage();
/*NOTREACHED*/
}
if (argc - optind < 2)
usage();
out = TIFFOpen(argv[argc-1], mode);
if (out == NULL)
return (-2);
if ((argc - optind) == 2)
pageNum = -1;
for (; optind < argc-1 ; optind++) {
char *imageCursor = argv[optind];
in = openSrcImage (&imageCursor);
if (in == NULL) {
(void) TIFFClose(out);
return (-3);
}
if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) {
TIFFError(TIFFFileName(in),
"Error, setting subdirectory at " TIFF_UINT64_FORMAT, diroff);
(void) TIFFClose(in);
(void) TIFFClose(out);
return (1);
}
for (;;) {
config = defconfig;
compression = defcompression;
predictor = defpredictor;
preset = defpreset;
fillorder = deffillorder;
rowsperstrip = defrowsperstrip;
tilewidth = deftilewidth;
tilelength = deftilelength;
g3opts = defg3opts;
if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) {
(void) TIFFClose(in);
(void) TIFFClose(out);
return (1);
}
if (imageCursor) { /* seek next image directory */
if (!nextSrcImage(in, &imageCursor)) break;
}else
if (!TIFFReadDirectory(in)) break;
}
(void) TIFFClose(in);
}
(void) TIFFClose(out);
return (0);
}
static void
processZIPOptions(char* cp)
{
if ( (cp = strchr(cp, ':')) ) {
do {
cp++;
if (isdigit((int)*cp))
defpredictor = atoi(cp);
else if (*cp == 'p')
defpreset = atoi(++cp);
else
usage();
} while( (cp = strchr(cp, ':')) );
}
}
static void
processG3Options(char* cp)
{
if( (cp = strchr(cp, ':')) ) {
if (defg3opts == (uint32) -1)
defg3opts = 0;
do {
cp++;
if (strneq(cp, "1d", 2))
defg3opts &= ~GROUP3OPT_2DENCODING;
else if (strneq(cp, "2d", 2))
defg3opts |= GROUP3OPT_2DENCODING;
else if (strneq(cp, "fill", 4))
defg3opts |= GROUP3OPT_FILLBITS;
else
usage();
} while( (cp = strchr(cp, ':')) );
}
}
static int
processCompressOptions(char* opt)
{
if (streq(opt, "none")) {
defcompression = COMPRESSION_NONE;
} else if (streq(opt, "packbits")) {
defcompression = COMPRESSION_PACKBITS;
} else if (strneq(opt, "jpeg", 4)) {
char* cp = strchr(opt, ':');
defcompression = COMPRESSION_JPEG;
while( cp )
{
if (isdigit((int)cp[1]))
quality = atoi(cp+1);
else if (cp[1] == 'r' )
jpegcolormode = JPEGCOLORMODE_RAW;
else
usage();
cp = strchr(cp+1,':');
}
} else if (strneq(opt, "g3", 2)) {
processG3Options(opt);
defcompression = COMPRESSION_CCITTFAX3;
} else if (streq(opt, "g4")) {
defcompression = COMPRESSION_CCITTFAX4;
} else if (strneq(opt, "lzw", 3)) {
char* cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_LZW;
} else if (strneq(opt, "zip", 3)) {
processZIPOptions(opt);
defcompression = COMPRESSION_ADOBE_DEFLATE;
} else if (strneq(opt, "lzma", 4)) {
processZIPOptions(opt);
defcompression = COMPRESSION_LZMA;
} else if (strneq(opt, "jbig", 4)) {
defcompression = COMPRESSION_JBIG;
} else if (strneq(opt, "sgilog", 6)) {
defcompression = COMPRESSION_SGILOG;
} else
return (0);
return (1);
}
char* stuff[] = {
"usage: tiffcp [options] input... output",
"where options are:",
" -a append to output instead of overwriting",
" -o offset set initial directory offset",
" -p contig pack samples contiguously (e.g. RGBRGB...)",
" -p separate store samples separately (e.g. RRR...GGG...BBB...)",
" -s write output in strips",
" -t write output in tiles",
" -x force the merged tiff pages in sequence",
" -8 write BigTIFF instead of default ClassicTIFF",
" -B write big-endian instead of native byte order",
" -L write little-endian instead of native byte order",
" -M disable use of memory-mapped files",
" -C disable strip chopping",
" -i ignore read errors",
" -b file[,#] bias (dark) monochrome image to be subtracted from all others",
" -,=% use % rather than , to separate image #'s (per Note below)",
"",
" -r # make each strip have no more than # rows",
" -w # set output tile width (pixels)",
" -l # set output tile length (pixels)",
"",
" -f lsb2msb force lsb-to-msb FillOrder for output",
" -f msb2lsb force msb-to-lsb FillOrder for output",
"",
" -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts] compress output with deflate encoding",
" -c lzma[:opts] compress output with LZMA2 encoding",
" -c jpeg[:opts] compress output with JPEG encoding",
" -c jbig compress output with ISO JBIG encoding",
" -c packbits compress output with packbits encoding",
" -c g3[:opts] compress output with CCITT Group 3 encoding",
" -c g4 compress output with CCITT Group 4 encoding",
" -c sgilog compress output with SGILOG encoding",
" -c none use no compression algorithm on output",
"",
"Group 3 options:",
" 1d use default CCITT Group 3 1D-encoding",
" 2d use optional CCITT Group 3 2D-encoding",
" fill byte-align EOL codes",
"For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs",
"",
"JPEG options:",
" # set compression quality level (0-100, default 75)",
" r output color image as RGB rather than YCbCr",
"For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality",
"",
"LZW, Deflate (ZIP) and LZMA2 options:",
" # set predictor value",
" p# set compression level (preset)",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing,",
"-c zip:3:p9 for Deflate encoding with maximum compression level and floating",
"point predictor.",
"",
"Note that input filenames may be of the form filename,x,y,z",
"where x, y, and z specify image numbers in the filename to copy.",
"example: tiffcp -c none -b esp.tif,1 esp.tif,0 test.tif",
" subtract 2nd image in esp.tif from 1st yielding uncompressed result test.tif",
NULL
};
static void
usage(void)
{
char buf[BUFSIZ];
int i;
setbuf(stderr, buf);
fprintf(stderr, "%s\n\n", TIFFGetVersion());
for (i = 0; stuff[i] != NULL; i++)
fprintf(stderr, "%s\n", stuff[i]);
exit(-1);
}
#define CopyField(tag, v) \
if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
#define CopyField2(tag, v1, v2) \
if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
#define CopyField3(tag, v1, v2, v3) \
if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
#define CopyField4(tag, v1, v2, v3, v4) \
if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
static void
cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
{
switch (type) {
case TIFF_SHORT:
if (count == 1) {
uint16 shortv;
CopyField(tag, shortv);
} else if (count == 2) {
uint16 shortv1, shortv2;
CopyField2(tag, shortv1, shortv2);
} else if (count == 4) {
uint16 *tr, *tg, *tb, *ta;
CopyField4(tag, tr, tg, tb, ta);
} else if (count == (uint16) -1) {
uint16 shortv1;
uint16* shortav;
CopyField2(tag, shortv1, shortav);
}
break;
case TIFF_LONG:
{ uint32 longv;
CopyField(tag, longv);
}
break;
case TIFF_RATIONAL:
if (count == 1) {
float floatv;
CopyField(tag, floatv);
} else if (count == (uint16) -1) {
float* floatav;
CopyField(tag, floatav);
}
break;
case TIFF_ASCII:
{ char* stringv;
CopyField(tag, stringv);
}
break;
case TIFF_DOUBLE:
if (count == 1) {
double doublev;
CopyField(tag, doublev);
} else if (count == (uint16) -1) {
double* doubleav;
CopyField(tag, doubleav);
}
break;
default:
TIFFError(TIFFFileName(in),
"Data type %d is not supported, tag %d skipped.",
tag, type);
}
}
static struct cpTag {
uint16 tag;
uint16 count;
TIFFDataType type;
} tags[] = {
{ TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
{ TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
{ TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
{ TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
{ TIFFTAG_MAKE, 1, TIFF_ASCII },
{ TIFFTAG_MODEL, 1, TIFF_ASCII },
{ TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_PAGENAME, 1, TIFF_ASCII },
{ TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
{ TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
{ TIFFTAG_DATETIME, 1, TIFF_ASCII },
{ TIFFTAG_ARTIST, 1, TIFF_ASCII },
{ TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
{ TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL },
{ TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
{ TIFFTAG_INKSET, 1, TIFF_SHORT },
{ TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
{ TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
{ TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
{ TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
{ TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
{ TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
{ TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_STONITS, 1, TIFF_DOUBLE },
};
#define NTAGS (sizeof (tags) / sizeof (tags[0]))
#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
typedef int (*copyFunc)
(TIFF* in, TIFF* out, uint32 l, uint32 w, uint16 samplesperpixel);
static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16, uint16);
/* PODD */
static int
tiffcp(TIFF* in, TIFF* out)
{
uint16 bitspersample = 1, samplesperpixel = 1;
uint16 input_compression, input_photometric = PHOTOMETRIC_MINISBLACK;
copyFunc cf;
uint32 width, length;
struct cpTag* p;
CopyField(TIFFTAG_IMAGEWIDTH, width);
CopyField(TIFFTAG_IMAGELENGTH, length);
CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample);
CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
CopyField(TIFFTAG_COMPRESSION, compression);
TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression);
TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric);
if (input_compression == COMPRESSION_JPEG) {
/* Force conversion to RGB */
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else if (input_photometric == PHOTOMETRIC_YCBCR) {
/* Otherwise, can't handle subsampled input */
uint16 subsamplinghor,subsamplingver;
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsamplinghor, &subsamplingver);
if (subsamplinghor!=1 || subsamplingver!=1) {
fprintf(stderr, "tiffcp: %s: Can't copy/convert subsampled image.\n",
TIFFFileName(in));
return FALSE;
}
}
if (compression == COMPRESSION_JPEG) {
if (input_photometric == PHOTOMETRIC_RGB &&
jpegcolormode == JPEGCOLORMODE_RGB)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else if (compression == COMPRESSION_SGILOG
|| compression == COMPRESSION_SGILOG24)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
samplesperpixel == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
else if (input_compression == COMPRESSION_JPEG &&
samplesperpixel == 3 ) {
/* RGB conversion was forced above
hence the output will be of the same type */
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
}
else
CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT);
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/*
* Will copy `Orientation' tag from input image
*/
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
switch (orientation) {
case ORIENTATION_BOTRIGHT:
case ORIENTATION_RIGHTBOT: /* XXX */
TIFFWarning(TIFFFileName(in), "using bottom-left orientation");
orientation = ORIENTATION_BOTLEFT;
/* fall thru... */
case ORIENTATION_LEFTBOT: /* XXX */
case ORIENTATION_BOTLEFT:
break;
case ORIENTATION_TOPRIGHT:
case ORIENTATION_RIGHTTOP: /* XXX */
default:
TIFFWarning(TIFFFileName(in), "using top-left orientation");
orientation = ORIENTATION_TOPLEFT;
/* fall thru... */
case ORIENTATION_LEFTTOP: /* XXX */
case ORIENTATION_TOPLEFT:
break;
}
TIFFSetField(out, TIFFTAG_ORIENTATION, orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) -1)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) -1)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0) {
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP,
&rowsperstrip)) {
rowsperstrip =
TIFFDefaultStripSize(out, rowsperstrip);
}
if (rowsperstrip > length && rowsperstrip != (uint32)-1)
rowsperstrip = length;
}
else if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (samplesperpixel <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
case COMPRESSION_JPEG:
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
break;
case COMPRESSION_JBIG:
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII);
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
case COMPRESSION_LZMA:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
if (preset != -1) {
if (compression == COMPRESSION_ADOBE_DEFLATE
|| compression == COMPRESSION_DEFLATE)
TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset);
else if (compression == COMPRESSION_LZMA)
TIFFSetField(out, TIFFTAG_LZMAPRESET, preset);
}
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS,
g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
}
{
uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{
uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
cp++;
inknameslen += (strlen(cp) + 1);
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (pageInSeq == 1) {
if (pageNum < 0) /* only one input file */ {
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1))
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
} else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
} else {
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
if (pageNum < 0) /* only one input file */
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
}
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
cf = pickCopyFunc(in, out, bitspersample, samplesperpixel);
return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE);
}
/*
* Copy Functions.
*/
#define DECLAREcpFunc(x) \
static int x(TIFF* in, TIFF* out, \
uint32 imagelength, uint32 imagewidth, tsample_t spp)
#define DECLAREreadFunc(x) \
static int x(TIFF* in, \
uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp)
typedef int (*readFunc)(TIFF*, uint8*, uint32, uint32, tsample_t);
#define DECLAREwriteFunc(x) \
static int x(TIFF* out, \
uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp)
typedef int (*writeFunc)(TIFF*, uint8*, uint32, uint32, tsample_t);
/*
* Contig -> contig by scanline for rows/strip change.
*/
DECLAREcpFunc(cpContig2ContigByRow)
{
tsize_t scanlinesize = TIFFScanlineSize(in);
tdata_t buf;
uint32 row;
buf = _TIFFmalloc(scanlinesize);
if (!buf)
return 0;
_TIFFmemset(buf, 0, scanlinesize);
(void) imagewidth; (void) spp;
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
if (TIFFWriteScanline(out, buf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
_TIFFfree(buf);
return 1;
bad:
_TIFFfree(buf);
return 0;
}
typedef void biasFn (void *image, void *bias, uint32 pixels);
#define subtract(bits) \
static void subtract##bits (void *i, void *b, uint32 pixels)\
{\
uint##bits *image = i;\
uint##bits *bias = b;\
while (pixels--) {\
*image = *image > *bias ? *image-*bias : 0;\
image++, bias++; \
} \
}
subtract(8)
subtract(16)
subtract(32)
static biasFn *lineSubtractFn (unsigned bits)
{
switch (bits) {
case 8: return subtract8;
case 16: return subtract16;
case 32: return subtract32;
}
return NULL;
}
/*
* Contig -> contig by scanline while subtracting a bias image.
*/
DECLAREcpFunc(cpBiasedContig2Contig)
{
if (spp == 1) {
tsize_t biasSize = TIFFScanlineSize(bias);
tsize_t bufSize = TIFFScanlineSize(in);
tdata_t buf, biasBuf;
uint32 biasWidth = 0, biasLength = 0;
TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth);
TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength);
if (biasSize == bufSize &&
imagelength == biasLength && imagewidth == biasWidth) {
uint16 sampleBits = 0;
biasFn *subtractLine;
TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits);
subtractLine = lineSubtractFn (sampleBits);
if (subtractLine) {
uint32 row;
buf = _TIFFmalloc(bufSize);
biasBuf = _TIFFmalloc(bufSize);
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, buf, row, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
if (TIFFReadScanline(bias, biasBuf, row, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read biased scanline %lu",
(unsigned long) row);
goto bad;
}
subtractLine (buf, biasBuf, imagewidth);
if (TIFFWriteScanline(out, buf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
_TIFFfree(buf);
_TIFFfree(biasBuf);
TIFFSetDirectory(bias,
TIFFCurrentDirectory(bias)); /* rewind */
return 1;
bad:
_TIFFfree(buf);
_TIFFfree(biasBuf);
return 0;
} else {
TIFFError(TIFFFileName(in),
"No support for biasing %d bit pixels\n",
sampleBits);
return 0;
}
}
TIFFError(TIFFFileName(in),
"Bias image %s,%d\nis not the same size as %s,%d\n",
TIFFFileName(bias), TIFFCurrentDirectory(bias),
TIFFFileName(in), TIFFCurrentDirectory(in));
return 0;
} else {
TIFFError(TIFFFileName(in),
"Can't bias %s,%d as it has >1 Sample/Pixel\n",
TIFFFileName(in), TIFFCurrentDirectory(in));
return 0;
}
}
/*
* Strip -> strip for change in encoding.
*/
DECLAREcpFunc(cpDecodedStrips)
{
tsize_t stripsize = TIFFStripSize(in);
tdata_t buf = _TIFFmalloc(stripsize);
(void) imagewidth; (void) spp;
if (buf) {
tstrip_t s, ns = TIFFNumberOfStrips(in);
uint32 row = 0;
_TIFFmemset(buf, 0, stripsize);
for (s = 0; s < ns && row < imagelength; s++) {
tsize_t cc = (row + rowsperstrip > imagelength) ?
TIFFVStripSize(in, imagelength - row) : stripsize;
if (TIFFReadEncodedStrip(in, s, buf, cc) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu",
(unsigned long) s);
goto bad;
}
if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write strip %lu",
(unsigned long) s);
goto bad;
}
row += rowsperstrip;
}
_TIFFfree(buf);
return 1;
} else {
TIFFError(TIFFFileName(in),
"Error, can't allocate memory buffer of size %lu "
"to read strips", (unsigned long) stripsize);
return 0;
}
bad:
_TIFFfree(buf);
return 0;
}
/*
* Separate -> separate by row for rows/strip change.
*/
DECLAREcpFunc(cpSeparate2SeparateByRow)
{
tsize_t scanlinesize = TIFFScanlineSize(in);
tdata_t buf;
uint32 row;
tsample_t s;
(void) imagewidth;
buf = _TIFFmalloc(scanlinesize);
if (!buf)
return 0;
_TIFFmemset(buf, 0, scanlinesize);
for (s = 0; s < spp; s++) {
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
if (TIFFWriteScanline(out, buf, row, s) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
}
_TIFFfree(buf);
return 1;
bad:
_TIFFfree(buf);
return 0;
}
/*
* Contig -> separate by row.
*/
DECLAREcpFunc(cpContig2SeparateByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
uint16 bps = 0;
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps != 8 )
{
TIFFError(TIFFFileName(in),
"Error, can only handle BitsPerSample=8 in %s",
"cpContig2SeparateByRow");
return 0;
}
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
/* unpack channels */
for (s = 0; s < spp; s++) {
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, inbuf, row, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = ((uint8*)inbuf) + s;
outp = (uint8*)outbuf;
for (n = imagewidth; n-- > 0;) {
*outp++ = *inp;
inp += spp;
}
if (TIFFWriteScanline(out, outbuf, row, s) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
/*
* Separate -> contig by row.
*/
DECLAREcpFunc(cpSeparate2ContigByRow)
{
tsize_t scanlinesizein = TIFFScanlineSize(in);
tsize_t scanlinesizeout = TIFFScanlineSize(out);
tdata_t inbuf;
tdata_t outbuf;
register uint8 *inp, *outp;
register uint32 n;
uint32 row;
tsample_t s;
uint16 bps = 0;
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps != 8 )
{
TIFFError(TIFFFileName(in),
"Error, can only handle BitsPerSample=8 in %s",
"cpSeparate2ContigByRow");
return 0;
}
inbuf = _TIFFmalloc(scanlinesizein);
outbuf = _TIFFmalloc(scanlinesizeout);
if (!inbuf || !outbuf)
goto bad;
_TIFFmemset(inbuf, 0, scanlinesizein);
_TIFFmemset(outbuf, 0, scanlinesizeout);
for (row = 0; row < imagelength; row++) {
/* merge channels */
for (s = 0; s < spp; s++) {
if (TIFFReadScanline(in, inbuf, row, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
goto bad;
}
inp = (uint8*)inbuf;
outp = ((uint8*)outbuf) + s;
for (n = imagewidth; n-- > 0;) {
*outp = *inp++;
outp += spp;
}
}
if (TIFFWriteScanline(out, outbuf, row, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write scanline %lu",
(unsigned long) row);
goto bad;
}
}
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 1;
bad:
if (inbuf) _TIFFfree(inbuf);
if (outbuf) _TIFFfree(outbuf);
return 0;
}
static void
cpStripToTile(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int64 inskew)
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0)
*out++ = *in++;
out += outskew;
in += inskew;
}
}
static void
cpContigBufToSeparateBuf(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp,
int bytes_per_sample )
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0)
{
int n = bytes_per_sample;
while( n-- ) {
*out++ = *in++;
}
in += (spp-1) * bytes_per_sample;
}
out += outskew;
in += inskew;
}
}
static void
cpSeparateBufToContigBuf(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp,
int bytes_per_sample)
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0) {
int n = bytes_per_sample;
while( n-- ) {
*out++ = *in++;
}
out += (spp-1)*bytes_per_sample;
}
out += outskew;
in += inskew;
}
}
static int
cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout,
uint32 imagelength, uint32 imagewidth, tsample_t spp)
{
int status = 0;
tdata_t buf = NULL;
tsize_t scanlinesize = TIFFRasterScanlineSize(in);
tsize_t bytes = scanlinesize * (tsize_t)imagelength;
/*
* XXX: Check for integer overflow.
*/
if (scanlinesize
&& imagelength
&& bytes / (tsize_t)imagelength == scanlinesize) {
buf = _TIFFmalloc(bytes);
if (buf) {
if ((*fin)(in, (uint8*)buf, imagelength,
imagewidth, spp)) {
status = (*fout)(out, (uint8*)buf,
imagelength, imagewidth, spp);
}
_TIFFfree(buf);
} else {
TIFFError(TIFFFileName(in),
"Error, can't allocate space for image buffer");
}
} else {
TIFFError(TIFFFileName(in), "Error, no space for image buffer");
}
return status;
}
DECLAREreadFunc(readContigStripsIntoBuffer)
{
tsize_t scanlinesize = TIFFScanlineSize(in);
uint8* bufp = buf;
uint32 row;
(void) imagewidth; (void) spp;
for (row = 0; row < imagelength; row++) {
if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
return 0;
}
bufp += scanlinesize;
}
return 1;
}
DECLAREreadFunc(readSeparateStripsIntoBuffer)
{
int status = 1;
tsize_t scanlinesize = TIFFScanlineSize(in);
tdata_t scanline;
if (!scanlinesize)
return 0;
scanline = _TIFFmalloc(scanlinesize);
if (!scanline)
return 0;
_TIFFmemset(scanline, 0, scanlinesize);
(void) imagewidth;
if (scanline) {
uint8* bufp = (uint8*) buf;
uint32 row;
tsample_t s;
for (row = 0; row < imagelength; row++) {
/* merge channels */
for (s = 0; s < spp; s++) {
uint8* bp = bufp + s;
tsize_t n = scanlinesize;
uint8* sbuf = scanline;
if (TIFFReadScanline(in, scanline, row, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read scanline %lu",
(unsigned long) row);
status = 0;
goto done;
}
while (n-- > 0)
*bp = *sbuf++, bp += spp;
}
bufp += scanlinesize * spp;
}
}
done:
_TIFFfree(scanline);
return status;
}
DECLAREreadFunc(readContigTilesIntoBuffer)
{
int status = 1;
tsize_t tilesize = TIFFTileSize(in);
tdata_t tilebuf;
uint32 imagew = TIFFScanlineSize(in);
uint32 tilew = TIFFTileRowSize(in);
int64 iskew = (int64)imagew - (int64)tilew;
uint8* bufp = (uint8*) buf;
uint32 tw, tl;
uint32 row;
(void) spp;
tilebuf = _TIFFmalloc(tilesize);
if (tilebuf == 0)
return 0;
_TIFFmemset(tilebuf, 0, tilesize);
(void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
(void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
for (row = 0; row < imagelength; row += tl) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth && colb < imagew; col += tw) {
if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read tile at %lu %lu",
(unsigned long) col,
(unsigned long) row);
status = 0;
goto done;
}
if (colb > iskew) {
uint32 width = imagew - colb;
uint32 oskew = tilew - width;
cpStripToTile(bufp + colb,
tilebuf, nrow, width,
oskew + iskew, oskew );
} else
cpStripToTile(bufp + colb,
tilebuf, nrow, tilew,
iskew, 0);
colb += tilew;
}
bufp += imagew * nrow;
}
done:
_TIFFfree(tilebuf);
return status;
}
DECLAREreadFunc(readSeparateTilesIntoBuffer)
{
int status = 1;
uint32 imagew = TIFFRasterScanlineSize(in);
uint32 tilew = TIFFTileRowSize(in);
int iskew = imagew - tilew*spp;
tsize_t tilesize = TIFFTileSize(in);
tdata_t tilebuf;
uint8* bufp = (uint8*) buf;
uint32 tw, tl;
uint32 row;
uint16 bps = 0, bytes_per_sample;
tilebuf = _TIFFmalloc(tilesize);
if (tilebuf == 0)
return 0;
_TIFFmemset(tilebuf, 0, tilesize);
(void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
(void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps == 0 )
{
TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample");
status = 0;
goto done;
}
if( (bps % 8) != 0 )
{
TIFFError(TIFFFileName(in), "Error, cannot handle BitsPerSample that is not a multiple of 8");
status = 0;
goto done;
}
bytes_per_sample = bps/8;
for (row = 0; row < imagelength; row += tl) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth; col += tw) {
tsample_t s;
for (s = 0; s < spp; s++) {
if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read tile at %lu %lu, "
"sample %lu",
(unsigned long) col,
(unsigned long) row,
(unsigned long) s);
status = 0;
goto done;
}
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew*spp > imagew) {
uint32 width = imagew - colb;
int oskew = tilew*spp - width;
cpSeparateBufToContigBuf(
bufp+colb+s*bytes_per_sample,
tilebuf, nrow,
width/(spp*bytes_per_sample),
oskew + iskew,
oskew/spp, spp,
bytes_per_sample);
} else
cpSeparateBufToContigBuf(
bufp+colb+s*bytes_per_sample,
tilebuf, nrow, tw,
iskew, 0, spp,
bytes_per_sample);
}
colb += tilew*spp;
}
bufp += imagew * nrow;
}
done:
_TIFFfree(tilebuf);
return status;
}
DECLAREwriteFunc(writeBufferToContigStrips)
{
uint32 row, rowsperstrip;
tstrip_t strip = 0;
(void) imagewidth; (void) spp;
(void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (row = 0; row < imagelength; row += rowsperstrip) {
uint32 nrows = (row+rowsperstrip > imagelength) ?
imagelength-row : rowsperstrip;
tsize_t stripsize = TIFFVStripSize(out, nrows);
if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write strip %u", strip - 1);
return 0;
}
buf += stripsize;
}
return 1;
}
DECLAREwriteFunc(writeBufferToSeparateStrips)
{
uint32 rowsize = imagewidth * spp;
uint32 rowsperstrip;
tsize_t stripsize = TIFFStripSize(out);
tdata_t obuf;
tstrip_t strip = 0;
tsample_t s;
obuf = _TIFFmalloc(stripsize);
if (obuf == NULL)
return (0);
_TIFFmemset(obuf, 0, stripsize);
(void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (s = 0; s < spp; s++) {
uint32 row;
for (row = 0; row < imagelength; row += rowsperstrip) {
uint32 nrows = (row+rowsperstrip > imagelength) ?
imagelength-row : rowsperstrip;
tsize_t stripsize = TIFFVStripSize(out, nrows);
cpContigBufToSeparateBuf(
obuf, (uint8*) buf + row*rowsize + s,
nrows, imagewidth, 0, 0, spp, 1);
if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write strip %u",
strip - 1);
_TIFFfree(obuf);
return 0;
}
}
}
_TIFFfree(obuf);
return 1;
}
DECLAREwriteFunc(writeBufferToContigTiles)
{
uint32 imagew = TIFFScanlineSize(out);
uint32 tilew = TIFFTileRowSize(out);
int iskew = imagew - tilew;
tsize_t tilesize = TIFFTileSize(out);
tdata_t obuf;
uint8* bufp = (uint8*) buf;
uint32 tl, tw;
uint32 row;
(void) spp;
obuf = _TIFFmalloc(TIFFTileSize(out));
if (obuf == NULL)
return 0;
_TIFFmemset(obuf, 0, tilesize);
(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
for (row = 0; row < imagelength; row += tilelength) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth && colb < imagew; col += tw) {
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew > imagew) {
uint32 width = imagew - colb;
int oskew = tilew - width;
cpStripToTile(obuf, bufp + colb, nrow, width,
oskew, oskew + iskew);
} else
cpStripToTile(obuf, bufp + colb, nrow, tilew,
0, iskew);
if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write tile at %lu %lu",
(unsigned long) col,
(unsigned long) row);
_TIFFfree(obuf);
return 0;
}
colb += tilew;
}
bufp += nrow * imagew;
}
_TIFFfree(obuf);
return 1;
}
DECLAREwriteFunc(writeBufferToSeparateTiles)
{
uint32 imagew = TIFFScanlineSize(out);
tsize_t tilew = TIFFTileRowSize(out);
uint32 iimagew = TIFFRasterScanlineSize(out);
int iskew = iimagew - tilew*spp;
tsize_t tilesize = TIFFTileSize(out);
tdata_t obuf;
uint8* bufp = (uint8*) buf;
uint32 tl, tw;
uint32 row;
uint16 bps = 0, bytes_per_sample;
obuf = _TIFFmalloc(TIFFTileSize(out));
if (obuf == NULL)
return 0;
_TIFFmemset(obuf, 0, tilesize);
(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
(void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
if( bps == 0 )
{
TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample");
_TIFFfree(obuf);
return 0;
}
if( (bps % 8) != 0 )
{
TIFFError(TIFFFileName(out), "Error, cannot handle BitsPerSample that is not a multiple of 8");
_TIFFfree(obuf);
return 0;
}
bytes_per_sample = bps/8;
for (row = 0; row < imagelength; row += tl) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth; col += tw) {
tsample_t s;
for (s = 0; s < spp; s++) {
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew > imagew) {
uint32 width = (imagew - colb);
int oskew = tilew - width;
cpContigBufToSeparateBuf(obuf,
bufp + (colb*spp) + s,
nrow, width/bytes_per_sample,
oskew, (oskew*spp)+iskew, spp,
bytes_per_sample);
} else
cpContigBufToSeparateBuf(obuf,
bufp + (colb*spp) + s,
nrow, tilewidth,
0, iskew, spp,
bytes_per_sample);
if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write tile at %lu %lu "
"sample %lu",
(unsigned long) col,
(unsigned long) row,
(unsigned long) s);
_TIFFfree(obuf);
return 0;
}
}
colb += tilew;
}
bufp += nrow * iimagew;
}
_TIFFfree(obuf);
return 1;
}
/*
* Contig strips -> contig tiles.
*/
DECLAREcpFunc(cpContigStrips2ContigTiles)
{
return cpImage(in, out,
readContigStripsIntoBuffer,
writeBufferToContigTiles,
imagelength, imagewidth, spp);
}
/*
* Contig strips -> separate tiles.
*/
DECLAREcpFunc(cpContigStrips2SeparateTiles)
{
return cpImage(in, out,
readContigStripsIntoBuffer,
writeBufferToSeparateTiles,
imagelength, imagewidth, spp);
}
/*
* Separate strips -> contig tiles.
*/
DECLAREcpFunc(cpSeparateStrips2ContigTiles)
{
return cpImage(in, out,
readSeparateStripsIntoBuffer,
writeBufferToContigTiles,
imagelength, imagewidth, spp);
}
/*
* Separate strips -> separate tiles.
*/
DECLAREcpFunc(cpSeparateStrips2SeparateTiles)
{
return cpImage(in, out,
readSeparateStripsIntoBuffer,
writeBufferToSeparateTiles,
imagelength, imagewidth, spp);
}
/*
* Contig strips -> contig tiles.
*/
DECLAREcpFunc(cpContigTiles2ContigTiles)
{
return cpImage(in, out,
readContigTilesIntoBuffer,
writeBufferToContigTiles,
imagelength, imagewidth, spp);
}
/*
* Contig tiles -> separate tiles.
*/
DECLAREcpFunc(cpContigTiles2SeparateTiles)
{
return cpImage(in, out,
readContigTilesIntoBuffer,
writeBufferToSeparateTiles,
imagelength, imagewidth, spp);
}
/*
* Separate tiles -> contig tiles.
*/
DECLAREcpFunc(cpSeparateTiles2ContigTiles)
{
return cpImage(in, out,
readSeparateTilesIntoBuffer,
writeBufferToContigTiles,
imagelength, imagewidth, spp);
}
/*
* Separate tiles -> separate tiles (tile dimension change).
*/
DECLAREcpFunc(cpSeparateTiles2SeparateTiles)
{
return cpImage(in, out,
readSeparateTilesIntoBuffer,
writeBufferToSeparateTiles,
imagelength, imagewidth, spp);
}
/*
* Contig tiles -> contig tiles (tile dimension change).
*/
DECLAREcpFunc(cpContigTiles2ContigStrips)
{
return cpImage(in, out,
readContigTilesIntoBuffer,
writeBufferToContigStrips,
imagelength, imagewidth, spp);
}
/*
* Contig tiles -> separate strips.
*/
DECLAREcpFunc(cpContigTiles2SeparateStrips)
{
return cpImage(in, out,
readContigTilesIntoBuffer,
writeBufferToSeparateStrips,
imagelength, imagewidth, spp);
}
/*
* Separate tiles -> contig strips.
*/
DECLAREcpFunc(cpSeparateTiles2ContigStrips)
{
return cpImage(in, out,
readSeparateTilesIntoBuffer,
writeBufferToContigStrips,
imagelength, imagewidth, spp);
}
/*
* Separate tiles -> separate strips.
*/
DECLAREcpFunc(cpSeparateTiles2SeparateStrips)
{
return cpImage(in, out,
readSeparateTilesIntoBuffer,
writeBufferToSeparateStrips,
imagelength, imagewidth, spp);
}
/*
* Select the appropriate copy function to use.
*/
static copyFunc
pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel)
{
uint16 shortv;
uint32 w, l, tw, tl;
int bychunk;
(void) TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &shortv);
if (shortv != config && bitspersample != 8 && samplesperpixel > 1) {
fprintf(stderr,
"%s: Cannot handle different planar configuration w/ bits/sample != 8\n",
TIFFFileName(in));
return (NULL);
}
TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l);
if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) {
uint32 irps = (uint32) -1L;
TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps);
/* if biased, force decoded copying to allow image subtraction */
bychunk = !bias && (rowsperstrip == irps);
}else{ /* either in or out is tiled */
if (bias) {
fprintf(stderr,
"%s: Cannot handle tiled configuration w/bias image\n",
TIFFFileName(in));
return (NULL);
}
if (TIFFIsTiled(out)) {
if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw))
tw = w;
if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl))
tl = l;
bychunk = (tw == tilewidth && tl == tilelength);
} else { /* out's not, so in must be tiled */
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
bychunk = (tw == w && tl == rowsperstrip);
}
}
#define T 1
#define F 0
#define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e)))
switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) {
/* Strips -> Tiles */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T):
return cpContigStrips2ContigTiles;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T):
return cpContigStrips2SeparateTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T):
return cpSeparateStrips2ContigTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T):
return cpSeparateStrips2SeparateTiles;
/* Tiles -> Tiles */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T):
return cpContigTiles2ContigTiles;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T):
return cpContigTiles2SeparateTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T):
return cpSeparateTiles2ContigTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T):
return cpSeparateTiles2SeparateTiles;
/* Tiles -> Strips */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T):
return cpContigTiles2ContigStrips;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T):
return cpContigTiles2SeparateStrips;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T):
return cpSeparateTiles2ContigStrips;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T):
return cpSeparateTiles2SeparateStrips;
/* Strips -> Strips */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F):
return bias ? cpBiasedContig2Contig : cpContig2ContigByRow;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T):
return cpDecodedStrips;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T):
return cpContig2SeparateByRow;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T):
return cpSeparate2ContigByRow;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T):
return cpSeparate2SeparateByRow;
}
#undef pack
#undef F
#undef T
fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n",
TIFFFileName(in));
return (NULL);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3087_1 |
crossvul-cpp_data_bad_345_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_345_7 |
crossvul-cpp_data_bad_1299_0 | /*
* card-cac1.c: Support for legacy CAC-1
* card-default.c: Support for cards with no driver
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
* Copyright (C) 2016 - 2018, Red Hat, Inc.
*
* CAC driver author: Robert Relyea <rrelyea@redhat.com>
* Further work: Jakub Jelen <jjelen@redhat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/sha.h>
#endif /* ENABLE_OPENSSL */
#include "internal.h"
#include "simpletlv.h"
#include "cardctl.h"
#ifdef ENABLE_ZLIB
#include "compression.h"
#endif
#include "iso7816.h"
#include "card-cac-common.h"
/*
* CAC hardware and APDU constants
*/
#define CAC_INS_GET_CERTIFICATE 0x36 /* CAC1 command to read a certificate */
/*
* OLD cac read certificate, only use with CAC-1 card.
*/
static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len)
{
u8 buf[CAC_MAX_SIZE];
u8 *out_ptr;
size_t size = 0;
size_t left = 0;
size_t len, next_len;
sc_apdu_t apdu;
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* get the size */
size = left = *out_buf ? *out_len : sizeof(buf);
out_ptr = *out_buf ? *out_buf : buf;
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 );
next_len = MIN(left, 100);
for (; left > 0; left -= len, out_ptr += len) {
len = next_len;
apdu.resp = out_ptr;
apdu.le = len;
apdu.resplen = left;
r = sc_transmit_apdu(card, &apdu);
if (r < 0) {
break;
}
if (apdu.resplen == 0) {
r = SC_ERROR_INTERNAL;
break;
}
/* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */
if (apdu.sw1 != 0x63 || apdu.sw2 < 1) {
/* we've either finished reading, or hit an error, break */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
left -= len;
break;
}
next_len = MIN(left, apdu.sw2);
}
if (r < 0) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
r = size - left;
if (*out_buf == NULL) {
*out_buf = malloc(r);
if (*out_buf == NULL) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,
SC_ERROR_OUT_OF_MEMORY);
}
memcpy(*out_buf, buf, r);
}
*out_len = r;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
/*
* Callers of this may be expecting a certificate,
* select file will have saved the object type for us
* as well as set that we want the cert from the object.
*/
static int cac_read_binary(sc_card_t *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
cac_private_data_t * priv = CAC_DATA(card);
int r = 0;
u8 *val = NULL;
u8 *cert_ptr;
size_t val_len;
size_t len, cert_len;
u8 cert_type;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* if we didn't return it all last time, return the remainder */
if (priv->cached) {
sc_log(card->ctx,
"returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (idx > priv->cache_buf_len) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED);
}
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
LOG_FUNC_RETURN(card->ctx, len);
}
sc_log(card->ctx,
"clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
free(priv->cache_buf);
priv->cache_buf = NULL;
priv->cache_buf_len = 0;
r = cac_cac1_get_certificate(card, &val, &val_len);
if (r < 0)
goto done;
if (val_len < 1) {
r = SC_ERROR_INVALID_DATA;
goto done;
}
cert_type = val[0];
cert_ptr = val + 1;
cert_len = val_len - 1;
/* if the info byte is 1, then the cert is compressed, decompress it */
if ((cert_type & 0x3) == 1) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len,
cert_ptr, cert_len, COMPRESSION_AUTO);
#else
sc_log(card->ctx, "CAC compression not supported, no zlib");
r = SC_ERROR_NOT_SUPPORTED;
#endif
if (r)
goto done;
} else if (cert_len > 0) {
priv->cache_buf = malloc(cert_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = cert_len;
memcpy(priv->cache_buf, cert_ptr, cert_len);
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
priv->cached = 1;
len = MIN(count, priv->cache_buf_len-idx);
if (len && priv->cache_buf)
memcpy(buf, &priv->cache_buf[idx], len);
r = len;
done:
if (val)
free(val);
LOG_FUNC_RETURN(card->ctx, r);
}
/*
* CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more
* of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead
* of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS
* if it doesn't like anything about the select, so we always 'request' FCI for CAC1
*
* The rest is just copied from iso7816_select_file
*/
static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
struct sc_context *ctx;
struct sc_apdu apdu;
unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen, pathtype;
struct sc_file *file = NULL;
cac_private_data_t * priv = CAC_DATA(card);
assert(card != NULL && in_path != NULL);
ctx = card->ctx;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
pathtype = in_path->type;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path=%s, path->value=%s path->type=%d (%x)",
sc_print_path(in_path),
sc_dump_hex(in_path->value, in_path->len),
in_path->type, in_path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
file_out, in_path->index, in_path->count);
/* Sigh, iso7816_select_file expects paths to keys to have specific
* formats. There is no override. We have to add some bytes to the
* path to make it happy.
* We only need to do this for private keys.
*/
if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
path += 2;
pathlen -= 2;
}
/* CAC has multiple different type of objects that aren't PKCS #15. When we read
* them we need convert them to something PKCS #15 would understand. Find the object
* and object type here:
*/
if (priv) { /* don't record anything if we haven't been initialized yet */
/* forget any old cached values */
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
}
priv->cache_buf_len = 0;
priv->cached = 0;
}
if (in_path->aid.len) {
if (!pathlen) {
memcpy(path, in_path->aid.value, in_path->aid.len);
pathlen = in_path->aid.len;
pathtype = SC_PATH_TYPE_DF_NAME;
} else {
/* First, select the application */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
apdu.data = in_path->aid.value;
apdu.datalen = in_path->aid.len;
apdu.lc = in_path->aid.len;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
switch (pathtype) {
/* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select.
* Unfortunately we'd also need to update the caching code as well. For now just
* use FILE_ID and change p1 here */
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 2;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
apdu.p2 = 0x00;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
if (file_out == NULL) {
/* For some cards 'SELECT' can be only with request to return FCI/FCP. */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) {
apdu.p2 = 0x00;
apdu.resplen = sizeof(buf);
if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_FUNC_RETURN(ctx, r);
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
/* CAC cards never return FCI, fake one */
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
*file_out = file;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
return cac_select_file_by_type(card, in_path, file_out);
}
static int cac_finish(sc_card_t *card)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
cac_free_private_data(priv);
}
return SC_SUCCESS;
}
/* select a CAC pki applet by index */
static int cac_select_pki_applet(sc_card_t *card, int index)
{
sc_path_t applet_path = cac_cac_pki_obj.path;
applet_path.aid.value[applet_path.aid.len-1] = index;
return cac_select_file_by_type(card, &applet_path, NULL);
}
/*
* Find the first existing CAC applet. If none found, then this isn't a CAC
*/
static int cac_find_first_pki_applet(sc_card_t *card, int *index_out)
{
int r, i;
for (i = 0; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
u8 data[2];
sc_apdu_t apdu;
/* Try to read first two bytes of the buffer to
* make sure it is not just malfunctioning card
*/
sc_format_apdu(card, &apdu, SC_APDU_CASE_2,
CAC_INS_GET_CERTIFICATE, 0x00, 0x00);
apdu.le = 0x02;
apdu.resplen = 2;
apdu.resp = data;
r = sc_transmit_apdu(card, &apdu);
/* SW1 = 0x63 means more data in CAC1 */
if (r == SC_SUCCESS && apdu.sw1 != 0x63)
continue;
*index_out = i;
return SC_SUCCESS;
}
}
return SC_ERROR_OBJECT_NOT_FOUND;
}
static int cac_populate_cac1(sc_card_t *card, int index, cac_private_data_t *priv)
{
int r, i;
cac_object_t pki_obj = cac_cac_pki_obj;
u8 buf[100];
u8 *val;
size_t val_len;
/* populate PKI objects */
for (i = index; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
pki_obj.name = get_cac_label(i);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: pki_object found, cert_next=%d (%s)",
i, pki_obj.name);
pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
pki_obj.fd = i+1; /* don't use id of zero */
cac_add_object_to_list(&priv->pki_list, &pki_obj);
}
}
/*
* create a cuid to simulate the cac 2 cuid.
*/
priv->cuid = cac_cac_cuid;
/* create a serial number by hashing the first 100 bytes of the
* first certificate on the card */
r = cac_select_pki_applet(card, index);
if (r < 0) {
return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
}
val = buf;
val_len = sizeof(buf);
r = cac_cac1_get_certificate(card, &val, &val_len);
if (r >= 0) {
priv->cac_id = malloc(20);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
#ifdef ENABLE_OPENSSL
SHA1(val, val_len, priv->cac_id);
priv->cac_id_len = 20;
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"cuid", priv->cac_id, priv->cac_id_len);
#else
sc_log(card->ctx, "OpenSSL Required");
return SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
}
return SC_SUCCESS;
}
/*
* Look for a CAC card. If it exists, initialize our data structures
*/
static int cac_find_and_initialize(sc_card_t *card, int initialize)
{
int r, index;
cac_private_data_t *priv = NULL;
/* already initialized? */
if (card->drv_data) {
return SC_SUCCESS;
}
/* is this a CAC Alt token without any accompanying structures */
r = cac_find_first_pki_applet(card, &index);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC-1");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
card->drv_data = priv; /* needed for the read_binary() */
r = cac_populate_cac1(card, index, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_I;
return r;
}
card->drv_data = NULL; /* reset on failure */
}
if (priv) {
cac_free_private_data(priv);
}
return r;
}
/* NOTE: returns a bool, 1 card matches, 0 it does not */
static int cac_match_card(sc_card_t *card)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
r = cac_find_and_initialize(card, 0);
return (r == SC_SUCCESS); /* never match */
}
static int cac_init(sc_card_t *card)
{
int r;
unsigned long flags;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_find_and_initialize(card, 1);
if (r < 0) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
}
flags = SC_ALGORITHM_RSA_RAW;
_sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
_sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
_sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static struct sc_card_operations cac_ops;
static struct sc_card_driver cac1_drv = {
"Common Access Card (CAC 1)",
"cac1",
&cac_ops,
NULL, 0, NULL
};
static struct sc_card_driver * sc_get_driver(void)
{
/* Inherit most of the things from the CAC driver */
struct sc_card_driver *cac_drv = sc_get_cac_driver();
cac_ops = *cac_drv->ops;
cac_ops.match_card = cac_match_card;
cac_ops.init = cac_init;
cac_ops.finish = cac_finish;
cac_ops.select_file = cac_select_file; /* need to record object type */
cac_ops.read_binary = cac_read_binary;
return &cac1_drv;
}
struct sc_card_driver * sc_get_cac1_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1299_0 |
crossvul-cpp_data_bad_2414_0 | /*
* symlink.c
*
* PURPOSE
* Symlink handling routines for the OSTA-UDF(tm) filesystem.
*
* COPYRIGHT
* This file is distributed under the terms of the GNU General Public
* License (GPL). Copies of the GPL can be obtained from:
* ftp://prep.ai.mit.edu/pub/gnu/GPL
* Each contributing author retains all rights to their own work.
*
* (C) 1998-2001 Ben Fennema
* (C) 1999 Stelias Computing Inc
*
* HISTORY
*
* 04/16/99 blf Created.
*
*/
#include "udfdecl.h"
#include <linux/uaccess.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/stat.h>
#include <linux/pagemap.h>
#include <linux/buffer_head.h>
#include "udf_i.h"
static int udf_pc_to_char(struct super_block *sb, unsigned char *from,
int fromlen, unsigned char *to, int tolen)
{
struct pathComponent *pc;
int elen = 0;
int comp_len;
unsigned char *p = to;
/* Reserve one byte for terminating \0 */
tolen--;
while (elen < fromlen) {
pc = (struct pathComponent *)(from + elen);
switch (pc->componentType) {
case 1:
/*
* Symlink points to some place which should be agreed
* upon between originator and receiver of the media. Ignore.
*/
if (pc->lengthComponentIdent > 0)
break;
/* Fall through */
case 2:
if (tolen == 0)
return -ENAMETOOLONG;
p = to;
*p++ = '/';
tolen--;
break;
case 3:
if (tolen < 3)
return -ENAMETOOLONG;
memcpy(p, "../", 3);
p += 3;
tolen -= 3;
break;
case 4:
if (tolen < 2)
return -ENAMETOOLONG;
memcpy(p, "./", 2);
p += 2;
tolen -= 2;
/* that would be . - just ignore */
break;
case 5:
comp_len = udf_get_filename(sb, pc->componentIdent,
pc->lengthComponentIdent,
p, tolen);
p += comp_len;
tolen -= comp_len;
if (tolen == 0)
return -ENAMETOOLONG;
*p++ = '/';
tolen--;
break;
}
elen += sizeof(struct pathComponent) + pc->lengthComponentIdent;
}
if (p > to + 1)
p[-1] = '\0';
else
p[0] = '\0';
return 0;
}
static int udf_symlink_filler(struct file *file, struct page *page)
{
struct inode *inode = page->mapping->host;
struct buffer_head *bh = NULL;
unsigned char *symlink;
int err;
unsigned char *p = kmap(page);
struct udf_inode_info *iinfo;
uint32_t pos;
/* We don't support symlinks longer than one block */
if (inode->i_size > inode->i_sb->s_blocksize) {
err = -ENAMETOOLONG;
goto out_unmap;
}
iinfo = UDF_I(inode);
pos = udf_block_map(inode, 0);
down_read(&iinfo->i_data_sem);
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) {
symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr;
} else {
bh = sb_bread(inode->i_sb, pos);
if (!bh) {
err = -EIO;
goto out_unlock_inode;
}
symlink = bh->b_data;
}
err = udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p, PAGE_SIZE);
brelse(bh);
if (err)
goto out_unlock_inode;
up_read(&iinfo->i_data_sem);
SetPageUptodate(page);
kunmap(page);
unlock_page(page);
return 0;
out_unlock_inode:
up_read(&iinfo->i_data_sem);
SetPageError(page);
out_unmap:
kunmap(page);
unlock_page(page);
return err;
}
/*
* symlinks can't do much...
*/
const struct address_space_operations udf_symlink_aops = {
.readpage = udf_symlink_filler,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2414_0 |
crossvul-cpp_data_bad_341_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by David Mattes <david.mattes@boeing.com> */
/* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#define MANU_ID "Gemplus"
#define APPLET_NAME "GemSAFE V1"
#define DRIVER_SERIAL_NUMBER "v0.9"
#define GEMSAFE_APP_PATH "3F001600"
#define GEMSAFE_PATH "3F0016000004"
/* Apparently, the Applet max read "quanta" is 248 bytes
* Gemalto ClassicClient reads files in chunks of 238 bytes
*/
#define GEMSAFE_READ_QUANTUM 248
#define GEMSAFE_MAX_OBJLEN 28672
int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *);
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags);
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags);
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags);
typedef struct cdata_st {
char *label;
int authority;
const char *path;
size_t index;
size_t count;
const char *id;
int obj_flags;
} cdata;
const unsigned int gemsafe_cert_max = 12;
cdata gemsafe_cert[] = {
{"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE},
};
typedef struct pdata_st {
const u8 atr[SC_MAX_ATR_SIZE];
const size_t atr_len;
const char *id;
const char *label;
const char *path;
const int ref;
const int type;
const unsigned int maxlen;
const unsigned int minlen;
const int flags;
const int tries_left;
const char pad_char;
const int obj_flags;
} pindata;
const unsigned int gemsafe_pin_max = 2;
const pindata gemsafe_pin[] = {
/* ATR-specific PIN policies, first match found is used: */
{ {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65,
0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC,
8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE },
/* default PIN policy comes last: */
{ { 0 }, 0,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD,
16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }
};
typedef struct prdata_st {
const char *id;
char *label;
unsigned int modulus_len;
int usage;
const char *path;
int ref;
const char *auth_id;
int obj_flags;
} prdata;
#define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION
#define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP
#define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP | \
SC_PKCS15_PRKEY_USAGE_SIGN
prdata gemsafe_prkeys[] = {
{ "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE},
};
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
static int gemsafe_detect_card( sc_pkcs15_card_t *p15card)
{
if (strcmp(p15card->card->name, "GemSAFE V1"))
return SC_ERROR_WRONG_CARD;
return SC_SUCCESS;
}
static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card)
{
int r;
unsigned int i;
struct sc_path path;
struct sc_file *file = NULL;
struct sc_card *card = p15card->card;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(p15card->card->ctx, "Setting pkcs15 parameters");
if (p15card->tokeninfo->label)
free(p15card->tokeninfo->label);
p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1);
if (!p15card->tokeninfo->label)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->label, APPLET_NAME);
if (p15card->tokeninfo->serial_number)
free(p15card->tokeninfo->serial_number);
p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1);
if (!p15card->tokeninfo->serial_number)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER);
/* the GemSAFE applet version number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
/* Manual says Le=0x05, but should be 0x08 to return full version number */
apdu.le = 0x08;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* the manufacturer ID, in this case GemPlus */
if (p15card->tokeninfo->manufacturer_id)
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1);
if (!p15card->tokeninfo->manufacturer_id)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID);
/* determine allocated key containers and length of certificates */
r = gemsafe_get_cert_len(card);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* set certs */
sc_log(p15card->card->ctx, "Setting certificates");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
if (gemsafe_cert[i].label == NULL)
continue;
sc_format_path(gemsafe_cert[i].path, &path);
sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id);
path.index = gemsafe_cert[i].index;
path.count = gemsafe_cert[i].count;
sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509,
gemsafe_cert[i].authority, &path, &p15Id,
gemsafe_cert[i].label, gemsafe_cert[i].obj_flags);
}
/* set gemsafe_pin */
sc_log(p15card->card->ctx, "Setting PIN");
for (i=0; i < gemsafe_pin_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id);
sc_format_path(gemsafe_pin[i].path, &path);
if (gemsafe_pin[i].atr_len == 0 ||
(gemsafe_pin[i].atr_len == p15card->card->atr.len &&
memcmp(p15card->card->atr.value, gemsafe_pin[i].atr,
p15card->card->atr.len) == 0)) {
sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label,
&path, gemsafe_pin[i].ref, gemsafe_pin[i].type,
gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen,
gemsafe_pin[i].flags, gemsafe_pin[i].tries_left,
gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags);
break;
}
};
/* set private keys */
sc_log(p15card->card->ctx, "Setting private keys");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id, authId, *pauthId;
struct sc_path path;
int key_ref = 0x03;
if (gemsafe_prkeys[i].label == NULL)
continue;
sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id);
if (gemsafe_prkeys[i].auth_id) {
sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId);
pauthId = &authId;
} else
pauthId = NULL;
sc_format_path(gemsafe_prkeys[i].path, &path);
/*
* The key ref may be different for different sites;
* by adding flags=n where the low order 4 bits can be
* the key ref we can force it.
*/
if ( p15card->card->flags & 0x0F) {
key_ref = p15card->card->flags & 0x0F;
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Overriding key_ref %d with %d\n",
gemsafe_prkeys[i].ref, key_ref);
} else
key_ref = gemsafe_prkeys[i].ref;
sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label,
SC_PKCS15_TYPE_PRKEY_RSA,
gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage,
&path, key_ref, pauthId,
gemsafe_prkeys[i].obj_flags);
}
/* select the application DF */
sc_log(p15card->card->ctx, "Selecting application DF");
sc_format_path(GEMSAFE_APP_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* set the application DF */
if (p15card->file_app)
free(p15card->file_app);
p15card->file_app = file;
return SC_SUCCESS;
}
int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_gemsafeV1_init(p15card);
else {
int r = gemsafe_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_gemsafeV1_init(p15card);
}
}
static sc_pkcs15_df_t *
sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type)
{
sc_pkcs15_df_t *df;
sc_file_t *file;
int created = 0;
while (1) {
for (df = p15card->df_list; df; df = df->next) {
if (df->type == type) {
if (created)
df->enumerated = 1;
return df;
}
}
assert(created == 0);
file = sc_file_new();
if (!file)
return NULL;
sc_format_path("11001101", &file->path);
sc_pkcs15_add_df(p15card, type, &file->path);
sc_file_free(file);
created++;
}
}
static int
sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type,
const char *label, void *data,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_object_t *obj;
int df_type;
obj = calloc(1, sizeof(*obj));
obj->type = type;
obj->data = data;
if (label)
strncpy(obj->label, label, sizeof(obj->label)-1);
obj->flags = obj_flags;
if (auth_id)
obj->auth_id = *auth_id;
switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
case SC_PKCS15_TYPE_AUTH:
df_type = SC_PKCS15_AODF;
break;
case SC_PKCS15_TYPE_PRKEY:
df_type = SC_PKCS15_PRKDF;
break;
case SC_PKCS15_TYPE_PUBKEY:
df_type = SC_PKCS15_PUKDF;
break;
case SC_PKCS15_TYPE_CERT:
df_type = SC_PKCS15_CDF;
break;
default:
sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type);
free(obj);
return SC_ERROR_INVALID_ARGUMENTS;
}
obj->df = sc_pkcs15emu_get_df(p15card, df_type);
sc_pkcs15_add_object(p15card, obj);
return 0;
}
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags)
{
sc_pkcs15_auth_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
info->auth_method = SC_AC_CHV;
info->auth_id = *id;
info->attrs.pin.min_length = min_length;
info->attrs.pin.max_length = max_length;
info->attrs.pin.stored_length = max_length;
info->attrs.pin.type = type;
info->attrs.pin.reference = ref;
info->attrs.pin.flags = flags;
info->attrs.pin.pad_char = pad_char;
info->tries_left = tries_left;
info->logged_in = SC_PIN_STATE_UNKNOWN;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags)
{
sc_pkcs15_cert_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->authority = authority;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_prkey_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->modulus_length = modulus_length;
info->usage = usage;
info->native = 1;
info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE
| SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE
| SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE
| SC_PKCS15_PRKEY_ACCESS_LOCAL;
info->key_reference = ref;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label,
info, auth_id, obj_flags);
}
/* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_5 |
crossvul-cpp_data_good_5111_0 | /* cosine.c
*
* CoSine IPNOS L2 debug output parsing
* Copyright (c) 2002 by Motonori Shindo <motonori@shin.do>
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* 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 "config.h"
#include "wtap-int.h"
#include "cosine.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/*
IPNOS: CONFIG VPN(100) VR(1.1.1.1)# diags
ipnos diags: Control (1/0) :: layer-2 ?
Registered commands for area "layer-2"
apply-pkt-log-profile Configure packet logging on an interface
create-pkt-log-profile Set packet-log-profile to be used for packet logging (see layer-2 pkt-log)
detail Get Layer 2 low-level details
ipnos diags: Control (1/0) :: layer-2 create ?
create-pkt-log-profile <pkt-log-profile-id ctl-tx-trace-length ctl-rx-trace-length data-tx-trace-length data-rx-trace-length pe-logging-or-control-blade>
ipnos diags: Control (1/0) :: layer-2 create 1 32 32 0 0 0
ipnos diags: Control (1/0) :: layer-2 create 2 32 32 100 100 0
ipnos diags: Control (1/0) :: layer-2 apply ?
apply-pkt-log-profile <slot port channel subif pkt-log-profile-id>
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 1
Successfully applied packet-log-profile on LI
-- Note that only the control packets are logged because the data packet size parameters are 0 in profile 1
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# ping 20.20.20.43
vpn 200 : [max tries 4, timeout 5 seconds, data length 64 bytes, ttl 255]
ping #1 ok, RTT 0.000 seconds
ping #2 ok, RTT 0.000 seconds
ping #3 ok, RTT 0.000 seconds
ping #4 ok, RTT 0.000 seconds
[finished]
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
2000-2-1,18:19:46.8: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2000-2-1,18:19:46.8: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000]
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0
Successfully applied packet-log-profile on LI
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 2
Successfully applied packet-log-profile on LI
-- Note that both control and data packets are logged because the data packet size parameter is 100 in profile 2
Please ignore the event-log messages getting mixed up with the ping command
ping 20.20.20.43 cou2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6B 60 84 AA
2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 09 29 00 08 6D FE FA AA
2000-2-1,18:20:17.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6B 60 84 AA
2000-2-1,18:20:17.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x8030000]
00 D0 D8 D2 FF 03 C0 21 0A 29 00 08 6D FE FA AA
nt 1 length 500
vpn 200 : [max tries 1, timeout 5 seconds, data length 500 bytes, ttl 255]
2000-2-1,18:20:24.1: l2-tx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4070, 0x801]
00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 27 00 00
FF 01 69 51 14 14 14 22 14 14 14 2B 08 00 AD B8
00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B
1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B
2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B
4C 4D 4E 4F
ping #1 ok, RTT 0.010 seconds
2000-2-1,18:20:24.1: l2-rx (PPP:3/7/1:100), Length:536, Pro:1, Off:8, Pri:7, RM:0, Err:0 [0x4071, 0x30801]
00 D0 D8 D2 FF 03 00 21 45 00 02 10 00 23 00 00
FF 01 69 55 14 14 14 2B 14 14 14 22 00 00 B5 B8
00 03 00 01 10 11 12 13 14 15 16 17 18 19 1A 1B
1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B
2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B
3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B
4C 4D 4E 4F
[finished]
IPNOS: CONFIG VPN(200) VR(3.3.3.3)# 2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6B 60 84 AA
2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 09 2A 00 08 6D FE FA AA
2000-2-1,18:20:27.0: l2-tx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6B 60 84 AA
2000-2-1,18:20:27.0: l2-rx (PPP:3/7/1:100), Length:16, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4001, 0x30000]
00 D0 D8 D2 FF 03 C0 21 0A 2A 00 08 6D FE FA AA
ipnos diags: Control (1/0) :: layer-2 apply 3 0x0701 100 0 0
Successfully applied packet-log-profile on LI
ipnos diags: Control (1/0) ::
*/
/* XXX TODO:
o Handle a case where an empty line doesn't exists as a delimiter of
each packet. If the output is sent to a control blade and
displayed as an event log, there's always an empty line between
each packet output, but it may not be true when it is an PE
output.
o Some telnet client on Windows may put in a line break at 80
columns when it save the session to a text file ("CRT" is such an
example). I don't think it's a good idea for the telnet client to
do so, but CRT is widely used in Windows community, I should
take care of that in the future.
*/
/* Magic text to check for CoSine L2 debug output */
#define COSINE_HDR_MAGIC_STR1 "l2-tx"
#define COSINE_HDR_MAGIC_STR2 "l2-rx"
/* Magic text for start of packet */
#define COSINE_REC_MAGIC_STR1 COSINE_HDR_MAGIC_STR1
#define COSINE_REC_MAGIC_STR2 COSINE_HDR_MAGIC_STR2
#define COSINE_HEADER_LINES_TO_CHECK 200
#define COSINE_LINE_LENGTH 240
static gboolean empty_line(const gchar *line);
static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr);
static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info);
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean cosine_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
static int parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf,
char *line, int *err, gchar **err_info);
static int parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
/* Returns TRUE if the line appears to be an empty line. Otherwise it
returns FALSE. */
static gboolean empty_line(const gchar *line)
{
while (*line) {
if (g_ascii_isspace(*line)) {
line++;
continue;
} else {
break;
}
}
if (*line == '\0')
return TRUE;
else
return FALSE;
}
/* Seeks to the beginning of the next packet, and returns the
byte offset. Copy the header line to hdr. Returns -1 on failure,
and sets "*err" to the error and sets "*err_info" to null or an
additional error string. */
static gint64 cosine_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr)
{
gint64 cur_off;
char buf[COSINE_LINE_LENGTH];
while (1) {
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error */
*err = file_error(wth->fh, err_info);
return -1;
}
if (file_gets(buf, sizeof(buf), wth->fh) == NULL) {
*err = file_error(wth->fh, err_info);
return -1;
}
if (strstr(buf, COSINE_REC_MAGIC_STR1) ||
strstr(buf, COSINE_REC_MAGIC_STR2)) {
g_strlcpy(hdr, buf, COSINE_LINE_LENGTH);
return cur_off;
}
}
return -1;
}
/* Look through the first part of a file to see if this is
* a CoSine L2 debug output.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" will be set to null or an additional error string.
*/
static gboolean cosine_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[COSINE_LINE_LENGTH];
gsize reclen;
guint line;
buf[COSINE_LINE_LENGTH-1] = '\0';
for (line = 0; line < COSINE_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, COSINE_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = strlen(buf);
if (reclen < strlen(COSINE_HDR_MAGIC_STR1) ||
reclen < strlen(COSINE_HDR_MAGIC_STR2)) {
continue;
}
if (strstr(buf, COSINE_HDR_MAGIC_STR1) ||
strstr(buf, COSINE_HDR_MAGIC_STR2)) {
return TRUE;
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val cosine_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for CoSine header */
if (!cosine_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_COSINE;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_COSINE;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = cosine_read;
wth->subtype_seek_read = cosine_seek_read;
wth->file_tsprec = WTAP_TSPREC_CSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
char line[COSINE_LINE_LENGTH];
/* Find the next packet */
offset = cosine_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
*data_offset = offset;
/* Parse the header and convert the ASCII hex dump to binary data */
return parse_cosine_packet(wth->fh, &wth->phdr, wth->frame_buffer,
line, err, err_info);
}
/* Used to read packets in random-access fashion */
static gboolean
cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info)
{
char line[COSINE_LINE_LENGTH];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)
return FALSE;
if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Parse the header and convert the ASCII hex dump to binary data */
return parse_cosine_packet(wth->random_fh, phdr, buf, line, err,
err_info);
}
/* Parses a packet record header. There are two possible formats:
1) output to a control blade with date and time
2002-5-10,20:1:31.4: l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0]
2) output to PE without date and time
l2-tx (FR:3/7/1:1), Length:18, Pro:0, Off:0, Pri:0, RM:0, Err:0 [0x4000, 0x0] */
static gboolean
parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
char *line, int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
int num_items_scanned;
int yy, mm, dd, hr, min, sec, csec, pkt_len;
int pro, off, pri, rm, error;
guint code1, code2;
char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = "";
struct tm tm;
guint8 *pd;
int i, hex_lines, n, caplen = 0;
if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:",
&yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {
/* appears to be output to a control blade */
num_items_scanned = sscanf(line,
"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
&yy, &mm, &dd, &hr, &min, &sec, &csec,
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 17) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: purported control blade line doesn't have code values");
return FALSE;
}
} else {
/* appears to be output to PE */
num_items_scanned = sscanf(line,
"%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]",
direction, if_name, &pkt_len,
&pro, &off, &pri, &rm, &error,
&code1, &code2);
if (num_items_scanned != 10) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: header line is neither control blade nor PE output");
return FALSE;
}
yy = mm = dd = hr = min = sec = csec = 0;
}
if (pkt_len < 0) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: packet header has a negative packet length");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
tm.tm_year = yy - 1900;
tm.tm_mon = mm - 1;
tm.tm_mday = dd;
tm.tm_hour = hr;
tm.tm_min = min;
tm.tm_sec = sec;
tm.tm_isdst = -1;
phdr->ts.secs = mktime(&tm);
phdr->ts.nsecs = csec * 10000000;
phdr->len = pkt_len;
/* XXX need to handle other encapsulations like Cisco HDLC,
Frame Relay and ATM */
if (strncmp(if_name, "TEST:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_TEST;
} else if (strncmp(if_name, "PPoATM:", 7) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM;
} else if (strncmp(if_name, "PPoFR:", 6) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR;
} else if (strncmp(if_name, "ATM:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ATM;
} else if (strncmp(if_name, "FR:", 3) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_FR;
} else if (strncmp(if_name, "HDLC:", 5) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_HDLC;
} else if (strncmp(if_name, "PPP:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_PPP;
} else if (strncmp(if_name, "ETH:", 4) == 0) {
pseudo_header->cosine.encap = COSINE_ENCAP_ETH;
} else {
pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN;
}
if (strncmp(direction, "l2-tx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_TX;
} else if (strncmp(direction, "l2-rx", 5) == 0) {
pseudo_header->cosine.direction = COSINE_DIR_RX;
}
g_strlcpy(pseudo_header->cosine.if_name, if_name,
COSINE_MAX_IF_NAME_LEN);
pseudo_header->cosine.pro = pro;
pseudo_header->cosine.off = off;
pseudo_header->cosine.pri = pri;
pseudo_header->cosine.rm = rm;
pseudo_header->cosine.err = error;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
/* Take a string representing one line from a hex dump and converts
* the text to binary data. We place the bytes in the buffer at the
* specified offset.
*
* Returns number of bytes successfully read, -1 if bad. */
static int
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
int num_items_scanned, i;
unsigned int bytes[16];
num_items_scanned = sscanf(rec, "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
&bytes[0], &bytes[1], &bytes[2], &bytes[3],
&bytes[4], &bytes[5], &bytes[6], &bytes[7],
&bytes[8], &bytes[9], &bytes[10], &bytes[11],
&bytes[12], &bytes[13], &bytes[14], &bytes[15]);
if (num_items_scanned == 0)
return -1;
if (num_items_scanned > 16)
num_items_scanned = 16;
for (i=0; i<num_items_scanned; i++) {
buf[byte_offset + i] = (guint8)bytes[i];
}
return num_items_scanned;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5111_0 |
crossvul-cpp_data_bad_4905_0 | /**
* eCryptfs: Linux filesystem encryption layer
*
* Copyright (C) 2008 International Business Machines Corp.
* Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/mount.h>
#include "ecryptfs_kernel.h"
struct ecryptfs_open_req {
struct file **lower_file;
struct path path;
struct completion done;
struct list_head kthread_ctl_list;
};
static struct ecryptfs_kthread_ctl {
#define ECRYPTFS_KTHREAD_ZOMBIE 0x00000001
u32 flags;
struct mutex mux;
struct list_head req_list;
wait_queue_head_t wait;
} ecryptfs_kthread_ctl;
static struct task_struct *ecryptfs_kthread;
/**
* ecryptfs_threadfn
* @ignored: ignored
*
* The eCryptfs kernel thread that has the responsibility of getting
* the lower file with RW permissions.
*
* Returns zero on success; non-zero otherwise
*/
static int ecryptfs_threadfn(void *ignored)
{
set_freezable();
while (1) {
struct ecryptfs_open_req *req;
wait_event_freezable(
ecryptfs_kthread_ctl.wait,
(!list_empty(&ecryptfs_kthread_ctl.req_list)
|| kthread_should_stop()));
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
mutex_unlock(&ecryptfs_kthread_ctl.mux);
goto out;
}
while (!list_empty(&ecryptfs_kthread_ctl.req_list)) {
req = list_first_entry(&ecryptfs_kthread_ctl.req_list,
struct ecryptfs_open_req,
kthread_ctl_list);
list_del(&req->kthread_ctl_list);
*req->lower_file = dentry_open(&req->path,
(O_RDWR | O_LARGEFILE), current_cred());
complete(&req->done);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
}
out:
return 0;
}
int __init ecryptfs_init_kthread(void)
{
int rc = 0;
mutex_init(&ecryptfs_kthread_ctl.mux);
init_waitqueue_head(&ecryptfs_kthread_ctl.wait);
INIT_LIST_HEAD(&ecryptfs_kthread_ctl.req_list);
ecryptfs_kthread = kthread_run(&ecryptfs_threadfn, NULL,
"ecryptfs-kthread");
if (IS_ERR(ecryptfs_kthread)) {
rc = PTR_ERR(ecryptfs_kthread);
printk(KERN_ERR "%s: Failed to create kernel thread; rc = [%d]"
"\n", __func__, rc);
}
return rc;
}
void ecryptfs_destroy_kthread(void)
{
struct ecryptfs_open_req *req, *tmp;
mutex_lock(&ecryptfs_kthread_ctl.mux);
ecryptfs_kthread_ctl.flags |= ECRYPTFS_KTHREAD_ZOMBIE;
list_for_each_entry_safe(req, tmp, &ecryptfs_kthread_ctl.req_list,
kthread_ctl_list) {
list_del(&req->kthread_ctl_list);
*req->lower_file = ERR_PTR(-EIO);
complete(&req->done);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
kthread_stop(ecryptfs_kthread);
wake_up(&ecryptfs_kthread_ctl.wait);
}
/**
* ecryptfs_privileged_open
* @lower_file: Result of dentry_open by root on lower dentry
* @lower_dentry: Lower dentry for file to open
* @lower_mnt: Lower vfsmount for file to open
*
* This function gets a r/w file opened againt the lower dentry.
*
* Returns zero on success; non-zero otherwise
*/
int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req req;
int flags = O_LARGEFILE;
int rc = 0;
init_completion(&req.done);
req.lower_file = lower_file;
req.path.dentry = lower_dentry;
req.path.mnt = lower_mnt;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(&req.path, flags, cred);
if (!IS_ERR(*lower_file))
goto out;
if ((flags & O_ACCMODE) == O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out;
}
list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_for_completion(&req.done);
if (IS_ERR(*lower_file))
rc = PTR_ERR(*lower_file);
out:
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4905_0 |
crossvul-cpp_data_bad_5368_1 | /* Copyright (c) 2001 Matej Pfajfar.
* Copyright (c) 2001-2004, Roger Dingledine.
* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
* Copyright (c) 2007-2015, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file buffers.c
* \brief Implements a generic interface buffer. Buffers are
* fairly opaque string holders that can read to or flush from:
* memory, file descriptors, or TLS connections.
**/
#define BUFFERS_PRIVATE
#include "or.h"
#include "addressmap.h"
#include "buffers.h"
#include "config.h"
#include "connection_edge.h"
#include "connection_or.h"
#include "control.h"
#include "reasons.h"
#include "ext_orport.h"
#include "../common/util.h"
#include "../common/torlog.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
//#define PARANOIA
#ifdef PARANOIA
/** Helper: If PARANOIA is defined, assert that the buffer in local variable
* <b>buf</b> is well-formed. */
#define check() STMT_BEGIN assert_buf_ok(buf); STMT_END
#else
#define check() STMT_NIL
#endif
/* Implementation notes:
*
* After flirting with memmove, and dallying with ring-buffers, we're finally
* getting up to speed with the 1970s and implementing buffers as a linked
* list of small chunks. Each buffer has such a list; data is removed from
* the head of the list, and added at the tail. The list is singly linked,
* and the buffer keeps a pointer to the head and the tail.
*
* Every chunk, except the tail, contains at least one byte of data. Data in
* each chunk is contiguous.
*
* When you need to treat the first N characters on a buffer as a contiguous
* string, use the buf_pullup function to make them so. Don't do this more
* than necessary.
*
* The major free Unix kernels have handled buffers like this since, like,
* forever.
*/
static void socks_request_set_socks5_error(socks_request_t *req,
socks5_reply_status_t reason);
static int parse_socks(const char *data, size_t datalen, socks_request_t *req,
int log_sockstype, int safe_socks, ssize_t *drain_out,
size_t *want_length_out);
static int parse_socks_client(const uint8_t *data, size_t datalen,
int state, char **reason,
ssize_t *drain_out);
/* Chunk manipulation functions */
#define CHUNK_HEADER_LEN STRUCT_OFFSET(chunk_t, mem[0])
/** Return the number of bytes needed to allocate a chunk to hold
* <b>memlen</b> bytes. */
#define CHUNK_ALLOC_SIZE(memlen) (CHUNK_HEADER_LEN + (memlen))
/** Return the number of usable bytes in a chunk allocated with
* malloc(<b>memlen</b>). */
#define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - CHUNK_HEADER_LEN)
/** Return the next character in <b>chunk</b> onto which data can be appended.
* If the chunk is full, this might be off the end of chunk->mem. */
static INLINE char *
CHUNK_WRITE_PTR(chunk_t *chunk)
{
return chunk->data + chunk->datalen;
}
/** Return the number of bytes that can be written onto <b>chunk</b> without
* running out of space. */
static INLINE size_t
CHUNK_REMAINING_CAPACITY(const chunk_t *chunk)
{
return (chunk->mem + chunk->memlen) - (chunk->data + chunk->datalen);
}
/** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
* to free up space at the end. */
static INLINE void
chunk_repack(chunk_t *chunk)
{
if (chunk->datalen && chunk->data != &chunk->mem[0]) {
memmove(chunk->mem, chunk->data, chunk->datalen);
}
chunk->data = &chunk->mem[0];
}
/** Keep track of total size of allocated chunks for consistency asserts */
static size_t total_bytes_allocated_in_chunks = 0;
static void
chunk_free_unchecked(chunk_t *chunk)
{
if (!chunk)
return;
#ifdef DEBUG_CHUNK_ALLOC
tor_assert(CHUNK_ALLOC_SIZE(chunk->memlen) == chunk->DBG_alloc);
#endif
tor_assert(total_bytes_allocated_in_chunks >=
CHUNK_ALLOC_SIZE(chunk->memlen));
total_bytes_allocated_in_chunks -= CHUNK_ALLOC_SIZE(chunk->memlen);
tor_free(chunk);
}
static INLINE chunk_t *
chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
return ch;
}
/** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
* new pointer to <b>chunk</b>. Old pointers are no longer valid. */
static INLINE chunk_t *
chunk_grow(chunk_t *chunk, size_t sz)
{
off_t offset;
size_t memlen_orig = chunk->memlen;
tor_assert(sz > chunk->memlen);
offset = chunk->data - chunk->mem;
chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz));
chunk->memlen = sz;
chunk->data = chunk->mem + offset;
#ifdef DEBUG_CHUNK_ALLOC
tor_assert(chunk->DBG_alloc == CHUNK_ALLOC_SIZE(memlen_orig));
chunk->DBG_alloc = CHUNK_ALLOC_SIZE(sz);
#endif
total_bytes_allocated_in_chunks +=
CHUNK_ALLOC_SIZE(sz) - CHUNK_ALLOC_SIZE(memlen_orig);
return chunk;
}
/** If a read onto the end of a chunk would be smaller than this number, then
* just start a new chunk. */
#define MIN_READ_LEN 8
/** Every chunk should take up at least this many bytes. */
#define MIN_CHUNK_ALLOC 256
/** No chunk should take up more than this many bytes. */
#define MAX_CHUNK_ALLOC 65536
/** Return the allocation size we'd like to use to hold <b>target</b>
* bytes. */
static INLINE size_t
preferred_chunk_size(size_t target)
{
size_t sz = MIN_CHUNK_ALLOC;
while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
sz <<= 1;
}
return sz;
}
/** Collapse data from the first N chunks from <b>buf</b> into buf->head,
* growing it as necessary, until buf->head has the first <b>bytes</b> bytes
* of data from the buffer, or until buf->head has all the data in <b>buf</b>.
*
* If <b>nulterminate</b> is true, ensure that there is a 0 byte in
* buf->head->mem right after all the data. */
STATIC void
buf_pullup(buf_t *buf, size_t bytes, int nulterminate)
{
/* XXXX nothing uses nulterminate; remove it. */
chunk_t *dest, *src;
size_t capacity;
if (!buf->head)
return;
check();
if (buf->datalen < bytes)
bytes = buf->datalen;
if (nulterminate) {
capacity = bytes + 1;
if (buf->head->datalen >= bytes && CHUNK_REMAINING_CAPACITY(buf->head)) {
*CHUNK_WRITE_PTR(buf->head) = '\0';
return;
}
} else {
capacity = bytes;
if (buf->head->datalen >= bytes)
return;
}
if (buf->head->memlen >= capacity) {
/* We don't need to grow the first chunk, but we might need to repack it.*/
size_t needed = capacity - buf->head->datalen;
if (CHUNK_REMAINING_CAPACITY(buf->head) < needed)
chunk_repack(buf->head);
tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= needed);
} else {
chunk_t *newhead;
size_t newsize;
/* We need to grow the chunk. */
chunk_repack(buf->head);
newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity));
newhead = chunk_grow(buf->head, newsize);
tor_assert(newhead->memlen >= capacity);
if (newhead != buf->head) {
if (buf->tail == buf->head)
buf->tail = newhead;
buf->head = newhead;
}
}
dest = buf->head;
while (dest->datalen < bytes) {
size_t n = bytes - dest->datalen;
src = dest->next;
tor_assert(src);
if (n >= src->datalen) {
memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
dest->datalen += src->datalen;
dest->next = src->next;
if (buf->tail == src)
buf->tail = dest;
chunk_free_unchecked(src);
} else {
memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
dest->datalen += n;
src->data += n;
src->datalen -= n;
tor_assert(dest->datalen == bytes);
}
}
if (nulterminate) {
tor_assert(CHUNK_REMAINING_CAPACITY(buf->head));
*CHUNK_WRITE_PTR(buf->head) = '\0';
}
check();
}
#ifdef TOR_UNIT_TESTS
void
buf_get_first_chunk_data(const buf_t *buf, const char **cp, size_t *sz)
{
if (!buf || !buf->head) {
*cp = NULL;
*sz = 0;
} else {
*cp = buf->head->data;
*sz = buf->head->datalen;
}
}
#endif
/** Remove the first <b>n</b> bytes from buf. */
static INLINE void
buf_remove_from_front(buf_t *buf, size_t n)
{
tor_assert(buf->datalen >= n);
while (n) {
tor_assert(buf->head);
if (buf->head->datalen > n) {
buf->head->datalen -= n;
buf->head->data += n;
buf->datalen -= n;
return;
} else {
chunk_t *victim = buf->head;
n -= victim->datalen;
buf->datalen -= victim->datalen;
buf->head = victim->next;
if (buf->tail == victim)
buf->tail = NULL;
chunk_free_unchecked(victim);
}
}
check();
}
/** Create and return a new buf with default chunk capacity <b>size</b>.
*/
buf_t *
buf_new_with_capacity(size_t size)
{
buf_t *b = buf_new();
b->default_chunk_size = preferred_chunk_size(size);
return b;
}
/** Allocate and return a new buffer with default capacity. */
buf_t *
buf_new(void)
{
buf_t *buf = tor_malloc_zero(sizeof(buf_t));
buf->magic = BUFFER_MAGIC;
buf->default_chunk_size = 4096;
return buf;
}
size_t
buf_get_default_chunk_size(const buf_t *buf)
{
return buf->default_chunk_size;
}
/** Remove all data from <b>buf</b>. */
void
buf_clear(buf_t *buf)
{
chunk_t *chunk, *next;
buf->datalen = 0;
for (chunk = buf->head; chunk; chunk = next) {
next = chunk->next;
chunk_free_unchecked(chunk);
}
buf->head = buf->tail = NULL;
}
/** Return the number of bytes stored in <b>buf</b> */
MOCK_IMPL(size_t,
buf_datalen, (const buf_t *buf))
{
return buf->datalen;
}
/** Return the total length of all chunks used in <b>buf</b>. */
size_t
buf_allocation(const buf_t *buf)
{
size_t total = 0;
const chunk_t *chunk;
for (chunk = buf->head; chunk; chunk = chunk->next) {
total += CHUNK_ALLOC_SIZE(chunk->memlen);
}
return total;
}
/** Return the number of bytes that can be added to <b>buf</b> without
* performing any additional allocation. */
size_t
buf_slack(const buf_t *buf)
{
if (!buf->tail)
return 0;
else
return CHUNK_REMAINING_CAPACITY(buf->tail);
}
/** Release storage held by <b>buf</b>. */
void
buf_free(buf_t *buf)
{
if (!buf)
return;
buf_clear(buf);
buf->magic = 0xdeadbeef;
tor_free(buf);
}
/** Return a new copy of <b>in_chunk</b> */
static chunk_t *
chunk_copy(const chunk_t *in_chunk)
{
chunk_t *newch = tor_memdup(in_chunk, CHUNK_ALLOC_SIZE(in_chunk->memlen));
total_bytes_allocated_in_chunks += CHUNK_ALLOC_SIZE(in_chunk->memlen);
#ifdef DEBUG_CHUNK_ALLOC
newch->DBG_alloc = CHUNK_ALLOC_SIZE(in_chunk->memlen);
#endif
newch->next = NULL;
if (in_chunk->data) {
off_t offset = in_chunk->data - in_chunk->mem;
newch->data = newch->mem + offset;
}
return newch;
}
/** Return a new copy of <b>buf</b> */
buf_t *
buf_copy(const buf_t *buf)
{
chunk_t *ch;
buf_t *out = buf_new();
out->default_chunk_size = buf->default_chunk_size;
for (ch = buf->head; ch; ch = ch->next) {
chunk_t *newch = chunk_copy(ch);
if (out->tail) {
out->tail->next = newch;
out->tail = newch;
} else {
out->head = out->tail = newch;
}
}
out->datalen = buf->datalen;
return out;
}
/** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
* the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
* than MAX_CHUNK_ALLOC. */
static chunk_t *
buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
{
chunk_t *chunk;
struct timeval now;
if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
} else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
} else {
chunk = chunk_new_with_alloc_size(preferred_chunk_size(capacity));
}
tor_gettimeofday_cached_monotonic(&now);
chunk->inserted_time = (uint32_t)tv_to_msec(&now);
if (buf->tail) {
tor_assert(buf->head);
buf->tail->next = chunk;
buf->tail = chunk;
} else {
tor_assert(!buf->head);
buf->head = buf->tail = chunk;
}
check();
return chunk;
}
/** Return the age of the oldest chunk in the buffer <b>buf</b>, in
* milliseconds. Requires the current time, in truncated milliseconds since
* the epoch, as its input <b>now</b>.
*/
uint32_t
buf_get_oldest_chunk_timestamp(const buf_t *buf, uint32_t now)
{
if (buf->head) {
return now - buf->head->inserted_time;
} else {
return 0;
}
}
size_t
buf_get_total_allocation(void)
{
return total_bytes_allocated_in_chunks;
}
/** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into
* <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set
* *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking,
* and the number of bytes read otherwise. */
static INLINE int
read_to_chunk(buf_t *buf, chunk_t *chunk, tor_socket_t fd, size_t at_most,
int *reached_eof, int *socket_error)
{
ssize_t read_result;
if (at_most > CHUNK_REMAINING_CAPACITY(chunk))
at_most = CHUNK_REMAINING_CAPACITY(chunk);
read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0);
if (read_result < 0) {
int e = tor_socket_errno(fd);
if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
#ifdef _WIN32
if (e == WSAENOBUFS)
log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
#endif
*socket_error = e;
return -1;
}
return 0; /* would block. */
} else if (read_result == 0) {
log_debug(LD_NET,"Encountered eof on fd %d", (int)fd);
*reached_eof = 1;
return 0;
} else { /* actually got bytes. */
buf->datalen += read_result;
chunk->datalen += read_result;
log_debug(LD_NET,"Read %ld bytes. %d on inbuf.", (long)read_result,
(int)buf->datalen);
tor_assert(read_result < INT_MAX);
return (int)read_result;
}
}
/** As read_to_chunk(), but return (negative) error code on error, blocking,
* or TLS, and the number of bytes read otherwise. */
static INLINE int
read_to_chunk_tls(buf_t *buf, chunk_t *chunk, tor_tls_t *tls,
size_t at_most)
{
int read_result;
tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
read_result = tor_tls_read(tls, CHUNK_WRITE_PTR(chunk), at_most);
if (read_result < 0)
return read_result;
buf->datalen += read_result;
chunk->datalen += read_result;
return read_result;
}
/** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
* <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0
* (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on
* error; else return the number of bytes read.
*/
/* XXXX024 indicate "read blocked" somehow? */
int
read_to_buf(tor_socket_t s, size_t at_most, buf_t *buf, int *reached_eof,
int *socket_error)
{
/* XXXX024 It's stupid to overload the return values for these functions:
* "error status" and "number of bytes read" are not mutually exclusive.
*/
int r = 0;
size_t total_read = 0;
check();
tor_assert(reached_eof);
tor_assert(SOCKET_OK(s));
while (at_most > total_read) {
size_t readlen = at_most - total_read;
chunk_t *chunk;
if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
if (readlen > chunk->memlen)
readlen = chunk->memlen;
} else {
size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
chunk = buf->tail;
if (cap < readlen)
readlen = cap;
}
r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
check();
if (r < 0)
return r; /* Error */
tor_assert(total_read+r < INT_MAX);
total_read += r;
if ((size_t)r < readlen) { /* eof, block, or no more to read. */
break;
}
}
return (int)total_read;
}
/** As read_to_buf, but reads from a TLS connection, and returns a TLS
* status value rather than the number of bytes read.
*
* Using TLS on OR connections complicates matters in two ways.
*
* First, a TLS stream has its own read buffer independent of the
* connection's read buffer. (TLS needs to read an entire frame from
* the network before it can decrypt any data. Thus, trying to read 1
* byte from TLS can require that several KB be read from the network
* and decrypted. The extra data is stored in TLS's decrypt buffer.)
* Because the data hasn't been read by Tor (it's still inside the TLS),
* this means that sometimes a connection "has stuff to read" even when
* poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
* used in connection.c to detect TLS objects with non-empty internal
* buffers and read from them again.
*
* Second, the TLS stream's events do not correspond directly to network
* events: sometimes, before a TLS stream can read, the network must be
* ready to write -- or vice versa.
*/
int
read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
{
int r = 0;
size_t total_read = 0;
check_no_tls_errors();
check();
while (at_most > total_read) {
size_t readlen = at_most - total_read;
chunk_t *chunk;
if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
if (readlen > chunk->memlen)
readlen = chunk->memlen;
} else {
size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
chunk = buf->tail;
if (cap < readlen)
readlen = cap;
}
r = read_to_chunk_tls(buf, chunk, tls, readlen);
check();
if (r < 0)
return r; /* Error */
tor_assert(total_read+r < INT_MAX);
total_read += r;
if ((size_t)r < readlen) /* eof, block, or no more to read. */
break;
}
return (int)total_read;
}
/** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
* <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
* the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
* written on success, 0 on blocking, -1 on failure.
*/
static INLINE int
flush_chunk(tor_socket_t s, buf_t *buf, chunk_t *chunk, size_t sz,
size_t *buf_flushlen)
{
ssize_t write_result;
if (sz > chunk->datalen)
sz = chunk->datalen;
write_result = tor_socket_send(s, chunk->data, sz, 0);
if (write_result < 0) {
int e = tor_socket_errno(s);
if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
#ifdef _WIN32
if (e == WSAENOBUFS)
log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
#endif
return -1;
}
log_debug(LD_NET,"write() would block, returning.");
return 0;
} else {
*buf_flushlen -= write_result;
buf_remove_from_front(buf, write_result);
tor_assert(write_result < INT_MAX);
return (int)write_result;
}
}
/** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
* <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
* more if there is a forced pending write size.) On success, deduct the
* bytes written from *<b>buf_flushlen</b>. Return the number of bytes
* written on success, and a TOR_TLS error code on failure or blocking.
*/
static INLINE int
flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
size_t sz, size_t *buf_flushlen)
{
int r;
size_t forced;
char *data;
forced = tor_tls_get_forced_write_size(tls);
if (forced > sz)
sz = forced;
if (chunk) {
data = chunk->data;
tor_assert(sz <= chunk->datalen);
} else {
data = NULL;
tor_assert(sz == 0);
}
r = tor_tls_write(tls, data, sz);
if (r < 0)
return r;
if (*buf_flushlen > (size_t)r)
*buf_flushlen -= r;
else
*buf_flushlen = 0;
buf_remove_from_front(buf, r);
log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
r,(int)*buf_flushlen,(int)buf->datalen);
return r;
}
/** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
* <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
* the number of bytes actually written, and remove the written bytes
* from the buffer. Return the number of bytes written on success,
* -1 on failure. Return 0 if write() would block.
*/
int
flush_buf(tor_socket_t s, buf_t *buf, size_t sz, size_t *buf_flushlen)
{
/* XXXX024 It's stupid to overload the return values for these functions:
* "error status" and "number of bytes flushed" are not mutually exclusive.
*/
int r;
size_t flushed = 0;
tor_assert(buf_flushlen);
tor_assert(SOCKET_OK(s));
tor_assert(*buf_flushlen <= buf->datalen);
tor_assert(sz <= *buf_flushlen);
check();
while (sz) {
size_t flushlen0;
tor_assert(buf->head);
if (buf->head->datalen >= sz)
flushlen0 = sz;
else
flushlen0 = buf->head->datalen;
r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
check();
if (r < 0)
return r;
flushed += r;
sz -= r;
if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
break;
}
tor_assert(flushed < INT_MAX);
return (int)flushed;
}
/** As flush_buf(), but writes data to a TLS connection. Can write more than
* <b>flushlen</b> bytes.
*/
int
flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
size_t *buf_flushlen)
{
int r;
size_t flushed = 0;
ssize_t sz;
tor_assert(buf_flushlen);
tor_assert(*buf_flushlen <= buf->datalen);
tor_assert(flushlen <= *buf_flushlen);
sz = (ssize_t) flushlen;
/* we want to let tls write even if flushlen is zero, because it might
* have a partial record pending */
check_no_tls_errors();
check();
do {
size_t flushlen0;
if (buf->head) {
if ((ssize_t)buf->head->datalen >= sz)
flushlen0 = sz;
else
flushlen0 = buf->head->datalen;
} else {
flushlen0 = 0;
}
r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
check();
if (r < 0)
return r;
flushed += r;
sz -= r;
if (r == 0) /* Can't flush any more now. */
break;
} while (sz > 0);
tor_assert(flushed < INT_MAX);
return (int)flushed;
}
/** Append <b>string_len</b> bytes from <b>string</b> to the end of
* <b>buf</b>.
*
* Return the new length of the buffer on success, -1 on failure.
*/
int
write_to_buf(const char *string, size_t string_len, buf_t *buf)
{
if (!string_len)
return (int)buf->datalen;
check();
while (string_len) {
size_t copy;
if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
buf_add_chunk_with_capacity(buf, string_len, 1);
copy = CHUNK_REMAINING_CAPACITY(buf->tail);
if (copy > string_len)
copy = string_len;
memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
string_len -= copy;
string += copy;
buf->datalen += copy;
buf->tail->datalen += copy;
}
check();
tor_assert(buf->datalen < INT_MAX);
return (int)buf->datalen;
}
/** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
* onto <b>string</b>.
*/
static INLINE void
peek_from_buf(char *string, size_t string_len, const buf_t *buf)
{
chunk_t *chunk;
tor_assert(string);
/* make sure we don't ask for too much */
tor_assert(string_len <= buf->datalen);
/* assert_buf_ok(buf); */
chunk = buf->head;
while (string_len) {
size_t copy = string_len;
tor_assert(chunk);
if (chunk->datalen < copy)
copy = chunk->datalen;
memcpy(string, chunk->data, copy);
string_len -= copy;
string += copy;
chunk = chunk->next;
}
}
/** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
* them into <b>string</b>. Return the new buffer size. <b>string_len</b>
* must be \<= the number of bytes on the buffer.
*/
int
fetch_from_buf(char *string, size_t string_len, buf_t *buf)
{
/* There must be string_len bytes in buf; write them onto string,
* then memmove buf back (that is, remove them from buf).
*
* Return the number of bytes still on the buffer. */
check();
peek_from_buf(string, string_len, buf);
buf_remove_from_front(buf, string_len);
check();
tor_assert(buf->datalen < INT_MAX);
return (int)buf->datalen;
}
/** True iff the cell command <b>command</b> is one that implies a
* variable-length cell in Tor link protocol <b>linkproto</b>. */
static INLINE int
cell_command_is_var_length(uint8_t command, int linkproto)
{
/* If linkproto is v2 (2), CELL_VERSIONS is the only variable-length cells
* work as implemented here. If it's 1, there are no variable-length cells.
* Tor does not support other versions right now, and so can't negotiate
* them.
*/
switch (linkproto) {
case 1:
/* Link protocol version 1 has no variable-length cells. */
return 0;
case 2:
/* In link protocol version 2, VERSIONS is the only variable-length cell */
return command == CELL_VERSIONS;
case 0:
case 3:
default:
/* In link protocol version 3 and later, and in version "unknown",
* commands 128 and higher indicate variable-length. VERSIONS is
* grandfathered in. */
return command == CELL_VERSIONS || command >= 128;
}
}
/** Check <b>buf</b> for a variable-length cell according to the rules of link
* protocol version <b>linkproto</b>. If one is found, pull it off the buffer
* and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
* Return 0 if whatever is on the start of buf_t is not a variable-length
* cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
* of a variable-length cell on <b>buf</b>, but the whole thing isn't there
* yet. */
int
fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
{
char hdr[VAR_CELL_MAX_HEADER_SIZE];
var_cell_t *result;
uint8_t command;
uint16_t length;
const int wide_circ_ids = linkproto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
const int circ_id_len = get_circ_id_size(wide_circ_ids);
const unsigned header_len = get_var_cell_header_size(wide_circ_ids);
check();
*out = NULL;
if (buf->datalen < header_len)
return 0;
peek_from_buf(hdr, header_len, buf);
command = get_uint8(hdr + circ_id_len);
if (!(cell_command_is_var_length(command, linkproto)))
return 0;
length = ntohs(get_uint16(hdr + circ_id_len + 1));
if (buf->datalen < (size_t)(header_len+length))
return 1;
result = var_cell_new(length);
result->command = command;
if (wide_circ_ids)
result->circ_id = ntohl(get_uint32(hdr));
else
result->circ_id = ntohs(get_uint16(hdr));
buf_remove_from_front(buf, header_len);
peek_from_buf((char*) result->payload, length, buf);
buf_remove_from_front(buf, length);
check();
*out = result;
return 1;
}
#ifdef USE_BUFFEREVENTS
/** Try to read <b>n</b> bytes from <b>buf</b> at <b>pos</b> (which may be
* NULL for the start of the buffer), copying the data only if necessary. Set
* *<b>data_out</b> to a pointer to the desired bytes. Set <b>free_out</b>
* to 1 if we needed to malloc *<b>data</b> because the original bytes were
* noncontiguous; 0 otherwise. Return the number of bytes actually available
* at *<b>data_out</b>.
*/
static ssize_t
inspect_evbuffer(struct evbuffer *buf, char **data_out, size_t n,
int *free_out, struct evbuffer_ptr *pos)
{
int n_vecs, i;
if (evbuffer_get_length(buf) < n)
n = evbuffer_get_length(buf);
if (n == 0)
return 0;
n_vecs = evbuffer_peek(buf, n, pos, NULL, 0);
tor_assert(n_vecs > 0);
if (n_vecs == 1) {
struct evbuffer_iovec v;
i = evbuffer_peek(buf, n, pos, &v, 1);
tor_assert(i == 1);
*data_out = v.iov_base;
*free_out = 0;
return v.iov_len;
} else {
ev_ssize_t copied;
*data_out = tor_malloc(n);
*free_out = 1;
copied = evbuffer_copyout(buf, *data_out, n);
tor_assert(copied >= 0 && (size_t)copied == n);
return copied;
}
}
/** As fetch_var_cell_from_buf, buf works on an evbuffer. */
int
fetch_var_cell_from_evbuffer(struct evbuffer *buf, var_cell_t **out,
int linkproto)
{
char *hdr = NULL;
int free_hdr = 0;
size_t n;
size_t buf_len;
uint8_t command;
uint16_t cell_length;
var_cell_t *cell;
int result = 0;
const int wide_circ_ids = linkproto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
const int circ_id_len = get_circ_id_size(wide_circ_ids);
const unsigned header_len = get_var_cell_header_size(wide_circ_ids);
*out = NULL;
buf_len = evbuffer_get_length(buf);
if (buf_len < header_len)
return 0;
n = inspect_evbuffer(buf, &hdr, header_len, &free_hdr, NULL);
tor_assert(n >= header_len);
command = get_uint8(hdr + circ_id_len);
if (!(cell_command_is_var_length(command, linkproto))) {
goto done;
}
cell_length = ntohs(get_uint16(hdr + circ_id_len + 1));
if (buf_len < (size_t)(header_len+cell_length)) {
result = 1; /* Not all here yet. */
goto done;
}
cell = var_cell_new(cell_length);
cell->command = command;
if (wide_circ_ids)
cell->circ_id = ntohl(get_uint32(hdr));
else
cell->circ_id = ntohs(get_uint16(hdr));
evbuffer_drain(buf, header_len);
evbuffer_remove(buf, cell->payload, cell_length);
*out = cell;
result = 1;
done:
if (free_hdr && hdr)
tor_free(hdr);
return result;
}
#endif
/** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
* <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
* Return the number of bytes actually copied.
*/
int
move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
{
/* We can do way better here, but this doesn't turn up in any profiles. */
char b[4096];
size_t cp, len;
len = *buf_flushlen;
if (len > buf_in->datalen)
len = buf_in->datalen;
cp = len; /* Remember the number of bytes we intend to copy. */
tor_assert(cp < INT_MAX);
while (len) {
/* This isn't the most efficient implementation one could imagine, since
* it does two copies instead of 1, but I kinda doubt that this will be
* critical path. */
size_t n = len > sizeof(b) ? sizeof(b) : len;
fetch_from_buf(b, n, buf_in);
write_to_buf(b, n, buf_out);
len -= n;
}
*buf_flushlen -= cp;
return (int)cp;
}
/** Internal structure: represents a position in a buffer. */
typedef struct buf_pos_t {
const chunk_t *chunk; /**< Which chunk are we pointing to? */
int pos;/**< Which character inside the chunk's data are we pointing to? */
size_t chunk_pos; /**< Total length of all previous chunks. */
} buf_pos_t;
/** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
static void
buf_pos_init(const buf_t *buf, buf_pos_t *out)
{
out->chunk = buf->head;
out->pos = 0;
out->chunk_pos = 0;
}
/** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
* position of <b>out</b>, or later. Return -1 if no instances are found;
* otherwise returns the absolute position of the character. */
static off_t
buf_find_pos_of_char(char ch, buf_pos_t *out)
{
const chunk_t *chunk;
int pos;
tor_assert(out);
if (out->chunk) {
if (out->chunk->datalen) {
tor_assert(out->pos < (off_t)out->chunk->datalen);
} else {
tor_assert(out->pos == 0);
}
}
pos = out->pos;
for (chunk = out->chunk; chunk; chunk = chunk->next) {
char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
if (cp) {
out->chunk = chunk;
tor_assert(cp - chunk->data < INT_MAX);
out->pos = (int)(cp - chunk->data);
return out->chunk_pos + out->pos;
} else {
out->chunk_pos += chunk->datalen;
pos = 0;
}
}
return -1;
}
/** Advance <b>pos</b> by a single character, if there are any more characters
* in the buffer. Returns 0 on success, -1 on failure. */
static INLINE int
buf_pos_inc(buf_pos_t *pos)
{
++pos->pos;
if (pos->pos == (off_t)pos->chunk->datalen) {
if (!pos->chunk->next)
return -1;
pos->chunk_pos += pos->chunk->datalen;
pos->chunk = pos->chunk->next;
pos->pos = 0;
}
return 0;
}
/** Return true iff the <b>n</b>-character string in <b>s</b> appears
* (verbatim) at <b>pos</b>. */
static int
buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
{
buf_pos_t p;
if (!n)
return 1;
memcpy(&p, pos, sizeof(p));
while (1) {
char ch = p.chunk->data[p.pos];
if (ch != *s)
return 0;
++s;
/* If we're out of characters that don't match, we match. Check this
* _before_ we test incrementing pos, in case we're at the end of the
* string. */
if (--n == 0)
return 1;
if (buf_pos_inc(&p)<0)
return 0;
}
}
/** Return the first position in <b>buf</b> at which the <b>n</b>-character
* string <b>s</b> occurs, or -1 if it does not occur. */
STATIC int
buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
{
buf_pos_t pos;
buf_pos_init(buf, &pos);
while (buf_find_pos_of_char(*s, &pos) >= 0) {
if (buf_matches_at_pos(&pos, s, n)) {
tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
return (int)(pos.chunk_pos + pos.pos);
} else {
if (buf_pos_inc(&pos)<0)
return -1;
}
}
return -1;
}
/** There is a (possibly incomplete) http statement on <b>buf</b>, of the
* form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain NULs.)
* If a) the headers include a Content-Length field and all bytes in
* the body are present, or b) there's no Content-Length field and
* all headers are present, then:
*
* - strdup headers into <b>*headers_out</b>, and NUL-terminate it.
* - memdup body into <b>*body_out</b>, and NUL-terminate it.
* - Then remove them from <b>buf</b>, and return 1.
*
* - If headers or body is NULL, discard that part of the buf.
* - If a headers or body doesn't fit in the arg, return -1.
* (We ensure that the headers or body don't exceed max len,
* _even if_ we're planning to discard them.)
* - If force_complete is true, then succeed even if not all of the
* content has arrived.
*
* Else, change nothing and return 0.
*/
int
fetch_from_buf_http(buf_t *buf,
char **headers_out, size_t max_headerlen,
char **body_out, size_t *body_used, size_t max_bodylen,
int force_complete)
{
char *headers, *p;
size_t headerlen, bodylen, contentlen;
int crlf_offset;
check();
if (!buf->head)
return 0;
crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
if (crlf_offset > (int)max_headerlen ||
(crlf_offset < 0 && buf->datalen > max_headerlen)) {
log_debug(LD_HTTP,"headers too long.");
return -1;
} else if (crlf_offset < 0) {
log_debug(LD_HTTP,"headers not all here yet.");
return 0;
}
/* Okay, we have a full header. Make sure it all appears in the first
* chunk. */
if ((int)buf->head->datalen < crlf_offset + 4)
buf_pullup(buf, crlf_offset+4, 0);
headerlen = crlf_offset + 4;
headers = buf->head->data;
bodylen = buf->datalen - headerlen;
log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
if (max_headerlen <= headerlen) {
log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
(int)headerlen, (int)max_headerlen-1);
return -1;
}
if (max_bodylen <= bodylen) {
log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
(int)bodylen, (int)max_bodylen-1);
return -1;
}
#define CONTENT_LENGTH "\r\nContent-Length: "
p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
if (p) {
int i;
i = atoi(p+strlen(CONTENT_LENGTH));
if (i < 0) {
log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
"someone is trying to crash us.");
return -1;
}
contentlen = i;
/* if content-length is malformed, then our body length is 0. fine. */
log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
if (bodylen < contentlen) {
if (!force_complete) {
log_debug(LD_HTTP,"body not all here yet.");
return 0; /* not all there yet */
}
}
if (bodylen > contentlen) {
bodylen = contentlen;
log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
}
}
/* all happy. copy into the appropriate places, and return 1 */
if (headers_out) {
*headers_out = tor_malloc(headerlen+1);
fetch_from_buf(*headers_out, headerlen, buf);
(*headers_out)[headerlen] = 0; /* NUL terminate it */
}
if (body_out) {
tor_assert(body_used);
*body_used = bodylen;
*body_out = tor_malloc(bodylen+1);
fetch_from_buf(*body_out, bodylen, buf);
(*body_out)[bodylen] = 0; /* NUL terminate it */
}
check();
return 1;
}
#ifdef USE_BUFFEREVENTS
/** As fetch_from_buf_http, buf works on an evbuffer. */
int
fetch_from_evbuffer_http(struct evbuffer *buf,
char **headers_out, size_t max_headerlen,
char **body_out, size_t *body_used, size_t max_bodylen,
int force_complete)
{
struct evbuffer_ptr crlf, content_length;
size_t headerlen, bodylen, contentlen;
/* Find the first \r\n\r\n in the buffer */
crlf = evbuffer_search(buf, "\r\n\r\n", 4, NULL);
if (crlf.pos < 0) {
/* We didn't find one. */
if (evbuffer_get_length(buf) > max_headerlen)
return -1; /* Headers too long. */
return 0; /* Headers not here yet. */
} else if (crlf.pos > (int)max_headerlen) {
return -1; /* Headers too long. */
}
headerlen = crlf.pos + 4; /* Skip over the \r\n\r\n */
bodylen = evbuffer_get_length(buf) - headerlen;
if (bodylen > max_bodylen)
return -1; /* body too long */
/* Look for the first occurrence of CONTENT_LENGTH insize buf before the
* crlfcrlf */
content_length = evbuffer_search_range(buf, CONTENT_LENGTH,
strlen(CONTENT_LENGTH), NULL, &crlf);
if (content_length.pos >= 0) {
/* We found a content_length: parse it and figure out if the body is here
* yet. */
struct evbuffer_ptr eol;
char *data = NULL;
int free_data = 0;
int n, i;
n = evbuffer_ptr_set(buf, &content_length, strlen(CONTENT_LENGTH),
EVBUFFER_PTR_ADD);
tor_assert(n == 0);
eol = evbuffer_search_eol(buf, &content_length, NULL, EVBUFFER_EOL_CRLF);
tor_assert(eol.pos > content_length.pos);
tor_assert(eol.pos <= crlf.pos);
inspect_evbuffer(buf, &data, eol.pos - content_length.pos, &free_data,
&content_length);
i = atoi(data);
if (free_data)
tor_free(data);
if (i < 0) {
log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
"someone is trying to crash us.");
return -1;
}
contentlen = i;
/* if content-length is malformed, then our body length is 0. fine. */
log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
if (bodylen < contentlen) {
if (!force_complete) {
log_debug(LD_HTTP,"body not all here yet.");
return 0; /* not all there yet */
}
}
if (bodylen > contentlen) {
bodylen = contentlen;
log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
}
}
if (headers_out) {
*headers_out = tor_malloc(headerlen+1);
evbuffer_remove(buf, *headers_out, headerlen);
(*headers_out)[headerlen] = '\0';
}
if (body_out) {
tor_assert(headers_out);
tor_assert(body_used);
*body_used = bodylen;
*body_out = tor_malloc(bodylen+1);
evbuffer_remove(buf, *body_out, bodylen);
(*body_out)[bodylen] = '\0';
}
return 1;
}
#endif
/**
* Wait this many seconds before warning the user about using SOCKS unsafely
* again (requires that WarnUnsafeSocks is turned on). */
#define SOCKS_WARN_INTERVAL 5
/** Warn that the user application has made an unsafe socks request using
* protocol <b>socks_protocol</b> on port <b>port</b>. Don't warn more than
* once per SOCKS_WARN_INTERVAL, unless <b>safe_socks</b> is set. */
static void
log_unsafe_socks_warning(int socks_protocol, const char *address,
uint16_t port, int safe_socks)
{
static ratelim_t socks_ratelim = RATELIM_INIT(SOCKS_WARN_INTERVAL);
const or_options_t *options = get_options();
if (! options->WarnUnsafeSocks)
return;
if (safe_socks) {
log_fn_ratelim(&socks_ratelim, LOG_WARN, LD_APP,
"Your application (using socks%d to port %d) is giving "
"Tor only an IP address. Applications that do DNS resolves "
"themselves may leak information. Consider using Socks4A "
"(e.g. via privoxy or socat) instead. For more information, "
"please see https://wiki.torproject.org/TheOnionRouter/"
"TorFAQ#SOCKSAndDNS.%s",
socks_protocol,
(int)port,
safe_socks ? " Rejecting." : "");
}
control_event_client_status(LOG_WARN,
"DANGEROUS_SOCKS PROTOCOL=SOCKS%d ADDRESS=%s:%d",
socks_protocol, address, (int)port);
}
/** Do not attempt to parse socks messages longer than this. This value is
* actually significantly higher than the longest possible socks message. */
#define MAX_SOCKS_MESSAGE_LEN 512
/** Return a new socks_request_t. */
socks_request_t *
socks_request_new(void)
{
return tor_malloc_zero(sizeof(socks_request_t));
}
/** Free all storage held in the socks_request_t <b>req</b>. */
void
socks_request_free(socks_request_t *req)
{
if (!req)
return;
if (req->username) {
memwipe(req->username, 0x10, req->usernamelen);
tor_free(req->username);
}
if (req->password) {
memwipe(req->password, 0x04, req->passwordlen);
tor_free(req->password);
}
memwipe(req, 0xCC, sizeof(socks_request_t));
tor_free(req);
}
/** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
* of the forms
* - socks4: "socksheader username\\0"
* - socks4a: "socksheader username\\0 destaddr\\0"
* - socks5 phase one: "version #methods methods"
* - socks5 phase two: "version command 0 addresstype..."
* If it's a complete and valid handshake, and destaddr fits in
* MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
* assign to <b>req</b>, and return 1.
*
* If it's invalid or too big, return -1.
*
* Else it's not all there yet, leave buf alone and return 0.
*
* If you want to specify the socks reply, write it into <b>req->reply</b>
* and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
*
* If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
* the connection is possibly leaking DNS requests locally or not.
*
* If <b>safe_socks</b> is true, then reject unsafe socks protocols.
*
* If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
* undefined.
*/
int
fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
int log_sockstype, int safe_socks)
{
int res;
ssize_t n_drain;
size_t want_length = 128;
if (buf->datalen < 2) /* version and another byte */
return 0;
do {
n_drain = 0;
buf_pullup(buf, want_length, 0);
tor_assert(buf->head && buf->head->datalen >= 2);
want_length = 0;
res = parse_socks(buf->head->data, buf->head->datalen, req, log_sockstype,
safe_socks, &n_drain, &want_length);
if (n_drain < 0)
buf_clear(buf);
else if (n_drain > 0)
buf_remove_from_front(buf, n_drain);
} while (res == 0 && buf->head && want_length < buf->datalen &&
buf->datalen >= 2);
return res;
}
#ifdef USE_BUFFEREVENTS
/* As fetch_from_buf_socks(), but targets an evbuffer instead. */
int
fetch_from_evbuffer_socks(struct evbuffer *buf, socks_request_t *req,
int log_sockstype, int safe_socks)
{
char *data;
ssize_t n_drain;
size_t datalen, buflen, want_length;
int res;
buflen = evbuffer_get_length(buf);
if (buflen < 2)
return 0;
{
/* See if we can find the socks request in the first chunk of the buffer.
*/
struct evbuffer_iovec v;
int i;
n_drain = 0;
i = evbuffer_peek(buf, -1, NULL, &v, 1);
tor_assert(i == 1);
data = v.iov_base;
datalen = v.iov_len;
want_length = 0;
res = parse_socks(data, datalen, req, log_sockstype,
safe_socks, &n_drain, &want_length);
if (n_drain < 0)
evbuffer_drain(buf, evbuffer_get_length(buf));
else if (n_drain > 0)
evbuffer_drain(buf, n_drain);
if (res)
return res;
}
/* Okay, the first chunk of the buffer didn't have a complete socks request.
* That means that either we don't have a whole socks request at all, or
* it's gotten split up. We're going to try passing parse_socks() bigger
* and bigger chunks until either it says "Okay, I got it", or it says it
* will need more data than we currently have. */
/* Loop while we have more data that we haven't given parse_socks() yet. */
do {
int free_data = 0;
const size_t last_wanted = want_length;
n_drain = 0;
data = NULL;
datalen = inspect_evbuffer(buf, &data, want_length, &free_data, NULL);
want_length = 0;
res = parse_socks(data, datalen, req, log_sockstype,
safe_socks, &n_drain, &want_length);
if (free_data)
tor_free(data);
if (n_drain < 0)
evbuffer_drain(buf, evbuffer_get_length(buf));
else if (n_drain > 0)
evbuffer_drain(buf, n_drain);
if (res == 0 && n_drain == 0 && want_length <= last_wanted) {
/* If we drained nothing, and we didn't ask for more than last time,
* then we probably wanted more data than the buffer actually had,
* and we're finding out that we're not satisified with it. It's
* time to break until we have more data. */
break;
}
buflen = evbuffer_get_length(buf);
} while (res == 0 && want_length <= buflen && buflen >= 2);
return res;
}
#endif
/** The size of the header of an Extended ORPort message: 2 bytes for
* COMMAND, 2 bytes for BODYLEN */
#define EXT_OR_CMD_HEADER_SIZE 4
/** Read <b>buf</b>, which should contain an Extended ORPort message
* from a transport proxy. If well-formed, create and populate
* <b>out</b> with the Extended ORport message. Return 0 if the
* buffer was incomplete, 1 if it was well-formed and -1 if we
* encountered an error while parsing it. */
int
fetch_ext_or_command_from_buf(buf_t *buf, ext_or_cmd_t **out)
{
char hdr[EXT_OR_CMD_HEADER_SIZE];
uint16_t len;
check();
if (buf->datalen < EXT_OR_CMD_HEADER_SIZE)
return 0;
peek_from_buf(hdr, sizeof(hdr), buf);
len = ntohs(get_uint16(hdr+2));
if (buf->datalen < (unsigned)len + EXT_OR_CMD_HEADER_SIZE)
return 0;
*out = ext_or_cmd_new(len);
(*out)->cmd = ntohs(get_uint16(hdr));
(*out)->len = len;
buf_remove_from_front(buf, EXT_OR_CMD_HEADER_SIZE);
fetch_from_buf((*out)->body, len, buf);
return 1;
}
#ifdef USE_BUFFEREVENTS
/** Read <b>buf</b>, which should contain an Extended ORPort message
* from a transport proxy. If well-formed, create and populate
* <b>out</b> with the Extended ORport message. Return 0 if the
* buffer was incomplete, 1 if it was well-formed and -1 if we
* encountered an error while parsing it. */
int
fetch_ext_or_command_from_evbuffer(struct evbuffer *buf, ext_or_cmd_t **out)
{
char hdr[EXT_OR_CMD_HEADER_SIZE];
uint16_t len;
size_t buf_len = evbuffer_get_length(buf);
if (buf_len < EXT_OR_CMD_HEADER_SIZE)
return 0;
evbuffer_copyout(buf, hdr, EXT_OR_CMD_HEADER_SIZE);
len = ntohs(get_uint16(hdr+2));
if (buf_len < (unsigned)len + EXT_OR_CMD_HEADER_SIZE)
return 0;
*out = ext_or_cmd_new(len);
(*out)->cmd = ntohs(get_uint16(hdr));
(*out)->len = len;
evbuffer_drain(buf, EXT_OR_CMD_HEADER_SIZE);
evbuffer_remove(buf, (*out)->body, len);
return 1;
}
#endif
/** Create a SOCKS5 reply message with <b>reason</b> in its REP field and
* have Tor send it as error response to <b>req</b>.
*/
static void
socks_request_set_socks5_error(socks_request_t *req,
socks5_reply_status_t reason)
{
req->replylen = 10;
memset(req->reply,0,10);
req->reply[0] = 0x05; // VER field.
req->reply[1] = reason; // REP field.
req->reply[3] = 0x01; // ATYP field.
}
/** Implementation helper to implement fetch_from_*_socks. Instead of looking
* at a buffer's contents, we look at the <b>datalen</b> bytes of data in
* <b>data</b>. Instead of removing data from the buffer, we set
* <b>drain_out</b> to the amount of data that should be removed (or -1 if the
* buffer should be cleared). Instead of pulling more data into the first
* chunk of the buffer, we set *<b>want_length_out</b> to the number of bytes
* we'd like to see in the input buffer, if they're available. */
static int
parse_socks(const char *data, size_t datalen, socks_request_t *req,
int log_sockstype, int safe_socks, ssize_t *drain_out,
size_t *want_length_out)
{
unsigned int len;
char tmpbuf[TOR_ADDR_BUF_LEN+1];
tor_addr_t destaddr;
uint32_t destip;
uint8_t socksver;
char *next, *startaddr;
unsigned char usernamelen, passlen;
struct in_addr in;
if (datalen < 2) {
/* We always need at least 2 bytes. */
*want_length_out = 2;
return 0;
}
if (req->socks_version == 5 && !req->got_auth) {
/* See if we have received authentication. Strictly speaking, we should
also check whether we actually negotiated username/password
authentication. But some broken clients will send us authentication
even if we negotiated SOCKS_NO_AUTH. */
if (*data == 1) { /* username/pass version 1 */
/* Format is: authversion [1 byte] == 1
usernamelen [1 byte]
username [usernamelen bytes]
passlen [1 byte]
password [passlen bytes] */
usernamelen = (unsigned char)*(data + 1);
if (datalen < 2u + usernamelen + 1u) {
*want_length_out = 2u + usernamelen + 1u;
return 0;
}
passlen = (unsigned char)*(data + 2u + usernamelen);
if (datalen < 2u + usernamelen + 1u + passlen) {
*want_length_out = 2u + usernamelen + 1u + passlen;
return 0;
}
req->replylen = 2; /* 2 bytes of response */
req->reply[0] = 1; /* authversion == 1 */
req->reply[1] = 0; /* authentication successful */
log_debug(LD_APP,
"socks5: Accepted username/password without checking.");
if (usernamelen) {
req->username = tor_memdup(data+2u, usernamelen);
req->usernamelen = usernamelen;
}
if (passlen) {
req->password = tor_memdup(data+3u+usernamelen, passlen);
req->passwordlen = passlen;
}
*drain_out = 2u + usernamelen + 1u + passlen;
req->got_auth = 1;
*want_length_out = 7; /* Minimal socks5 command. */
return 0;
} else if (req->auth_type == SOCKS_USER_PASS) {
/* unknown version byte */
log_warn(LD_APP, "Socks5 username/password version %d not recognized; "
"rejecting.", (int)*data);
return -1;
}
}
socksver = *data;
switch (socksver) { /* which version of socks? */
case 5: /* socks5 */
if (req->socks_version != 5) { /* we need to negotiate a method */
unsigned char nummethods = (unsigned char)*(data+1);
int have_user_pass, have_no_auth;
int r=0;
tor_assert(!req->socks_version);
if (datalen < 2u+nummethods) {
*want_length_out = 2u+nummethods;
return 0;
}
if (!nummethods)
return -1;
req->replylen = 2; /* 2 bytes of response */
req->reply[0] = 5; /* socks5 reply */
have_user_pass = (memchr(data+2, SOCKS_USER_PASS, nummethods) !=NULL);
have_no_auth = (memchr(data+2, SOCKS_NO_AUTH, nummethods) !=NULL);
if (have_user_pass && !(have_no_auth && req->socks_prefer_no_auth)) {
req->auth_type = SOCKS_USER_PASS;
req->reply[1] = SOCKS_USER_PASS; /* tell client to use "user/pass"
auth method */
req->socks_version = 5; /* remember we've already negotiated auth */
log_debug(LD_APP,"socks5: accepted method 2 (username/password)");
r=0;
} else if (have_no_auth) {
req->reply[1] = SOCKS_NO_AUTH; /* tell client to use "none" auth
method */
req->socks_version = 5; /* remember we've already negotiated auth */
log_debug(LD_APP,"socks5: accepted method 0 (no authentication)");
r=0;
} else {
log_warn(LD_APP,
"socks5: offered methods don't include 'no auth' or "
"username/password. Rejecting.");
req->reply[1] = '\xFF'; /* reject all methods */
r=-1;
}
/* Remove packet from buf. Some SOCKS clients will have sent extra
* junk at this point; let's hope it's an authentication message. */
*drain_out = 2u + nummethods;
return r;
}
if (req->auth_type != SOCKS_NO_AUTH && !req->got_auth) {
log_warn(LD_APP,
"socks5: negotiated authentication, but none provided");
return -1;
}
/* we know the method; read in the request */
log_debug(LD_APP,"socks5: checking request");
if (datalen < 7) {/* basic info plus >=1 for addr plus 2 for port */
*want_length_out = 7;
return 0; /* not yet */
}
req->command = (unsigned char) *(data+1);
if (req->command != SOCKS_COMMAND_CONNECT &&
req->command != SOCKS_COMMAND_RESOLVE &&
req->command != SOCKS_COMMAND_RESOLVE_PTR) {
/* not a connect or resolve or a resolve_ptr? we don't support it. */
socks_request_set_socks5_error(req,SOCKS5_COMMAND_NOT_SUPPORTED);
log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
req->command);
return -1;
}
switch (*(data+3)) { /* address type */
case 1: /* IPv4 address */
case 4: /* IPv6 address */ {
const int is_v6 = *(data+3) == 4;
const unsigned addrlen = is_v6 ? 16 : 4;
log_debug(LD_APP,"socks5: ipv4 address type");
if (datalen < 6+addrlen) {/* ip/port there? */
*want_length_out = 6+addrlen;
return 0; /* not yet */
}
if (is_v6)
tor_addr_from_ipv6_bytes(&destaddr, data+4);
else
tor_addr_from_ipv4n(&destaddr, get_uint32(data+4));
tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
log_warn(LD_APP,
"socks5 IP takes %d bytes, which doesn't fit in %d. "
"Rejecting.",
(int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
return -1;
}
strlcpy(req->address,tmpbuf,sizeof(req->address));
req->port = ntohs(get_uint16(data+4+addrlen));
*drain_out = 6+addrlen;
if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
!addressmap_have_mapping(req->address,0)) {
log_unsafe_socks_warning(5, req->address, req->port, safe_socks);
if (safe_socks) {
socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
return -1;
}
}
return 1;
}
case 3: /* fqdn */
log_debug(LD_APP,"socks5: fqdn address type");
if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
socks_request_set_socks5_error(req,
SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
"hostname type. Rejecting.");
return -1;
}
len = (unsigned char)*(data+4);
if (datalen < 7+len) { /* addr/port there? */
*want_length_out = 7+len;
return 0; /* not yet */
}
if (len+1 > MAX_SOCKS_ADDR_LEN) {
socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
log_warn(LD_APP,
"socks5 hostname is %d bytes, which doesn't fit in "
"%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
return -1;
}
memcpy(req->address,data+5,len);
req->address[len] = 0;
req->port = ntohs(get_uint16(data+5+len));
*drain_out = 5+len+2;
if (string_is_valid_ipv4_address(req->address) ||
string_is_valid_ipv6_address(req->address)) {
log_unsafe_socks_warning(5,req->address,req->port,safe_socks);
if (safe_socks) {
socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
return -1;
}
} else if (!string_is_valid_hostname(req->address)) {
socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
log_warn(LD_PROTOCOL,
"Your application (using socks5 to port %d) gave Tor "
"a malformed hostname: %s. Rejecting the connection.",
req->port, escaped(req->address));
return -1;
}
if (log_sockstype)
log_notice(LD_APP,
"Your application (using socks5 to port %d) instructed "
"Tor to take care of the DNS resolution itself if "
"necessary. This is good.", req->port);
return 1;
default: /* unsupported */
socks_request_set_socks5_error(req,
SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
(int) *(data+3));
return -1;
}
tor_assert(0);
case 4: { /* socks4 */
enum {socks4, socks4a} socks4_prot = socks4a;
const char *authstart, *authend;
/* http://ss5.sourceforge.net/socks4.protocol.txt */
/* http://ss5.sourceforge.net/socks4A.protocol.txt */
req->socks_version = 4;
if (datalen < SOCKS4_NETWORK_LEN) {/* basic info available? */
*want_length_out = SOCKS4_NETWORK_LEN;
return 0; /* not yet */
}
// buf_pullup(buf, 1280, 0);
req->command = (unsigned char) *(data+1);
if (req->command != SOCKS_COMMAND_CONNECT &&
req->command != SOCKS_COMMAND_RESOLVE) {
/* not a connect or resolve? we don't support it. (No resolve_ptr with
* socks4.) */
log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
req->command);
return -1;
}
req->port = ntohs(get_uint16(data+2));
destip = ntohl(get_uint32(data+4));
if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
return -1;
}
if (destip >> 8) {
log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
in.s_addr = htonl(destip);
tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
(int)strlen(tmpbuf));
return -1;
}
log_debug(LD_APP,
"socks4: successfully read destip (%s)",
safe_str_client(tmpbuf));
socks4_prot = socks4;
}
authstart = data + SOCKS4_NETWORK_LEN;
next = memchr(authstart, 0,
datalen-SOCKS4_NETWORK_LEN);
if (!next) {
if (datalen >= 1024) {
log_debug(LD_APP, "Socks4 user name too long; rejecting.");
return -1;
}
log_debug(LD_APP,"socks4: Username not here yet.");
*want_length_out = datalen+1024; /* More than we need, but safe */
return 0;
}
authend = next;
tor_assert(next < data+datalen);
startaddr = NULL;
if (socks4_prot != socks4a &&
!addressmap_have_mapping(tmpbuf,0)) {
log_unsafe_socks_warning(4, tmpbuf, req->port, safe_socks);
if (safe_socks)
return -1;
}
if (socks4_prot == socks4a) {
if (next+1 == data+datalen) {
log_debug(LD_APP,"socks4: No part of destaddr here yet.");
*want_length_out = datalen + 1024; /* More than we need, but safe */
return 0;
}
startaddr = next+1;
next = memchr(startaddr, 0, data + datalen - startaddr);
if (!next) {
if (datalen >= 1024) {
log_debug(LD_APP,"socks4: Destaddr too long.");
return -1;
}
log_debug(LD_APP,"socks4: Destaddr not all here yet.");
*want_length_out = datalen + 1024; /* More than we need, but safe */
return 0;
}
if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
return -1;
}
// tor_assert(next < buf->cur+buf->datalen);
if (log_sockstype)
log_notice(LD_APP,
"Your application (using socks4a to port %d) instructed "
"Tor to take care of the DNS resolution itself if "
"necessary. This is good.", req->port);
}
log_debug(LD_APP,"socks4: Everything is here. Success.");
strlcpy(req->address, startaddr ? startaddr : tmpbuf,
sizeof(req->address));
if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
log_warn(LD_PROTOCOL,
"Your application (using socks4 to port %d) gave Tor "
"a malformed hostname: %s. Rejecting the connection.",
req->port, escaped(req->address));
return -1;
}
if (authend != authstart) {
req->got_auth = 1;
req->usernamelen = authend - authstart;
req->username = tor_memdup(authstart, authend - authstart);
}
/* next points to the final \0 on inbuf */
*drain_out = next - data + 1;
return 1;
}
case 'G': /* get */
case 'H': /* head */
case 'P': /* put/post */
case 'C': /* connect */
strlcpy((char*)req->reply,
"HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
"<html>\n"
"<head>\n"
"<title>Tor is not an HTTP Proxy</title>\n"
"</head>\n"
"<body>\n"
"<h1>Tor is not an HTTP Proxy</h1>\n"
"<p>\n"
"It appears you have configured your web browser to use Tor as an HTTP proxy."
"\n"
"This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
"Please configure your client accordingly.\n"
"</p>\n"
"<p>\n"
"See <a href=\"https://www.torproject.org/documentation.html\">"
"https://www.torproject.org/documentation.html</a> for more "
"information.\n"
"<!-- Plus this comment, to make the body response more than 512 bytes, so "
" IE will be willing to display it. Comment comment comment comment "
" comment comment comment comment comment comment comment comment.-->\n"
"</p>\n"
"</body>\n"
"</html>\n"
, MAX_SOCKS_REPLY_LEN);
req->replylen = strlen((char*)req->reply)+1;
/* fall through */
default: /* version is not socks4 or socks5 */
log_warn(LD_APP,
"Socks version %d not recognized. (Tor is not an http proxy.)",
*(data));
{
/* Tell the controller the first 8 bytes. */
char *tmp = tor_strndup(data, datalen < 8 ? datalen : 8);
control_event_client_status(LOG_WARN,
"SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
escaped(tmp));
tor_free(tmp);
}
return -1;
}
}
/** Inspect a reply from SOCKS server stored in <b>buf</b> according
* to <b>state</b>, removing the protocol data upon success. Return 0 on
* incomplete response, 1 on success and -1 on error, in which case
* <b>reason</b> is set to a descriptive message (free() when finished
* with it).
*
* As a special case, 2 is returned when user/pass is required
* during SOCKS5 handshake and user/pass is configured.
*/
int
fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
{
ssize_t drain = 0;
int r;
if (buf->datalen < 2)
return 0;
buf_pullup(buf, MAX_SOCKS_MESSAGE_LEN, 0);
tor_assert(buf->head && buf->head->datalen >= 2);
r = parse_socks_client((uint8_t*)buf->head->data, buf->head->datalen,
state, reason, &drain);
if (drain > 0)
buf_remove_from_front(buf, drain);
else if (drain < 0)
buf_clear(buf);
return r;
}
#ifdef USE_BUFFEREVENTS
/** As fetch_from_buf_socks_client, buf works on an evbuffer */
int
fetch_from_evbuffer_socks_client(struct evbuffer *buf, int state,
char **reason)
{
ssize_t drain = 0;
uint8_t *data;
size_t datalen;
int r;
/* Linearize the SOCKS response in the buffer, up to 128 bytes.
* (parse_socks_client shouldn't need to see anything beyond that.) */
datalen = evbuffer_get_length(buf);
if (datalen > MAX_SOCKS_MESSAGE_LEN)
datalen = MAX_SOCKS_MESSAGE_LEN;
data = evbuffer_pullup(buf, datalen);
r = parse_socks_client(data, datalen, state, reason, &drain);
if (drain > 0)
evbuffer_drain(buf, drain);
else if (drain < 0)
evbuffer_drain(buf, evbuffer_get_length(buf));
return r;
}
#endif
/** Implementation logic for fetch_from_*_socks_client. */
static int
parse_socks_client(const uint8_t *data, size_t datalen,
int state, char **reason,
ssize_t *drain_out)
{
unsigned int addrlen;
*drain_out = 0;
if (datalen < 2)
return 0;
switch (state) {
case PROXY_SOCKS4_WANT_CONNECT_OK:
/* Wait for the complete response */
if (datalen < 8)
return 0;
if (data[1] != 0x5a) {
*reason = tor_strdup(socks4_response_code_to_string(data[1]));
return -1;
}
/* Success */
*drain_out = 8;
return 1;
case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
/* we don't have any credentials */
if (data[1] != 0x00) {
*reason = tor_strdup("server doesn't support any of our "
"available authentication methods");
return -1;
}
log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
*drain_out = -1;
return 1;
case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
/* we have a username and password. return 1 if we can proceed without
* providing authentication, or 2 otherwise. */
switch (data[1]) {
case 0x00:
log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
"doesn't require authentication.");
*drain_out = -1;
return 1;
case 0x02:
log_info(LD_NET, "SOCKS 5 client: need authentication.");
*drain_out = -1;
return 2;
/* fall through */
}
*reason = tor_strdup("server doesn't support any of our available "
"authentication methods");
return -1;
case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
/* handle server reply to rfc1929 authentication */
if (data[1] != 0x00) {
*reason = tor_strdup("authentication failed");
return -1;
}
log_info(LD_NET, "SOCKS 5 client: authentication successful.");
*drain_out = -1;
return 1;
case PROXY_SOCKS5_WANT_CONNECT_OK:
/* response is variable length. BND.ADDR, etc, isn't needed
* (don't bother with buf_pullup()), but make sure to eat all
* the data used */
/* wait for address type field to arrive */
if (datalen < 4)
return 0;
switch (data[3]) {
case 0x01: /* ip4 */
addrlen = 4;
break;
case 0x04: /* ip6 */
addrlen = 16;
break;
case 0x03: /* fqdn (can this happen here?) */
if (datalen < 5)
return 0;
addrlen = 1 + data[4];
break;
default:
*reason = tor_strdup("invalid response to connect request");
return -1;
}
/* wait for address and port */
if (datalen < 6 + addrlen)
return 0;
if (data[1] != 0x00) {
*reason = tor_strdup(socks5_response_code_to_string(data[1]));
return -1;
}
*drain_out = 6 + addrlen;
return 1;
}
/* shouldn't get here... */
tor_assert(0);
return -1;
}
/** Return 1 iff buf looks more like it has an (obsolete) v0 controller
* command on it than any valid v1 controller command. */
int
peek_buf_has_control0_command(buf_t *buf)
{
if (buf->datalen >= 4) {
char header[4];
uint16_t cmd;
peek_from_buf(header, sizeof(header), buf);
cmd = ntohs(get_uint16(header+2));
if (cmd <= 0x14)
return 1; /* This is definitely not a v1 control command. */
}
return 0;
}
#ifdef USE_BUFFEREVENTS
int
peek_evbuffer_has_control0_command(struct evbuffer *buf)
{
int result = 0;
if (evbuffer_get_length(buf) >= 4) {
int free_out = 0;
char *data = NULL;
size_t n = inspect_evbuffer(buf, &data, 4, &free_out, NULL);
uint16_t cmd;
tor_assert(n >= 4);
cmd = ntohs(get_uint16(data+2));
if (cmd <= 0x14)
result = 1;
if (free_out)
tor_free(data);
}
return result;
}
#endif
/** Return the index within <b>buf</b> at which <b>ch</b> first appears,
* or -1 if <b>ch</b> does not appear on buf. */
static off_t
buf_find_offset_of_char(buf_t *buf, char ch)
{
chunk_t *chunk;
off_t offset = 0;
for (chunk = buf->head; chunk; chunk = chunk->next) {
char *cp = memchr(chunk->data, ch, chunk->datalen);
if (cp)
return offset + (cp - chunk->data);
else
offset += chunk->datalen;
}
return -1;
}
/** Try to read a single LF-terminated line from <b>buf</b>, and write it
* (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
* at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
* line, not counting the terminating NUL. Return 1 if we read a whole line,
* return 0 if we don't have a whole line yet, and return -1 if the line
* length exceeds *<b>data_len</b>.
*/
int
fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
{
size_t sz;
off_t offset;
if (!buf->head)
return 0;
offset = buf_find_offset_of_char(buf, '\n');
if (offset < 0)
return 0;
sz = (size_t) offset;
if (sz+2 > *data_len) {
*data_len = sz + 2;
return -1;
}
fetch_from_buf(data_out, sz+1, buf);
data_out[sz+1] = '\0';
*data_len = sz+1;
return 1;
}
/** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
* zlib state <b>state</b>, appending the result to <b>buf</b>. If
* <b>done</b> is true, flush the data in the state and finish the
* compression/uncompression. Return -1 on failure, 0 on success. */
int
write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
const char *data, size_t data_len,
int done)
{
char *next;
size_t old_avail, avail;
int over = 0;
do {
int need_new_chunk = 0;
if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
size_t cap = data_len / 4;
buf_add_chunk_with_capacity(buf, cap, 1);
}
next = CHUNK_WRITE_PTR(buf->tail);
avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
case TOR_ZLIB_DONE:
over = 1;
break;
case TOR_ZLIB_ERR:
return -1;
case TOR_ZLIB_OK:
if (data_len == 0)
over = 1;
break;
case TOR_ZLIB_BUF_FULL:
if (avail) {
/* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
* automatically, whether were going to or not. */
need_new_chunk = 1;
}
break;
}
buf->datalen += old_avail - avail;
buf->tail->datalen += old_avail - avail;
if (need_new_chunk) {
buf_add_chunk_with_capacity(buf, data_len/4, 1);
}
} while (!over);
check();
return 0;
}
#ifdef USE_BUFFEREVENTS
int
write_to_evbuffer_zlib(struct evbuffer *buf, tor_zlib_state_t *state,
const char *data, size_t data_len,
int done)
{
char *next;
size_t old_avail, avail;
int over = 0, n;
struct evbuffer_iovec vec[1];
do {
{
size_t cap = data_len / 4;
if (cap < 128)
cap = 128;
/* XXXX NM this strategy is fragmentation-prone. We should really have
* two iovecs, and write first into the one, and then into the
* second if the first gets full. */
n = evbuffer_reserve_space(buf, cap, vec, 1);
tor_assert(n == 1);
}
next = vec[0].iov_base;
avail = old_avail = vec[0].iov_len;
switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
case TOR_ZLIB_DONE:
over = 1;
break;
case TOR_ZLIB_ERR:
return -1;
case TOR_ZLIB_OK:
if (data_len == 0)
over = 1;
break;
case TOR_ZLIB_BUF_FULL:
if (avail) {
/* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
* automatically, whether were going to or not. */
}
break;
}
/* XXXX possible infinite loop on BUF_FULL. */
vec[0].iov_len = old_avail - avail;
evbuffer_commit_space(buf, vec, 1);
} while (!over);
check();
return 0;
}
#endif
/** Set *<b>output</b> to contain a copy of the data in *<b>input</b> */
int
generic_buffer_set_to_copy(generic_buffer_t **output,
const generic_buffer_t *input)
{
#ifdef USE_BUFFEREVENTS
struct evbuffer_ptr ptr;
size_t remaining = evbuffer_get_length(input);
if (*output) {
evbuffer_drain(*output, evbuffer_get_length(*output));
} else {
if (!(*output = evbuffer_new()))
return -1;
}
evbuffer_ptr_set((struct evbuffer*)input, &ptr, 0, EVBUFFER_PTR_SET);
while (remaining) {
struct evbuffer_iovec v[4];
int n_used, i;
n_used = evbuffer_peek((struct evbuffer*)input, -1, &ptr, v, 4);
if (n_used < 0)
return -1;
for (i=0;i<n_used;++i) {
evbuffer_add(*output, v[i].iov_base, v[i].iov_len);
tor_assert(v[i].iov_len <= remaining);
remaining -= v[i].iov_len;
evbuffer_ptr_set((struct evbuffer*)input,
&ptr, v[i].iov_len, EVBUFFER_PTR_ADD);
}
}
#else
if (*output)
buf_free(*output);
*output = buf_copy(input);
#endif
return 0;
}
/** Log an error and exit if <b>buf</b> is corrupted.
*/
void
assert_buf_ok(buf_t *buf)
{
tor_assert(buf);
tor_assert(buf->magic == BUFFER_MAGIC);
if (! buf->head) {
tor_assert(!buf->tail);
tor_assert(buf->datalen == 0);
} else {
chunk_t *ch;
size_t total = 0;
tor_assert(buf->tail);
for (ch = buf->head; ch; ch = ch->next) {
total += ch->datalen;
tor_assert(ch->datalen <= ch->memlen);
tor_assert(ch->data >= &ch->mem[0]);
tor_assert(ch->data <= &ch->mem[0]+ch->memlen);
if (ch->data == &ch->mem[0]+ch->memlen) {
static int warned = 0;
if (! warned) {
log_warn(LD_BUG, "Invariant violation in buf.c related to #15083");
warned = 1;
}
}
tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
if (!ch->next)
tor_assert(ch == buf->tail);
}
tor_assert(buf->datalen == total);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5368_1 |
crossvul-cpp_data_good_3322_0 | /*
* irc-ctcp.c - IRC CTCP protocol
*
* Copyright (C) 2003-2017 Sébastien Helleu <flashcode@flashtux.org>
*
* This file is part of WeeChat, the extensible chat client.
*
* WeeChat is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* WeeChat is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WeeChat. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <sys/utsname.h>
#include <locale.h>
#include "../weechat-plugin.h"
#include "irc.h"
#include "irc-ctcp.h"
#include "irc-channel.h"
#include "irc-color.h"
#include "irc-config.h"
#include "irc-msgbuffer.h"
#include "irc-nick.h"
#include "irc-protocol.h"
#include "irc-server.h"
struct t_irc_ctcp_reply irc_ctcp_default_reply[] =
{ { "clientinfo", "$clientinfo" },
{ "finger", "WeeChat $versiongit" },
{ "source", "$download" },
{ "time", "$time" },
{ "userinfo", "$username ($realname)" },
{ "version", "WeeChat $versiongit ($compilation)" },
{ NULL, NULL },
};
/*
* Gets default reply for a CTCP query.
*
* Returns NULL if CTCP is unknown.
*/
const char *
irc_ctcp_get_default_reply (const char *ctcp)
{
int i;
for (i = 0; irc_ctcp_default_reply[i].name; i++)
{
if (weechat_strcasecmp (irc_ctcp_default_reply[i].name, ctcp) == 0)
return irc_ctcp_default_reply[i].reply;
}
/* unknown CTCP */
return NULL;
}
/*
* Gets reply for a CTCP query.
*/
const char *
irc_ctcp_get_reply (struct t_irc_server *server, const char *ctcp)
{
struct t_config_option *ptr_option;
char option_name[512];
snprintf (option_name, sizeof (option_name), "%s.%s", server->name, ctcp);
/* search for CTCP in configuration file, for server */
ptr_option = weechat_config_search_option (irc_config_file,
irc_config_section_ctcp,
option_name);
if (ptr_option)
return weechat_config_string (ptr_option);
/* search for CTCP in configuration file */
ptr_option = weechat_config_search_option (irc_config_file,
irc_config_section_ctcp,
ctcp);
if (ptr_option)
return weechat_config_string (ptr_option);
/*
* no CTCP reply found in config, then return default reply, or NULL
* for unknown CTCP
*/
return irc_ctcp_get_default_reply (ctcp);
}
/*
* Displays CTCP requested by a nick.
*/
void
irc_ctcp_display_request (struct t_irc_server *server,
time_t date,
const char *command,
struct t_irc_channel *channel,
const char *nick,
const char *address,
const char *ctcp,
const char *arguments,
const char *reply)
{
/* CTCP blocked and user doesn't want to see message? then just return */
if (reply && !reply[0]
&& !weechat_config_boolean (irc_config_look_display_ctcp_blocked))
return;
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, nick, NULL, "ctcp",
(channel) ? channel->buffer : NULL),
date,
irc_protocol_tags (command, "irc_ctcp", NULL, address),
_("%sCTCP requested by %s%s%s: %s%s%s%s%s%s"),
weechat_prefix ("network"),
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
IRC_COLOR_CHAT_CHANNEL,
ctcp,
IRC_COLOR_RESET,
(arguments) ? " " : "",
(arguments) ? arguments : "",
(reply && !reply[0]) ? _(" (blocked)") : "");
}
/*
* Displays reply from a nick to a CTCP query.
*/
void
irc_ctcp_display_reply_from_nick (struct t_irc_server *server, time_t date,
const char *command, const char *nick,
const char *address, char *arguments)
{
char *pos_end, *pos_space, *pos_args, *pos_usec;
struct timeval tv;
long sec1, usec1, sec2, usec2, difftime;
while (arguments && arguments[0])
{
pos_end = strrchr (arguments + 1, '\01');
if (pos_end)
pos_end[0] = '\0';
pos_space = strchr (arguments + 1, ' ');
if (pos_space)
{
pos_space[0] = '\0';
pos_args = pos_space + 1;
while (pos_args[0] == ' ')
{
pos_args++;
}
if (strcmp (arguments + 1, "PING") == 0)
{
pos_usec = strchr (pos_args, ' ');
if (pos_usec)
{
pos_usec[0] = '\0';
gettimeofday (&tv, NULL);
sec1 = atol (pos_args);
usec1 = atol (pos_usec + 1);
sec2 = tv.tv_sec;
usec2 = tv.tv_usec;
difftime = ((sec2 * 1000000) + usec2) -
((sec1 * 1000000) + usec1);
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, nick, NULL, "ctcp", NULL),
date,
irc_protocol_tags (command, "irc_ctcp", NULL, NULL),
/* TRANSLATORS: %.3fs is a float number + "s" ("seconds") */
_("%sCTCP reply from %s%s%s: %s%s%s %.3fs"),
weechat_prefix ("network"),
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
IRC_COLOR_CHAT_CHANNEL,
arguments + 1,
IRC_COLOR_RESET,
(float)difftime / 1000000.0);
pos_usec[0] = ' ';
}
}
else
{
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, nick, NULL, "ctcp", NULL),
date,
irc_protocol_tags (command, "irc_ctcp", NULL, address),
_("%sCTCP reply from %s%s%s: %s%s%s%s%s"),
weechat_prefix ("network"),
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
IRC_COLOR_CHAT_CHANNEL,
arguments + 1,
IRC_COLOR_RESET,
" ",
pos_args);
}
pos_space[0] = ' ';
}
else
{
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, nick, NULL, "ctcp", NULL),
date,
irc_protocol_tags (command, NULL, NULL, address),
_("%sCTCP reply from %s%s%s: %s%s%s%s%s"),
weechat_prefix ("network"),
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
IRC_COLOR_CHAT_CHANNEL,
arguments + 1,
"",
"",
"");
}
if (pos_end)
pos_end[0] = '\01';
arguments = (pos_end) ? pos_end + 1 : NULL;
}
}
/*
* Displays CTCP replied to a nick.
*/
void
irc_ctcp_reply_to_nick (struct t_irc_server *server,
const char *command,
struct t_irc_channel *channel,
const char *nick, const char *ctcp,
const char *arguments)
{
struct t_hashtable *hashtable;
int number;
char hash_key[32];
const char *str_args;
char *str_args_color;
hashtable = irc_server_sendf (
server,
IRC_SERVER_SEND_OUTQ_PRIO_LOW | IRC_SERVER_SEND_RETURN_HASHTABLE,
NULL,
"NOTICE %s :\01%s%s%s\01",
nick, ctcp,
(arguments) ? " " : "",
(arguments) ? arguments : "");
if (hashtable)
{
if (weechat_config_boolean (irc_config_look_display_ctcp_reply))
{
number = 1;
while (1)
{
snprintf (hash_key, sizeof (hash_key), "args%d", number);
str_args = weechat_hashtable_get (hashtable, hash_key);
if (!str_args)
break;
str_args_color = irc_color_decode (str_args, 1);
if (!str_args_color)
break;
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, nick, NULL, "ctcp",
(channel) ? channel->buffer : NULL),
0,
irc_protocol_tags (
command,
"irc_ctcp,irc_ctcp_reply,self_msg,notify_none,"
"no_highlight",
NULL, NULL),
_("%sCTCP reply to %s%s%s: %s%s%s%s%s"),
weechat_prefix ("network"),
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
IRC_COLOR_CHAT_CHANNEL,
ctcp,
(str_args_color[0]) ? IRC_COLOR_RESET : "",
(str_args_color[0]) ? " " : "",
str_args_color);
free (str_args_color);
number++;
}
}
weechat_hashtable_free (hashtable);
}
}
/*
* Replaces variables in CTCP format.
*
* Note: result must be freed after use.
*/
char *
irc_ctcp_replace_variables (struct t_irc_server *server, const char *format)
{
char *res, *temp, *username, *realname;
const char *info;
time_t now;
struct tm *local_time;
char buf[1024];
struct utsname *buf_uname;
/*
* $clientinfo: supported CTCP, example:
* ACTION DCC CLIENTINFO FINGER PING SOURCE TIME USERINFO VERSION
*/
temp = weechat_string_replace (
format, "$clientinfo",
"ACTION DCC CLIENTINFO FINGER PING SOURCE TIME USERINFO VERSION");
if (!temp)
return NULL;
res = temp;
/*
* $git: git version (output of "git describe" for a development version
* only, empty string if unknown), example:
* v0.3.9-104-g7eb5cc4
*/
info = weechat_info_get ("version_git", "");
temp = weechat_string_replace (res, "$git", info);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $versiongit: WeeChat version + git version (if known), examples:
* 0.3.9
* 0.4.0-dev
* 0.4.0-dev (git: v0.3.9-104-g7eb5cc4)
*/
info = weechat_info_get ("version_git", "");
snprintf (buf, sizeof (buf), "%s%s%s%s",
weechat_info_get ("version", ""),
(info && info[0]) ? " (git: " : "",
(info && info[0]) ? info : "",
(info && info[0]) ? ")" : "");
temp = weechat_string_replace (res, "$versiongit", buf);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $version: WeeChat version, examples:
* 0.3.9
* 0.4.0-dev
*/
info = weechat_info_get ("version", "");
temp = weechat_string_replace (res, "$version", info);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $compilation: compilation date, example:
* Dec 16 2012
*/
info = weechat_info_get ("date", "");
temp = weechat_string_replace (res, "$compilation", info);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $osinfo: info about OS, example:
* Linux 2.6.32-5-amd64 / x86_64
*/
buf_uname = (struct utsname *)malloc (sizeof (struct utsname));
if (buf_uname)
{
if (uname (buf_uname) >= 0)
{
snprintf (buf, sizeof (buf), "%s %s / %s",
buf_uname->sysname, buf_uname->release,
buf_uname->machine);
temp = weechat_string_replace (res, "$osinfo", buf);
free (res);
if (!temp)
{
free (buf_uname);
return NULL;
}
res = temp;
}
free (buf_uname);
}
/*
* $site: WeeChat web site, example:
* https://weechat.org/
*/
info = weechat_info_get ("weechat_site", "");
temp = weechat_string_replace (res, "$site", info);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $download: WeeChat download page, example:
* https://weechat.org/download
*/
info = weechat_info_get ("weechat_site_download", "");
temp = weechat_string_replace (res, "$download", info);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $time: local date/time of user, example:
* Sun, 16 Dec 2012 10:40:48 +0100
*/
now = time (NULL);
local_time = localtime (&now);
setlocale (LC_ALL, "C");
strftime (buf, sizeof (buf),
weechat_config_string (irc_config_look_ctcp_time_format),
local_time);
setlocale (LC_ALL, "");
temp = weechat_string_replace (res, "$time", buf);
free (res);
if (!temp)
return NULL;
res = temp;
/*
* $username: user name, example:
* name
*/
username = weechat_string_eval_expression (
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_USERNAME),
NULL, NULL, NULL);
if (username)
{
temp = weechat_string_replace (res, "$username", username);
free (res);
if (!temp)
return NULL;
res = temp;
free (username);
}
/*
* $realname: real name, example:
* John doe
*/
realname = weechat_string_eval_expression (
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_REALNAME),
NULL, NULL, NULL);
if (realname)
{
temp = weechat_string_replace (res, "$realname", realname);
free (res);
if (!temp)
return NULL;
res = temp;
free (realname);
}
/* return result */
return res;
}
/*
* Returns filename for DCC, without double quotes.
*
* Note: result must be freed after use.
*/
char *
irc_ctcp_dcc_filename_without_quotes (const char *filename)
{
int length;
length = strlen (filename);
if (length > 1)
{
if ((filename[0] == '\"') && (filename[length - 1] == '\"'))
return weechat_strndup (filename + 1, length - 2);
}
return strdup (filename);
}
/*
* Parses CTCP DCC.
*/
void
irc_ctcp_recv_dcc (struct t_irc_server *server, const char *nick,
const char *arguments, char *message)
{
char *dcc_args, *pos, *pos_file, *pos_addr, *pos_port, *pos_size;
char *pos_start_resume, *filename;
struct t_infolist *infolist;
struct t_infolist_item *item;
char charset_modifier[256];
if (!arguments || !arguments[0])
return;
if (strncmp (arguments, "SEND ", 5) == 0)
{
arguments += 5;
while (arguments[0] == ' ')
{
arguments++;
}
dcc_args = strdup (arguments);
if (!dcc_args)
{
weechat_printf (
server->buffer,
_("%s%s: not enough memory for \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
return;
}
/* DCC filename */
pos_file = dcc_args;
while (pos_file[0] == ' ')
{
pos_file++;
}
/* look for file size */
pos_size = strrchr (pos_file, ' ');
if (!pos_size)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_size;
pos_size++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* look for DCC port */
pos_port = strrchr (pos_file, ' ');
if (!pos_port)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_port;
pos_port++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* look for DCC IP address */
pos_addr = strrchr (pos_file, ' ');
if (!pos_addr)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_addr;
pos_addr++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* remove double quotes around filename */
filename = irc_ctcp_dcc_filename_without_quotes (pos_file);
/* add DCC file via xfer plugin */
infolist = weechat_infolist_new ();
if (infolist)
{
item = weechat_infolist_new_item (infolist);
if (item)
{
weechat_infolist_new_var_string (item, "plugin_name", weechat_plugin->name);
weechat_infolist_new_var_string (item, "plugin_id", server->name);
weechat_infolist_new_var_string (item, "type_string", "file_recv");
weechat_infolist_new_var_string (item, "protocol_string", "dcc");
weechat_infolist_new_var_string (item, "remote_nick", nick);
weechat_infolist_new_var_string (item, "local_nick", server->nick);
weechat_infolist_new_var_string (item, "filename",
(filename) ? filename : pos_file);
weechat_infolist_new_var_string (item, "size", pos_size);
weechat_infolist_new_var_string (item, "proxy",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_PROXY));
weechat_infolist_new_var_string (item, "remote_address", pos_addr);
weechat_infolist_new_var_integer (item, "port", atoi (pos_port));
(void) weechat_hook_signal_send ("xfer_add",
WEECHAT_HOOK_SIGNAL_POINTER,
infolist);
}
weechat_infolist_free (infolist);
}
(void) weechat_hook_signal_send ("irc_dcc",
WEECHAT_HOOK_SIGNAL_STRING,
message);
if (filename)
free (filename);
free (dcc_args);
}
else if (strncmp (arguments, "RESUME ", 7) == 0)
{
arguments += 7;
while (arguments[0] == ' ')
{
arguments++;
}
dcc_args = strdup (arguments);
if (!dcc_args)
{
weechat_printf (
server->buffer,
_("%s%s: not enough memory for \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
return;
}
/* DCC filename */
pos_file = dcc_args;
while (pos_file[0] == ' ')
{
pos_file++;
}
/* look for resume start position */
pos_start_resume = strrchr (pos_file, ' ');
if (!pos_start_resume)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_start_resume;
pos_start_resume++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* look for DCC port */
pos_port = strrchr (pos_file, ' ');
if (!pos_port)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_port;
pos_port++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* remove double quotes around filename */
filename = irc_ctcp_dcc_filename_without_quotes (pos_file);
/* accept resume via xfer plugin */
infolist = weechat_infolist_new ();
if (infolist)
{
item = weechat_infolist_new_item (infolist);
if (item)
{
weechat_infolist_new_var_string (item, "plugin_name", weechat_plugin->name);
weechat_infolist_new_var_string (item, "plugin_id", server->name);
weechat_infolist_new_var_string (item, "type_string", "file_recv");
weechat_infolist_new_var_string (item, "filename",
(filename) ? filename : pos_file);
weechat_infolist_new_var_integer (item, "port", atoi (pos_port));
weechat_infolist_new_var_string (item, "start_resume", pos_start_resume);
(void) weechat_hook_signal_send ("xfer_accept_resume",
WEECHAT_HOOK_SIGNAL_POINTER,
infolist);
}
weechat_infolist_free (infolist);
}
(void) weechat_hook_signal_send ("irc_dcc",
WEECHAT_HOOK_SIGNAL_STRING,
message);
if (filename)
free (filename);
free (dcc_args);
}
else if (strncmp (arguments, "ACCEPT ", 7) == 0)
{
arguments += 7;
while (arguments[0] == ' ')
{
arguments++;
}
dcc_args = strdup (arguments);
if (!dcc_args)
{
weechat_printf (
server->buffer,
_("%s%s: not enough memory for \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
return;
}
/* DCC filename */
pos_file = dcc_args;
while (pos_file[0] == ' ')
{
pos_file++;
}
/* look for resume start position */
pos_start_resume = strrchr (pos_file, ' ');
if (!pos_start_resume)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_start_resume;
pos_start_resume++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* look for DCC port */
pos_port = strrchr (pos_file, ' ');
if (!pos_port)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos = pos_port;
pos_port++;
while (pos[0] == ' ')
{
pos--;
}
pos[1] = '\0';
/* remove double quotes around filename */
filename = irc_ctcp_dcc_filename_without_quotes (pos_file);
/* resume file via xfer plugin */
infolist = weechat_infolist_new ();
if (infolist)
{
item = weechat_infolist_new_item (infolist);
if (item)
{
weechat_infolist_new_var_string (item, "plugin_name", weechat_plugin->name);
weechat_infolist_new_var_string (item, "plugin_id", server->name);
weechat_infolist_new_var_string (item, "type_string", "file_recv");
weechat_infolist_new_var_string (item, "filename",
(filename) ? filename : pos_file);
weechat_infolist_new_var_integer (item, "port", atoi (pos_port));
weechat_infolist_new_var_string (item, "start_resume", pos_start_resume);
(void) weechat_hook_signal_send ("xfer_start_resume",
WEECHAT_HOOK_SIGNAL_POINTER,
infolist);
}
weechat_infolist_free (infolist);
}
(void) weechat_hook_signal_send ("irc_dcc",
WEECHAT_HOOK_SIGNAL_STRING,
message);
if (filename)
free (filename);
free (dcc_args);
}
else if (strncmp (arguments, "CHAT ", 5) == 0)
{
arguments += 5;
while (arguments[0] == ' ')
{
arguments++;
}
dcc_args = strdup (arguments);
if (!dcc_args)
{
weechat_printf (
server->buffer,
_("%s%s: not enough memory for \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
return;
}
/* CHAT type */
pos_file = dcc_args;
while (pos_file[0] == ' ')
{
pos_file++;
}
/* DCC IP address */
pos_addr = strchr (pos_file, ' ');
if (!pos_addr)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos_addr[0] = '\0';
pos_addr++;
while (pos_addr[0] == ' ')
{
pos_addr++;
}
/* look for DCC port */
pos_port = strchr (pos_addr, ' ');
if (!pos_port)
{
weechat_printf (
server->buffer,
_("%s%s: cannot parse \"%s\" command"),
weechat_prefix ("error"), IRC_PLUGIN_NAME, "privmsg");
free (dcc_args);
return;
}
pos_port[0] = '\0';
pos_port++;
while (pos_port[0] == ' ')
{
pos_port++;
}
if (weechat_strcasecmp (pos_file, "chat") != 0)
{
weechat_printf (
server->buffer,
_("%s%s: unknown DCC CHAT type received from %s%s%s: \"%s\""),
weechat_prefix ("error"),
IRC_PLUGIN_NAME,
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
pos_file);
free (dcc_args);
return;
}
/* add DCC chat via xfer plugin */
infolist = weechat_infolist_new ();
if (infolist)
{
item = weechat_infolist_new_item (infolist);
if (item)
{
weechat_infolist_new_var_string (item, "plugin_name", weechat_plugin->name);
weechat_infolist_new_var_string (item, "plugin_id", server->name);
weechat_infolist_new_var_string (item, "type_string", "chat_recv");
weechat_infolist_new_var_string (item, "remote_nick", nick);
weechat_infolist_new_var_string (item, "local_nick", server->nick);
snprintf (charset_modifier, sizeof (charset_modifier),
"irc.%s.%s", server->name, nick);
weechat_infolist_new_var_string (item, "charset_modifier", charset_modifier);
weechat_infolist_new_var_string (item, "proxy",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_PROXY));
weechat_infolist_new_var_string (item, "remote_address", pos_addr);
weechat_infolist_new_var_integer (item, "port", atoi (pos_port));
(void) weechat_hook_signal_send ("xfer_add",
WEECHAT_HOOK_SIGNAL_POINTER,
infolist);
}
weechat_infolist_free (infolist);
}
(void) weechat_hook_signal_send ("irc_dcc",
WEECHAT_HOOK_SIGNAL_STRING,
message);
free (dcc_args);
}
}
/*
* Receives a CTCP and if needed replies to query.
*/
void
irc_ctcp_recv (struct t_irc_server *server, time_t date, const char *command,
struct t_irc_channel *channel, const char *address,
const char *nick, const char *remote_nick, char *arguments,
char *message)
{
char *pos_end, *pos_space, *pos_args;
const char *reply;
char *decoded_reply;
struct t_irc_channel *ptr_channel;
struct t_irc_nick *ptr_nick;
int nick_is_me;
while (arguments && arguments[0])
{
pos_end = strrchr (arguments + 1, '\01');
if (pos_end)
pos_end[0] = '\0';
pos_args = NULL;
pos_space = strchr (arguments + 1, ' ');
if (pos_space)
{
pos_space[0] = '\0';
pos_args = pos_space + 1;
while (pos_args[0] == ' ')
{
pos_args++;
}
}
/* CTCP ACTION */
if (strcmp (arguments + 1, "ACTION") == 0)
{
nick_is_me = (irc_server_strcasecmp (server, server->nick, nick) == 0);
if (channel)
{
ptr_nick = irc_nick_search (server, channel, nick);
irc_channel_nick_speaking_add (channel,
nick,
(pos_args) ?
weechat_string_has_highlight (pos_args,
server->nick) : 0);
irc_channel_nick_speaking_time_remove_old (channel);
irc_channel_nick_speaking_time_add (server, channel, nick,
time (NULL));
weechat_printf_date_tags (
channel->buffer,
date,
irc_protocol_tags (
command,
(nick_is_me) ?
"irc_action,self_msg,notify_none,no_highlight" :
"irc_action,notify_message",
nick, address),
"%s%s%s%s%s%s%s",
weechat_prefix ("action"),
irc_nick_mode_for_display (server, ptr_nick, 0),
(ptr_nick) ? ptr_nick->color : ((nick) ? irc_nick_find_color (nick) : IRC_COLOR_CHAT_NICK),
nick,
(pos_args) ? IRC_COLOR_RESET : "",
(pos_args) ? " " : "",
(pos_args) ? pos_args : "");
}
else
{
ptr_channel = irc_channel_search (server, remote_nick);
if (!ptr_channel)
{
ptr_channel = irc_channel_new (server,
IRC_CHANNEL_TYPE_PRIVATE,
remote_nick, 0, 0);
if (!ptr_channel)
{
weechat_printf (
server->buffer,
_("%s%s: cannot create new private buffer \"%s\""),
weechat_prefix ("error"), IRC_PLUGIN_NAME,
remote_nick);
}
}
if (ptr_channel)
{
if (!ptr_channel->topic)
irc_channel_set_topic (ptr_channel, address);
weechat_printf_date_tags (
ptr_channel->buffer,
date,
irc_protocol_tags (
command,
(nick_is_me) ?
"irc_action,self_msg,notify_none,no_highlight" :
"irc_action,notify_private",
nick, address),
"%s%s%s%s%s%s",
weechat_prefix ("action"),
(nick_is_me) ?
IRC_COLOR_CHAT_NICK_SELF : irc_nick_color_for_pv (ptr_channel, nick),
nick,
(pos_args) ? IRC_COLOR_RESET : "",
(pos_args) ? " " : "",
(pos_args) ? pos_args : "");
(void) weechat_hook_signal_send ("irc_pv",
WEECHAT_HOOK_SIGNAL_STRING,
message);
}
}
}
/* CTCP PING */
else if (strcmp (arguments + 1, "PING") == 0)
{
reply = irc_ctcp_get_reply (server, arguments + 1);
irc_ctcp_display_request (server, date, command, channel, nick,
address, arguments + 1, pos_args, reply);
if (!reply || reply[0])
{
irc_ctcp_reply_to_nick (server, command, channel, nick,
arguments + 1, pos_args);
}
}
/* CTCP DCC */
else if (strcmp (arguments + 1, "DCC") == 0)
{
irc_ctcp_recv_dcc (server, nick, pos_args, message);
}
/* other CTCP */
else
{
reply = irc_ctcp_get_reply (server, arguments + 1);
if (reply)
{
irc_ctcp_display_request (server, date, command, channel, nick,
address, arguments + 1, pos_args,
reply);
if (reply[0])
{
decoded_reply = irc_ctcp_replace_variables (server, reply);
if (decoded_reply)
{
irc_ctcp_reply_to_nick (server, command, channel, nick,
arguments + 1, decoded_reply);
free (decoded_reply);
}
}
}
else
{
if (weechat_config_boolean (irc_config_look_display_ctcp_unknown))
{
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, nick, NULL, "ctcp",
(channel) ? channel->buffer : NULL),
date,
irc_protocol_tags (command, "irc_ctcp", NULL, address),
_("%sUnknown CTCP requested by %s%s%s: %s%s%s%s%s"),
weechat_prefix ("network"),
irc_nick_color_for_msg (server, 0, NULL, nick),
nick,
IRC_COLOR_RESET,
IRC_COLOR_CHAT_CHANNEL,
arguments + 1,
(pos_args) ? IRC_COLOR_RESET : "",
(pos_args) ? " " : "",
(pos_args) ? pos_args : "");
}
}
}
(void) weechat_hook_signal_send ("irc_ctcp",
WEECHAT_HOOK_SIGNAL_STRING,
message);
if (pos_space)
pos_space[0] = ' ';
if (pos_end)
pos_end[0] = '\01';
arguments = (pos_end) ? pos_end + 1 : NULL;
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3322_0 |
crossvul-cpp_data_bad_734_1 | /* This file is part of libmspack.
* (C) 2003-2018 Stuart Caie.
*
* libmspack is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*
* For further details, see the file COPYING.LIB distributed with libmspack
*/
/* CHM decompression implementation */
#include <system.h>
#include <chm.h>
/* prototypes */
static struct mschmd_header * chmd_open(
struct mschm_decompressor *base, const char *filename);
static struct mschmd_header * chmd_fast_open(
struct mschm_decompressor *base, const char *filename);
static struct mschmd_header *chmd_real_open(
struct mschm_decompressor *base, const char *filename, int entire);
static void chmd_close(
struct mschm_decompressor *base, struct mschmd_header *chm);
static int chmd_read_headers(
struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire);
static int chmd_fast_find(
struct mschm_decompressor *base, struct mschmd_header *chm,
const char *filename, struct mschmd_file *f_ptr, int f_size);
static unsigned char *read_chunk(
struct mschm_decompressor_p *self, struct mschmd_header *chm,
struct mspack_file *fh, unsigned int chunk);
static int search_chunk(
struct mschmd_header *chm, const unsigned char *chunk, const char *filename,
const unsigned char **result, const unsigned char **result_end);
static inline int compare(
const char *s1, const char *s2, int l1, int l2);
static int chmd_extract(
struct mschm_decompressor *base, struct mschmd_file *file,
const char *filename);
static int chmd_sys_write(
struct mspack_file *file, void *buffer, int bytes);
static int chmd_init_decomp(
struct mschm_decompressor_p *self, struct mschmd_file *file);
static int read_reset_table(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
int entry, off_t *length_ptr, off_t *offset_ptr);
static int read_spaninfo(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
off_t *length_ptr);
static int find_sys_file(
struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec,
struct mschmd_file **f_ptr, const char *name);
static unsigned char *read_sys_file(
struct mschm_decompressor_p *self, struct mschmd_file *file);
static int chmd_error(
struct mschm_decompressor *base);
static int read_off64(
off_t *var, unsigned char *mem, struct mspack_system *sys,
struct mspack_file *fh);
/* filenames of the system files used for decompression.
* Content and ControlData are essential.
* ResetTable is preferred, but SpanInfo can be used if not available
*/
static const char *content_name = "::DataSpace/Storage/MSCompressed/Content";
static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData";
static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo";
static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/"
"{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable";
/***************************************
* MSPACK_CREATE_CHM_DECOMPRESSOR
***************************************
* constructor
*/
struct mschm_decompressor *
mspack_create_chm_decompressor(struct mspack_system *sys)
{
struct mschm_decompressor_p *self = NULL;
if (!sys) sys = mspack_default_system;
if (!mspack_valid_system(sys)) return NULL;
if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) {
self->base.open = &chmd_open;
self->base.close = &chmd_close;
self->base.extract = &chmd_extract;
self->base.last_error = &chmd_error;
self->base.fast_open = &chmd_fast_open;
self->base.fast_find = &chmd_fast_find;
self->system = sys;
self->error = MSPACK_ERR_OK;
self->d = NULL;
}
return (struct mschm_decompressor *) self;
}
/***************************************
* MSPACK_DESTROY_CAB_DECOMPRESSOR
***************************************
* destructor
*/
void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
if (self) {
struct mspack_system *sys = self->system;
if (self->d) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
sys->free(self->d);
}
sys->free(self);
}
}
/***************************************
* CHMD_OPEN
***************************************
* opens a file and tries to read it as a CHM file.
* Calls chmd_real_open() with entire=1.
*/
static struct mschmd_header *chmd_open(struct mschm_decompressor *base,
const char *filename)
{
return chmd_real_open(base, filename, 1);
}
/***************************************
* CHMD_FAST_OPEN
***************************************
* opens a file and tries to read it as a CHM file, but does not read
* the file headers. Calls chmd_real_open() with entire=0
*/
static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base,
const char *filename)
{
return chmd_real_open(base, filename, 0);
}
/***************************************
* CHMD_REAL_OPEN
***************************************
* the real implementation of chmd_open() and chmd_fast_open(). It simply
* passes the "entire" parameter to chmd_read_headers(), which will then
* either read all headers, or a bare mininum.
*/
static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base,
const char *filename, int entire)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mschmd_header *chm = NULL;
struct mspack_system *sys;
struct mspack_file *fh;
int error;
if (!base) return NULL;
sys = self->system;
if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) {
if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) {
chm->filename = filename;
error = chmd_read_headers(sys, fh, chm, entire);
if (error) {
/* if the error is DATAFORMAT, and there are some results, return
* partial results with a warning, rather than nothing */
if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) {
sys->message(fh, "WARNING; contents are corrupt");
error = MSPACK_ERR_OK;
}
else {
chmd_close(base, chm);
chm = NULL;
}
}
self->error = error;
}
else {
self->error = MSPACK_ERR_NOMEMORY;
}
sys->close(fh);
}
else {
self->error = MSPACK_ERR_OPEN;
}
return chm;
}
/***************************************
* CHMD_CLOSE
***************************************
* frees all memory associated with a given mschmd_header
*/
static void chmd_close(struct mschm_decompressor *base,
struct mschmd_header *chm)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mschmd_file *fi, *nfi;
struct mspack_system *sys;
unsigned int i;
if (!base) return;
sys = self->system;
self->error = MSPACK_ERR_OK;
/* free files */
for (fi = chm->files; fi; fi = nfi) {
nfi = fi->next;
sys->free(fi);
}
for (fi = chm->sysfiles; fi; fi = nfi) {
nfi = fi->next;
sys->free(fi);
}
/* if this CHM was being decompressed, free decompression state */
if (self->d && (self->d->chm == chm)) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
sys->free(self->d);
self->d = NULL;
}
/* if this CHM had a chunk cache, free it and contents */
if (chm->chunk_cache) {
for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]);
sys->free(chm->chunk_cache);
}
sys->free(chm);
}
/***************************************
* CHMD_READ_HEADERS
***************************************
* reads the basic CHM file headers. If the "entire" parameter is
* non-zero, all file entries will also be read. fills out a pre-existing
* mschmd_header structure, allocates memory for files as necessary
*/
/* The GUIDs found in CHM headers */
static const unsigned char guids[32] = {
/* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */
0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11,
0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC,
/* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */
0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11,
0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC
};
/* reads an encoded integer into a variable; 7 bits of data per byte,
* the high bit is used to indicate that there is another byte */
#define READ_ENCINT(var) do { \
(var) = 0; \
do { \
if (p >= end) goto chunk_end; \
(var) = ((var) << 7) | (*p & 0x7F); \
} while (*p++ & 0x80); \
} while (0)
static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (memcmp(&name[2], &content_name[2], 31L) == 0) {
if (memcmp(&name[33], &content_name[33], 8L) == 0) {
chm->sec1.content = fi;
}
else if (memcmp(&name[33], &control_name[33], 11L) == 0) {
chm->sec1.control = fi;
}
else if (memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
chm->sec1.spaninfo = fi;
}
else if (memcmp(&name[33], &rtable_name[33], 72L) == 0) {
chm->sec1.rtable = fi;
}
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
}
/***************************************
* CHMD_FAST_FIND
***************************************
* uses PMGI index chunks and quickref data to quickly locate a file
* directly from the on-disk index.
*
* TODO: protect against infinite loops in chunks (where pgml_NextChunk
* or a PMGI index entry point to an already visited chunk)
*/
static int chmd_fast_find(struct mschm_decompressor *base,
struct mschmd_header *chm, const char *filename,
struct mschmd_file *f_ptr, int f_size)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mspack_file *fh;
/* p and end are initialised to prevent MSVC warning about "potentially"
* uninitialised usage. This is provably untrue, but MS won't fix:
* https://developercommunity.visualstudio.com/content/problem/363489/c4701-false-positive-warning.html */
const unsigned char *chunk, *p = NULL, *end = NULL;
int err = MSPACK_ERR_OK, result = -1;
unsigned int n, sec;
if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) {
return MSPACK_ERR_ARGS;
}
sys = self->system;
/* clear the results structure */
memset(f_ptr, 0, f_size);
if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) {
return MSPACK_ERR_OPEN;
}
/* go through PMGI chunk hierarchy to reach PMGL chunk */
if (chm->index_root < chm->num_chunks) {
n = chm->index_root;
for (;;) {
if (!(chunk = read_chunk(self, chm, fh, n))) {
sys->close(fh);
return self->error;
}
/* search PMGI/PMGL chunk. exit early if no entry found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) {
break;
}
/* found result. loop around for next chunk if this is PMGI */
if (chunk[3] == 0x4C) break; else READ_ENCINT(n);
}
}
else {
/* PMGL chunks only, search from first_pmgl to last_pmgl */
for (n = chm->first_pmgl; n <= chm->last_pmgl;
n = EndGetI32(&chunk[pmgl_NextChunk]))
{
if (!(chunk = read_chunk(self, chm, fh, n))) {
err = self->error;
break;
}
/* search PMGL chunk. exit if file found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) {
break;
}
/* stop simple infinite loops: can't visit the same chunk twice */
if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) {
break;
}
}
}
/* if we found a file, read it */
if (result > 0) {
READ_ENCINT(sec);
f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0
: (struct mschmd_section *) &chm->sec1;
READ_ENCINT(f_ptr->offset);
READ_ENCINT(f_ptr->length);
}
else if (result < 0) {
err = MSPACK_ERR_DATAFORMAT;
}
sys->close(fh);
return self->error = err;
chunk_end:
D(("read beyond end of chunk entries"))
sys->close(fh);
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* reads the given chunk into memory, storing it in a chunk cache
* so it doesn't need to be read from disk more than once
*/
static unsigned char *read_chunk(struct mschm_decompressor_p *self,
struct mschmd_header *chm,
struct mspack_file *fh,
unsigned int chunk_num)
{
struct mspack_system *sys = self->system;
unsigned char *buf;
/* check arguments - most are already checked by chmd_fast_find */
if (chunk_num >= chm->num_chunks) return NULL;
/* ensure chunk cache is available */
if (!chm->chunk_cache) {
size_t size = sizeof(unsigned char *) * chm->num_chunks;
if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
memset(chm->chunk_cache, 0, size);
}
/* try to answer out of chunk cache */
if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num];
/* need to read chunk - allocate memory for it */
if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
/* seek to block and read it */
if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)),
MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
sys->free(buf);
return NULL;
}
if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) {
self->error = MSPACK_ERR_READ;
sys->free(buf);
return NULL;
}
/* check the signature. Is is PMGL or PMGI? */
if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) &&
((buf[3] == 0x4C) || (buf[3] == 0x49))))
{
self->error = MSPACK_ERR_SEEK;
sys->free(buf);
return NULL;
}
/* all OK. Store chunk in cache and return it */
return chm->chunk_cache[chunk_num] = buf;
}
/* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on
* data format error, 0 if entry definitely not found, 1 if entry
* found. In the latter case, *result and *result_end are set pointing
* to that entry's data (either the "next chunk" ENCINT for a PMGI or
* the section, offset and length ENCINTs for a PMGL).
*
* In the case of PMGL chunks, the entry has definitely been
* found. In the case of PMGI chunks, the entry which points to the
* chunk that may eventually contain that entry has been found.
*/
static int search_chunk(struct mschmd_header *chm,
const unsigned char *chunk,
const char *filename,
const unsigned char **result,
const unsigned char **result_end)
{
const unsigned char *start, *end, *p;
unsigned int qr_size, num_entries, qr_entries, qr_density, name_len;
unsigned int L, R, M, fname_len, entries_off, is_pmgl;
int cmp;
fname_len = strlen(filename);
/* PMGL chunk or PMGI chunk? (note: read_chunk() has already
* checked the rest of the characters in the chunk signature) */
if (chunk[3] == 0x4C) {
is_pmgl = 1;
entries_off = pmgl_Entries;
}
else {
is_pmgl = 0;
entries_off = pmgi_Entries;
}
/* Step 1: binary search first filename of each QR entry
* - target filename == entry
* found file
* - target filename < all entries
* file not found
* - target filename > all entries
* proceed to step 2 using final entry
* - target filename between two searched entries
* proceed to step 2
*/
qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]);
start = &chunk[chm->chunk_size - 2];
end = &chunk[chm->chunk_size - qr_size];
num_entries = EndGetI16(start);
qr_density = 1 + (1 << chm->density);
qr_entries = (num_entries + qr_density-1) / qr_density;
if (num_entries == 0) {
D(("chunk has no entries"))
return -1;
}
if (qr_size > chm->chunk_size) {
D(("quickref size > chunk size"))
return -1;
}
*result_end = end;
if (((int)qr_entries * 2) > (start - end)) {
D(("WARNING; more quickrefs than quickref space"))
qr_entries = 0; /* but we can live with it */
}
if (qr_entries > 0) {
L = 0;
R = qr_entries - 1;
do {
/* pick new midpoint */
M = (L + R) >> 1;
/* compare filename with entry QR points to */
p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)];
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
cmp = compare(filename, (char *)p, fname_len, name_len);
if (cmp == 0) break;
else if (cmp < 0) { if (M) R = M - 1; else return 0; }
else if (cmp > 0) L = M + 1;
} while (L <= R);
M = (L + R) >> 1;
if (cmp == 0) {
/* exact match! */
p += name_len;
*result = p;
return 1;
}
/* otherwise, read the group of entries for QR entry M */
p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)];
num_entries -= (M * qr_density);
if (num_entries > qr_density) num_entries = qr_density;
}
else {
p = &chunk[entries_off];
}
/* Step 2: linear search through the set of entries reached in step 1.
* - filename == any entry
* found entry
* - filename < all entries (PMGI) or any entry (PMGL)
* entry not found, stop now
* - filename > all entries
* entry not found (PMGL) / maybe found (PMGI)
* -
*/
*result = NULL;
while (num_entries-- > 0) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
cmp = compare(filename, (char *)p, fname_len, name_len);
p += name_len;
if (cmp == 0) {
/* entry found */
*result = p;
return 1;
}
if (cmp < 0) {
/* entry not found (PMGL) / maybe found (PMGI) */
break;
}
/* read and ignore the rest of this entry */
if (is_pmgl) {
READ_ENCINT(R); /* skip section */
READ_ENCINT(R); /* skip offset */
READ_ENCINT(R); /* skip length */
}
else {
*result = p; /* store potential final result */
READ_ENCINT(R); /* skip chunk number */
}
}
/* PMGL? not found. PMGI? maybe found */
return (is_pmgl) ? 0 : (*result ? 1 : 0);
chunk_end:
D(("reached end of chunk data while searching"))
return -1;
}
#if HAVE_TOWLOWER
# include <wctype.h>
# define TOLOWER(x) towlower(x)
#else
# include <ctype.h>
# define TOLOWER(x) tolower(x)
#endif
/* decodes a UTF-8 character from s[] into c. Will not read past e.
* doesn't test that extension bytes are %10xxxxxx.
* allows some overlong encodings.
*/
#define GET_UTF8_CHAR(s, e, c) do { \
unsigned char x = *s++; \
if (x < 0x80) c = x; \
else if (x >= 0xC2 && x < 0xE0 && s < e) { \
c = (x & 0x1F) << 6 | (*s++ & 0x3F); \
} \
else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \
c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \
s += 2; \
} \
else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \
c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \
(s[1] & 0x3F) << 6 | (s[2] & 0x3F); \
if (c > 0x10FFFF) c = 0xFFFD; \
s += 3; \
} \
else c = 0xFFFD; \
} while (0)
/* case-insensitively compares two UTF8 encoded strings. String length for
* both strings must be provided, null bytes are not terminators */
static inline int compare(const char *s1, const char *s2, int l1, int l2) {
register const unsigned char *p1 = (const unsigned char *) s1;
register const unsigned char *p2 = (const unsigned char *) s2;
register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2;
int c1, c2;
while (p1 < e1 && p2 < e2) {
GET_UTF8_CHAR(p1, e1, c1);
GET_UTF8_CHAR(p2, e2, c2);
if (c1 == c2) continue;
c1 = TOLOWER(c1);
c2 = TOLOWER(c2);
if (c1 != c2) return c1 - c2;
}
return l1 - l2;
}
/***************************************
* CHMD_EXTRACT
***************************************
* extracts a file from a CHM helpfile
*/
static int chmd_extract(struct mschm_decompressor *base,
struct mschmd_file *file, const char *filename)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mschmd_header *chm;
struct mspack_file *fh;
off_t bytes;
if (!self) return MSPACK_ERR_ARGS;
if (!file || !file->section) return self->error = MSPACK_ERR_ARGS;
sys = self->system;
chm = file->section->chm;
/* create decompression state if it doesn't exist */
if (!self->d) {
self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state));
if (!self->d) return self->error = MSPACK_ERR_NOMEMORY;
self->d->chm = chm;
self->d->offset = 0;
self->d->state = NULL;
self->d->sys = *sys;
self->d->sys.write = &chmd_sys_write;
self->d->infh = NULL;
self->d->outfh = NULL;
}
/* open input chm file if not open, or the open one is a different chm */
if (!self->d->infh || (self->d->chm != chm)) {
if (self->d->infh) sys->close(self->d->infh);
if (self->d->state) lzxd_free(self->d->state);
self->d->chm = chm;
self->d->offset = 0;
self->d->state = NULL;
self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ);
if (!self->d->infh) return self->error = MSPACK_ERR_OPEN;
}
/* open file for output */
if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) {
return self->error = MSPACK_ERR_OPEN;
}
/* if file is empty, simply creating it is enough */
if (!file->length) {
sys->close(fh);
return self->error = MSPACK_ERR_OK;
}
self->error = MSPACK_ERR_OK;
switch (file->section->id) {
case 0: /* Uncompressed section file */
/* simple seek + copy */
if (sys->seek(self->d->infh, file->section->chm->sec0.offset
+ file->offset, MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
}
else {
unsigned char buf[512];
off_t length = file->length;
while (length > 0) {
int run = sizeof(buf);
if ((off_t)run > length) run = (int)length;
if (sys->read(self->d->infh, &buf[0], run) != run) {
self->error = MSPACK_ERR_READ;
break;
}
if (sys->write(fh, &buf[0], run) != run) {
self->error = MSPACK_ERR_WRITE;
break;
}
length -= run;
}
}
break;
case 1: /* MSCompressed section file */
/* (re)initialise compression state if we it is not yet initialised,
* or we have advanced too far and have to backtrack
*/
if (!self->d->state || (file->offset < self->d->offset)) {
if (self->d->state) {
lzxd_free(self->d->state);
self->d->state = NULL;
}
if (chmd_init_decomp(self, file)) break;
}
/* seek to input data */
if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) {
self->error = MSPACK_ERR_SEEK;
break;
}
/* get to correct offset. */
self->d->outfh = NULL;
if ((bytes = file->offset - self->d->offset)) {
self->error = lzxd_decompress(self->d->state, bytes);
}
/* if getting to the correct offset was error free, unpack file */
if (!self->error) {
self->d->outfh = fh;
self->error = lzxd_decompress(self->d->state, file->length);
}
/* save offset in input source stream, in case there is a section 0
* file between now and the next section 1 file extracted */
self->d->inoffset = sys->tell(self->d->infh);
/* if an LZX error occured, the LZX decompressor is now useless */
if (self->error) {
if (self->d->state) lzxd_free(self->d->state);
self->d->state = NULL;
}
break;
}
sys->close(fh);
return self->error;
}
/***************************************
* CHMD_SYS_WRITE
***************************************
* chmd_sys_write is the internal writer function which the decompressor
* uses. If either writes data to disk (self->d->outfh) with the real
* sys->write() function, or does nothing with the data when
* self->d->outfh == NULL. advances self->d->offset.
*/
static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file;
self->d->offset += bytes;
if (self->d->outfh) {
return self->system->write(self->d->outfh, buffer, bytes);
}
return bytes;
}
/***************************************
* CHMD_INIT_DECOMP
***************************************
* Initialises the LZX decompressor to decompress the compressed stream,
* from the nearest reset offset and length that is needed for the given
* file.
*/
static int chmd_init_decomp(struct mschm_decompressor_p *self,
struct mschmd_file *file)
{
int window_size, window_bits, reset_interval, entry, err;
struct mspack_system *sys = self->system;
struct mschmd_sec_mscompressed *sec;
unsigned char *data;
off_t length, offset;
sec = (struct mschmd_sec_mscompressed *) file->section;
/* ensure we have a mscompressed content section */
err = find_sys_file(self, sec, &sec->content, content_name);
if (err) return self->error = err;
/* ensure we have a ControlData file */
err = find_sys_file(self, sec, &sec->control, control_name);
if (err) return self->error = err;
/* read ControlData */
if (sec->control->length < lzxcd_SIZEOF) {
D(("ControlData file is too short"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
if (!(data = read_sys_file(self, sec->control))) {
D(("can't read mscompressed control data file"))
return self->error;
}
/* check LZXC signature */
if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) {
sys->free(data);
return self->error = MSPACK_ERR_SIGNATURE;
}
/* read reset_interval and window_size and validate version number */
switch (EndGetI32(&data[lzxcd_Version])) {
case 1:
reset_interval = EndGetI32(&data[lzxcd_ResetInterval]);
window_size = EndGetI32(&data[lzxcd_WindowSize]);
break;
case 2:
reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE;
window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE;
break;
default:
D(("bad controldata version"))
sys->free(data);
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* free ControlData */
sys->free(data);
/* find window_bits from window_size */
switch (window_size) {
case 0x008000: window_bits = 15; break;
case 0x010000: window_bits = 16; break;
case 0x020000: window_bits = 17; break;
case 0x040000: window_bits = 18; break;
case 0x080000: window_bits = 19; break;
case 0x100000: window_bits = 20; break;
case 0x200000: window_bits = 21; break;
default:
D(("bad controldata window size"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* validate reset_interval */
if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) {
D(("bad controldata reset interval"))
return self->error = MSPACK_ERR_DATAFORMAT;
}
/* which reset table entry would we like? */
entry = file->offset / reset_interval;
/* convert from reset interval multiple (usually 64k) to 32k frames */
entry *= reset_interval / LZX_FRAME_SIZE;
/* read the reset table entry */
if (read_reset_table(self, sec, entry, &length, &offset)) {
/* the uncompressed length given in the reset table is dishonest.
* the uncompressed data is always padded out from the given
* uncompressed length up to the next reset interval */
length += reset_interval - 1;
length &= -reset_interval;
}
else {
/* if we can't read the reset table entry, just start from
* the beginning. Use spaninfo to get the uncompressed length */
entry = 0;
offset = 0;
err = read_spaninfo(self, sec, &length);
}
if (err) return self->error = err;
/* get offset of compressed data stream:
* = offset of uncompressed section from start of file
* + offset of compressed stream from start of uncompressed section
* + offset of chosen reset interval from start of compressed stream */
self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset;
/* set start offset and overall remaining stream length */
self->d->offset = entry * LZX_FRAME_SIZE;
length -= self->d->offset;
/* initialise LZX stream */
self->d->state = lzxd_init(&self->d->sys, self->d->infh,
(struct mspack_file *) self, window_bits,
reset_interval / LZX_FRAME_SIZE,
4096, length, 0);
if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY;
return self->error;
}
/***************************************
* READ_RESET_TABLE
***************************************
* Reads one entry out of the reset table. Also reads the uncompressed
* data length. Writes these to offset_ptr and length_ptr respectively.
* Returns non-zero for success, zero for failure.
*/
static int read_reset_table(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
int entry, off_t *length_ptr, off_t *offset_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
unsigned int pos, entrysize;
/* do we have a ResetTable file? */
int err = find_sys_file(self, sec, &sec->rtable, rtable_name);
if (err) return 0;
/* read ResetTable file */
if (sec->rtable->length < lzxrt_headerSIZEOF) {
D(("ResetTable file is too short"))
return 0;
}
if (!(data = read_sys_file(self, sec->rtable))) {
D(("can't read reset table"))
return 0;
}
/* check sanity of reset table */
if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) {
D(("bad reset table frame length"))
sys->free(data);
return 0;
}
/* get the uncompressed length of the LZX stream */
if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) {
sys->free(data);
return 0;
}
entrysize = EndGetI32(&data[lzxrt_EntrySize]);
pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize);
/* ensure reset table entry for this offset exists */
if (entry < EndGetI32(&data[lzxrt_NumEntries]) &&
pos <= (sec->rtable->length - entrysize))
{
switch (entrysize) {
case 4:
*offset_ptr = EndGetI32(&data[pos]);
err = 0;
break;
case 8:
err = read_off64(offset_ptr, &data[pos], sys, self->d->infh);
break;
default:
D(("reset table entry size neither 4 nor 8"))
err = 1;
break;
}
}
else {
D(("bad reset interval"))
err = 1;
}
/* free the reset table */
sys->free(data);
/* return success */
return (err == 0);
}
/***************************************
* READ_SPANINFO
***************************************
* Reads the uncompressed data length from the spaninfo file.
* Returns zero for success or a non-zero error code for failure.
*/
static int read_spaninfo(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
off_t *length_ptr)
{
struct mspack_system *sys = self->system;
unsigned char *data;
/* find SpanInfo file */
int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name);
if (err) return MSPACK_ERR_DATAFORMAT;
/* check it's large enough */
if (sec->spaninfo->length != 8) {
D(("SpanInfo file is wrong size"))
return MSPACK_ERR_DATAFORMAT;
}
/* read the SpanInfo file */
if (!(data = read_sys_file(self, sec->spaninfo))) {
D(("can't read SpanInfo file"))
return self->error;
}
/* get the uncompressed length of the LZX stream */
err = read_off64(length_ptr, data, sys, self->d->infh);
sys->free(data);
if (err) return MSPACK_ERR_DATAFORMAT;
if (*length_ptr <= 0) {
D(("output length is invalid"))
return MSPACK_ERR_DATAFORMAT;
}
return MSPACK_ERR_OK;
}
/***************************************
* FIND_SYS_FILE
***************************************
* Uses chmd_fast_find to locate a system file, and fills out that system
* file's entry and links it into the list of system files. Returns zero
* for success, non-zero for both failure and the file not existing.
*/
static int find_sys_file(struct mschm_decompressor_p *self,
struct mschmd_sec_mscompressed *sec,
struct mschmd_file **f_ptr, const char *name)
{
struct mspack_system *sys = self->system;
struct mschmd_file result;
/* already loaded */
if (*f_ptr) return MSPACK_ERR_OK;
/* try using fast_find to find the file - return DATAFORMAT error if
* it fails, or successfully doesn't find the file */
if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm,
name, &result, (int)sizeof(result)) || !result.section)
{
return MSPACK_ERR_DATAFORMAT;
}
if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) {
return MSPACK_ERR_NOMEMORY;
}
/* copy result */
*(*f_ptr) = result;
(*f_ptr)->filename = (char *) name;
/* link file into sysfiles list */
(*f_ptr)->next = sec->base.chm->sysfiles;
sec->base.chm->sysfiles = *f_ptr;
return MSPACK_ERR_OK;
}
/***************************************
* READ_SYS_FILE
***************************************
* Allocates memory for a section 0 (uncompressed) file and reads it into
* memory.
*/
static unsigned char *read_sys_file(struct mschm_decompressor_p *self,
struct mschmd_file *file)
{
struct mspack_system *sys = self->system;
unsigned char *data = NULL;
int len;
if (!file || !file->section || (file->section->id != 0)) {
self->error = MSPACK_ERR_DATAFORMAT;
return NULL;
}
len = (int) file->length;
if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) {
self->error = MSPACK_ERR_NOMEMORY;
return NULL;
}
if (sys->seek(self->d->infh, file->section->chm->sec0.offset
+ file->offset, MSPACK_SYS_SEEK_START))
{
self->error = MSPACK_ERR_SEEK;
sys->free(data);
return NULL;
}
if (sys->read(self->d->infh, data, len) != len) {
self->error = MSPACK_ERR_READ;
sys->free(data);
return NULL;
}
return data;
}
/***************************************
* CHMD_ERROR
***************************************
* returns the last error that occurred
*/
static int chmd_error(struct mschm_decompressor *base) {
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
return (self) ? self->error : MSPACK_ERR_ARGS;
}
/***************************************
* READ_OFF64
***************************************
* Reads a 64-bit signed integer from memory in Intel byte order.
* If running on a system with a 64-bit off_t, this is simply done.
* If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF
* are accepted, offsets beyond that cause an error message.
*/
static int read_off64(off_t *var, unsigned char *mem,
struct mspack_system *sys, struct mspack_file *fh)
{
#if LARGEFILE_SUPPORT
*var = EndGetI64(mem);
#else
*var = EndGetI32(mem);
if ((*var & 0x80000000) || EndGetI32(mem+4)) {
sys->message(fh, (char *)largefile_msg);
return 1;
}
#endif
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_734_1 |
crossvul-cpp_data_bad_3020_0 | /*
* Copyright (c) 2014-2015 Hisilicon Limited.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/delay.h>
#include <linux/of_mdio.h>
#include "hns_dsaf_main.h"
#include "hns_dsaf_mac.h"
#include "hns_dsaf_gmac.h"
static const struct mac_stats_string g_gmac_stats_string[] = {
{"gmac_rx_octets_total_ok", MAC_STATS_FIELD_OFF(rx_good_bytes)},
{"gmac_rx_octets_bad", MAC_STATS_FIELD_OFF(rx_bad_bytes)},
{"gmac_rx_uc_pkts", MAC_STATS_FIELD_OFF(rx_uc_pkts)},
{"gmac_rx_mc_pkts", MAC_STATS_FIELD_OFF(rx_mc_pkts)},
{"gmac_rx_bc_pkts", MAC_STATS_FIELD_OFF(rx_bc_pkts)},
{"gmac_rx_pkts_64octets", MAC_STATS_FIELD_OFF(rx_64bytes)},
{"gmac_rx_pkts_65to127", MAC_STATS_FIELD_OFF(rx_65to127)},
{"gmac_rx_pkts_128to255", MAC_STATS_FIELD_OFF(rx_128to255)},
{"gmac_rx_pkts_256to511", MAC_STATS_FIELD_OFF(rx_256to511)},
{"gmac_rx_pkts_512to1023", MAC_STATS_FIELD_OFF(rx_512to1023)},
{"gmac_rx_pkts_1024to1518", MAC_STATS_FIELD_OFF(rx_1024to1518)},
{"gmac_rx_pkts_1519tomax", MAC_STATS_FIELD_OFF(rx_1519tomax)},
{"gmac_rx_fcs_errors", MAC_STATS_FIELD_OFF(rx_fcs_err)},
{"gmac_rx_tagged", MAC_STATS_FIELD_OFF(rx_vlan_pkts)},
{"gmac_rx_data_err", MAC_STATS_FIELD_OFF(rx_data_err)},
{"gmac_rx_align_errors", MAC_STATS_FIELD_OFF(rx_align_err)},
{"gmac_rx_long_errors", MAC_STATS_FIELD_OFF(rx_oversize)},
{"gmac_rx_jabber_errors", MAC_STATS_FIELD_OFF(rx_jabber_err)},
{"gmac_rx_pause_maccontrol", MAC_STATS_FIELD_OFF(rx_pfc_tc0)},
{"gmac_rx_unknown_maccontrol", MAC_STATS_FIELD_OFF(rx_unknown_ctrl)},
{"gmac_rx_very_long_err", MAC_STATS_FIELD_OFF(rx_long_err)},
{"gmac_rx_runt_err", MAC_STATS_FIELD_OFF(rx_minto64)},
{"gmac_rx_short_err", MAC_STATS_FIELD_OFF(rx_under_min)},
{"gmac_rx_filt_pkt", MAC_STATS_FIELD_OFF(rx_filter_pkts)},
{"gmac_rx_octets_total_filt", MAC_STATS_FIELD_OFF(rx_filter_bytes)},
{"gmac_rx_overrun_cnt", MAC_STATS_FIELD_OFF(rx_fifo_overrun_err)},
{"gmac_rx_length_err", MAC_STATS_FIELD_OFF(rx_len_err)},
{"gmac_rx_fail_comma", MAC_STATS_FIELD_OFF(rx_comma_err)},
{"gmac_tx_octets_ok", MAC_STATS_FIELD_OFF(tx_good_bytes)},
{"gmac_tx_octets_bad", MAC_STATS_FIELD_OFF(tx_bad_bytes)},
{"gmac_tx_uc_pkts", MAC_STATS_FIELD_OFF(tx_uc_pkts)},
{"gmac_tx_mc_pkts", MAC_STATS_FIELD_OFF(tx_mc_pkts)},
{"gmac_tx_bc_pkts", MAC_STATS_FIELD_OFF(tx_bc_pkts)},
{"gmac_tx_pkts_64octets", MAC_STATS_FIELD_OFF(tx_64bytes)},
{"gmac_tx_pkts_65to127", MAC_STATS_FIELD_OFF(tx_65to127)},
{"gmac_tx_pkts_128to255", MAC_STATS_FIELD_OFF(tx_128to255)},
{"gmac_tx_pkts_256to511", MAC_STATS_FIELD_OFF(tx_256to511)},
{"gmac_tx_pkts_512to1023", MAC_STATS_FIELD_OFF(tx_512to1023)},
{"gmac_tx_pkts_1024to1518", MAC_STATS_FIELD_OFF(tx_1024to1518)},
{"gmac_tx_pkts_1519tomax", MAC_STATS_FIELD_OFF(tx_1519tomax)},
{"gmac_tx_excessive_length_drop", MAC_STATS_FIELD_OFF(tx_jabber_err)},
{"gmac_tx_underrun", MAC_STATS_FIELD_OFF(tx_underrun_err)},
{"gmac_tx_tagged", MAC_STATS_FIELD_OFF(tx_vlan)},
{"gmac_tx_crc_error", MAC_STATS_FIELD_OFF(tx_crc_err)},
{"gmac_tx_pause_frames", MAC_STATS_FIELD_OFF(tx_pfc_tc0)}
};
static void hns_gmac_enable(void *mac_drv, enum mac_commom_mode mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
/*enable GE rX/tX */
if ((mode == MAC_COMM_MODE_TX) || (mode == MAC_COMM_MODE_RX_AND_TX))
dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_TX_EN_B, 1);
if ((mode == MAC_COMM_MODE_RX) || (mode == MAC_COMM_MODE_RX_AND_TX))
dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_RX_EN_B, 1);
}
static void hns_gmac_disable(void *mac_drv, enum mac_commom_mode mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
/*disable GE rX/tX */
if ((mode == MAC_COMM_MODE_TX) || (mode == MAC_COMM_MODE_RX_AND_TX))
dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_TX_EN_B, 0);
if ((mode == MAC_COMM_MODE_RX) || (mode == MAC_COMM_MODE_RX_AND_TX))
dsaf_set_dev_bit(drv, GMAC_PORT_EN_REG, GMAC_PORT_RX_EN_B, 0);
}
/* hns_gmac_get_en - get port enable
* @mac_drv:mac device
* @rx:rx enable
* @tx:tx enable
*/
static void hns_gmac_get_en(void *mac_drv, u32 *rx, u32 *tx)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 porten;
porten = dsaf_read_dev(drv, GMAC_PORT_EN_REG);
*tx = dsaf_get_bit(porten, GMAC_PORT_TX_EN_B);
*rx = dsaf_get_bit(porten, GMAC_PORT_RX_EN_B);
}
static void hns_gmac_free(void *mac_drv)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct dsaf_device *dsaf_dev
= (struct dsaf_device *)dev_get_drvdata(drv->dev);
u32 mac_id = drv->mac_id;
dsaf_dev->misc_op->ge_srst(dsaf_dev, mac_id, 0);
}
static void hns_gmac_set_tx_auto_pause_frames(void *mac_drv, u16 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_field(drv, GMAC_FC_TX_TIMER_REG, GMAC_FC_TX_TIMER_M,
GMAC_FC_TX_TIMER_S, newval);
}
static void hns_gmac_get_tx_auto_pause_frames(void *mac_drv, u16 *newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
*newval = dsaf_get_dev_field(drv, GMAC_FC_TX_TIMER_REG,
GMAC_FC_TX_TIMER_M, GMAC_FC_TX_TIMER_S);
}
static void hns_gmac_set_rx_auto_pause_frames(void *mac_drv, u32 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_bit(drv, GMAC_PAUSE_EN_REG,
GMAC_PAUSE_EN_RX_FDFC_B, !!newval);
}
static void hns_gmac_config_max_frame_length(void *mac_drv, u16 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_field(drv, GMAC_MAX_FRM_SIZE_REG, GMAC_MAX_FRM_SIZE_M,
GMAC_MAX_FRM_SIZE_S, newval);
dsaf_set_dev_field(drv, GAMC_RX_MAX_FRAME, GMAC_MAX_FRM_SIZE_M,
GMAC_MAX_FRM_SIZE_S, newval);
}
static void hns_gmac_config_pad_and_crc(void *mac_drv, u8 newval)
{
u32 tx_ctrl;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
tx_ctrl = dsaf_read_dev(drv, GMAC_TRANSMIT_CONTROL_REG);
dsaf_set_bit(tx_ctrl, GMAC_TX_PAD_EN_B, !!newval);
dsaf_set_bit(tx_ctrl, GMAC_TX_CRC_ADD_B, !!newval);
dsaf_write_dev(drv, GMAC_TRANSMIT_CONTROL_REG, tx_ctrl);
}
static void hns_gmac_config_an_mode(void *mac_drv, u8 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_bit(drv, GMAC_TRANSMIT_CONTROL_REG,
GMAC_TX_AN_EN_B, !!newval);
}
static void hns_gmac_tx_loop_pkt_dis(void *mac_drv)
{
u32 tx_loop_pkt_pri;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
tx_loop_pkt_pri = dsaf_read_dev(drv, GMAC_TX_LOOP_PKT_PRI_REG);
dsaf_set_bit(tx_loop_pkt_pri, GMAC_TX_LOOP_PKT_EN_B, 1);
dsaf_set_bit(tx_loop_pkt_pri, GMAC_TX_LOOP_PKT_HIG_PRI_B, 0);
dsaf_write_dev(drv, GMAC_TX_LOOP_PKT_PRI_REG, tx_loop_pkt_pri);
}
static void hns_gmac_set_duplex_type(void *mac_drv, u8 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_bit(drv, GMAC_DUPLEX_TYPE_REG,
GMAC_DUPLEX_TYPE_B, !!newval);
}
static void hns_gmac_get_duplex_type(void *mac_drv,
enum hns_gmac_duplex_mdoe *duplex_mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
*duplex_mode = (enum hns_gmac_duplex_mdoe)dsaf_get_dev_bit(
drv, GMAC_DUPLEX_TYPE_REG, GMAC_DUPLEX_TYPE_B);
}
static void hns_gmac_get_port_mode(void *mac_drv, enum hns_port_mode *port_mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
*port_mode = (enum hns_port_mode)dsaf_get_dev_field(
drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S);
}
static void hns_gmac_port_mode_get(void *mac_drv,
struct hns_gmac_port_mode_cfg *port_mode)
{
u32 tx_ctrl;
u32 recv_ctrl;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
port_mode->port_mode = (enum hns_port_mode)dsaf_get_dev_field(
drv, GMAC_PORT_MODE_REG, GMAC_PORT_MODE_M, GMAC_PORT_MODE_S);
tx_ctrl = dsaf_read_dev(drv, GMAC_TRANSMIT_CONTROL_REG);
recv_ctrl = dsaf_read_dev(drv, GMAC_RECV_CONTROL_REG);
port_mode->max_frm_size =
dsaf_get_dev_field(drv, GMAC_MAX_FRM_SIZE_REG,
GMAC_MAX_FRM_SIZE_M, GMAC_MAX_FRM_SIZE_S);
port_mode->short_runts_thr =
dsaf_get_dev_field(drv, GMAC_SHORT_RUNTS_THR_REG,
GMAC_SHORT_RUNTS_THR_M,
GMAC_SHORT_RUNTS_THR_S);
port_mode->pad_enable = dsaf_get_bit(tx_ctrl, GMAC_TX_PAD_EN_B);
port_mode->crc_add = dsaf_get_bit(tx_ctrl, GMAC_TX_CRC_ADD_B);
port_mode->an_enable = dsaf_get_bit(tx_ctrl, GMAC_TX_AN_EN_B);
port_mode->runt_pkt_en =
dsaf_get_bit(recv_ctrl, GMAC_RECV_CTRL_RUNT_PKT_EN_B);
port_mode->strip_pad_en =
dsaf_get_bit(recv_ctrl, GMAC_RECV_CTRL_STRIP_PAD_EN_B);
}
static void hns_gmac_pause_frm_cfg(void *mac_drv, u32 rx_pause_en,
u32 tx_pause_en)
{
u32 pause_en;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
pause_en = dsaf_read_dev(drv, GMAC_PAUSE_EN_REG);
dsaf_set_bit(pause_en, GMAC_PAUSE_EN_RX_FDFC_B, !!rx_pause_en);
dsaf_set_bit(pause_en, GMAC_PAUSE_EN_TX_FDFC_B, !!tx_pause_en);
dsaf_write_dev(drv, GMAC_PAUSE_EN_REG, pause_en);
}
static void hns_gmac_get_pausefrm_cfg(void *mac_drv, u32 *rx_pause_en,
u32 *tx_pause_en)
{
u32 pause_en;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
pause_en = dsaf_read_dev(drv, GMAC_PAUSE_EN_REG);
*rx_pause_en = dsaf_get_bit(pause_en, GMAC_PAUSE_EN_RX_FDFC_B);
*tx_pause_en = dsaf_get_bit(pause_en, GMAC_PAUSE_EN_TX_FDFC_B);
}
static int hns_gmac_adjust_link(void *mac_drv, enum mac_speed speed,
u32 full_duplex)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_bit(drv, GMAC_DUPLEX_TYPE_REG,
GMAC_DUPLEX_TYPE_B, !!full_duplex);
switch (speed) {
case MAC_SPEED_10:
dsaf_set_dev_field(
drv, GMAC_PORT_MODE_REG,
GMAC_PORT_MODE_M, GMAC_PORT_MODE_S, 0x6);
break;
case MAC_SPEED_100:
dsaf_set_dev_field(
drv, GMAC_PORT_MODE_REG,
GMAC_PORT_MODE_M, GMAC_PORT_MODE_S, 0x7);
break;
case MAC_SPEED_1000:
dsaf_set_dev_field(
drv, GMAC_PORT_MODE_REG,
GMAC_PORT_MODE_M, GMAC_PORT_MODE_S, 0x8);
break;
default:
dev_err(drv->dev,
"hns_gmac_adjust_link fail, speed%d mac%d\n",
speed, drv->mac_id);
return -EINVAL;
}
return 0;
}
static void hns_gmac_set_uc_match(void *mac_drv, u16 en)
{
struct mac_driver *drv = mac_drv;
dsaf_set_dev_bit(drv, GMAC_REC_FILT_CONTROL_REG,
GMAC_UC_MATCH_EN_B, !en);
dsaf_set_dev_bit(drv, GMAC_STATION_ADDR_HIGH_2_REG,
GMAC_ADDR_EN_B, !en);
}
static void hns_gmac_set_promisc(void *mac_drv, u8 en)
{
struct mac_driver *drv = mac_drv;
if (drv->mac_cb->mac_type == HNAE_PORT_DEBUG)
hns_gmac_set_uc_match(mac_drv, en);
}
static void hns_gmac_init(void *mac_drv)
{
u32 port;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct dsaf_device *dsaf_dev
= (struct dsaf_device *)dev_get_drvdata(drv->dev);
port = drv->mac_id;
dsaf_dev->misc_op->ge_srst(dsaf_dev, port, 0);
mdelay(10);
dsaf_dev->misc_op->ge_srst(dsaf_dev, port, 1);
mdelay(10);
hns_gmac_disable(mac_drv, MAC_COMM_MODE_RX_AND_TX);
hns_gmac_tx_loop_pkt_dis(mac_drv);
if (drv->mac_cb->mac_type == HNAE_PORT_DEBUG)
hns_gmac_set_uc_match(mac_drv, 0);
hns_gmac_config_pad_and_crc(mac_drv, 1);
dsaf_set_dev_bit(drv, GMAC_MODE_CHANGE_EN_REG,
GMAC_MODE_CHANGE_EB_B, 1);
/* reduce gmac tx water line to avoid gmac hang-up
* in speed 100M and duplex half.
*/
dsaf_set_dev_field(drv, GMAC_TX_WATER_LINE_REG, GMAC_TX_WATER_LINE_MASK,
GMAC_TX_WATER_LINE_SHIFT, 8);
}
void hns_gmac_update_stats(void *mac_drv)
{
struct mac_hw_stats *hw_stats = NULL;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
hw_stats = &drv->mac_cb->hw_stats;
/* RX */
hw_stats->rx_good_bytes
+= dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_OK_REG);
hw_stats->rx_bad_bytes
+= dsaf_read_dev(drv, GMAC_RX_OCTETS_BAD_REG);
hw_stats->rx_uc_pkts += dsaf_read_dev(drv, GMAC_RX_UC_PKTS_REG);
hw_stats->rx_mc_pkts += dsaf_read_dev(drv, GMAC_RX_MC_PKTS_REG);
hw_stats->rx_bc_pkts += dsaf_read_dev(drv, GMAC_RX_BC_PKTS_REG);
hw_stats->rx_64bytes
+= dsaf_read_dev(drv, GMAC_RX_PKTS_64OCTETS_REG);
hw_stats->rx_65to127
+= dsaf_read_dev(drv, GMAC_RX_PKTS_65TO127OCTETS_REG);
hw_stats->rx_128to255
+= dsaf_read_dev(drv, GMAC_RX_PKTS_128TO255OCTETS_REG);
hw_stats->rx_256to511
+= dsaf_read_dev(drv, GMAC_RX_PKTS_255TO511OCTETS_REG);
hw_stats->rx_512to1023
+= dsaf_read_dev(drv, GMAC_RX_PKTS_512TO1023OCTETS_REG);
hw_stats->rx_1024to1518
+= dsaf_read_dev(drv, GMAC_RX_PKTS_1024TO1518OCTETS_REG);
hw_stats->rx_1519tomax
+= dsaf_read_dev(drv, GMAC_RX_PKTS_1519TOMAXOCTETS_REG);
hw_stats->rx_fcs_err += dsaf_read_dev(drv, GMAC_RX_FCS_ERRORS_REG);
hw_stats->rx_vlan_pkts += dsaf_read_dev(drv, GMAC_RX_TAGGED_REG);
hw_stats->rx_data_err += dsaf_read_dev(drv, GMAC_RX_DATA_ERR_REG);
hw_stats->rx_align_err
+= dsaf_read_dev(drv, GMAC_RX_ALIGN_ERRORS_REG);
hw_stats->rx_oversize
+= dsaf_read_dev(drv, GMAC_RX_LONG_ERRORS_REG);
hw_stats->rx_jabber_err
+= dsaf_read_dev(drv, GMAC_RX_JABBER_ERRORS_REG);
hw_stats->rx_pfc_tc0
+= dsaf_read_dev(drv, GMAC_RX_PAUSE_MACCTRL_FRAM_REG);
hw_stats->rx_unknown_ctrl
+= dsaf_read_dev(drv, GMAC_RX_UNKNOWN_MACCTRL_FRAM_REG);
hw_stats->rx_long_err
+= dsaf_read_dev(drv, GMAC_RX_VERY_LONG_ERR_CNT_REG);
hw_stats->rx_minto64
+= dsaf_read_dev(drv, GMAC_RX_RUNT_ERR_CNT_REG);
hw_stats->rx_under_min
+= dsaf_read_dev(drv, GMAC_RX_SHORT_ERR_CNT_REG);
hw_stats->rx_filter_pkts
+= dsaf_read_dev(drv, GMAC_RX_FILT_PKT_CNT_REG);
hw_stats->rx_filter_bytes
+= dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_FILT_REG);
hw_stats->rx_fifo_overrun_err
+= dsaf_read_dev(drv, GMAC_RX_OVERRUN_CNT_REG);
hw_stats->rx_len_err
+= dsaf_read_dev(drv, GMAC_RX_LENGTHFIELD_ERR_CNT_REG);
hw_stats->rx_comma_err
+= dsaf_read_dev(drv, GMAC_RX_FAIL_COMMA_CNT_REG);
/* TX */
hw_stats->tx_good_bytes
+= dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_OK_REG);
hw_stats->tx_bad_bytes
+= dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_BAD_REG);
hw_stats->tx_uc_pkts += dsaf_read_dev(drv, GMAC_TX_UC_PKTS_REG);
hw_stats->tx_mc_pkts += dsaf_read_dev(drv, GMAC_TX_MC_PKTS_REG);
hw_stats->tx_bc_pkts += dsaf_read_dev(drv, GMAC_TX_BC_PKTS_REG);
hw_stats->tx_64bytes
+= dsaf_read_dev(drv, GMAC_TX_PKTS_64OCTETS_REG);
hw_stats->tx_65to127
+= dsaf_read_dev(drv, GMAC_TX_PKTS_65TO127OCTETS_REG);
hw_stats->tx_128to255
+= dsaf_read_dev(drv, GMAC_TX_PKTS_128TO255OCTETS_REG);
hw_stats->tx_256to511
+= dsaf_read_dev(drv, GMAC_TX_PKTS_255TO511OCTETS_REG);
hw_stats->tx_512to1023
+= dsaf_read_dev(drv, GMAC_TX_PKTS_512TO1023OCTETS_REG);
hw_stats->tx_1024to1518
+= dsaf_read_dev(drv, GMAC_TX_PKTS_1024TO1518OCTETS_REG);
hw_stats->tx_1519tomax
+= dsaf_read_dev(drv, GMAC_TX_PKTS_1519TOMAXOCTETS_REG);
hw_stats->tx_jabber_err
+= dsaf_read_dev(drv, GMAC_TX_EXCESSIVE_LENGTH_DROP_REG);
hw_stats->tx_underrun_err
+= dsaf_read_dev(drv, GMAC_TX_UNDERRUN_REG);
hw_stats->tx_vlan += dsaf_read_dev(drv, GMAC_TX_TAGGED_REG);
hw_stats->tx_crc_err += dsaf_read_dev(drv, GMAC_TX_CRC_ERROR_REG);
hw_stats->tx_pfc_tc0
+= dsaf_read_dev(drv, GMAC_TX_PAUSE_FRAMES_REG);
}
static void hns_gmac_set_mac_addr(void *mac_drv, char *mac_addr)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 high_val = mac_addr[1] | (mac_addr[0] << 8);
u32 low_val = mac_addr[5] | (mac_addr[4] << 8)
| (mac_addr[3] << 16) | (mac_addr[2] << 24);
u32 val = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_2_REG);
u32 sta_addr_en = dsaf_get_bit(val, GMAC_ADDR_EN_B);
dsaf_write_dev(drv, GMAC_STATION_ADDR_LOW_2_REG, low_val);
dsaf_write_dev(drv, GMAC_STATION_ADDR_HIGH_2_REG,
high_val | (sta_addr_en << GMAC_ADDR_EN_B));
}
static int hns_gmac_config_loopback(void *mac_drv, enum hnae_loop loop_mode,
u8 enable)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
switch (loop_mode) {
case MAC_INTERNALLOOP_MAC:
dsaf_set_dev_bit(drv, GMAC_LOOP_REG, GMAC_LP_REG_CF2MI_LP_EN_B,
!!enable);
break;
default:
dev_err(drv->dev, "loop_mode error\n");
return -EINVAL;
}
return 0;
}
static void hns_gmac_get_info(void *mac_drv, struct mac_info *mac_info)
{
enum hns_gmac_duplex_mdoe duplex;
enum hns_port_mode speed;
u32 rx_pause;
u32 tx_pause;
u32 rx;
u32 tx;
u16 fc_tx_timer;
struct hns_gmac_port_mode_cfg port_mode = { GMAC_10M_MII, 0 };
hns_gmac_port_mode_get(mac_drv, &port_mode);
mac_info->pad_and_crc_en = port_mode.crc_add && port_mode.pad_enable;
mac_info->auto_neg = port_mode.an_enable;
hns_gmac_get_tx_auto_pause_frames(mac_drv, &fc_tx_timer);
mac_info->tx_pause_time = fc_tx_timer;
hns_gmac_get_en(mac_drv, &rx, &tx);
mac_info->port_en = rx && tx;
hns_gmac_get_duplex_type(mac_drv, &duplex);
mac_info->duplex = duplex;
hns_gmac_get_port_mode(mac_drv, &speed);
switch (speed) {
case GMAC_10M_SGMII:
mac_info->speed = MAC_SPEED_10;
break;
case GMAC_100M_SGMII:
mac_info->speed = MAC_SPEED_100;
break;
case GMAC_1000M_SGMII:
mac_info->speed = MAC_SPEED_1000;
break;
default:
mac_info->speed = 0;
break;
}
hns_gmac_get_pausefrm_cfg(mac_drv, &rx_pause, &tx_pause);
mac_info->rx_pause_en = rx_pause;
mac_info->tx_pause_en = tx_pause;
}
static void hns_gmac_autoneg_stat(void *mac_drv, u32 *enable)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
*enable = dsaf_get_dev_bit(drv, GMAC_TRANSMIT_CONTROL_REG,
GMAC_TX_AN_EN_B);
}
static void hns_gmac_get_link_status(void *mac_drv, u32 *link_stat)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
*link_stat = dsaf_get_dev_bit(drv, GMAC_AN_NEG_STATE_REG,
GMAC_AN_NEG_STAT_RX_SYNC_OK_B);
}
static void hns_gmac_get_regs(void *mac_drv, void *data)
{
u32 *regs = data;
int i;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
/* base config registers */
regs[0] = dsaf_read_dev(drv, GMAC_DUPLEX_TYPE_REG);
regs[1] = dsaf_read_dev(drv, GMAC_FD_FC_TYPE_REG);
regs[2] = dsaf_read_dev(drv, GMAC_FC_TX_TIMER_REG);
regs[3] = dsaf_read_dev(drv, GMAC_FD_FC_ADDR_LOW_REG);
regs[4] = dsaf_read_dev(drv, GMAC_FD_FC_ADDR_HIGH_REG);
regs[5] = dsaf_read_dev(drv, GMAC_IPG_TX_TIMER_REG);
regs[6] = dsaf_read_dev(drv, GMAC_PAUSE_THR_REG);
regs[7] = dsaf_read_dev(drv, GMAC_MAX_FRM_SIZE_REG);
regs[8] = dsaf_read_dev(drv, GMAC_PORT_MODE_REG);
regs[9] = dsaf_read_dev(drv, GMAC_PORT_EN_REG);
regs[10] = dsaf_read_dev(drv, GMAC_PAUSE_EN_REG);
regs[11] = dsaf_read_dev(drv, GMAC_SHORT_RUNTS_THR_REG);
regs[12] = dsaf_read_dev(drv, GMAC_AN_NEG_STATE_REG);
regs[13] = dsaf_read_dev(drv, GMAC_TX_LOCAL_PAGE_REG);
regs[14] = dsaf_read_dev(drv, GMAC_TRANSMIT_CONTROL_REG);
regs[15] = dsaf_read_dev(drv, GMAC_REC_FILT_CONTROL_REG);
regs[16] = dsaf_read_dev(drv, GMAC_PTP_CONFIG_REG);
/* rx static registers */
regs[17] = dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_OK_REG);
regs[18] = dsaf_read_dev(drv, GMAC_RX_OCTETS_BAD_REG);
regs[19] = dsaf_read_dev(drv, GMAC_RX_UC_PKTS_REG);
regs[20] = dsaf_read_dev(drv, GMAC_RX_MC_PKTS_REG);
regs[21] = dsaf_read_dev(drv, GMAC_RX_BC_PKTS_REG);
regs[22] = dsaf_read_dev(drv, GMAC_RX_PKTS_64OCTETS_REG);
regs[23] = dsaf_read_dev(drv, GMAC_RX_PKTS_65TO127OCTETS_REG);
regs[24] = dsaf_read_dev(drv, GMAC_RX_PKTS_128TO255OCTETS_REG);
regs[25] = dsaf_read_dev(drv, GMAC_RX_PKTS_255TO511OCTETS_REG);
regs[26] = dsaf_read_dev(drv, GMAC_RX_PKTS_512TO1023OCTETS_REG);
regs[27] = dsaf_read_dev(drv, GMAC_RX_PKTS_1024TO1518OCTETS_REG);
regs[28] = dsaf_read_dev(drv, GMAC_RX_PKTS_1519TOMAXOCTETS_REG);
regs[29] = dsaf_read_dev(drv, GMAC_RX_FCS_ERRORS_REG);
regs[30] = dsaf_read_dev(drv, GMAC_RX_TAGGED_REG);
regs[31] = dsaf_read_dev(drv, GMAC_RX_DATA_ERR_REG);
regs[32] = dsaf_read_dev(drv, GMAC_RX_ALIGN_ERRORS_REG);
regs[33] = dsaf_read_dev(drv, GMAC_RX_LONG_ERRORS_REG);
regs[34] = dsaf_read_dev(drv, GMAC_RX_JABBER_ERRORS_REG);
regs[35] = dsaf_read_dev(drv, GMAC_RX_PAUSE_MACCTRL_FRAM_REG);
regs[36] = dsaf_read_dev(drv, GMAC_RX_UNKNOWN_MACCTRL_FRAM_REG);
regs[37] = dsaf_read_dev(drv, GMAC_RX_VERY_LONG_ERR_CNT_REG);
regs[38] = dsaf_read_dev(drv, GMAC_RX_RUNT_ERR_CNT_REG);
regs[39] = dsaf_read_dev(drv, GMAC_RX_SHORT_ERR_CNT_REG);
regs[40] = dsaf_read_dev(drv, GMAC_RX_FILT_PKT_CNT_REG);
regs[41] = dsaf_read_dev(drv, GMAC_RX_OCTETS_TOTAL_FILT_REG);
/* tx static registers */
regs[42] = dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_OK_REG);
regs[43] = dsaf_read_dev(drv, GMAC_OCTETS_TRANSMITTED_BAD_REG);
regs[44] = dsaf_read_dev(drv, GMAC_TX_UC_PKTS_REG);
regs[45] = dsaf_read_dev(drv, GMAC_TX_MC_PKTS_REG);
regs[46] = dsaf_read_dev(drv, GMAC_TX_BC_PKTS_REG);
regs[47] = dsaf_read_dev(drv, GMAC_TX_PKTS_64OCTETS_REG);
regs[48] = dsaf_read_dev(drv, GMAC_TX_PKTS_65TO127OCTETS_REG);
regs[49] = dsaf_read_dev(drv, GMAC_TX_PKTS_128TO255OCTETS_REG);
regs[50] = dsaf_read_dev(drv, GMAC_TX_PKTS_255TO511OCTETS_REG);
regs[51] = dsaf_read_dev(drv, GMAC_TX_PKTS_512TO1023OCTETS_REG);
regs[52] = dsaf_read_dev(drv, GMAC_TX_PKTS_1024TO1518OCTETS_REG);
regs[53] = dsaf_read_dev(drv, GMAC_TX_PKTS_1519TOMAXOCTETS_REG);
regs[54] = dsaf_read_dev(drv, GMAC_TX_EXCESSIVE_LENGTH_DROP_REG);
regs[55] = dsaf_read_dev(drv, GMAC_TX_UNDERRUN_REG);
regs[56] = dsaf_read_dev(drv, GMAC_TX_TAGGED_REG);
regs[57] = dsaf_read_dev(drv, GMAC_TX_CRC_ERROR_REG);
regs[58] = dsaf_read_dev(drv, GMAC_TX_PAUSE_FRAMES_REG);
regs[59] = dsaf_read_dev(drv, GAMC_RX_MAX_FRAME);
regs[60] = dsaf_read_dev(drv, GMAC_LINE_LOOP_BACK_REG);
regs[61] = dsaf_read_dev(drv, GMAC_CF_CRC_STRIP_REG);
regs[62] = dsaf_read_dev(drv, GMAC_MODE_CHANGE_EN_REG);
regs[63] = dsaf_read_dev(drv, GMAC_SIXTEEN_BIT_CNTR_REG);
regs[64] = dsaf_read_dev(drv, GMAC_LD_LINK_COUNTER_REG);
regs[65] = dsaf_read_dev(drv, GMAC_LOOP_REG);
regs[66] = dsaf_read_dev(drv, GMAC_RECV_CONTROL_REG);
regs[67] = dsaf_read_dev(drv, GMAC_VLAN_CODE_REG);
regs[68] = dsaf_read_dev(drv, GMAC_RX_OVERRUN_CNT_REG);
regs[69] = dsaf_read_dev(drv, GMAC_RX_LENGTHFIELD_ERR_CNT_REG);
regs[70] = dsaf_read_dev(drv, GMAC_RX_FAIL_COMMA_CNT_REG);
regs[71] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_0_REG);
regs[72] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_0_REG);
regs[73] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_1_REG);
regs[74] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_1_REG);
regs[75] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_2_REG);
regs[76] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_2_REG);
regs[77] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_3_REG);
regs[78] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_3_REG);
regs[79] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_4_REG);
regs[80] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_4_REG);
regs[81] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_5_REG);
regs[82] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_5_REG);
regs[83] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_MSK_0_REG);
regs[84] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_MSK_0_REG);
regs[85] = dsaf_read_dev(drv, GMAC_STATION_ADDR_LOW_MSK_1_REG);
regs[86] = dsaf_read_dev(drv, GMAC_STATION_ADDR_HIGH_MSK_1_REG);
regs[87] = dsaf_read_dev(drv, GMAC_MAC_SKIP_LEN_REG);
regs[88] = dsaf_read_dev(drv, GMAC_TX_LOOP_PKT_PRI_REG);
/* mark end of mac regs */
for (i = 89; i < 96; i++)
regs[i] = 0xaaaaaaaa;
}
static void hns_gmac_get_stats(void *mac_drv, u64 *data)
{
u32 i;
u64 *buf = data;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct mac_hw_stats *hw_stats = NULL;
hw_stats = &drv->mac_cb->hw_stats;
for (i = 0; i < ARRAY_SIZE(g_gmac_stats_string); i++) {
buf[i] = DSAF_STATS_READ(hw_stats,
g_gmac_stats_string[i].offset);
}
}
static void hns_gmac_get_strings(u32 stringset, u8 *data)
{
char *buff = (char *)data;
u32 i;
if (stringset != ETH_SS_STATS)
return;
for (i = 0; i < ARRAY_SIZE(g_gmac_stats_string); i++) {
snprintf(buff, ETH_GSTRING_LEN, "%s",
g_gmac_stats_string[i].desc);
buff = buff + ETH_GSTRING_LEN;
}
}
static int hns_gmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ARRAY_SIZE(g_gmac_stats_string);
return 0;
}
static int hns_gmac_get_regs_count(void)
{
return ETH_GMAC_DUMP_NUM;
}
void *hns_gmac_config(struct hns_mac_cb *mac_cb, struct mac_params *mac_param)
{
struct mac_driver *mac_drv;
mac_drv = devm_kzalloc(mac_cb->dev, sizeof(*mac_drv), GFP_KERNEL);
if (!mac_drv)
return NULL;
mac_drv->mac_init = hns_gmac_init;
mac_drv->mac_enable = hns_gmac_enable;
mac_drv->mac_disable = hns_gmac_disable;
mac_drv->mac_free = hns_gmac_free;
mac_drv->adjust_link = hns_gmac_adjust_link;
mac_drv->set_tx_auto_pause_frames = hns_gmac_set_tx_auto_pause_frames;
mac_drv->config_max_frame_length = hns_gmac_config_max_frame_length;
mac_drv->mac_pausefrm_cfg = hns_gmac_pause_frm_cfg;
mac_drv->mac_id = mac_param->mac_id;
mac_drv->mac_mode = mac_param->mac_mode;
mac_drv->io_base = mac_param->vaddr;
mac_drv->dev = mac_param->dev;
mac_drv->mac_cb = mac_cb;
mac_drv->set_mac_addr = hns_gmac_set_mac_addr;
mac_drv->set_an_mode = hns_gmac_config_an_mode;
mac_drv->config_loopback = hns_gmac_config_loopback;
mac_drv->config_pad_and_crc = hns_gmac_config_pad_and_crc;
mac_drv->config_half_duplex = hns_gmac_set_duplex_type;
mac_drv->set_rx_ignore_pause_frames = hns_gmac_set_rx_auto_pause_frames;
mac_drv->get_info = hns_gmac_get_info;
mac_drv->autoneg_stat = hns_gmac_autoneg_stat;
mac_drv->get_pause_enable = hns_gmac_get_pausefrm_cfg;
mac_drv->get_link_status = hns_gmac_get_link_status;
mac_drv->get_regs = hns_gmac_get_regs;
mac_drv->get_regs_count = hns_gmac_get_regs_count;
mac_drv->get_ethtool_stats = hns_gmac_get_stats;
mac_drv->get_sset_count = hns_gmac_get_sset_count;
mac_drv->get_strings = hns_gmac_get_strings;
mac_drv->update_stats = hns_gmac_update_stats;
mac_drv->set_promiscuous = hns_gmac_set_promisc;
return (void *)mac_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3020_0 |
crossvul-cpp_data_good_395_5 | /*
Copyright 1996-2014 Han The Thanh <thanh@pdftex.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, see <http://www.gnu.org/licenses/>. */
#include "ptexlib.h"
#include <stdarg.h>
#include <string.h>
#define t1_log(str) tex_printf("%s",str)
#define get_length1() t1_length1 = t1_offset() - t1_save_offset
#define get_length2() t1_length2 = t1_offset() - t1_save_offset
#define get_length3() t1_length3 = fixedcontent? t1_offset() - t1_save_offset : 0
#define save_offset() t1_save_offset = t1_offset()
#define t1_open() open_input(&t1_file, kpse_type1_format, FOPEN_RBIN_MODE)
#define t1_close() xfclose(t1_file, cur_file_name)
#define t1_getchar() getc(t1_file)
#define t1_putchar fb_putchar
#define t1_offset fb_offset
#define t1_ungetchar(c) ungetc(c, t1_file)
#define t1_eof() feof(t1_file)
#define t1_prefix(s) str_prefix(t1_line_array, s)
#define t1_buf_prefix(s) str_prefix(t1_buf_array, s)
#define t1_suffix(s) str_suffix(t1_line_array, t1_line_ptr, s)
#define t1_buf_suffix(s) str_suffix(t1_buf_array, t1_buf_ptr, s)
#define t1_charstrings() strstr(t1_line_array, charstringname)
#define t1_subrs() t1_prefix("/Subrs")
#define t1_end_eexec() t1_suffix("mark currentfile closefile")
#define t1_cleartomark() t1_prefix("cleartomark")
#define enc_open() open_input(&enc_file, kpse_enc_format, FOPEN_RBIN_MODE)
#define enc_close() xfclose(enc_file, cur_file_name)
#define enc_getchar() getc(enc_file)
#define enc_eof() feof(enc_file)
#define valid_code(c) (c >= 0 && c < 256)
#define fixedcontent false /* false for pdfTeX, true for dvips */
static const char *standard_glyph_names[256] = {
/* 0x00 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0x10 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0x20 */
"space", "exclam", "quotedbl", "numbersign", "dollar", "percent",
"ampersand", "quoteright", "parenleft", "parenright", "asterisk",
"plus", "comma", "hyphen", "period", "slash",
/* 0x30 */
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "colon", "semicolon", "less", "equal", "greater", "question",
/* 0x40 */
"at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O",
/* 0x50 */
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft",
"backslash", "bracketright", "asciicircum", "underscore",
/* 0x60 */
"quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o",
/* 0x70 */
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar",
"braceright", "asciitilde", notdef,
/* 0x80 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0x90 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0xa0 */
notdef, "exclamdown", "cent", "sterling", "fraction", "yen", "florin",
"section", "currency", "quotesingle", "quotedblleft", "guillemotleft",
"guilsinglleft", "guilsinglright", "fi", "fl",
/* 0xb0 */
notdef, "endash", "dagger", "daggerdbl", "periodcentered", notdef,
"paragraph", "bullet", "quotesinglbase", "quotedblbase",
"quotedblright", "guillemotright", "ellipsis", "perthousand", notdef,
"questiondown",
/* 0xc0 */
notdef, "grave", "acute", "circumflex", "tilde", "macron", "breve",
"dotaccent", "dieresis", notdef,
"ring", "cedilla", notdef, "hungarumlaut", "ogonek", "caron",
/* 0xd0 */
"emdash", notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0xe0 */
notdef, "AE", notdef, "ordfeminine", notdef, notdef, notdef, notdef,
"Lslash", "Oslash", "OE", "ordmasculine", notdef, notdef, notdef,
notdef,
/* 0xf0 */
notdef, "ae", notdef, notdef, notdef, "dotlessi", notdef, notdef, "lslash",
"oslash", "oe", "germandbls", notdef, notdef, notdef, notdef
};
integer t1_length1, t1_length2, t1_length3;
static integer t1_save_offset;
static integer t1_fontname_offset;
static fd_entry *fd_cur;
static char charstringname[] = "/CharStrings";
enum { ENC_STANDARD, ENC_BUILTIN } t1_encoding;
#define T1_BUF_SIZE 0x10
#define ENC_BUF_SIZE 0x1000
#define CS_HSTEM 1
#define CS_VSTEM 3
#define CS_VMOVETO 4
#define CS_RLINETO 5
#define CS_HLINETO 6
#define CS_VLINETO 7
#define CS_RRCURVETO 8
#define CS_CLOSEPATH 9
#define CS_CALLSUBR 10
#define CS_RETURN 11
#define CS_ESCAPE 12
#define CS_HSBW 13
#define CS_ENDCHAR 14
#define CS_RMOVETO 21
#define CS_HMOVETO 22
#define CS_VHCURVETO 30
#define CS_HVCURVETO 31
#define CS_1BYTE_MAX (CS_HVCURVETO + 1)
#define CS_DOTSECTION CS_1BYTE_MAX + 0
#define CS_VSTEM3 CS_1BYTE_MAX + 1
#define CS_HSTEM3 CS_1BYTE_MAX + 2
#define CS_SEAC CS_1BYTE_MAX + 6
#define CS_SBW CS_1BYTE_MAX + 7
#define CS_DIV CS_1BYTE_MAX + 12
#define CS_CALLOTHERSUBR CS_1BYTE_MAX + 16
#define CS_POP CS_1BYTE_MAX + 17
#define CS_SETCURRENTPOINT CS_1BYTE_MAX + 33
#define CS_2BYTE_MAX (CS_SETCURRENTPOINT + 1)
#define CS_MAX CS_2BYTE_MAX
typedef unsigned char byte;
typedef struct {
byte nargs; /* number of arguments */
boolean bottom; /* take arguments from bottom of stack? */
boolean clear; /* clear stack? */
boolean valid;
} cc_entry; /* CharString Command */
typedef struct {
char *name; /* glyph name (or notdef for Subrs entry) */
byte *data;
unsigned short len; /* length of the whole string */
unsigned short cslen; /* length of the encoded part of the string */
boolean used;
boolean valid;
} cs_entry;
static unsigned short t1_dr, t1_er;
static const unsigned short t1_c1 = 52845, t1_c2 = 22719;
static unsigned short t1_cslen;
static short t1_lenIV;
static char enc_line[ENC_BUF_SIZE];
/* define t1_line_ptr, t1_line_array & t1_line_limit */
typedef char t1_line_entry;
define_array(t1_line);
/* define t1_buf_ptr, t1_buf_array & t1_buf_limit */
typedef char t1_buf_entry;
define_array(t1_buf);
static int cs_start;
static cs_entry *cs_tab, *cs_ptr, *cs_notdef;
static char *cs_dict_start, *cs_dict_end;
static int cs_count, cs_size, cs_size_pos;
static cs_entry *subr_tab;
static char *subr_array_start, *subr_array_end;
static int subr_max, subr_size, subr_size_pos;
/* This list contains the begin/end tokens commonly used in the */
/* /Subrs array of a Type 1 font. */
static const char *cs_token_pairs_list[][2] = {
{" RD", "NP"},
{" -|", "|"},
{" RD", "noaccess put"},
{" -|", "noaccess put"},
{NULL, NULL}
};
static const char **cs_token_pair;
static boolean t1_pfa, t1_cs, t1_scan, t1_eexec_encrypt, t1_synthetic;
static int t1_in_eexec; /* 0 before eexec-encrypted, 1 during, 2 after */
static long t1_block_length;
static int last_hexbyte;
static FILE *t1_file;
static FILE *enc_file;
static void enc_getline(void)
{
char *p;
int c;
restart:
if (enc_eof())
pdftex_fail("unexpected end of file");
p = enc_line;
do {
c = enc_getchar();
append_char_to_buf(c, p, enc_line, ENC_BUF_SIZE);
} while (c != 10);
append_eol(p, enc_line, ENC_BUF_SIZE);
if (p - enc_line < 2 || *enc_line == '%')
goto restart;
}
/* read encoding from .enc file, return glyph_names array, or pdffail() */
char **load_enc_file(char *enc_name)
{
char buf[ENC_BUF_SIZE], *p, *r;
int i, names_count;
char **glyph_names;
set_cur_file_name(enc_name);
if (!enc_open()) {
pdftex_fail("cannot open encoding file for reading");
}
glyph_names = xtalloc(256, char *);
for (i = 0; i < 256; i++)
glyph_names[i] = notdef;
t1_log("{");
t1_log(cur_file_name = (char *) nameoffile + 1);
enc_getline();
if (*enc_line != '/' || (r = strchr(enc_line, '[')) == NULL) {
remove_eol(r, enc_line);
pdftex_fail
("invalid encoding vector (a name or `[' missing): `%s'", enc_line);
}
names_count = 0;
r++; /* skip '[' */
skip(r, ' ');
for (;;) {
while (*r == '/') {
for (p = buf, r++;
*r != ' ' && *r != 10 && *r != ']' && *r != '/'; *p++ = *r++);
*p = 0;
skip(r, ' ');
if (names_count > 255)
pdftex_fail("encoding vector contains more than 256 names");
if (strcmp(buf, notdef) != 0)
glyph_names[names_count] = xstrdup(buf);
names_count++;
}
if (*r != 10 && *r != '%') {
if (str_prefix(r, "] def"))
goto done;
else {
remove_eol(r, enc_line);
pdftex_fail
("invalid encoding vector: a name or `] def' expected: `%s'", enc_line);
}
}
enc_getline();
r = enc_line;
}
done:
enc_close();
t1_log("}");
cur_file_name = NULL;
return glyph_names;
}
static void t1_check_pfa(void)
{
const int c = t1_getchar();
t1_pfa = (c != 128) ? true : false;
t1_ungetchar(c);
}
static int t1_getbyte(void)
{
int c = t1_getchar();
if (t1_pfa)
return c;
if (t1_block_length == 0) {
if (c != 128)
pdftex_fail("invalid marker");
c = t1_getchar();
if (c == 3) {
while (!t1_eof())
t1_getchar();
return EOF;
}
t1_block_length = t1_getchar() & 0xff;
t1_block_length |= (t1_getchar() & 0xff) << 8;
t1_block_length |= (t1_getchar() & 0xff) << 16;
t1_block_length |= (t1_getchar() & 0xff) << 24;
c = t1_getchar();
}
t1_block_length--;
return c;
}
static int hexval(int c)
{
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
else if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
else if (c >= '0' && c <= '9')
return c - '0';
else
return -1;
}
static byte edecrypt(byte cipher)
{
byte plain;
if (t1_pfa) {
while (cipher == 10 || cipher == 13)
cipher = t1_getbyte();
last_hexbyte = cipher = (hexval(cipher) << 4) + hexval(t1_getbyte());
}
plain = (cipher ^ (t1_dr >> 8));
t1_dr = (cipher + t1_dr) * t1_c1 + t1_c2;
return plain;
}
static byte cdecrypt(byte cipher, unsigned short *cr)
{
const byte plain = (cipher ^ (*cr >> 8));
*cr = (cipher + *cr) * t1_c1 + t1_c2;
return plain;
}
static byte eencrypt(byte plain)
{
const byte cipher = (plain ^ (t1_er >> 8));
t1_er = (cipher + t1_er) * t1_c1 + t1_c2;
return cipher;
}
static byte cencrypt(byte plain, unsigned short *cr)
{
const byte cipher = (plain ^ (*cr >> 8));
*cr = (cipher + *cr) * t1_c1 + t1_c2;
return cipher;
}
static char *eol(char *s)
{
char *p = strend(s);
if (p - s > 1 && p[-1] != 10) {
*p++ = 10;
*p = 0;
}
return p;
}
static float t1_scan_num(char *p, char **r)
{
float f;
skip(p, ' ');
if (sscanf(p, "%g", &f) != 1) {
remove_eol(p, t1_line_array);
pdftex_fail("a number expected: `%s'", t1_line_array);
}
if (r != NULL) {
for (; isdigit((unsigned char)*p) || *p == '.' ||
*p == 'e' || *p == 'E' || *p == '+' || *p == '-'; p++);
*r = p;
}
return f;
}
static boolean str_suffix(const char *begin_buf, const char *end_buf,
const char *s)
{
const char *s1 = end_buf - 1, *s2 = strend(s) - 1;
if (*s1 == 10)
s1--;
while (s1 >= begin_buf && s2 >= s) {
if (*s1-- != *s2--)
return false;
}
return s2 < s;
}
static void t1_getline(void)
{
int c, l, eexec_scan;
char *p;
static const char eexec_str[] = "currentfile eexec";
static int eexec_len = 17; /* strlen(eexec_str) */
restart:
if (t1_eof())
pdftex_fail("unexpected end of file");
t1_line_ptr = t1_line_array;
alloc_array(t1_line, 1, T1_BUF_SIZE);
t1_cslen = 0;
eexec_scan = 0;
c = t1_getbyte();
if (c == EOF)
goto exit;
while (!t1_eof()) {
if (t1_in_eexec == 1)
c = edecrypt((byte)c);
alloc_array(t1_line, 1, T1_BUF_SIZE);
append_char_to_buf(c, t1_line_ptr, t1_line_array, t1_line_limit);
if (t1_in_eexec == 0 && eexec_scan >= 0 && eexec_scan < eexec_len) {
if (t1_line_array[eexec_scan] == eexec_str[eexec_scan])
eexec_scan++;
else
eexec_scan = -1;
}
if (c == 10 || (t1_pfa && eexec_scan == eexec_len && c == 32))
break;
if (t1_cs && t1_cslen == 0 && (t1_line_ptr - t1_line_array > 4) &&
(t1_suffix(" RD ") || t1_suffix(" -| "))) {
p = t1_line_ptr - 5;
while (*p != ' ')
p--;
t1_cslen = l = t1_scan_num(p + 1, 0);
cs_start = t1_line_ptr - t1_line_array; /* cs_start is an index now */
alloc_array(t1_line, l, T1_BUF_SIZE);
while (l-- > 0)
*t1_line_ptr++ = edecrypt((byte)t1_getbyte());
}
c = t1_getbyte();
}
alloc_array(t1_line, 2, T1_BUF_SIZE); /* append_eol can append 2 chars */
append_eol(t1_line_ptr, t1_line_array, t1_line_limit);
if (t1_line_ptr - t1_line_array < 2)
goto restart;
if (eexec_scan == eexec_len)
t1_in_eexec = 1;
exit:
/* ensure that t1_buf_array has as much room as t1_line_array */
t1_buf_ptr = t1_buf_array;
alloc_array(t1_buf, t1_line_limit, t1_line_limit);
}
static void t1_putline(void)
{
char *p = t1_line_array;
if (t1_line_ptr - t1_line_array <= 1)
return;
if (t1_eexec_encrypt) {
while (p < t1_line_ptr)
t1_putchar(eencrypt(*p++));
} else
while (p < t1_line_ptr)
t1_putchar(*p++);
}
static void t1_puts(const char *s)
{
if (s != t1_line_array)
strcpy(t1_line_array, s);
t1_line_ptr = strend(t1_line_array);
t1_putline();
}
__attribute__ ((format(printf, 1, 2)))
static void t1_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsprintf(t1_line_array, fmt, args);
t1_puts(t1_line_array);
va_end(args);
}
static void t1_init_params(const char *open_name_prefix)
{
t1_log(open_name_prefix);
t1_log(cur_file_name);
t1_lenIV = 4;
t1_dr = 55665;
t1_er = 55665;
t1_in_eexec = 0;
t1_cs = false;
t1_scan = true;
t1_synthetic = false;
t1_eexec_encrypt = false;
t1_block_length = 0;
t1_check_pfa();
}
static void t1_close_font_file(const char *close_name_suffix)
{
t1_log(close_name_suffix);
t1_close();
cur_file_name = NULL;
}
static void t1_check_block_len(boolean decrypt)
{
int l, c;
if (t1_block_length == 0)
return;
c = t1_getbyte();
if (decrypt)
c = edecrypt((byte)c);
l = t1_block_length;
if (!(l == 0 && (c == 10 || c == 13))) {
pdftex_fail("%i bytes more than expected", l + 1);
}
}
static void t1_start_eexec(void)
{
int i;
assert(is_included(fd_cur->fm));
get_length1();
save_offset();
if (!t1_pfa)
t1_check_block_len(false);
for (t1_line_ptr = t1_line_array, i = 0; i < 4; i++) {
edecrypt((byte)t1_getbyte());
*t1_line_ptr++ = 0;
}
t1_eexec_encrypt = true;
t1_putline(); /* to put the first four bytes */
}
static void t1_stop_eexec(void)
{
int c;
assert(is_included(fd_cur->fm));
get_length2();
save_offset();
t1_eexec_encrypt = false;
if (!t1_pfa)
t1_check_block_len(true);
else {
c = edecrypt((byte)t1_getbyte());
if (!(c == 10 || c == 13)) {
if (last_hexbyte == 0)
t1_puts("00");
else
pdftex_fail("unexpected data after eexec");
}
}
t1_cs = false;
t1_in_eexec = 2;
}
/* macros for various transforms; currently only slant and extend are used */
#define do_xshift(x,a) {x[4]+=a;}
#define do_yshift(x,a) {x[5]+=a;}
#define do_xscale(x,a) {x[0]*=a; x[2]*=a; x[4]*=a;}
#define do_yscale(x,a) {x[1]*=a; x[3]*=a; x[5]*=a;}
#define do_extend(x,a) {do_xscale(x,a);}
#define do_scale(x,a) {do_xscale(x,a); do_yscale(x,a);}
#define do_slant(x,a) {x[0]+=x[1]*(a); x[2]+=x[3]*(a); x[4]+=x[5]*(a);}
#define do_shear(x,a) {x[1]+=x[0]*(a); x[3]+=x[2]*(a); x[5]+=x[4]*(a);}
#define do_rotate(x,a) \
{float t, u=cos(a), v=sin(a); \
t =x[0]*u+x[1]*-v; \
x[1] =x[0]*v+x[1]* u; x[0]=t; \
t =x[2]*u+x[3]*-v; \
x[3] =x[2]*v+x[3]* u; x[2]=t; \
t =x[4]*u+x[5]*-v; \
x[5] =x[4]*v+x[5]* u; x[4]=t;}
static void t1_modify_fm(void)
{
/*
* font matrix is given as six numbers a0..a5, which stands for the matrix
*
* a0 a1 0
* M = a2 a3 0
* a4 a5 1
*
* ExtendFont is given as
*
* e 0 0
* E = 0 1 0
* 0 0 1
*
* SlantFont is given as
*
* 1 0 0
* S = s 1 0
* 0 0 1
*
* The slant transform must be done _before_ the extend transform
* for compatibility!
*/
float a[6];
int i, c;
char *p, *q, *r;
if ((p = strchr(t1_line_array, '[')) == 0)
if ((p = strchr(t1_line_array, '{')) == 0) {
remove_eol(p, t1_line_array);
pdftex_fail("FontMatrix: an array expected: `%s'", t1_line_array);
}
c = *p++; /* save the character '[' resp. '{' */
strncpy(t1_buf_array, t1_line_array, (size_t) (p - t1_line_array));
r = t1_buf_array + (p - t1_line_array);
for (i = 0; i < 6; i++) {
a[i] = t1_scan_num(p, &q);
p = q;
}
if (fm_slant(fd_cur->fm) != 0)
do_slant(a, fm_slant(fd_cur->fm) * 1E-3);
if (fm_extend(fd_cur->fm) != 0)
do_extend(a, fm_extend(fd_cur->fm) * 1E-3);
for (i = 0; i < 6; i++) {
sprintf(r, "%g ", a[i]);
r = strend(r);
}
if (c == '[') {
while (*p != ']' && *p != 0)
p++;
} else {
while (*p != '}' && *p != 0)
p++;
}
if (*p == 0) {
remove_eol(p, t1_line_array);
pdftex_fail
("FontMatrix: cannot find the corresponding character to '%c': `%s'",
c, t1_line_array);
}
strcpy(r, p);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
static void t1_modify_italic(void)
{
float a;
char *p, *r;
if (fm_slant(fd_cur->fm) == 0)
return;
p = strchr(t1_line_array, ' ');
strncpy(t1_buf_array, t1_line_array, (size_t) (p - t1_line_array + 1));
a = t1_scan_num(p + 1, &r);
a -= atan(fm_slant(fd_cur->fm) * 1E-3) * (180 / M_PI);
sprintf(t1_buf_array + (p - t1_line_array + 1), "%g", a);
strcpy(strend(t1_buf_array), r);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
fd_cur->font_dim[ITALIC_ANGLE_CODE].val = round(a);
fd_cur->font_dim[ITALIC_ANGLE_CODE].set = true;
}
static void t1_scan_keys(void)
{
int i, k;
char *p, *q, *r;
const key_entry *key;
if (fm_extend(fd_cur->fm) != 0 || fm_slant(fd_cur->fm) != 0) {
if (t1_prefix("/FontMatrix")) {
t1_modify_fm();
return;
}
if (t1_prefix("/ItalicAngle")) {
t1_modify_italic();
return;
}
}
if (t1_prefix("/FontType")) {
p = t1_line_array + strlen("FontType") + 1;
if ((i = t1_scan_num(p, 0)) != 1)
pdftex_fail("Type%d fonts unsupported by pdfTeX", i);
return;
}
for (key = font_key; key - font_key < FONT_KEYS_NUM; key++) {
if (key->t1name[0] != '\0' &&
str_prefix(t1_line_array + 1, key->t1name))
break;
}
if (key - font_key == FONT_KEYS_NUM)
return;
p = t1_line_array + strlen(key->t1name) + 1;
skip(p, ' ');
if ((k = key - font_key) == FONTNAME_CODE) {
if (*p != '/') {
remove_eol(p, t1_line_array);
pdftex_fail("a name expected: `%s'", t1_line_array);
}
r = ++p; /* skip the slash */
for (q = t1_buf_array; *p != ' ' && *p != 10; *q++ = *p++);
*q = 0;
if (fm_slant(fd_cur->fm) != 0) {
sprintf(q, "-Slant_%i", (int) fm_slant(fd_cur->fm));
q = strend(q);
}
if (fm_extend(fd_cur->fm) != 0) {
sprintf(q, "-Extend_%i", (int) fm_extend(fd_cur->fm));
}
xfree(fd_cur->fontname);
fd_cur->fontname = xstrdup(t1_buf_array);
/* at this moment we cannot call make_subset_tag() yet, as the encoding
* is not read; thus we mark the offset of the subset tag and write it
* later */
if (is_subsetted(fd_cur->fm)) {
assert(is_included(fd_cur->fm));
t1_fontname_offset = t1_offset() + (r - t1_line_array);
strcpy(t1_buf_array, p);
sprintf(r, "ABCDEF+%s%s", fd_cur->fontname, t1_buf_array);
t1_line_ptr = eol(r);
}
return;
}
if ((k == STEMV_CODE || k == FONTBBOX1_CODE)
&& (*p == '[' || *p == '{'))
p++;
if (k == FONTBBOX1_CODE) {
for (i = 0; i < 4; i++, k++) {
fd_cur->font_dim[k].val = t1_scan_num(p, &r);
fd_cur->font_dim[k].set = true;
p = r;
}
return;
}
fd_cur->font_dim[k].val = t1_scan_num(p, 0);
fd_cur->font_dim[k].set = true;
}
static void t1_scan_param(void)
{
static const char *lenIV = "/lenIV";
if (!t1_scan || *t1_line_array != '/')
return;
if (t1_prefix(lenIV)) {
t1_lenIV = t1_scan_num(t1_line_array + strlen(lenIV), 0);
if (t1_lenIV < 0)
pdftex_fail("negative value of lenIV is not supported");
return;
}
t1_scan_keys();
}
static void copy_glyph_names(char **glyph_names, int a, int b)
{
if (glyph_names[b] != notdef) {
xfree(glyph_names[b]);
glyph_names[b] = notdef;
}
if (glyph_names[a] != notdef) {
glyph_names[b] = xstrdup(glyph_names[a]);
}
}
/* read encoding from Type1 font file, return glyph_names array, or pdffail() */
static char **t1_builtin_enc(void)
{
int i, a, b, c, counter = 0;
char *r, *p, **glyph_names;
/* At this moment "/Encoding" is the prefix of t1_line_array */
glyph_names = xtalloc(256, char *);
for (i = 0; i < 256; i++)
glyph_names[i] = notdef;
if (t1_suffix("def")) { /* predefined encoding */
if (sscanf(t1_line_array + strlen("/Encoding"), "%255s", t1_buf_array) == 1
&& strcmp(t1_buf_array, "StandardEncoding") == 0) {
t1_encoding = ENC_STANDARD;
for (i = 0; i < 256; i++) {
if (standard_glyph_names[i] != notdef)
glyph_names[i] = xstrdup(standard_glyph_names[i]);
}
return glyph_names;
}
pdftex_fail("cannot subset font (unknown predefined encoding `%s')",
t1_buf_array);
}
/* At this moment "/Encoding" is the prefix of t1_line_array, and the encoding is
* not a predefined encoding.
*
* We have two possible forms of Encoding vector. The first case is
*
* /Encoding [/a /b /c...] readonly def
*
* and the second case can look like
*
* /Encoding 256 array 0 1 255 {1 index exch /.notdef put} for
* dup 0 /x put
* dup 1 /y put
* ...
* readonly def
*/
t1_encoding = ENC_BUILTIN;
if (t1_prefix("/Encoding [") || t1_prefix("/Encoding[")) { /* the first case */
r = strchr(t1_line_array, '[') + 1;
skip(r, ' ');
for (;;) {
while (*r == '/') {
for (p = t1_buf_array, r++;
*r != 32 && *r != 10 && *r != ']' && *r != '/';
*p++ = *r++);
*p = 0;
skip(r, ' ');
if (counter > 255)
pdftex_fail("encoding vector contains more than 256 names");
if (strcmp(t1_buf_array, notdef) != 0)
glyph_names[counter] = xstrdup(t1_buf_array);
counter++;
}
if (*r != 10 && *r != '%') {
if (str_prefix(r, "] def") || str_prefix(r, "] readonly def"))
break;
else {
remove_eol(r, t1_line_array);
pdftex_fail
("a name or `] def' or `] readonly def' expected: `%s'", t1_line_array);
}
}
t1_getline();
r = t1_line_array;
}
} else { /* the second case */
p = strchr(t1_line_array, 10);
for (;;) {
if (*p == 10) {
t1_getline();
p = t1_line_array;
}
/*
check for `dup <index> <glyph> put'
*/
if (sscanf(p, "dup %i%255s put", &i, t1_buf_array) == 2 &&
*t1_buf_array == '/' && valid_code(i)) {
if (strcmp(t1_buf_array + 1, notdef) != 0)
glyph_names[i] = xstrdup(t1_buf_array + 1);
p = strstr(p, " put") + strlen(" put");
skip(p, ' ');
}
/*
check for `dup dup <to> exch <from> get put'
*/
else if (sscanf(p, "dup dup %i exch %i get put", &b, &a) == 2
&& valid_code(a) && valid_code(b)) {
copy_glyph_names(glyph_names, a, b);
p = strstr(p, " get put") + strlen(" get put");
skip(p, ' ');
}
/*
check for `dup dup <from> <size> getinterval <to> exch putinterval'
*/
else if (sscanf(p, "dup dup %i %i getinterval %i exch putinterval",
&a, &c, &b) == 3
&& valid_code(a) && valid_code(b) && valid_code(c)) {
for (i = 0; i < c; i++)
copy_glyph_names(glyph_names, a + i, b + i);
p = strstr(p, " putinterval") + strlen(" putinterval");
skip(p, ' ');
}
/*
check for `def' or `readonly def'
*/
else if ((p == t1_line_array || (p > t1_line_array && p[-1] == ' '))
&& strcmp(p, "def\n") == 0)
return glyph_names;
/*
skip an unrecognizable word
*/
else {
while (*p != ' ' && *p != 10)
p++;
skip(p, ' ');
}
}
}
return glyph_names;
}
static void t1_check_end(void)
{
if (t1_eof())
return;
t1_getline();
if (t1_prefix("{restore}"))
t1_putline();
}
static boolean t1_open_fontfile(const char *open_name_prefix)
{
ff_entry *ff;
ff = check_ff_exist(fd_cur->fm->ff_name, is_truetype(fd_cur->fm));
if (ff->ff_path != NULL) {
t1_file = xfopen(cur_file_name = ff->ff_path, FOPEN_RBIN_MODE);
recorder_record_input(ff->ff_path);
} else {
set_cur_file_name(fd_cur->fm->ff_name);
pdftex_fail("cannot open Type 1 font file for reading");
}
t1_init_params(open_name_prefix);
return true; /* font file found */
}
static void t1_include(void)
{
do {
t1_getline();
t1_scan_param();
t1_putline();
} while (t1_in_eexec == 0);
t1_start_eexec();
do {
t1_getline();
t1_scan_param();
t1_putline();
} while (!(t1_charstrings() || t1_subrs()));
t1_cs = true;
do {
t1_getline();
t1_putline();
} while (!t1_end_eexec());
t1_stop_eexec();
if (fixedcontent) { /* copy 512 zeros (not needed for PDF) */
do {
t1_getline();
t1_putline();
} while (!t1_cleartomark());
t1_check_end(); /* write "{restore}if" if found */
}
get_length3();
}
#define check_subr(subr) \
if (subr >= subr_size || subr < 0) \
pdftex_fail("Subrs array: entry index out of range (%i)", subr);
static const char **check_cs_token_pair(void)
{
const char **p = (const char **) cs_token_pairs_list;
for (; p[0] != NULL; ++p)
if (t1_buf_prefix(p[0]) && t1_buf_suffix(p[1]))
return p;
return NULL;
}
static void cs_store(boolean is_subr)
{
char *p;
cs_entry *ptr;
int subr;
for (p = t1_line_array, t1_buf_ptr = t1_buf_array; *p != ' ';
*t1_buf_ptr++ = *p++);
*t1_buf_ptr = 0;
if (is_subr) {
subr = t1_scan_num(p + 1, 0);
check_subr(subr);
ptr = subr_tab + subr;
} else {
ptr = cs_ptr++;
if (cs_ptr - cs_tab > cs_size)
pdftex_fail
("CharStrings dict: more entries than dict size (%i)", cs_size);
if (strcmp(t1_buf_array + 1, notdef) == 0) /* skip the slash */
ptr->name = notdef;
else
ptr->name = xstrdup(t1_buf_array + 1);
}
/* copy " RD " + cs data to t1_buf_array */
memcpy(t1_buf_array, t1_line_array + cs_start - 4,
(unsigned) (t1_cslen + 4));
/* copy the end of cs data to t1_buf_array */
for (p = t1_line_array + cs_start + t1_cslen,
t1_buf_ptr = t1_buf_array + t1_cslen + 4;
*p != 10; *t1_buf_ptr++ = *p++);
*t1_buf_ptr++ = 10;
if (is_subr && cs_token_pair == NULL)
cs_token_pair = check_cs_token_pair();
ptr->len = t1_buf_ptr - t1_buf_array;
ptr->cslen = t1_cslen;
ptr->data = xtalloc(ptr->len, byte);
memcpy(ptr->data, t1_buf_array, ptr->len);
ptr->valid = true;
}
#define store_subr() cs_store(true)
#define store_cs() cs_store(false)
#define CC_STACK_SIZE 24
static integer cc_stack[CC_STACK_SIZE], *stack_ptr = cc_stack;
static cc_entry cc_tab[CS_MAX];
static boolean is_cc_init = false;
#define cc_pop(N) \
if (stack_ptr - cc_stack < (N)) \
stack_error(N); \
stack_ptr -= N
#define stack_error(N) { \
pdftex_fail("CharString: invalid access (%i) to stack (%i entries)", \
(int) N, (int)(stack_ptr - cc_stack)); \
goto cs_error; \
}
/*
static integer cc_get(integer index)
{
if (index < 0) {
if (stack_ptr + index < cc_stack )
stack_error(stack_ptr - cc_stack + index);
return *(stack_ptr + index);
}
else {
if (cc_stack + index >= stack_ptr)
stack_error(index);
return cc_stack[index];
}
}
*/
#define cc_get(N) ((N) < 0 ? *(stack_ptr + (N)) : *(cc_stack + (N)))
#define cc_push(V) *stack_ptr++ = V
#define cc_clear() stack_ptr = cc_stack
#define set_cc(N, B, A, C) \
cc_tab[N].nargs = A; \
cc_tab[N].bottom = B; \
cc_tab[N].clear = C; \
cc_tab[N].valid = true
static void cc_init(void)
{
int i;
if (is_cc_init)
return;
for (i = 0; i < CS_MAX; i++)
cc_tab[i].valid = false;
set_cc(CS_HSTEM, true, 2, true);
set_cc(CS_VSTEM, true, 2, true);
set_cc(CS_VMOVETO, true, 1, true);
set_cc(CS_RLINETO, true, 2, true);
set_cc(CS_HLINETO, true, 1, true);
set_cc(CS_VLINETO, true, 1, true);
set_cc(CS_RRCURVETO, true, 6, true);
set_cc(CS_CLOSEPATH, false, 0, true);
set_cc(CS_CALLSUBR, false, 1, false);
set_cc(CS_RETURN, false, 0, false);
/*
set_cc(CS_ESCAPE, false, 0, false);
*/
set_cc(CS_HSBW, true, 2, true);
set_cc(CS_ENDCHAR, false, 0, true);
set_cc(CS_RMOVETO, true, 2, true);
set_cc(CS_HMOVETO, true, 1, true);
set_cc(CS_VHCURVETO, true, 4, true);
set_cc(CS_HVCURVETO, true, 4, true);
set_cc(CS_DOTSECTION, false, 0, true);
set_cc(CS_VSTEM3, true, 6, true);
set_cc(CS_HSTEM3, true, 6, true);
set_cc(CS_SEAC, true, 5, true);
set_cc(CS_SBW, true, 4, true);
set_cc(CS_DIV, false, 2, false);
set_cc(CS_CALLOTHERSUBR, false, 0, false);
set_cc(CS_POP, false, 0, false);
set_cc(CS_SETCURRENTPOINT, true, 2, true);
is_cc_init = true;
}
#define cs_getchar() cdecrypt(*data++, &cr)
#define mark_subr(n) cs_mark(0, n)
#define mark_cs(s) cs_mark(s, 0)
__attribute__ ((format(printf, 3, 4)))
static void cs_fail(const char *cs_name, int subr, const char *fmt, ...)
{
char buf[SMALL_BUF_SIZE];
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
if (cs_name == NULL)
pdftex_fail("Subr (%i): %s", (int) subr, buf);
else
pdftex_fail("CharString (/%s): %s", cs_name, buf);
}
/* fix a return-less subr by appending CS_RETURN */
static void append_cs_return(cs_entry *ptr)
{
unsigned short cr;
int i;
byte *p, *q, *data, *new_data;
assert(ptr != NULL && ptr->valid && ptr->used);
/* decrypt the cs data to t1_buf_array, append CS_RETURN */
p = (byte *) t1_buf_array;
data = ptr->data + 4;
cr = 4330;
for (i = 0; i < ptr->cslen; i++)
*p++ = cs_getchar();
*p = CS_RETURN;
/* encrypt the new cs data to new_data */
new_data = xtalloc(ptr->len + 1, byte);
memcpy(new_data, ptr->data, 4);
p = new_data + 4;
q = (byte *) t1_buf_array;
cr = 4330;
for (i = 0; i < ptr->cslen + 1; i++)
*p++ = cencrypt(*q++, &cr);
memcpy(p, ptr->data + 4 + ptr->cslen, ptr->len - ptr->cslen - 4);
/* update *ptr */
xfree(ptr->data);
ptr->data = new_data;
ptr->len++;
ptr->cslen++;
}
static void cs_mark(const char *cs_name, int subr)
{
byte *data;
int i, b, cs_len;
int last_cmd = 0;
integer a, a1, a2;
unsigned short cr;
static integer lastargOtherSubr3 = 3; /* the argument of last call to
OtherSubrs[3] */
cs_entry *ptr;
cc_entry *cc;
if (cs_name == NULL) {
check_subr(subr);
ptr = subr_tab + subr;
if (!ptr->valid)
return;
} else {
if (cs_notdef != NULL &&
(cs_name == notdef || strcmp(cs_name, notdef) == 0))
ptr = cs_notdef;
else {
for (ptr = cs_tab; ptr < cs_ptr; ptr++)
if (strcmp(ptr->name, cs_name) == 0)
break;
if (ptr == cs_ptr) {
pdftex_warn("glyph `%s' undefined", cs_name);
return;
}
if (ptr->name == notdef)
cs_notdef = ptr;
}
}
/* only marked CharString entries and invalid entries can be skipped;
valid marked subrs must be parsed to keep the stack in sync */
if (!ptr->valid || (ptr->used && cs_name != NULL))
return;
ptr->used = true;
cr = 4330;
cs_len = ptr->cslen;
data = ptr->data + 4;
for (i = 0; i < t1_lenIV; i++, cs_len--)
cs_getchar();
while (cs_len > 0) {
--cs_len;
b = cs_getchar();
if (b >= 32) {
if (b <= 246)
a = b - 139;
else if (b <= 250) {
--cs_len;
a = ((b - 247) << 8) + 108 + cs_getchar();
} else if (b <= 254) {
--cs_len;
a = -((b - 251) << 8) - 108 - cs_getchar();
} else {
cs_len -= 4;
a = (cs_getchar() & 0xff) << 24;
a |= (cs_getchar() & 0xff) << 16;
a |= (cs_getchar() & 0xff) << 8;
a |= (cs_getchar() & 0xff) << 0;
if (sizeof(integer) > 4 && (a & 0x80000000))
a |= ~0x7FFFFFFF;
}
cc_push(a);
} else {
if (b == CS_ESCAPE) {
b = cs_getchar() + CS_1BYTE_MAX;
cs_len--;
}
if (b >= CS_MAX) {
cs_fail(cs_name, subr, "command value out of range: %i",
(int) b);
goto cs_error;
}
cc = cc_tab + b;
if (!cc->valid) {
cs_fail(cs_name, subr, "command not valid: %i", (int) b);
goto cs_error;
}
if (cc->bottom) {
if (stack_ptr - cc_stack < cc->nargs)
cs_fail(cs_name, subr,
"less arguments on stack (%i) than required (%i)",
(int) (stack_ptr - cc_stack), (int) cc->nargs);
else if (stack_ptr - cc_stack > cc->nargs)
cs_fail(cs_name, subr,
"more arguments on stack (%i) than required (%i)",
(int) (stack_ptr - cc_stack), (int) cc->nargs);
}
last_cmd = b;
switch (cc - cc_tab) {
case CS_CALLSUBR:
a1 = cc_get(-1);
cc_pop(1);
mark_subr(a1);
if (!subr_tab[a1].valid) {
cs_fail(cs_name, subr, "cannot call subr (%i)", (int) a1);
goto cs_error;
}
break;
case CS_DIV:
cc_pop(2);
cc_push(0);
break;
case CS_CALLOTHERSUBR:
if (cc_get(-1) == 3)
lastargOtherSubr3 = cc_get(-3);
a1 = cc_get(-2) + 2;
cc_pop(a1);
break;
case CS_POP:
cc_push(lastargOtherSubr3);
/* the only case when we care about the value being pushed onto
stack is when POP follows CALLOTHERSUBR (changing hints by
OtherSubrs[3])
*/
break;
case CS_SEAC:
a1 = cc_get(3);
a2 = cc_get(4);
cc_clear();
mark_cs(standard_glyph_names[a1]);
mark_cs(standard_glyph_names[a2]);
break;
default:
if (cc->clear)
cc_clear();
}
}
}
if (cs_name == NULL && last_cmd != CS_RETURN) {
pdftex_warn("last command in subr `%i' is not a RETURN; "
"I will add it now but please consider fixing the font",
(int) subr);
append_cs_return(ptr);
}
return;
cs_error: /* an error occured during parsing */
cc_clear();
ptr->valid = false;
ptr->used = false;
}
/**********************************************************************/
/* AVL search tree for glyph code by glyph name */
static int comp_t1_glyphs(const void *pa, const void *pb, void *p)
{
return strcmp(*((const char * const *) pa), *((const char * const *) pb));
}
static struct avl_table *create_t1_glyph_tree(char **glyph_names)
{
int i;
void **aa;
static struct avl_table *gl_tree;
gl_tree = avl_create(comp_t1_glyphs, NULL, &avl_xallocator);
assert(gl_tree != NULL);
for (i = 0; i < 256; i++) {
if (glyph_names[i] != notdef &&
(char **) avl_find(gl_tree, &glyph_names[i]) == NULL) {
/* no strdup here, just point to the glyph_names array members */
aa = avl_probe(gl_tree, &glyph_names[i]);
assert(aa != NULL);
}
}
return gl_tree;
}
static void destroy_t1_glyph_tree(struct avl_table *gl_tree)
{
assert(gl_tree != NULL);
avl_destroy(gl_tree, NULL);
}
/**********************************************************************/
static void t1_subset_ascii_part(void)
{
int j, *p;
char *glyph, **gg, **glyph_names;
struct avl_table *gl_tree;
struct avl_traverser t;
void **aa;
assert(fd_cur != NULL);
assert(fd_cur->gl_tree != NULL);
t1_getline();
while (!t1_prefix("/Encoding")) {
t1_scan_param();
if (!(t1_prefix("/UniqueID")
&& !strncmp(t1_line_array + strlen(t1_line_array) -4, "def", 3)))
t1_putline();
t1_getline();
}
glyph_names = t1_builtin_enc();
fd_cur->builtin_glyph_names = glyph_names;
if (is_subsetted(fd_cur->fm)) {
assert(is_included(fd_cur->fm));
if (fd_cur->tx_tree != NULL) {
/* take over collected non-reencoded characters from TeX */
avl_t_init(&t, fd_cur->tx_tree);
for (p = (int *) avl_t_first(&t, fd_cur->tx_tree); p != NULL;
p = (int *) avl_t_next(&t)) {
if ((char *) avl_find(fd_cur->gl_tree, glyph_names[*p]) == NULL) {
glyph = xstrdup(glyph_names[*p]);
aa = avl_probe(fd_cur->gl_tree, glyph);
assert(aa != NULL);
}
}
}
make_subset_tag(fd_cur);
assert(t1_fontname_offset != 0);
strncpy(fb_array + t1_fontname_offset, fd_cur->subset_tag, 6);
}
/* now really all glyphs needed from this font are in the fd_cur->gl_tree */
if (t1_encoding == ENC_STANDARD)
t1_puts("/Encoding StandardEncoding def\n");
else {
t1_puts
("/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n");
gl_tree = create_t1_glyph_tree(glyph_names);
avl_t_init(&t, fd_cur->gl_tree);
j = 0;
for (glyph = (char *) avl_t_first(&t, fd_cur->gl_tree); glyph != NULL;
glyph = (char *) avl_t_next(&t)) {
if ((gg = (char **) avl_find(gl_tree, &glyph)) != NULL) {
t1_printf("dup %i /%s put\n", (int) (gg - glyph_names), *gg);
j++;
}
}
destroy_t1_glyph_tree(gl_tree);
if (j == 0)
/* We didn't mark anything for the Encoding array. */
/* We add "dup 0 /.notdef put" for compatibility */
/* with Acrobat 5.0. */
t1_puts("dup 0 /.notdef put\n");
t1_puts("readonly def\n");
}
do {
t1_getline();
t1_scan_param();
if (!t1_prefix("/UniqueID")) /* ignore UniqueID for subsetted fonts */
t1_putline();
} while (t1_in_eexec == 0);
}
static void cs_init(void)
{
cs_ptr = cs_tab = NULL;
cs_dict_start = cs_dict_end = NULL;
cs_count = cs_size = cs_size_pos = 0;
cs_token_pair = NULL;
subr_tab = NULL;
subr_array_start = subr_array_end = NULL;
subr_max = subr_size = subr_size_pos = 0;
}
static void init_cs_entry(cs_entry *cs)
{
cs->data = NULL;
cs->name = NULL;
cs->len = 0;
cs->cslen = 0;
cs->used = false;
cs->valid = false;
}
static void t1_read_subrs(void)
{
int i, s;
cs_entry *ptr;
t1_getline();
while (!(t1_charstrings() || t1_subrs())) {
t1_scan_param();
if (!t1_prefix("/UniqueID")) /* ignore UniqueID for subsetted fonts */
t1_putline();
t1_getline();
}
found:
t1_cs = true;
t1_scan = false;
if (!t1_subrs())
return;
subr_size_pos = strlen("/Subrs") + 1;
/* subr_size_pos points to the number indicating dict size after "/Subrs" */
subr_size = t1_scan_num(t1_line_array + subr_size_pos, 0);
if (subr_size == 0) {
while (!t1_charstrings())
t1_getline();
return;
}
subr_tab = xtalloc(subr_size, cs_entry);
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
init_cs_entry(ptr);
subr_array_start = xstrdup(t1_line_array);
t1_getline();
while (t1_cslen) {
store_subr();
t1_getline();
}
/* mark the first four entries without parsing */
for (i = 0; i < subr_size && i < 4; i++)
subr_tab[i].used = true;
/* the end of the Subrs array might have more than one line so we need to
concatnate them to subr_array_end. Unfortunately some fonts don't have
the Subrs array followed by the CharStrings dict immediately (synthetic
fonts). If we cannot find CharStrings in next POST_SUBRS_SCAN lines then
we will treat the font as synthetic and ignore everything until next
Subrs is found
*/
#define POST_SUBRS_SCAN 5
s = 0;
*t1_buf_array = 0;
for (i = 0; i < POST_SUBRS_SCAN; i++) {
if (t1_charstrings())
break;
s += t1_line_ptr - t1_line_array;
alloc_array(t1_buf, s, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
t1_getline();
}
subr_array_end = xstrdup(t1_buf_array);
if (i == POST_SUBRS_SCAN) { /* CharStrings not found;
suppose synthetic font */
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->valid)
xfree(ptr->data);
xfree(subr_tab);
xfree(subr_array_start);
xfree(subr_array_end);
cs_init();
t1_cs = false;
t1_synthetic = true;
while (!(t1_charstrings() || t1_subrs()))
t1_getline();
goto found;
}
}
#define t1_subr_flush() t1_flush_cs(true)
#define t1_cs_flush() t1_flush_cs(false)
static void t1_flush_cs(boolean is_subr)
{
char *p;
byte *r, *return_cs = NULL;
cs_entry *tab, *end_tab, *ptr;
char *start_line, *line_end;
int count, size_pos;
unsigned short cr, cs_len = 0; /* to avoid warning about uninitialized use of cs_len */
if (is_subr) {
start_line = subr_array_start;
line_end = subr_array_end;
size_pos = subr_size_pos;
tab = subr_tab;
count = subr_max + 1;
end_tab = subr_tab + count;
} else {
start_line = cs_dict_start;
line_end = cs_dict_end;
size_pos = cs_size_pos;
tab = cs_tab;
end_tab = cs_ptr;
count = cs_count;
}
t1_line_ptr = t1_line_array;
for (p = start_line; p - start_line < size_pos;)
*t1_line_ptr++ = *p++;
while (isdigit((unsigned char)*p))
p++;
sprintf(t1_line_ptr, "%u", count);
strcat(t1_line_ptr, p);
t1_line_ptr = eol(t1_line_array);
t1_putline();
/* create return_cs to replace unused subr's */
if (is_subr) {
cr = 4330;
cs_len = 0;
/* at this point we have t1_lenIV >= 0;
* a negative value would be caught in t1_scan_param() */
return_cs = xtalloc(t1_lenIV + 1, byte);
for (cs_len = 0, r = return_cs; cs_len < t1_lenIV; cs_len++, r++)
*r = cencrypt(0x00, &cr);
*r = cencrypt(CS_RETURN, &cr);
cs_len++;
}
for (ptr = tab; ptr < end_tab; ptr++) {
if (ptr->used) {
if (is_subr)
sprintf(t1_line_array, "dup %lu %u",
(unsigned long) (ptr - tab), ptr->cslen);
else
sprintf(t1_line_array, "/%s %u", ptr->name, ptr->cslen);
p = strend(t1_line_array);
memcpy(p, ptr->data, ptr->len);
t1_line_ptr = p + ptr->len;
t1_putline();
} else {
/* replace unsused subr's by return_cs */
if (is_subr) {
sprintf(t1_line_array, "dup %lu %u%s ",
(unsigned long) (ptr - tab), cs_len, cs_token_pair[0]);
p = strend(t1_line_array);
memcpy(p, return_cs, cs_len);
t1_line_ptr = p + cs_len;
t1_putline();
sprintf(t1_line_array, " %s", cs_token_pair[1]);
t1_line_ptr = eol(t1_line_array);
t1_putline();
}
}
xfree(ptr->data);
if (ptr->name != notdef)
xfree(ptr->name);
}
sprintf(t1_line_array, "%s", line_end);
t1_line_ptr = eol(t1_line_array);
t1_putline();
if (is_subr)
xfree(return_cs);
xfree(tab);
xfree(start_line);
xfree(line_end);
}
static void t1_mark_glyphs(void)
{
char *glyph;
struct avl_traverser t;
cs_entry *ptr;
if (t1_synthetic || fd_cur->all_glyphs) { /* mark everything */
if (cs_tab != NULL)
for (ptr = cs_tab; ptr < cs_ptr; ptr++)
if (ptr->valid)
ptr->used = true;
if (subr_tab != NULL) {
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->valid)
ptr->used = true;
subr_max = subr_size - 1;
}
return;
}
mark_cs(notdef);
avl_t_init(&t, fd_cur->gl_tree);
for (glyph = (char *) avl_t_first(&t, fd_cur->gl_tree); glyph != NULL;
glyph = (char *) avl_t_next(&t)) {
mark_cs(glyph);
}
if (subr_tab != NULL)
for (subr_max = -1, ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->used && ptr - subr_tab > subr_max)
subr_max = ptr - subr_tab;
}
static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/* if no number follows "/CharStrings", let's read the next line */
if (sscanf(p, "%i", &i) != 1) {
/* pdftex_warn("no number found after `%s', I assume it's on the next line",
charstringname); */
strcpy(t1_buf_array, t1_line_array);
/* t1_getline always appends EOL to t1_line_array; let's change it to
* space before appending the next line
*/
*(strend(t1_buf_array) - 1) = ' ';
t1_getline();
alloc_array(t1_buf, strlen(t1_line_array) + strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
alloc_array(t1_line, strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
static void t1_subset_charstrings(void)
{
cs_entry *ptr;
/* at this point t1_line_array contains "/CharStrings".
when we hit a case like this:
dup/CharStrings
229 dict dup begin
we read the next line and concatenate to t1_line_array before moving on
*/
t1_check_unusual_charstring();
cs_size_pos = strstr(t1_line_array, charstringname)
+ strlen(charstringname) - t1_line_array + 1;
/* cs_size_pos points to the number indicating
dict size after "/CharStrings" */
cs_size = t1_scan_num(t1_line_array + cs_size_pos, 0);
cs_ptr = cs_tab = xtalloc(cs_size, cs_entry);
for (ptr = cs_tab; ptr - cs_tab < cs_size; ptr++)
init_cs_entry(ptr);
cs_notdef = NULL;
cs_dict_start = xstrdup(t1_line_array);
t1_getline();
while (t1_cslen) {
store_cs();
t1_getline();
}
cs_dict_end = xstrdup(t1_line_array);
t1_mark_glyphs();
if (subr_tab != NULL) {
if (cs_token_pair == NULL)
pdftex_fail
("This Type 1 font uses mismatched subroutine begin/end token pairs.");
t1_subr_flush();
}
for (cs_count = 0, ptr = cs_tab; ptr < cs_ptr; ptr++)
if (ptr->used)
cs_count++;
t1_cs_flush();
}
static void t1_subset_end(void)
{
if (t1_synthetic) { /* copy to "dup /FontName get exch definefont pop" */
while (!strstr(t1_line_array, "definefont")) {
t1_getline();
t1_putline();
}
while (!t1_end_eexec())
t1_getline(); /* ignore the rest */
t1_putline(); /* write "mark currentfile closefile" */
} else
while (!t1_end_eexec()) { /* copy to "mark currentfile closefile" */
t1_getline();
t1_putline();
}
t1_stop_eexec();
if (fixedcontent) { /* copy 512 zeros (not needed for PDF) */
while (!t1_cleartomark()) {
t1_getline();
t1_putline();
}
if (!t1_synthetic) /* don't check "{restore}if" for synthetic fonts */
t1_check_end(); /* write "{restore}if" if found */
}
get_length3();
}
void writet1(fd_entry *fd)
{
fd_cur = fd; /* fd_cur is global inside writet1.c */
assert(fd_cur->fm != NULL);
assert(is_type1(fd->fm));
assert(is_included(fd->fm));
t1_save_offset = 0;
if (!is_subsetted(fd_cur->fm)) { /* include entire font */
if (!(fd->ff_found = t1_open_fontfile("<<")))
return;
t1_include();
t1_close_font_file(">>");
return;
}
/* partial downloading */
if (!(fd->ff_found = t1_open_fontfile("<")))
return;
t1_subset_ascii_part();
t1_start_eexec();
cc_init();
cs_init();
t1_read_subrs();
t1_subset_charstrings();
t1_subset_end();
t1_close_font_file(">");
}
void t1_free(void)
{
xfree(t1_line_array);
xfree(t1_buf_array);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_395_5 |
crossvul-cpp_data_good_5280_2 | /* Generated by re2c 0.13.7.5 */
#line 1 "ext/standard/var_unserializer.re"
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "ext/standard/php_var.h"
#include "php_incomplete_class.h"
/* {{{ reference-handling for unserializer: var_* */
#define VAR_ENTRIES_MAX 1024
#define VAR_ENTRIES_DBG 0
typedef struct {
zval *data[VAR_ENTRIES_MAX];
long used_slots;
void *next;
} var_entries;
static inline void var_push(php_unserialize_data_t *var_hashx, zval **rval)
{
var_entries *var_hash = (*var_hashx)->last;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first) {
(*var_hashx)->first = var_hash;
} else {
((var_entries *) (*var_hashx)->last)->next = var_hash;
}
(*var_hashx)->last = var_hash;
}
var_hash->data[var_hash->used_slots++] = *rval;
}
PHPAPI void var_push_dtor(php_unserialize_data_t *var_hashx, zval **rval)
{
var_entries *var_hash;
if (!var_hashx || !*var_hashx) {
return;
}
var_hash = (*var_hashx)->last_dtor;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push_dtor(%p, %ld): %d\n", *rval, var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first_dtor) {
(*var_hashx)->first_dtor = var_hash;
} else {
((var_entries *) (*var_hashx)->last_dtor)->next = var_hash;
}
(*var_hashx)->last_dtor = var_hash;
}
Z_ADDREF_PP(rval);
var_hash->data[var_hash->used_slots++] = *rval;
}
PHPAPI void var_push_dtor_no_addref(php_unserialize_data_t *var_hashx, zval **rval)
{
var_entries *var_hash;
if (!var_hashx || !*var_hashx) {
return;
}
var_hash = (*var_hashx)->last_dtor;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push_dtor_no_addref(%p, %ld): %d (%d)\n", *rval, var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(rval), Z_REFCOUNT_PP(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first_dtor) {
(*var_hashx)->first_dtor = var_hash;
} else {
((var_entries *) (*var_hashx)->last_dtor)->next = var_hash;
}
(*var_hashx)->last_dtor = var_hash;
}
var_hash->data[var_hash->used_slots++] = *rval;
}
PHPAPI void var_replace(php_unserialize_data_t *var_hashx, zval *ozval, zval **nzval)
{
long i;
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_replace(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_PP(nzval));
#endif
while (var_hash) {
for (i = 0; i < var_hash->used_slots; i++) {
if (var_hash->data[i] == ozval) {
var_hash->data[i] = *nzval;
/* do not break here */
}
}
var_hash = var_hash->next;
}
}
static int var_access(php_unserialize_data_t *var_hashx, long id, zval ***store)
{
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_access(%ld): %ld\n", var_hash?var_hash->used_slots:-1L, id);
#endif
while (id >= VAR_ENTRIES_MAX && var_hash && var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = var_hash->next;
id -= VAR_ENTRIES_MAX;
}
if (!var_hash) return !SUCCESS;
if (id < 0 || id >= var_hash->used_slots) return !SUCCESS;
*store = &var_hash->data[id];
return SUCCESS;
}
PHPAPI void var_destroy(php_unserialize_data_t *var_hashx)
{
void *next;
long i;
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy(%ld)\n", var_hash?var_hash->used_slots:-1L);
#endif
while (var_hash) {
next = var_hash->next;
efree(var_hash);
var_hash = next;
}
var_hash = (*var_hashx)->first_dtor;
while (var_hash) {
for (i = 0; i < var_hash->used_slots; i++) {
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy dtor(%p, %ld)\n", var_hash->data[i], Z_REFCOUNT_P(var_hash->data[i]));
#endif
zval_ptr_dtor(&var_hash->data[i]);
}
next = var_hash->next;
efree(var_hash);
var_hash = next;
}
}
/* }}} */
static char *unserialize_str(const unsigned char **p, size_t *len, size_t maxlen)
{
size_t i, j;
char *str = safe_emalloc(*len, 1, 1);
unsigned char *end = *(unsigned char **)p+maxlen;
if (end < *p) {
efree(str);
return NULL;
}
for (i = 0; i < *len; i++) {
if (*p >= end) {
efree(str);
return NULL;
}
if (**p != '\\') {
str[i] = (char)**p;
} else {
unsigned char ch = 0;
for (j = 0; j < 2; j++) {
(*p)++;
if (**p >= '0' && **p <= '9') {
ch = (ch << 4) + (**p -'0');
} else if (**p >= 'a' && **p <= 'f') {
ch = (ch << 4) + (**p -'a'+10);
} else if (**p >= 'A' && **p <= 'F') {
ch = (ch << 4) + (**p -'A'+10);
} else {
efree(str);
return NULL;
}
}
str[i] = (char)ch;
}
(*p)++;
}
str[i] = 0;
*len = i;
return str;
}
#define YYFILL(n) do { } while (0)
#define YYCTYPE unsigned char
#define YYCURSOR cursor
#define YYLIMIT limit
#define YYMARKER marker
#line 249 "ext/standard/var_unserializer.re"
static inline long parse_iv2(const unsigned char *p, const unsigned char **q)
{
char cursor;
long result = 0;
int neg = 0;
switch (*p) {
case '-':
neg++;
/* fall-through */
case '+':
p++;
}
while (1) {
cursor = (char)*p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
if (q) *q = p;
if (neg) return -result;
return result;
}
static inline long parse_iv(const unsigned char *p)
{
return parse_iv2(p, NULL);
}
/* no need to check for length - re2c already did */
static inline size_t parse_uiv(const unsigned char *p)
{
unsigned char cursor;
size_t result = 0;
if (*p == '+') {
p++;
}
while (1) {
cursor = *p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
return result;
}
#define UNSERIALIZE_PARAMETER zval **rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash TSRMLS_DC
#define UNSERIALIZE_PASSTHRU rval, p, max, var_hash TSRMLS_CC
static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
var_push_dtor_no_addref(var_hash, &key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
var_push_dtor_no_addref(var_hash, &key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
var_push_dtor_no_addref(var_hash, &key);
var_push_dtor_no_addref(var_hash, &data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
if (zend_hash_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
var_push_dtor(var_hash, &data);
var_push_dtor_no_addref(var_hash, &key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
return 1;
}
static inline int finish_nested_data(UNSERIALIZE_PARAMETER)
{
if (*((*p)++) == '}')
return 1;
#if SOMETHING_NEW_MIGHT_LEAD_TO_CRASH_ENABLE_IF_YOU_ARE_BRAVE
zval_ptr_dtor(rval);
#endif
return 0;
}
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (max - (*p)) <= datalen) {
zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ce->name);
object_init_ex(*rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
long elements;
elements = parse_iv2((*p) + 2, p);
(*p) += 2;
if (ce->serialize == NULL) {
object_init_ex(*rval, ce);
} else {
/* If this class implements Serializable, it should not land here but in object_custom(). The passed string
obviously doesn't descend from the regular serializer. */
zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ce->name);
return 0;
}
return elements;
}
#ifdef PHP_WIN32
# pragma optimize("", off)
#endif
static inline int object_common2(UNSERIALIZE_PARAMETER, long elements)
{
zval *retval_ptr = NULL;
zval fname;
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) {
/* We've got partially constructed object on our hands here. Wipe it. */
if(Z_TYPE_PP(rval) == IS_OBJECT) {
zend_hash_clean(Z_OBJPROP_PP(rval));
zend_object_store_ctor_failed(*rval TSRMLS_CC);
}
ZVAL_NULL(*rval);
return 0;
}
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY &&
zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) {
INIT_PZVAL(&fname);
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0);
BG(serialize_lock)++;
call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC);
BG(serialize_lock)--;
}
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#ifdef PHP_WIN32
# pragma optimize("", on)
#endif
PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 496 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 861 "ext/standard/var_unserializer.re"
{ return 0; }
#line 558 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 855 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 607 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych <= '/') goto yy18;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 708 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
long elements;
char *class_name;
zend_class_entry *ce;
zend_class_entry **pce;
int incomplete_class = 0;
int custom_object = 0;
zval *user_func;
zval *retval_ptr;
zval **args[1];
zval *arg_func_name;
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
INIT_PZVAL(*rval);
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
class_name = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(class_name, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = estrndup(class_name, len);
do {
/* Try to find class directly */
BG(serialize_lock)++;
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
ce = *pce;
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
MAKE_STD_ZVAL(user_func);
ZVAL_STRING(user_func, PG(unserialize_callback_func), 1);
args[0] = &arg_func_name;
MAKE_STD_ZVAL(arg_func_name);
ZVAL_STRING(arg_func_name, class_name, 1);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "defined (%s) but not found", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
}
BG(serialize_lock)--;
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
/* The callback function may have defined the class */
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
ce = *pce;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Function %s() hasn't defined the class it was called for", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 785 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 699 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
INIT_PZVAL(*rval);
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 819 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 678 "ext/standard/var_unserializer.re"
{
long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
INIT_PZVAL(*rval);
array_init_size(*rval, elements);
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 861 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 643 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
efree(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 0);
return 1;
}
#line 917 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 610 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 1);
return 1;
}
#line 971 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 600 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
use_double:
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1069 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 585 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
if (!strncmp(start + 2, "NAN", 3)) {
ZVAL_DOUBLE(*rval, php_get_nan());
} else if (!strncmp(start + 2, "INF", 3)) {
ZVAL_DOUBLE(*rval, php_get_inf());
} else if (!strncmp(start + 2, "-INF", 4)) {
ZVAL_DOUBLE(*rval, -php_get_inf());
}
return 1;
}
#line 1143 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 558 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp(YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_LONG(*rval, parse_iv(start + 2));
return 1;
}
#line 1197 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 551 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_BOOL(*rval, parse_iv(start + 2));
return 1;
}
#line 1212 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 544 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_NULL(*rval);
return 1;
}
#line 1222 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 521 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval == *rval_ref) return 0;
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_UNSET_ISREF_PP(rval);
return 1;
}
#line 1268 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 500 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_SET_ISREF_PP(rval);
return 1;
}
#line 1312 "ext/standard/var_unserializer.c"
}
#line 863 "ext/standard/var_unserializer.re"
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5280_2 |
crossvul-cpp_data_good_651_2 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre, Romain Bouqueau, Cyril Concolato
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / Media Tools sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/media_dev.h>
#include <gpac/constants.h>
#include <gpac/mpeg4_odf.h>
#include <gpac/maths.h>
#ifndef GPAC_DISABLE_OGG
#include <gpac/internal/ogg.h>
#endif
static const struct {
u32 w, h;
} std_par[ ] =
{
{ 4, 3}, {3, 2}, {16, 9}, {5, 3}, {5, 4}, {8, 5}, {2, 1},
{0, 0},
};
GF_EXPORT
void gf_media_reduce_aspect_ratio(u32 *width, u32 *height)
{
u32 i=0;
u32 w = *width;
u32 h = *height;
while (std_par[i].w) {
if (std_par[i].w * h == std_par[i].h * w) {
*width = std_par[i].w;
*height = std_par[i].h;
return;
}
i++;
}
}
GF_EXPORT
void gf_media_get_reduced_frame_rate(u32 *timescale, u32 *sample_dur)
{
u32 res;
if (! *sample_dur) return;
res = *timescale / *sample_dur;
if (res **sample_dur == *timescale) {
*timescale = res;
*sample_dur = 1;
} else if ((double)(*timescale * 1001 - (res+1) * *sample_dur * 1000) / ((res+1) * *sample_dur * 1000) < 0.001) {
*timescale = (res+1) * 1000;
*sample_dur = 1001;
}
}
GF_EXPORT
const char *gf_m4v_get_profile_name(u8 video_pl)
{
switch (video_pl) {
case 0x00:
return "Reserved (0x00) Profile";
case 0x01:
return "Simple Profile @ Level 1";
case 0x02:
return "Simple Profile @ Level 2";
case 0x03:
return "Simple Profile @ Level 3";
case 0x08:
return "Simple Profile @ Level 0";
case 0x10:
return "Simple Scalable Profile @ Level 0";
case 0x11:
return "Simple Scalable Profile @ Level 1";
case 0x12:
return "Simple Scalable Profile @ Level 2";
case 0x21:
return "Core Profile @ Level 1";
case 0x22:
return "Core Profile @ Level 2";
case 0x32:
return "Main Profile @ Level 2";
case 0x33:
return "Main Profile @ Level 3";
case 0x34:
return "Main Profile @ Level 4";
case 0x42:
return "N-bit Profile @ Level 2";
case 0x51:
return "Scalable Texture Profile @ Level 1";
case 0x61:
return "Simple Face Animation Profile @ Level 1";
case 0x62:
return "Simple Face Animation Profile @ Level 2";
case 0x63:
return "Simple FBA Profile @ Level 1";
case 0x64:
return "Simple FBA Profile @ Level 2";
case 0x71:
return "Basic Animated Texture Profile @ Level 1";
case 0x72:
return "Basic Animated Texture Profile @ Level 2";
case 0x7F:
return "AVC/H264 Profile";
case 0x81:
return "Hybrid Profile @ Level 1";
case 0x82:
return "Hybrid Profile @ Level 2";
case 0x91:
return "Advanced Real Time Simple Profile @ Level 1";
case 0x92:
return "Advanced Real Time Simple Profile @ Level 2";
case 0x93:
return "Advanced Real Time Simple Profile @ Level 3";
case 0x94:
return "Advanced Real Time Simple Profile @ Level 4";
case 0xA1:
return "Core Scalable Profile @ Level1";
case 0xA2:
return "Core Scalable Profile @ Level2";
case 0xA3:
return "Core Scalable Profile @ Level3";
case 0xB1:
return "Advanced Coding Efficiency Profile @ Level 1";
case 0xB2:
return "Advanced Coding Efficiency Profile @ Level 2";
case 0xB3:
return "Advanced Coding Efficiency Profile @ Level 3";
case 0xB4:
return "Advanced Coding Efficiency Profile @ Level 4";
case 0xC1:
return "Advanced Core Profile @ Level 1";
case 0xC2:
return "Advanced Core Profile @ Level 2";
case 0xD1:
return "Advanced Scalable Texture @ Level1";
case 0xD2:
return "Advanced Scalable Texture @ Level2";
case 0xE1:
return "Simple Studio Profile @ Level 1";
case 0xE2:
return "Simple Studio Profile @ Level 2";
case 0xE3:
return "Simple Studio Profile @ Level 3";
case 0xE4:
return "Simple Studio Profile @ Level 4";
case 0xE5:
return "Core Studio Profile @ Level 1";
case 0xE6:
return "Core Studio Profile @ Level 2";
case 0xE7:
return "Core Studio Profile @ Level 3";
case 0xE8:
return "Core Studio Profile @ Level 4";
case 0xF0:
return "Advanced Simple Profile @ Level 0";
case 0xF1:
return "Advanced Simple Profile @ Level 1";
case 0xF2:
return "Advanced Simple Profile @ Level 2";
case 0xF3:
return "Advanced Simple Profile @ Level 3";
case 0xF4:
return "Advanced Simple Profile @ Level 4";
case 0xF5:
return "Advanced Simple Profile @ Level 5";
case 0xF7:
return "Advanced Simple Profile @ Level 3b";
case 0xF8:
return "Fine Granularity Scalable Profile @ Level 0";
case 0xF9:
return "Fine Granularity Scalable Profile @ Level 1";
case 0xFA:
return "Fine Granularity Scalable Profile @ Level 2";
case 0xFB:
return "Fine Granularity Scalable Profile @ Level 3";
case 0xFC:
return "Fine Granularity Scalable Profile @ Level 4";
case 0xFD:
return "Fine Granularity Scalable Profile @ Level 5";
case 0xFE:
return "Not part of MPEG-4 Visual profiles";
case 0xFF:
return "No visual capability required";
default:
return "ISO Reserved Profile";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
#define MPEG12_START_CODE_PREFIX 0x000001
#define MPEG12_PICTURE_START_CODE 0x00000100
#define MPEG12_SLICE_MIN_START 0x00000101
#define MPEG12_SLICE_MAX_START 0x000001af
#define MPEG12_USER_DATA_START_CODE 0x000001b2
#define MPEG12_SEQUENCE_START_CODE 0x000001b3
#define MPEG12_SEQUENCE_ERR_START_CODE 0x000001b4
#define MPEG12_EXT_START_CODE 0x000001b5
#define MPEG12_SEQUENCE_END_START_CODE 0x000001b7
#define MPEG12_GOP_START_CODE 0x000001b8
s32 gf_mv12_next_start_code(unsigned char *pbuffer, u32 buflen, u32 *optr, u32 *scode)
{
u32 value;
u32 offset;
if (buflen < 4) return -1;
for (offset = 0; offset < buflen - 3; offset++, pbuffer++) {
#ifdef GPAC_BIG_ENDIAN
value = *(u32 *)pbuffer >> 8;
#else
value = (pbuffer[0] << 16) | (pbuffer[1] << 8) | (pbuffer[2] << 0);
#endif
if (value == MPEG12_START_CODE_PREFIX) {
*optr = offset;
*scode = (value << 8) | pbuffer[3];
return 0;
}
}
return -1;
}
s32 gf_mv12_next_slice_start(unsigned char *pbuffer, u32 startoffset, u32 buflen, u32 *slice_offset)
{
u32 slicestart, code;
while (gf_mv12_next_start_code(pbuffer + startoffset, buflen - startoffset, &slicestart, &code) >= 0) {
if ((code >= MPEG12_SLICE_MIN_START) && (code <= MPEG12_SLICE_MAX_START)) {
*slice_offset = slicestart + startoffset;
return 0;
}
startoffset += slicestart + 4;
}
return -1;
}
/*
MPEG-4 video (14496-2)
*/
#define M4V_VO_START_CODE 0x00
#define M4V_VOL_START_CODE 0x20
#define M4V_VOP_START_CODE 0xB6
#define M4V_VISOBJ_START_CODE 0xB5
#define M4V_VOS_START_CODE 0xB0
#define M4V_GOV_START_CODE 0xB3
#define M4V_UDTA_START_CODE 0xB2
#define M2V_PIC_START_CODE 0x00
#define M2V_SEQ_START_CODE 0xB3
#define M2V_EXT_START_CODE 0xB5
#define M2V_GOP_START_CODE 0xB8
struct __tag_m4v_parser
{
GF_BitStream *bs;
Bool mpeg12;
u32 current_object_type;
u64 current_object_start;
u32 tc_dec, prev_tc_dec, tc_disp, prev_tc_disp;
};
GF_EXPORT
GF_M4VParser *gf_m4v_parser_new(char *data, u64 data_size, Bool mpeg12video)
{
GF_M4VParser *tmp;
if (!data || !data_size) return NULL;
GF_SAFEALLOC(tmp, GF_M4VParser);
if (!tmp) return NULL;
tmp->bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
tmp->mpeg12 = mpeg12video;
return tmp;
}
GF_M4VParser *gf_m4v_parser_bs_new(GF_BitStream *bs, Bool mpeg12video)
{
GF_M4VParser *tmp;
GF_SAFEALLOC(tmp, GF_M4VParser);
if (!tmp) return NULL;
tmp->bs = bs;
tmp->mpeg12 = mpeg12video;
return tmp;
}
GF_EXPORT
void gf_m4v_parser_del(GF_M4VParser *m4v)
{
gf_bs_del(m4v->bs);
gf_free(m4v);
}
#define M4V_CACHE_SIZE 4096
s32 M4V_LoadObject(GF_M4VParser *m4v)
{
u32 v, bpos, found;
char m4v_cache[M4V_CACHE_SIZE];
u64 end, cache_start, load_size;
if (!m4v) return 0;
bpos = 0;
found = 0;
load_size = 0;
end = 0;
cache_start = 0;
v = 0xffffffff;
while (!end) {
/*refill cache*/
if (bpos == (u32) load_size) {
if (!gf_bs_available(m4v->bs)) break;
load_size = gf_bs_available(m4v->bs);
if (load_size>M4V_CACHE_SIZE) load_size=M4V_CACHE_SIZE;
bpos = 0;
cache_start = gf_bs_get_position(m4v->bs);
gf_bs_read_data(m4v->bs, m4v_cache, (u32) load_size);
}
v = ( (v<<8) & 0xFFFFFF00) | ((u8) m4v_cache[bpos]);
bpos++;
if ((v & 0xFFFFFF00) == 0x00000100) {
end = cache_start+bpos-4;
found = 1;
break;
}
}
if (!found) return -1;
m4v->current_object_start = end;
gf_bs_seek(m4v->bs, end+3);
m4v->current_object_type = gf_bs_read_u8(m4v->bs);
return (s32) m4v->current_object_type;
}
GF_EXPORT
void gf_m4v_rewrite_pl(char **o_data, u32 *o_dataLen, u8 PL)
{
u32 pos = 0;
unsigned char *data = (unsigned char *)*o_data;
u32 dataLen = *o_dataLen;
while (pos+4<dataLen) {
if (!data[pos] && !data[pos+1] && (data[pos+2]==0x01) && (data[pos+3]==M4V_VOS_START_CODE)) {
data[pos+4] = PL;
return;
}
pos ++;
}
/*emulate VOS at beggining*/
(*o_data) = (char *)gf_malloc(sizeof(char)*(dataLen+5));
(*o_data)[0] = 0;
(*o_data)[1] = 0;
(*o_data)[2] = 1;
(*o_data)[3] = (char) M4V_VOS_START_CODE;
(*o_data)[4] = PL;
memcpy( (*o_data + 5), data, sizeof(char)*dataLen);
gf_free(data);
(*o_dataLen) = dataLen + 5;
}
static GF_Err M4V_Reset(GF_M4VParser *m4v, u64 start)
{
gf_bs_seek(m4v->bs, start);
assert(start < 1<<31);
m4v->current_object_start = (u32) start;
m4v->current_object_type = 0;
return GF_OK;
}
static GF_Err gf_m4v_parse_config_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
{
unsigned char p[4];
u32 ext_type;
s32 o_type;
u8 go, par;
if (!m4v || !dsi) return GF_BAD_PARAM;
memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
dsi->VideoPL = 0;
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
case M2V_SEQ_START_CODE:
dsi->RAP_stream = 1;
gf_bs_read_data(m4v->bs, (char *) p, 4);
dsi->width = (p[0] << 4) | ((p[1] >> 4) & 0xf);
dsi->height = ((p[1] & 0xf) << 8) | p[2];
dsi->VideoPL = GPAC_OTI_VIDEO_MPEG1;
par = (p[3] >> 4) & 0xf;
switch (par) {
case 2:
dsi->par_num = dsi->height/3;
dsi->par_den = dsi->width/4;
break;
case 3:
dsi->par_num = dsi->height/9;
dsi->par_den = dsi->width/16;
break;
case 4:
dsi->par_num = dsi->height/2;
dsi->par_den = dsi->width/21;
break;
default:
dsi->par_den = dsi->par_num = 0;
break;
}
switch (p[3] & 0xf) {
case 0:
break;
case 1:
dsi->fps = 24000.0/1001.0;
break;
case 2:
dsi->fps = 24.0;
break;
case 3:
dsi->fps = 25.0;
break;
case 4:
dsi->fps = 30000.0/1001.0;
break;
case 5:
dsi->fps = 30.0;
break;
case 6:
dsi->fps = 50.0;
break;
case 7:
dsi->fps = ((60.0*1000.0)/1001.0);
break;
case 8:
dsi->fps = 60.0;
break;
case 9:
dsi->fps = 1;
break;
case 10:
dsi->fps = 5;
break;
case 11:
dsi->fps = 10;
break;
case 12:
dsi->fps = 12;
break;
case 13:
dsi->fps = 15;
break;
}
break;
case M2V_EXT_START_CODE:
gf_bs_read_data(m4v->bs, (char *) p, 4);
ext_type = ((p[0] >> 4) & 0xf);
if (ext_type == 1) {
dsi->VideoPL = 0x65;
dsi->height = ((p[1] & 0x1) << 13) | ((p[2] & 0x80) << 5) | (dsi->height & 0x0fff);
dsi->width = (((p[2] >> 5) & 0x3) << 12) | (dsi->width & 0x0fff);
}
break;
case M2V_PIC_START_CODE:
if (dsi->width) go = 0;
break;
default:
break;
/*EOS*/
case -1:
go = 0;
m4v->current_object_start = gf_bs_get_position(m4v->bs);
break;
}
}
M4V_Reset(m4v, 0);
return GF_OK;
}
static const struct {
u32 w, h;
} m4v_sar[6] = { { 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 }, { 40, 33 } };
static u8 m4v_get_sar_idx(u32 w, u32 h)
{
u32 i;
for (i=0; i<6; i++) {
if ((m4v_sar[i].w==w) && (m4v_sar[i].h==h)) return i;
}
return 0xF;
}
static GF_Err gf_m4v_parse_config_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
{
s32 o_type;
u8 go, verid, par;
s32 clock_rate;
if (!m4v || !dsi) return GF_BAD_PARAM;
memset(dsi, 0, sizeof(GF_M4VDecSpecInfo));
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
/*vosh*/
case M4V_VOS_START_CODE:
dsi->VideoPL = (u8) gf_bs_read_u8(m4v->bs);
break;
case M4V_VOL_START_CODE:
verid = 0;
dsi->RAP_stream = gf_bs_read_int(m4v->bs, 1);
dsi->objectType = gf_bs_read_int(m4v->bs, 8);
if (gf_bs_read_int(m4v->bs, 1)) {
verid = gf_bs_read_int(m4v->bs, 4);
gf_bs_read_int(m4v->bs, 3);
}
par = gf_bs_read_int(m4v->bs, 4);
if (par == 0xF) {
dsi->par_num = gf_bs_read_int(m4v->bs, 8);
dsi->par_den = gf_bs_read_int(m4v->bs, 8);
} else if (par<6) {
dsi->par_num = m4v_sar[par].w;
dsi->par_den = m4v_sar[par].h;
}
if (gf_bs_read_int(m4v->bs, 1)) {
gf_bs_read_int(m4v->bs, 3);
if (gf_bs_read_int(m4v->bs, 1)) gf_bs_read_int(m4v->bs, 79);
}
dsi->has_shape = gf_bs_read_int(m4v->bs, 2);
if (dsi->has_shape && (verid!=1) ) gf_bs_read_int(m4v->bs, 4);
gf_bs_read_int(m4v->bs, 1);
/*clock rate*/
dsi->clock_rate = gf_bs_read_int(m4v->bs, 16);
/*marker*/
gf_bs_read_int(m4v->bs, 1);
clock_rate = dsi->clock_rate-1;
if (clock_rate >= 65536) clock_rate = 65535;
if (clock_rate > 0) {
for (dsi->NumBitsTimeIncrement = 1; dsi->NumBitsTimeIncrement < 16; dsi->NumBitsTimeIncrement++) {
if (clock_rate == 1) break;
clock_rate = (clock_rate >> 1);
}
} else {
/*fix from vivien for divX*/
dsi->NumBitsTimeIncrement = 1;
}
/*fixed FPS stream*/
dsi->time_increment = 0;
if (gf_bs_read_int(m4v->bs, 1)) {
dsi->time_increment = gf_bs_read_int(m4v->bs, dsi->NumBitsTimeIncrement);
}
if (!dsi->has_shape) {
gf_bs_read_int(m4v->bs, 1);
dsi->width = gf_bs_read_int(m4v->bs, 13);
gf_bs_read_int(m4v->bs, 1);
dsi->height = gf_bs_read_int(m4v->bs, 13);
} else {
dsi->width = dsi->height = 0;
}
/*shape will be done later*/
gf_bs_align(m4v->bs);
break;
case M4V_VOP_START_CODE:
case M4V_GOV_START_CODE:
go = 0;
break;
/*EOS*/
case -1:
go = 0;
m4v->current_object_start = gf_bs_get_position(m4v->bs);
break;
/*don't interest us*/
case M4V_UDTA_START_CODE:
default:
break;
}
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4v_parse_config(GF_M4VParser *m4v, GF_M4VDecSpecInfo *dsi)
{
if (m4v->mpeg12) {
return gf_m4v_parse_config_mpeg12(m4v, dsi);
} else {
return gf_m4v_parse_config_mpeg4(m4v, dsi);
}
}
static GF_Err gf_m4v_parse_frame_mpeg12(GF_M4VParser *m4v, GF_M4VDecSpecInfo dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
{
u8 go, hasVOP, firstObj, val;
s32 o_type;
if (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;
*size = 0;
firstObj = 1;
hasVOP = 0;
*is_coded = GF_FALSE;
m4v->current_object_type = (u32) -1;
*frame_type = 0;
M4V_Reset(m4v, m4v->current_object_start);
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
case M2V_PIC_START_CODE:
/*done*/
if (hasVOP) {
go = 0;
break;
}
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
hasVOP = 1;
*is_coded = 1;
/*val = */gf_bs_read_u8(m4v->bs);
val = gf_bs_read_u8(m4v->bs);
*frame_type = ( (val >> 3) & 0x7 ) - 1;
break;
case M2V_GOP_START_CODE:
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
if (hasVOP) go = 0;
break;
case M2V_SEQ_START_CODE:
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
if (hasVOP) {
go = 0;
break;
}
/**/
break;
default:
break;
case -1:
*size = gf_bs_get_position(m4v->bs) - *start;
return GF_EOS;
}
}
*size = m4v->current_object_start - *start;
return GF_OK;
}
static GF_Err gf_m4v_parse_frame_mpeg4(GF_M4VParser *m4v, GF_M4VDecSpecInfo dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
{
u8 go, hasVOP, firstObj, secs;
s32 o_type;
u32 vop_inc = 0;
if (!m4v || !size || !start || !frame_type) return GF_BAD_PARAM;
*size = 0;
firstObj = 1;
hasVOP = 0;
*is_coded = 0;
m4v->current_object_type = (u32) -1;
*frame_type = 0;
M4V_Reset(m4v, m4v->current_object_start);
go = 1;
while (go) {
o_type = M4V_LoadObject(m4v);
switch (o_type) {
case M4V_VOP_START_CODE:
/*done*/
if (hasVOP) {
go = 0;
break;
}
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
hasVOP = 1;
/*coding type*/
*frame_type = gf_bs_read_int(m4v->bs, 2);
/*modulo time base*/
secs = 0;
while (gf_bs_read_int(m4v->bs, 1) != 0)
secs ++;
/*no support for B frames in parsing*/
secs += (dsi.enh_layer || *frame_type!=2) ? m4v->tc_dec : m4v->tc_disp;
/*marker*/
gf_bs_read_int(m4v->bs, 1);
/*vop_time_inc*/
if (dsi.NumBitsTimeIncrement)
vop_inc = gf_bs_read_int(m4v->bs, dsi.NumBitsTimeIncrement);
m4v->prev_tc_dec = m4v->tc_dec;
m4v->prev_tc_disp = m4v->tc_disp;
if (dsi.enh_layer || *frame_type!=2) {
m4v->tc_disp = m4v->tc_dec;
m4v->tc_dec = secs;
}
*time_inc = secs * dsi.clock_rate + vop_inc;
/*marker*/
gf_bs_read_int(m4v->bs, 1);
/*coded*/
*is_coded = gf_bs_read_int(m4v->bs, 1);
gf_bs_align(m4v->bs);
break;
case M4V_GOV_START_CODE:
if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
if (hasVOP) go = 0;
break;
case M4V_VOS_START_CODE:
case M4V_VOL_START_CODE:
if (hasVOP) {
go = 0;
} else if (firstObj) {
*start = m4v->current_object_start;
firstObj = 0;
}
break;
case M4V_VO_START_CODE:
default:
break;
case -1:
*size = gf_bs_get_position(m4v->bs) - *start;
return GF_EOS;
}
}
*size = m4v->current_object_start - *start;
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4v_parse_frame(GF_M4VParser *m4v, GF_M4VDecSpecInfo dsi, u8 *frame_type, u32 *time_inc, u64 *size, u64 *start, Bool *is_coded)
{
if (m4v->mpeg12) {
return gf_m4v_parse_frame_mpeg12(m4v, dsi, frame_type, time_inc, size, start, is_coded);
} else {
return gf_m4v_parse_frame_mpeg4(m4v, dsi, frame_type, time_inc, size, start, is_coded);
}
}
GF_Err gf_m4v_rewrite_par(char **o_data, u32 *o_dataLen, s32 par_n, s32 par_d)
{
u64 start, end, size;
GF_BitStream *mod;
GF_M4VParser *m4v;
Bool go = 1;
m4v = gf_m4v_parser_new(*o_data, *o_dataLen, 0);
mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
start = 0;
while (go) {
u32 type = M4V_LoadObject(m4v);
end = gf_bs_get_position(m4v->bs) - 4;
size = end - start;
/*store previous object*/
if (size) {
assert (size < 1<<31);
if (size) gf_bs_write_data(mod, *o_data + start, (u32) size);
start = end;
}
switch (type) {
case M4V_VOL_START_CODE:
gf_bs_write_int(mod, 0, 8);
gf_bs_write_int(mod, 0, 8);
gf_bs_write_int(mod, 1, 8);
gf_bs_write_int(mod, M4V_VOL_START_CODE, 8);
gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 1), 1);
gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 8), 8);
start = gf_bs_read_int(m4v->bs, 1);
gf_bs_write_int(mod, (u32) start, 1);
if (start) {
gf_bs_write_int(mod, gf_bs_read_int(m4v->bs, 7), 7);
}
start = gf_bs_read_int(m4v->bs, 4);
if (start == 0xF) {
gf_bs_read_int(m4v->bs, 8);
gf_bs_read_int(m4v->bs, 8);
}
if ((par_n>=0) && (par_d>=0)) {
u8 par = m4v_get_sar_idx(par_n, par_d);
gf_bs_write_int(mod, par, 4);
if (par==0xF) {
gf_bs_write_int(mod, par_n, 8);
gf_bs_write_int(mod, par_d, 8);
}
} else {
gf_bs_write_int(mod, 0x0, 4);
}
case -1:
go = 0;
break;
default:
break;
}
}
while (gf_bs_bits_available(m4v->bs)) {
u32 b = gf_bs_read_int(m4v->bs, 1);
gf_bs_write_int(mod, b, 1);
}
gf_m4v_parser_del(m4v);
gf_free(*o_data);
gf_bs_get_content(mod, o_data, o_dataLen);
gf_bs_del(mod);
return GF_OK;
}
GF_EXPORT
u64 gf_m4v_get_object_start(GF_M4VParser *m4v)
{
return m4v->current_object_start;
}
GF_EXPORT
Bool gf_m4v_is_valid_object_type(GF_M4VParser *m4v)
{
return ((s32) m4v->current_object_type==-1) ? 0 : 1;
}
GF_EXPORT
GF_Err gf_m4v_get_config(char *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)
{
GF_Err e;
GF_M4VParser *vparse;
if (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;
vparse = gf_m4v_parser_new(rawdsi, rawdsi_size, 0);
e = gf_m4v_parse_config(vparse, dsi);
dsi->next_object_start = (u32) vparse->current_object_start;
gf_m4v_parser_del(vparse);
return e;
}
GF_EXPORT
GF_Err gf_mpegv12_get_config(char *rawdsi, u32 rawdsi_size, GF_M4VDecSpecInfo *dsi)
{
GF_Err e;
GF_M4VParser *vparse;
if (!rawdsi || !rawdsi_size) return GF_NON_COMPLIANT_BITSTREAM;
vparse = gf_m4v_parser_new(rawdsi, rawdsi_size, GF_TRUE);
e = gf_m4v_parse_config(vparse, dsi);
dsi->next_object_start = (u32) vparse->current_object_start;
gf_m4v_parser_del(vparse);
return e;
}
#endif
/*
AAC parser
*/
GF_EXPORT
const char *gf_m4a_object_type_name(u32 objectType)
{
switch (objectType) {
case 0:
return "MPEG-4 Audio Reserved";
case 1:
return "MPEG-4 Audio AAC Main";
case 2:
return "MPEG-4 Audio AAC LC";
case 3:
return "MPEG-4 Audio AAC SSR";
case 4:
return "MPEG-4 Audio AAC LTP";
case 5:
return "MPEG-4 Audio SBR";
case 6:
return "MPEG-4 Audio AAC Scalable";
case 7:
return "MPEG-4 Audio TwinVQ";
case 8:
return "MPEG-4 Audio CELP";
case 9:
return "MPEG-4 Audio HVXC";
case 10:
return "MPEG-4 Audio Reserved";
case 11:
return "MPEG-4 Audio Reserved";
case 12:
return "MPEG-4 Audio TTSI";
case 13:
return "MPEG-4 Audio Main synthetic";
case 14:
return "MPEG-4 Audio Wavetable synthesis";
case 15:
return "MPEG-4 Audio General MIDI";
case 16:
return "MPEG-4 Audio Algorithmic Synthesis and Audio FX";
case 17:
return "MPEG-4 Audio ER AAC LC";
case 18:
return "MPEG-4 Audio Reserved";
case 19:
return "MPEG-4 Audio ER AAC LTP";
case 20:
return "MPEG-4 Audio ER AAC scalable";
case 21:
return "MPEG-4 Audio ER TwinVQ";
case 22:
return "MPEG-4 Audio ER BSAC";
case 23:
return "MPEG-4 Audio ER AAC LD";
case 24:
return "MPEG-4 Audio ER CELP";
case 25:
return "MPEG-4 Audio ER HVXC";
case 26:
return "MPEG-4 Audio ER HILN";
case 27:
return "MPEG-4 Audio ER Parametric";
case 28:
return "MPEG-4 Audio SSC";
case 29:
return "MPEG-4 Audio ParametricStereo";
case 30:
return "MPEG-4 Audio Reserved";
case 31:
return "MPEG-4 Audio Reserved";
case 32:
return "MPEG-1 Audio Layer-1";
case 33:
return "MPEG-1 Audio Layer-2";
case 34:
return "MPEG-1 Audio Layer-3";
case 35:
return "MPEG-4 Audio DST";
case 36:
return "MPEG-4 Audio ALS";
default:
return "MPEG-4 Audio Unknown";
}
}
GF_EXPORT
const char *gf_m4a_get_profile_name(u8 audio_pl)
{
switch (audio_pl) {
case 0x00:
return "ISO Reserved (0x00)";
case 0x01:
return "Main Audio Profile @ Level 1";
case 0x02:
return "Main Audio Profile @ Level 2";
case 0x03:
return "Main Audio Profile @ Level 3";
case 0x04:
return "Main Audio Profile @ Level 4";
case 0x05:
return "Scalable Audio Profile @ Level 1";
case 0x06:
return "Scalable Audio Profile @ Level 2";
case 0x07:
return "Scalable Audio Profile @ Level 3";
case 0x08:
return "Scalable Audio Profile @ Level 4";
case 0x09:
return "Speech Audio Profile @ Level 1";
case 0x0A:
return "Speech Audio Profile @ Level 2";
case 0x0B:
return "Synthetic Audio Profile @ Level 1";
case 0x0C:
return "Synthetic Audio Profile @ Level 2";
case 0x0D:
return "Synthetic Audio Profile @ Level 3";
case 0x0E:
return "High Quality Audio Profile @ Level 1";
case 0x0F:
return "High Quality Audio Profile @ Level 2";
case 0x10:
return "High Quality Audio Profile @ Level 3";
case 0x11:
return "High Quality Audio Profile @ Level 4";
case 0x12:
return "High Quality Audio Profile @ Level 5";
case 0x13:
return "High Quality Audio Profile @ Level 6";
case 0x14:
return "High Quality Audio Profile @ Level 7";
case 0x15:
return "High Quality Audio Profile @ Level 8";
case 0x16:
return "Low Delay Audio Profile @ Level 1";
case 0x17:
return "Low Delay Audio Profile @ Level 2";
case 0x18:
return "Low Delay Audio Profile @ Level 3";
case 0x19:
return "Low Delay Audio Profile @ Level 4";
case 0x1A:
return "Low Delay Audio Profile @ Level 5";
case 0x1B:
return "Low Delay Audio Profile @ Level 6";
case 0x1C:
return "Low Delay Audio Profile @ Level 7";
case 0x1D:
return "Low Delay Audio Profile @ Level 8";
case 0x1E:
return "Natural Audio Profile @ Level 1";
case 0x1F:
return "Natural Audio Profile @ Level 2";
case 0x20:
return "Natural Audio Profile @ Level 3";
case 0x21:
return "Natural Audio Profile @ Level 4";
case 0x22:
return "Mobile Audio Internetworking Profile @ Level 1";
case 0x23:
return "Mobile Audio Internetworking Profile @ Level 2";
case 0x24:
return "Mobile Audio Internetworking Profile @ Level 3";
case 0x25:
return "Mobile Audio Internetworking Profile @ Level 4";
case 0x26:
return "Mobile Audio Internetworking Profile @ Level 5";
case 0x27:
return "Mobile Audio Internetworking Profile @ Level 6";
case 0x28:
return "AAC Profile @ Level 1";
case 0x29:
return "AAC Profile @ Level 2";
case 0x2A:
return "AAC Profile @ Level 4";
case 0x2B:
return "AAC Profile @ Level 5";
case 0x2C:
return "High Efficiency AAC Profile @ Level 2";
case 0x2D:
return "High Efficiency AAC Profile @ Level 3";
case 0x2E:
return "High Efficiency AAC Profile @ Level 4";
case 0x2F:
return "High Efficiency AAC Profile @ Level 5";
case 0x30:
return "High Efficiency AAC v2 Profile @ Level 2";
case 0x31:
return "High Efficiency AAC v2 Profile @ Level 3";
case 0x32:
return "High Efficiency AAC v2 Profile @ Level 4";
case 0x33:
return "High Efficiency AAC v2 Profile @ Level 5";
case 0x34:
return "Low Delay AAC Profile";
case 0x35:
return "Baseline MPEG Surround Profile @ Level 1";
case 0x36:
return "Baseline MPEG Surround Profile @ Level 2";
case 0x37:
return "Baseline MPEG Surround Profile @ Level 3";
case 0x38:
return "Baseline MPEG Surround Profile @ Level 4";
case 0x39:
return "Baseline MPEG Surround Profile @ Level 5";
case 0x3A:
return "Baseline MPEG Surround Profile @ Level 6";
case 0x50:
return "AAC Profile @ Level 6";
case 0x51:
return "AAC Profile @ Level 7";
case 0x52:
return "High Efficiency AAC Profile @ Level 6";
case 0x53:
return "High Efficiency AAC Profile @ Level 7";
case 0x54:
return "High Efficiency AAC v2 Profile @ Level 6";
case 0x55:
return "High Efficiency AAC v2 Profile @ Level 7";
case 0x56:
return "Extended High Efficiency AAC Profile @ Level 6";
case 0x57:
return "Extended High Efficiency AAC Profile @ Level 7";
case 0xFE:
return "Not part of MPEG-4 audio profiles";
case 0xFF:
return "No audio capability required";
default:
return "ISO Reserved / User Private";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
GF_EXPORT
u32 gf_m4a_get_profile(GF_M4ADecSpecInfo *cfg)
{
switch (cfg->base_object_type) {
case 2: /*AAC LC*/
if (cfg->nb_chan<=2)
return (cfg->base_sr<=24000) ? 0x28 : 0x29; /*LC@L1 or LC@L2*/
if (cfg->nb_chan<=5)
return (cfg->base_sr<=48000) ? 0x2A : 0x2B; /*LC@L4 or LC@L5*/
return (cfg->base_sr<=48000) ? 0x50 : 0x51; /*LC@L4 or LC@L5*/
case 5: /*HE-AAC - SBR*/
if (cfg->nb_chan<=2)
return (cfg->base_sr<=24000) ? 0x2C : 0x2D; /*HE@L2 or HE@L3*/
if (cfg->nb_chan<=5)
return (cfg->base_sr<=48000) ? 0x2E : 0x2F; /*HE@L4 or HE@L5*/
return (cfg->base_sr<=48000) ? 0x52 : 0x53; /*HE@L6 or HE@L7*/
case 29: /*HE-AACv2 - SBR+PS*/
if (cfg->nb_chan<=2)
return (cfg->base_sr<=24000) ? 0x30 : 0x31; /*HE-AACv2@L2 or HE-AACv2@L3*/
if (cfg->nb_chan<=5)
return (cfg->base_sr<=48000) ? 0x32 : 0x33; /*HE-AACv2@L4 or HE-AACv2@L5*/
return (cfg->base_sr<=48000) ? 0x54 : 0x55; /*HE-AACv2@L6 or HE-AACv2@L7*/
/*default to HQ*/
default:
if (cfg->nb_chan<=2) return (cfg->base_sr<24000) ? 0x0E : 0x0F; /*HQ@L1 or HQ@L2*/
return 0x10; /*HQ@L3*/
}
}
GF_EXPORT
GF_Err gf_m4a_parse_config(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg, Bool size_known)
{
u32 channel_configuration = 0;
memset(cfg, 0, sizeof(GF_M4ADecSpecInfo));
cfg->base_object_type = gf_bs_read_int(bs, 5);
/*extended object type*/
if (cfg->base_object_type==31) {
cfg->base_object_type = 32 + gf_bs_read_int(bs, 6);
}
cfg->base_sr_index = gf_bs_read_int(bs, 4);
if (cfg->base_sr_index == 0x0F) {
cfg->base_sr = gf_bs_read_int(bs, 24);
} else {
cfg->base_sr = GF_M4ASampleRates[cfg->base_sr_index];
}
channel_configuration = gf_bs_read_int(bs, 4);
if (channel_configuration) {
cfg->nb_chan = GF_M4ANumChannels[channel_configuration-1];
}
if (cfg->base_object_type==5 || cfg->base_object_type==29) {
if (cfg->base_object_type==29) {
cfg->has_ps = 1;
cfg->nb_chan = 1;
}
cfg->has_sbr = GF_TRUE;
cfg->sbr_sr_index = gf_bs_read_int(bs, 4);
if (cfg->sbr_sr_index == 0x0F) {
cfg->sbr_sr = gf_bs_read_int(bs, 24);
} else {
cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
}
cfg->sbr_object_type = gf_bs_read_int(bs, 5);
}
/*object cfg*/
switch (cfg->base_object_type) {
case 1:
case 2:
case 3:
case 4:
case 6:
case 7:
case 17:
case 19:
case 20:
case 21:
case 22:
case 23:
{
Bool ext_flag;
/*frame length flag*/
/*fl_flag = */gf_bs_read_int(bs, 1);
/*depends on core coder*/
if (gf_bs_read_int(bs, 1))
/*delay = */gf_bs_read_int(bs, 14);
ext_flag = gf_bs_read_int(bs, 1);
if (! channel_configuration) {
u32 i;
cfg->program_config_element_present = 1;
cfg->element_instance_tag = gf_bs_read_int(bs, 4);
cfg->object_type = gf_bs_read_int(bs, 2);
cfg->sampling_frequency_index = gf_bs_read_int(bs, 4);
cfg->num_front_channel_elements = gf_bs_read_int(bs, 4);
cfg->num_side_channel_elements = gf_bs_read_int(bs, 4);
cfg->num_back_channel_elements = gf_bs_read_int(bs, 4);
cfg->num_lfe_channel_elements = gf_bs_read_int(bs, 2);
cfg->num_assoc_data_elements = gf_bs_read_int(bs, 3);
cfg->num_valid_cc_elements = gf_bs_read_int(bs, 4);
cfg-> mono_mixdown_present = (Bool) gf_bs_read_int(bs, 1);
if (cfg->mono_mixdown_present) {
cfg->mono_mixdown_element_number = gf_bs_read_int(bs, 4);
}
cfg->stereo_mixdown_present = gf_bs_read_int(bs, 1);
if (cfg->stereo_mixdown_present) {
cfg->stereo_mixdown_element_number = gf_bs_read_int(bs, 4);
}
cfg->matrix_mixdown_idx_present = gf_bs_read_int(bs, 1);
if (cfg->matrix_mixdown_idx_present) {
cfg->matrix_mixdown_idx = gf_bs_read_int(bs, 2);
cfg->pseudo_surround_enable = gf_bs_read_int(bs, 1);
}
for (i = 0; i < cfg->num_front_channel_elements; i++) {
cfg->front_element_is_cpe[i] = gf_bs_read_int(bs, 1);
cfg->front_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_side_channel_elements; i++) {
cfg->side_element_is_cpe[i] = gf_bs_read_int(bs, 1);
cfg->side_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_back_channel_elements; i++) {
cfg->back_element_is_cpe[i] = gf_bs_read_int(bs, 1);
cfg->back_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_lfe_channel_elements; i++) {
cfg->lfe_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for ( i = 0; i < cfg->num_assoc_data_elements; i++) {
cfg->assoc_data_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
for (i = 0; i < cfg->num_valid_cc_elements; i++) {
cfg->cc_element_is_ind_sw[i] = gf_bs_read_int(bs, 1);
cfg->valid_cc_element_tag_select[i] = gf_bs_read_int(bs, 4);
}
gf_bs_align(bs);
cfg->comment_field_bytes = gf_bs_read_int(bs, 8);
gf_bs_read_data(bs, (char *) cfg->comments, cfg->comment_field_bytes);
cfg->nb_chan = cfg->num_front_channel_elements + cfg->num_back_channel_elements + cfg->num_side_channel_elements + cfg->num_lfe_channel_elements;
}
if ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {
gf_bs_read_int(bs, 3);
}
if (ext_flag) {
if (cfg->base_object_type == 22) {
gf_bs_read_int(bs, 5);
gf_bs_read_int(bs, 11);
}
if ((cfg->base_object_type == 17)
|| (cfg->base_object_type == 19)
|| (cfg->base_object_type == 20)
|| (cfg->base_object_type == 23)
) {
gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1);
}
/*ext_flag = */gf_bs_read_int(bs, 1);
}
}
break;
}
/*ER cfg*/
switch (cfg->base_object_type) {
case 17:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
{
u32 epConfig = gf_bs_read_int(bs, 2);
if ((epConfig == 2) || (epConfig == 3) ) {
}
if (epConfig == 3) {
gf_bs_read_int(bs, 1);
}
}
break;
}
if (size_known && (cfg->base_object_type != 5) && (cfg->base_object_type != 29) ) {
while (gf_bs_available(bs)>=2) {
u32 sync = gf_bs_peek_bits(bs, 11, 0);
if (sync==0x2b7) {
gf_bs_read_int(bs, 11);
cfg->sbr_object_type = gf_bs_read_int(bs, 5);
cfg->has_sbr = gf_bs_read_int(bs, 1);
if (cfg->has_sbr) {
cfg->sbr_sr_index = gf_bs_read_int(bs, 4);
if (cfg->sbr_sr_index == 0x0F) {
cfg->sbr_sr = gf_bs_read_int(bs, 24);
} else {
cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
}
}
} else if (sync == 0x548) {
gf_bs_read_int(bs, 11);
cfg->has_ps = gf_bs_read_int(bs, 1);
if (cfg->has_ps)
cfg->nb_chan = 1;
} else {
break;
}
}
}
cfg->audioPL = gf_m4a_get_profile(cfg);
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4a_get_config(char *dsi, u32 dsi_size, GF_M4ADecSpecInfo *cfg)
{
GF_BitStream *bs;
if (!dsi || !dsi_size || (dsi_size<2) ) return GF_NON_COMPLIANT_BITSTREAM;
bs = gf_bs_new(dsi, dsi_size, GF_BITSTREAM_READ);
gf_m4a_parse_config(bs, cfg, 1);
gf_bs_del(bs);
return GF_OK;
}
u32 gf_latm_get_value(GF_BitStream *bs)
{
u32 i, tmp, value = 0;
u32 bytesForValue = gf_bs_read_int(bs, 2);
for (i=0; i <= bytesForValue; i++) {
value <<= 8;
tmp = gf_bs_read_int(bs, 8);
value += tmp;
}
return value;
}
GF_EXPORT
u32 gf_m4a_get_channel_cfg(u32 nb_chan)
{
u32 i, count = sizeof(GF_M4ANumChannels)/sizeof(u32);
for (i=0; i<count; i++) {
if (GF_M4ANumChannels[i] == nb_chan) return i+1;
}
return 0;
}
GF_EXPORT
GF_Err gf_m4a_write_config_bs(GF_BitStream *bs, GF_M4ADecSpecInfo *cfg)
{
if (!cfg->base_sr_index) {
if (!cfg->base_sr) return GF_BAD_PARAM;
while (GF_M4ASampleRates[cfg->base_sr_index]) {
if (GF_M4ASampleRates[cfg->base_sr_index]==cfg->base_sr)
break;
cfg->base_sr_index++;
}
}
if (cfg->sbr_sr && !cfg->sbr_sr_index) {
while (GF_M4ASampleRates[cfg->sbr_sr_index]) {
if (GF_M4ASampleRates[cfg->sbr_sr_index]==cfg->sbr_sr)
break;
cfg->sbr_sr_index++;
}
}
/*extended object type*/
if (cfg->base_object_type>=32) {
gf_bs_write_int(bs, 31, 5);
gf_bs_write_int(bs, cfg->base_object_type-32, 6);
} else {
gf_bs_write_int(bs, cfg->base_object_type, 5);
}
gf_bs_write_int(bs, cfg->base_sr_index, 4);
if (cfg->base_sr_index == 0x0F) {
gf_bs_write_int(bs, cfg->base_sr, 24);
}
if (cfg->program_config_element_present) {
gf_bs_write_int(bs, 0, 4);
} else {
gf_bs_write_int(bs, gf_m4a_get_channel_cfg( cfg->nb_chan) , 4);
}
if (cfg->base_object_type==5 || cfg->base_object_type==29) {
if (cfg->base_object_type == 29) {
cfg->has_ps = 1;
cfg->nb_chan = 1;
}
cfg->has_sbr = 1;
gf_bs_write_int(bs, cfg->sbr_sr_index, 4);
if (cfg->sbr_sr_index == 0x0F) {
gf_bs_write_int(bs, cfg->sbr_sr, 24);
}
gf_bs_write_int(bs, cfg->sbr_object_type, 5);
}
/*object cfg*/
switch (cfg->base_object_type) {
case 1:
case 2:
case 3:
case 4:
case 6:
case 7:
case 17:
case 19:
case 20:
case 21:
case 22:
case 23:
{
/*frame length flag*/
gf_bs_write_int(bs, 0, 1);
/*depends on core coder*/
gf_bs_write_int(bs, 0, 1);
/*ext flag*/
gf_bs_write_int(bs, 0, 1);
if (cfg->program_config_element_present) {
u32 i;
gf_bs_write_int(bs, cfg->element_instance_tag, 4);
gf_bs_write_int(bs, cfg->object_type, 2);
gf_bs_write_int(bs, cfg->sampling_frequency_index, 4);
gf_bs_write_int(bs, cfg->num_front_channel_elements, 4);
gf_bs_write_int(bs, cfg->num_side_channel_elements, 4);
gf_bs_write_int(bs, cfg->num_back_channel_elements, 4);
gf_bs_write_int(bs, cfg->num_lfe_channel_elements, 2);
gf_bs_write_int(bs, cfg->num_assoc_data_elements, 3);
gf_bs_write_int(bs, cfg->num_valid_cc_elements, 4);
gf_bs_write_int(bs, cfg-> mono_mixdown_present, 1);
if (cfg->mono_mixdown_present) {
gf_bs_write_int(bs, cfg->mono_mixdown_element_number, 4);
}
gf_bs_write_int(bs, cfg->stereo_mixdown_present, 1);
if (cfg->stereo_mixdown_present) {
gf_bs_write_int(bs, cfg->stereo_mixdown_element_number, 4);
}
gf_bs_write_int(bs, cfg->matrix_mixdown_idx_present, 1);
if (cfg->matrix_mixdown_idx_present) {
gf_bs_write_int(bs, cfg->matrix_mixdown_idx, 2);
gf_bs_write_int(bs, cfg->pseudo_surround_enable, 1);
}
for (i = 0; i < cfg->num_front_channel_elements; i++) {
gf_bs_write_int(bs, cfg->front_element_is_cpe[i], 1);
gf_bs_write_int(bs, cfg->front_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_side_channel_elements; i++) {
gf_bs_write_int(bs, cfg->side_element_is_cpe[i], 1);
gf_bs_write_int(bs, cfg->side_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_back_channel_elements; i++) {
gf_bs_write_int(bs, cfg->back_element_is_cpe[i], 1);
gf_bs_write_int(bs, cfg->back_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_lfe_channel_elements; i++) {
gf_bs_write_int(bs, cfg->lfe_element_tag_select[i], 4);
}
for ( i = 0; i < cfg->num_assoc_data_elements; i++) {
gf_bs_write_int(bs, cfg->assoc_data_element_tag_select[i], 4);
}
for (i = 0; i < cfg->num_valid_cc_elements; i++) {
gf_bs_write_int(bs, cfg->cc_element_is_ind_sw[i], 1);
gf_bs_write_int(bs, cfg->valid_cc_element_tag_select[i], 4);
}
gf_bs_align(bs);
gf_bs_write_int(bs, cfg->comment_field_bytes, 8);
gf_bs_write_data(bs, (char *) cfg->comments, cfg->comment_field_bytes);
}
if ((cfg->base_object_type == 6) || (cfg->base_object_type == 20)) {
gf_bs_write_int(bs, 0, 3);
}
}
break;
}
/*ER cfg - not supported*/
/*implicit sbr - not used yet*/
if (0 && (cfg->base_object_type != 5) && (cfg->base_object_type != 29) ) {
gf_bs_write_int(bs, 0x2b7, 11);
cfg->sbr_object_type = gf_bs_read_int(bs, 5);
cfg->has_sbr = gf_bs_read_int(bs, 1);
if (cfg->has_sbr) {
cfg->sbr_sr_index = gf_bs_read_int(bs, 4);
if (cfg->sbr_sr_index == 0x0F) {
cfg->sbr_sr = gf_bs_read_int(bs, 24);
} else {
cfg->sbr_sr = GF_M4ASampleRates[cfg->sbr_sr_index];
}
}
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_m4a_write_config(GF_M4ADecSpecInfo *cfg, char **dsi, u32 *dsi_size)
{
GF_BitStream *bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_m4a_write_config_bs(bs, cfg);
gf_bs_get_content(bs, dsi, dsi_size);
gf_bs_del(bs);
return GF_OK;
}
#endif /*GPAC_DISABLE_AV_PARSERS*/
GF_EXPORT
u8 gf_mp3_version(u32 hdr)
{
return ((hdr >> 19) & 0x3);
}
GF_EXPORT
const char *gf_mp3_version_name(u32 hdr)
{
u32 v = gf_mp3_version(hdr);
switch (v) {
case 0:
return "MPEG-2.5";
case 1:
return "Reserved";
case 2:
return "MPEG-2";
case 3:
return "MPEG-1";
default:
return "Unknown";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
GF_EXPORT
u8 gf_mp3_layer(u32 hdr)
{
return 4 - (((hdr >> 17) & 0x3));
}
GF_EXPORT
u8 gf_mp3_num_channels(u32 hdr)
{
if (((hdr >> 6) & 0x3) == 3) return 1;
return 2;
}
GF_EXPORT
u16 gf_mp3_sampling_rate(u32 hdr)
{
u16 res;
/* extract the necessary fields from the MP3 header */
u8 version = gf_mp3_version(hdr);
u8 sampleRateIndex = (hdr >> 10) & 0x3;
switch (sampleRateIndex) {
case 0:
res = 44100;
break;
case 1:
res = 48000;
break;
case 2:
res = 32000;
break;
default:
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] Samplerate index not valid\n"));
return 0;
}
/*reserved or MPEG-1*/
if (version & 1) return res;
/*MPEG-2*/
res /= 2;
/*MPEG-2.5*/
if (version == 0) res /= 2;
return res;
}
GF_EXPORT
u16 gf_mp3_window_size(u32 hdr)
{
u8 version = gf_mp3_version(hdr);
u8 layer = gf_mp3_layer(hdr);
if (layer == 3) {
if (version == 3) return 1152;
return 576;
}
if (layer == 2) return 1152;
return 384;
}
GF_EXPORT
u8 gf_mp3_object_type_indication(u32 hdr)
{
switch (gf_mp3_version(hdr)) {
case 3:
return GPAC_OTI_AUDIO_MPEG1;
case 2:
case 0:
return GPAC_OTI_AUDIO_MPEG2_PART3;
default:
return 0x00;
}
}
/*aligned bitrate parsing with libMAD*/
static
u32 const bitrate_table[5][15] = {
/* MPEG-1 */
{ 0, 32000, 64000, 96000, 128000, 160000, 192000, 224000, /* Layer I */
256000, 288000, 320000, 352000, 384000, 416000, 448000
},
{ 0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer II */
128000, 160000, 192000, 224000, 256000, 320000, 384000
},
{ 0, 32000, 40000, 48000, 56000, 64000, 80000, 96000, /* Layer III */
112000, 128000, 160000, 192000, 224000, 256000, 320000
},
/* MPEG-2 LSF */
{ 0, 32000, 48000, 56000, 64000, 80000, 96000, 112000, /* Layer I */
128000, 144000, 160000, 176000, 192000, 224000, 256000
},
{ 0, 8000, 16000, 24000, 32000, 40000, 48000, 56000, /* Layers */
64000, 80000, 96000, 112000, 128000, 144000, 160000
} /* II & III */
};
u32 gf_mp3_bit_rate(u32 hdr)
{
u8 version = gf_mp3_version(hdr);
u8 layer = gf_mp3_layer(hdr);
u8 bitRateIndex = (hdr >> 12) & 0xF;
if (bitRateIndex == 15) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[MPEG-1/2 Audio] Bitrate index not valid\n"));
return 0;
}
/*MPEG-1*/
if (version & 1)
return bitrate_table[layer - 1][bitRateIndex];
/*MPEG-2/2.5*/
else
return bitrate_table[3 + (layer >> 1)][bitRateIndex];
}
GF_EXPORT
u16 gf_mp3_frame_size(u32 hdr)
{
u8 version = gf_mp3_version(hdr);
u8 layer = gf_mp3_layer(hdr);
u32 pad = ( (hdr >> 9) & 0x1) ? 1 : 0;
u32 bitrate = gf_mp3_bit_rate(hdr);
u32 samplerate = gf_mp3_sampling_rate(hdr);
u32 frameSize = 0;
if (!samplerate || !bitrate) return 0;
if (layer==1) {
frameSize = (( 12 * bitrate / samplerate) + pad) * 4;
} else {
u32 slots_per_frame = 144;
if ((layer == 3) && !(version & 1)) slots_per_frame = 72;
frameSize = (slots_per_frame * bitrate / samplerate) + pad;
}
return (u16) frameSize;
}
GF_EXPORT
u32 gf_mp3_get_next_header(FILE* in)
{
u8 b, state = 0;
u32 dropped = 0;
unsigned char bytes[4];
bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
while (1) {
if (fread(&b, 1, 1, in) == 0) return 0;
if (state==3) {
bytes[state] = b;
return GF_4CC(bytes[0], bytes[1], bytes[2], bytes[3]);
}
if (state==2) {
if (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {
if (bytes[1] == 0xFF) state = 1;
else state = 0;
} else {
bytes[state] = b;
state = 3;
}
}
if (state==1) {
if (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
bytes[state] = b;
state = 2;
} else {
state = 0;
}
}
if (state==0) {
if (b == 0xFF) {
bytes[state] = b;
state = 1;
} else {
if ((dropped == 0) && ((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
bytes[0] = (u8) 0xFF;
bytes[1] = b;
state = 2;
} else {
dropped++;
}
}
}
}
return 0;
}
GF_EXPORT
u32 gf_mp3_get_next_header_mem(const char *buffer, u32 size, u32 *pos)
{
u32 cur;
u8 b, state = 0;
u32 dropped = 0;
unsigned char bytes[4];
bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0;
cur = 0;
*pos = 0;
while (cur<size) {
b = (u8) buffer[cur];
cur++;
if (state==3) {
u32 val;
bytes[state] = b;
val = GF_4CC(bytes[0], bytes[1], bytes[2], bytes[3]);
if (gf_mp3_frame_size(val)) {
*pos = dropped;
return val;
}
state = 0;
dropped = cur;
}
if (state==2) {
if (((b & 0xF0) == 0) || ((b & 0xF0) == 0xF0) || ((b & 0x0C) == 0x0C)) {
if (bytes[1] == 0xFF) {
state = 1;
dropped+=1;
} else {
state = 0;
dropped = cur;
}
} else {
bytes[state] = b;
state = 3;
}
}
if (state==1) {
if (((b & 0xE0) == 0xE0) && ((b & 0x18) != 0x08) && ((b & 0x06) != 0)) {
bytes[state] = b;
state = 2;
} else {
state = 0;
dropped = cur;
}
}
if (state==0) {
if (b == 0xFF) {
bytes[state] = b;
state = 1;
} else {
dropped++;
}
}
}
return 0;
}
#endif /*GPAC_DISABLE_AV_PARSERS*/
GF_EXPORT
Bool gf_avc_is_rext_profile(u8 profile_idc)
{
switch (profile_idc) {
case 100:
case 110:
case 122:
case 244:
case 44:
case 83:
case 86:
case 118:
case 128:
case 138:
case 139:
case 134:
case 135:
return GF_TRUE;
default:
return GF_FALSE;
}
}
GF_EXPORT
const char *gf_avc_get_profile_name(u8 video_prof)
{
switch (video_prof) {
case 0x42:
return "Baseline";
case 0x4D:
return "Main";
case 0x53:
return "Scalable Baseline";
case 0x56:
return "Scalable High";
case 0x58:
return "Extended";
case 0x64:
return "High";
case 0x6E:
return "High 10";
case 0x7A:
return "High 4:2:2";
case 0x90:
case 0xF4:
return "High 4:4:4";
default:
return "Unknown";
}
}
GF_EXPORT
const char *gf_hevc_get_profile_name(u8 video_prof)
{
switch (video_prof) {
case 0x01:
return "Main";
case 0x02:
return "Main 10";
case 0x03:
return "Main Still Picture";
default:
return "Unknown";
}
}
GF_EXPORT
const char *gf_avc_hevc_get_chroma_format_name(u8 chroma_format)
{
switch (chroma_format) {
case 1:
return "YUV 4:2:0";
case 2:
return "YUV 4:2:2";
case 3:
return "YUV 4:4:4";
default:
return "Unknown";
}
}
#ifndef GPAC_DISABLE_AV_PARSERS
static u8 avc_golomb_bits[256] = {
8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0
};
static u32 bs_get_ue(GF_BitStream *bs)
{
u8 coded;
u32 bits = 0, read = 0;
while (1) {
read = gf_bs_peek_bits(bs, 8, 0);
if (read) break;
//check whether we still have bits once the peek is done since we may have less than 8 bits available
if (!gf_bs_available(bs)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AVC/HEVC] Not enough bits in bitstream !!\n"));
return 0;
}
gf_bs_read_int(bs, 8);
bits += 8;
}
coded = avc_golomb_bits[read];
gf_bs_read_int(bs, coded);
bits += coded;
return gf_bs_read_int(bs, bits + 1) - 1;
}
static s32 bs_get_se(GF_BitStream *bs)
{
u32 v = bs_get_ue(bs);
if ((v & 0x1) == 0) return (s32) (0 - (v>>1));
return (v + 1) >> 1;
}
u32 gf_media_nalu_is_start_code(GF_BitStream *bs)
{
u8 s1, s2, s3, s4;
Bool is_sc = 0;
u64 pos = gf_bs_get_position(bs);
s1 = gf_bs_read_int(bs, 8);
s2 = gf_bs_read_int(bs, 8);
if (!s1 && !s2) {
s3 = gf_bs_read_int(bs, 8);
if (s3==0x01) is_sc = 3;
else if (!s3) {
s4 = gf_bs_read_int(bs, 8);
if (s4==0x01) is_sc = 4;
}
}
gf_bs_seek(bs, pos+is_sc);
return is_sc;
}
/*read that amount of data at each IO access rather than fetching byte by byte...*/
#define AVC_CACHE_SIZE 4096
static u32 gf_media_nalu_locate_start_code_bs(GF_BitStream *bs, Bool locate_trailing)
{
u32 v, bpos, nb_cons_zeros=0;
char avc_cache[AVC_CACHE_SIZE];
u64 end, cache_start, load_size;
u64 start = gf_bs_get_position(bs);
if (start<3) return 0;
load_size = 0;
bpos = 0;
cache_start = 0;
end = 0;
v = 0xffffffff;
while (!end) {
/*refill cache*/
if (bpos == (u32) load_size) {
if (!gf_bs_available(bs)) break;
load_size = gf_bs_available(bs);
if (load_size>AVC_CACHE_SIZE) load_size=AVC_CACHE_SIZE;
bpos = 0;
cache_start = gf_bs_get_position(bs);
gf_bs_read_data(bs, avc_cache, (u32) load_size);
}
v = ( (v<<8) & 0xFFFFFF00) | ((u32) avc_cache[bpos]);
bpos++;
if (locate_trailing) {
if ( (v & 0x000000FF) == 0) nb_cons_zeros++;
else nb_cons_zeros = 0;
}
if (v == 0x00000001) end = cache_start+bpos-4;
else if ( (v & 0x00FFFFFF) == 0x00000001) end = cache_start+bpos-3;
}
gf_bs_seek(bs, start);
if (!end) end = gf_bs_get_size(bs);
if (locate_trailing) {
if (nb_cons_zeros>=3)
return (u32) (end - start - nb_cons_zeros);
}
return (u32) (end-start);
}
GF_EXPORT
u32 gf_media_nalu_next_start_code_bs(GF_BitStream *bs)
{
return gf_media_nalu_locate_start_code_bs(bs, 0);
}
GF_EXPORT
u32 gf_media_nalu_payload_end_bs(GF_BitStream *bs)
{
return gf_media_nalu_locate_start_code_bs(bs, 1);
}
GF_EXPORT
u32 gf_media_nalu_next_start_code(const u8 *data, u32 data_len, u32 *sc_size)
{
u32 v, bpos;
u32 end;
bpos = 0;
end = 0;
v = 0xffffffff;
while (!end) {
/*refill cache*/
if (bpos == (u32) data_len)
break;
v = ( (v<<8) & 0xFFFFFF00) | ((u32) data[bpos]);
bpos++;
if (v == 0x00000001) {
end = bpos-4;
*sc_size = 4;
return end;
}
else if ( (v & 0x00FFFFFF) == 0x00000001) {
end = bpos-3;
*sc_size = 3;
return end;
}
}
if (!end) end = data_len;
return (u32) (end);
}
Bool gf_media_avc_slice_is_intra(AVCState *avc)
{
switch (avc->s_info.slice_type) {
case GF_AVC_TYPE_I:
case GF_AVC_TYPE2_I:
case GF_AVC_TYPE_SI:
case GF_AVC_TYPE2_SI:
return 1;
default:
return 0;
}
}
Bool gf_media_avc_slice_is_IDR(AVCState *avc)
{
if (avc->sei.recovery_point.valid)
{
avc->sei.recovery_point.valid = 0;
return 1;
}
if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE)
return 0;
return gf_media_avc_slice_is_intra(avc);
}
static const struct {
u32 w, h;
} avc_sar[14] =
{
{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },
{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
{ 64, 33 }, { 160,99 },
};
/*ISO 14496-10 (N11084) E.1.2*/
static void avc_parse_hrd_parameters(GF_BitStream *bs, AVC_HRD *hrd)
{
int i, cpb_cnt_minus1;
cpb_cnt_minus1 = bs_get_ue(bs); /*cpb_cnt_minus1*/
if (cpb_cnt_minus1 > 31)
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] invalid cpb_cnt_minus1 value: %d (expected in [0;31])\n", cpb_cnt_minus1));
gf_bs_read_int(bs, 4); /*bit_rate_scale*/
gf_bs_read_int(bs, 4); /*cpb_size_scale*/
/*for( SchedSelIdx = 0; SchedSelIdx <= cpb_cnt_minus1; SchedSelIdx++ ) {*/
for (i=0; i<=cpb_cnt_minus1; i++) {
bs_get_ue(bs); /*bit_rate_value_minus1[ SchedSelIdx ]*/
bs_get_ue(bs); /*cpb_size_value_minus1[ SchedSelIdx ]*/
gf_bs_read_int(bs, 1); /*cbr_flag[ SchedSelIdx ]*/
}
gf_bs_read_int(bs, 5); /*initial_cpb_removal_delay_length_minus1*/
hrd->cpb_removal_delay_length_minus1 = gf_bs_read_int(bs, 5); /*cpb_removal_delay_length_minus1*/
hrd->dpb_output_delay_length_minus1 = gf_bs_read_int(bs, 5); /*dpb_output_delay_length_minus1*/
hrd->time_offset_length = gf_bs_read_int(bs, 5); /*time_offset_length*/
return;
}
/*returns the nal_size without emulation prevention bytes*/
static u32 avc_emulation_bytes_add_count(char *buffer, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size) {
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
\96 0x00000300
\96 0x00000301
\96 0x00000302
\96 0x00000303"
*/
if (num_zero == 2 && buffer[i] < 0x04) {
/*emulation code found*/
num_zero = 0;
emulation_bytes_count++;
if (!buffer[i])
num_zero = 1;
} else {
if (!buffer[i])
num_zero++;
else
num_zero = 0;
}
i++;
}
return emulation_bytes_count;
}
static u32 avc_add_emulation_bytes(const char *buffer_src, char *buffer_dst, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size) {
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
0x00000300
0x00000301
0x00000302
0x00000303"
*/
if (num_zero == 2 && (u8)buffer_src[i] < 0x04) {
/*add emulation code*/
num_zero = 0;
buffer_dst[i+emulation_bytes_count] = 0x03;
emulation_bytes_count++;
if (!buffer_src[i])
num_zero = 1;
} else {
if (!buffer_src[i])
num_zero++;
else
num_zero = 0;
}
buffer_dst[i+emulation_bytes_count] = buffer_src[i];
i++;
}
return nal_size+emulation_bytes_count;
}
/*returns the nal_size without emulation prevention bytes*/
static u32 avc_emulation_bytes_remove_count(const char *buffer, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size)
{
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
\96 0x00000300
\96 0x00000301
\96 0x00000302
\96 0x00000303"
*/
if (num_zero == 2
&& buffer[i] == 0x03
&& i+1 < nal_size /*next byte is readable*/
&& buffer[i+1] < 0x04)
{
/*emulation code found*/
num_zero = 0;
emulation_bytes_count++;
i++;
}
if (!buffer[i])
num_zero++;
else
num_zero = 0;
i++;
}
return emulation_bytes_count;
}
/*nal_size is updated to allow better error detection*/
static u32 avc_remove_emulation_bytes(const char *buffer_src, char *buffer_dst, u32 nal_size)
{
u32 i = 0, emulation_bytes_count = 0;
u8 num_zero = 0;
while (i < nal_size)
{
/*ISO 14496-10: "Within the NAL unit, any four-byte sequence that starts with 0x000003
other than the following sequences shall not occur at any byte-aligned position:
0x00000300
0x00000301
0x00000302
0x00000303"
*/
if (num_zero == 2
&& buffer_src[i] == 0x03
&& i+1 < nal_size /*next byte is readable*/
&& buffer_src[i+1] < 0x04)
{
/*emulation code found*/
num_zero = 0;
emulation_bytes_count++;
i++;
}
buffer_dst[i-emulation_bytes_count] = buffer_src[i];
if (!buffer_src[i])
num_zero++;
else
num_zero = 0;
i++;
}
return nal_size-emulation_bytes_count;
}
GF_EXPORT
s32 gf_media_avc_read_sps(const char *sps_data, u32 sps_size, AVCState *avc, u32 subseq_sps, u32 *vui_flag_pos)
{
AVC_SPS *sps;
u32 ChromaArrayType = 0;
s32 mb_width, mb_height, sps_id = -1;
u32 profile_idc, level_idc, pcomp, i, chroma_format_idc, cl=0, cr=0, ct=0, cb=0, luma_bd, chroma_bd;
u8 separate_colour_plane_flag = 0;
GF_BitStream *bs;
char *sps_data_without_emulation_bytes = NULL;
u32 sps_data_without_emulation_bytes_size = 0;
/*SPS still contains emulation bytes*/
sps_data_without_emulation_bytes = gf_malloc(sps_size*sizeof(char));
sps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(sps_data, sps_data_without_emulation_bytes, sps_size);
bs = gf_bs_new(sps_data_without_emulation_bytes, sps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
sps_id = -1;
goto exit;
}
if (vui_flag_pos) *vui_flag_pos = 0;
/*nal hdr*/ gf_bs_read_int(bs, 8);
profile_idc = gf_bs_read_int(bs, 8);
pcomp = gf_bs_read_int(bs, 8);
/*sanity checks*/
if (pcomp & 0x3)
goto exit;
level_idc = gf_bs_read_int(bs, 8);
/*SubsetSps is used to be sure that AVC SPS are not going to be scratched
by subset SPS. According to the SVC standard, subset SPS can have the same sps_id
than its base layer, but it does not refer to the same SPS. */
sps_id = bs_get_ue(bs) + GF_SVC_SSPS_ID_SHIFT * subseq_sps;
if (sps_id >=32) {
sps_id = -1;
goto exit;
}
if (sps_id < 0) {
sps_id = -1;
goto exit;
}
luma_bd = chroma_bd = 0;
chroma_format_idc = ChromaArrayType = 1;
sps = &avc->sps[sps_id];
sps->state |= subseq_sps ? AVC_SUBSPS_PARSED : AVC_SPS_PARSED;
/*High Profile and SVC*/
switch (profile_idc) {
case 100:
case 110:
case 122:
case 244:
case 44:
/*sanity checks: note1 from 7.4.2.1.1 of iso/iec 14496-10-N11084*/
if (pcomp & 0xE0)
goto exit;
case 83:
case 86:
case 118:
case 128:
chroma_format_idc = bs_get_ue(bs);
ChromaArrayType = chroma_format_idc;
if (chroma_format_idc == 3) {
separate_colour_plane_flag = gf_bs_read_int(bs, 1);
/*
Depending on the value of separate_colour_plane_flag, the value of the variable ChromaArrayType is assigned as follows.
\96 If separate_colour_plane_flag is equal to 0, ChromaArrayType is set equal to chroma_format_idc.
\96 Otherwise (separate_colour_plane_flag is equal to 1), ChromaArrayType is set equal to 0.
*/
if (separate_colour_plane_flag) ChromaArrayType = 0;
}
luma_bd = bs_get_ue(bs);
chroma_bd = bs_get_ue(bs);
/*qpprime_y_zero_transform_bypass_flag = */ gf_bs_read_int(bs, 1);
/*seq_scaling_matrix_present_flag*/
if (gf_bs_read_int(bs, 1)) {
u32 k;
for (k=0; k<8; k++) {
if (gf_bs_read_int(bs, 1)) {
u32 z, last = 8, next = 8;
u32 sl = k<6 ? 16 : 64;
for (z=0; z<sl; z++) {
if (next) {
s32 delta = bs_get_se(bs);
next = (last + delta + 256) % 256;
}
last = next ? next : last;
}
}
}
}
break;
}
sps->profile_idc = profile_idc;
sps->level_idc = level_idc;
sps->prof_compat = pcomp;
sps->log2_max_frame_num = bs_get_ue(bs) + 4;
sps->poc_type = bs_get_ue(bs);
sps->chroma_format = chroma_format_idc;
sps->luma_bit_depth_m8 = luma_bd;
sps->chroma_bit_depth_m8 = chroma_bd;
if (sps->poc_type == 0) {
sps->log2_max_poc_lsb = bs_get_ue(bs) + 4;
} else if(sps->poc_type == 1) {
sps->delta_pic_order_always_zero_flag = gf_bs_read_int(bs, 1);
sps->offset_for_non_ref_pic = bs_get_se(bs);
sps->offset_for_top_to_bottom_field = bs_get_se(bs);
sps->poc_cycle_length = bs_get_ue(bs);
if (sps->poc_cycle_length > ARRAY_LENGTH(sps->offset_for_ref_frame)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] offset_for_ref_frame overflow from poc_cycle_length\n"));
goto exit;
}
for(i=0; i<sps->poc_cycle_length; i++) sps->offset_for_ref_frame[i] = bs_get_se(bs);
}
if (sps->poc_type > 2) {
sps_id = -1;
goto exit;
}
sps->max_num_ref_frames = bs_get_ue(bs);
sps->gaps_in_frame_num_value_allowed_flag = gf_bs_read_int(bs, 1);
mb_width = bs_get_ue(bs) + 1;
mb_height= bs_get_ue(bs) + 1;
sps->frame_mbs_only_flag = gf_bs_read_int(bs, 1);
sps->width = mb_width * 16;
sps->height = (2-sps->frame_mbs_only_flag) * mb_height * 16;
if (!sps->frame_mbs_only_flag) sps->mb_adaptive_frame_field_flag = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 1); /*direct_8x8_inference_flag*/
if (gf_bs_read_int(bs, 1)) { /*crop*/
int CropUnitX, CropUnitY, SubWidthC = -1, SubHeightC = -1;
if (chroma_format_idc == 1) {
SubWidthC = 2, SubHeightC = 2;
} else if (chroma_format_idc == 2) {
SubWidthC = 2, SubHeightC = 1;
} else if ((chroma_format_idc == 3) && (separate_colour_plane_flag == 0)) {
SubWidthC = 1, SubHeightC = 1;
}
if (ChromaArrayType == 0) {
assert(SubWidthC==-1);
CropUnitX = 1;
CropUnitY = 2-sps->frame_mbs_only_flag;
} else {
CropUnitX = SubWidthC;
CropUnitY = SubHeightC * (2-sps->frame_mbs_only_flag);
}
cl = bs_get_ue(bs); /*crop_left*/
cr = bs_get_ue(bs); /*crop_right*/
ct = bs_get_ue(bs); /*crop_top*/
cb = bs_get_ue(bs); /*crop_bottom*/
sps->width -= CropUnitX * (cl + cr);
sps->height -= CropUnitY * (ct + cb);
cl *= CropUnitX;
cr *= CropUnitX;
ct *= CropUnitY;
cb *= CropUnitY;
}
sps->crop.left = cl;
sps->crop.right = cr;
sps->crop.top = ct;
sps->crop.bottom = cb;
if (vui_flag_pos) {
*vui_flag_pos = (u32) gf_bs_get_bit_offset(bs);
}
/*vui_parameters_present_flag*/
sps->vui_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui_parameters_present_flag) {
sps->vui.aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.aspect_ratio_info_present_flag) {
s32 aspect_ratio_idc = gf_bs_read_int(bs, 8);
if (aspect_ratio_idc == 255) {
sps->vui.par_num = gf_bs_read_int(bs, 16); /*AR num*/
sps->vui.par_den = gf_bs_read_int(bs, 16); /*AR den*/
} else if (aspect_ratio_idc<14) {
sps->vui.par_num = avc_sar[aspect_ratio_idc].w;
sps->vui.par_den = avc_sar[aspect_ratio_idc].h;
}
}
sps->vui.overscan_info_present_flag = gf_bs_read_int(bs, 1);
if(sps->vui.overscan_info_present_flag)
gf_bs_read_int(bs, 1); /* overscan_appropriate_flag */
/* default values */
sps->vui.video_format = 5;
sps->vui.colour_primaries = 2;
sps->vui.transfer_characteristics = 2;
sps->vui.matrix_coefficients = 2;
/* now read values if possible */
sps->vui.video_signal_type_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.video_signal_type_present_flag) {
sps->vui.video_format = gf_bs_read_int(bs, 3);
sps->vui.video_full_range_flag = gf_bs_read_int(bs, 1);
sps->vui.colour_description_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.colour_description_present_flag) {
sps->vui.colour_primaries = gf_bs_read_int(bs, 8);
sps->vui.transfer_characteristics = gf_bs_read_int(bs, 8);
sps->vui.matrix_coefficients = gf_bs_read_int(bs, 8);
}
}
if (gf_bs_read_int(bs, 1)) { /* chroma_location_info_present_flag */
bs_get_ue(bs); /* chroma_sample_location_type_top_field */
bs_get_ue(bs); /* chroma_sample_location_type_bottom_field */
}
sps->vui.timing_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.timing_info_present_flag) {
sps->vui.num_units_in_tick = gf_bs_read_int(bs, 32);
sps->vui.time_scale = gf_bs_read_int(bs, 32);
sps->vui.fixed_frame_rate_flag = gf_bs_read_int(bs, 1);
}
sps->vui.nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.nal_hrd_parameters_present_flag)
avc_parse_hrd_parameters(bs, &sps->vui.hrd);
sps->vui.vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (sps->vui.vcl_hrd_parameters_present_flag)
avc_parse_hrd_parameters(bs, &sps->vui.hrd);
if (sps->vui.nal_hrd_parameters_present_flag || sps->vui.vcl_hrd_parameters_present_flag)
sps->vui.low_delay_hrd_flag = gf_bs_read_int(bs, 1);
sps->vui.pic_struct_present_flag = gf_bs_read_int(bs, 1);
}
/*end of seq_parameter_set_data*/
if (subseq_sps) {
if ((profile_idc==83) || (profile_idc==86)) {
u8 extended_spatial_scalability_idc;
/*parsing seq_parameter_set_svc_extension*/
/*inter_layer_deblocking_filter_control_present_flag=*/ gf_bs_read_int(bs, 1);
extended_spatial_scalability_idc = gf_bs_read_int(bs, 2);
if (ChromaArrayType == 1 || ChromaArrayType == 2) {
/*chroma_phase_x_plus1_flag*/ gf_bs_read_int(bs, 1);
}
if( ChromaArrayType == 1 ) {
/*chroma_phase_y_plus1*/ gf_bs_read_int(bs, 2);
}
if (extended_spatial_scalability_idc == 1) {
if( ChromaArrayType > 0 ) {
/*seq_ref_layer_chroma_phase_x_plus1_flag*/gf_bs_read_int(bs, 1);
/*seq_ref_layer_chroma_phase_y_plus1*/gf_bs_read_int(bs, 2);
}
/*seq_scaled_ref_layer_left_offset*/ bs_get_se(bs);
/*seq_scaled_ref_layer_top_offset*/bs_get_se(bs);
/*seq_scaled_ref_layer_right_offset*/bs_get_se(bs);
/*seq_scaled_ref_layer_bottom_offset*/bs_get_se(bs);
}
if (/*seq_tcoeff_level_prediction_flag*/gf_bs_read_int(bs, 1)) {
/*adaptive_tcoeff_level_prediction_flag*/ gf_bs_read_int(bs, 1);
}
/*slice_header_restriction_flag*/gf_bs_read_int(bs, 1);
/*svc_vui_parameters_present*/
if (gf_bs_read_int(bs, 1)) {
u32 i, vui_ext_num_entries_minus1;
vui_ext_num_entries_minus1 = bs_get_ue(bs);
for (i=0; i <= vui_ext_num_entries_minus1; i++) {
u8 vui_ext_nal_hrd_parameters_present_flag, vui_ext_vcl_hrd_parameters_present_flag, vui_ext_timing_info_present_flag;
/*u8 vui_ext_dependency_id =*/ gf_bs_read_int(bs, 3);
/*u8 vui_ext_quality_id =*/ gf_bs_read_int(bs, 4);
/*u8 vui_ext_temporal_id =*/ gf_bs_read_int(bs, 3);
vui_ext_timing_info_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_timing_info_present_flag) {
/*u32 vui_ext_num_units_in_tick = */gf_bs_read_int(bs, 32);
/*u32 vui_ext_time_scale = */gf_bs_read_int(bs, 32);
/*u8 vui_ext_fixed_frame_rate_flag = */gf_bs_read_int(bs, 1);
}
vui_ext_nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_nal_hrd_parameters_present_flag) {
//hrd_parameters( )
}
vui_ext_vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (vui_ext_vcl_hrd_parameters_present_flag) {
//hrd_parameters( )
}
if ( vui_ext_nal_hrd_parameters_present_flag || vui_ext_vcl_hrd_parameters_present_flag) {
/*vui_ext_low_delay_hrd_flag*/gf_bs_read_int(bs, 1);
}
/*vui_ext_pic_struct_present_flag*/gf_bs_read_int(bs, 1);
}
}
}
else if ((profile_idc==118) || (profile_idc==128)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] MVC not supported - skipping parsing end of Subset SPS\n"));
goto exit;
}
if (gf_bs_read_int(bs, 1)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] skipping parsing end of Subset SPS (additional_extension2)\n"));
goto exit;
}
}
exit:
gf_bs_del(bs);
gf_free(sps_data_without_emulation_bytes);
return sps_id;
}
GF_EXPORT
s32 gf_media_avc_read_pps(const char *pps_data, u32 pps_size, AVCState *avc)
{
GF_BitStream *bs;
char *pps_data_without_emulation_bytes = NULL;
u32 pps_data_without_emulation_bytes_size = 0;
s32 pps_id;
AVC_PPS *pps;
/*PPS still contains emulation bytes*/
pps_data_without_emulation_bytes = gf_malloc(pps_size*sizeof(char));
pps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(pps_data, pps_data_without_emulation_bytes, pps_size);
bs = gf_bs_new(pps_data_without_emulation_bytes, pps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
pps_id = -1;
goto exit;
}
/*nal hdr*/gf_bs_read_u8(bs);
pps_id = bs_get_ue(bs);
if (pps_id>=255) {
pps_id = -1;
goto exit;
}
pps = &avc->pps[pps_id];
pps->id = pps_id;
if (!pps->status) pps->status = 1;
pps->sps_id = bs_get_ue(bs);
if (pps->sps_id >= 32) {
pps->sps_id = 0;
pps_id = -1;
goto exit;
}
/*sps_id may be refer to regular SPS or subseq sps, depending on the coded slice refering to the pps*/
if (!avc->sps[pps->sps_id].state && !avc->sps[pps->sps_id + GF_SVC_SSPS_ID_SHIFT].state) {
pps_id = -1;
goto exit;
}
avc->sps_active_idx = pps->sps_id; /*set active sps*/
pps->entropy_coding_mode_flag = gf_bs_read_int(bs, 1);
pps->pic_order_present= gf_bs_read_int(bs, 1);
pps->slice_group_count= bs_get_ue(bs) + 1;
if (pps->slice_group_count > 1 ) /*pps->mb_slice_group_map_type = */bs_get_ue(bs);
/*pps->ref_count[0]= */bs_get_ue(bs) /*+ 1*/;
/*pps->ref_count[1]= */bs_get_ue(bs) /*+ 1*/;
/*
if ((pps->ref_count[0] > 32) || (pps->ref_count[1] > 32)) goto exit;
*/
/*pps->weighted_pred = */gf_bs_read_int(bs, 1);
/*pps->weighted_bipred_idc = */gf_bs_read_int(bs, 2);
/*pps->init_qp = */bs_get_se(bs) /*+ 26*/;
/*pps->init_qs= */bs_get_se(bs) /*+ 26*/;
/*pps->chroma_qp_index_offset = */bs_get_se(bs);
/*pps->deblocking_filter_parameters_present = */gf_bs_read_int(bs, 1);
/*pps->constrained_intra_pred = */gf_bs_read_int(bs, 1);
pps->redundant_pic_cnt_present = gf_bs_read_int(bs, 1);
exit:
gf_bs_del(bs);
gf_free(pps_data_without_emulation_bytes);
return pps_id;
}
s32 gf_media_avc_read_sps_ext(const char *spse_data, u32 spse_size)
{
GF_BitStream *bs;
char *spse_data_without_emulation_bytes = NULL;
u32 spse_data_without_emulation_bytes_size = 0;
s32 sps_id;
/*PPS still contains emulation bytes*/
spse_data_without_emulation_bytes = gf_malloc(spse_size*sizeof(char));
spse_data_without_emulation_bytes_size = avc_remove_emulation_bytes(spse_data, spse_data_without_emulation_bytes, spse_size);
bs = gf_bs_new(spse_data_without_emulation_bytes, spse_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
/*nal header*/gf_bs_read_u8(bs);
sps_id = bs_get_ue(bs);
gf_bs_del(bs);
gf_free(spse_data_without_emulation_bytes);
return sps_id;
}
static s32 SVC_ReadNal_header_extension(GF_BitStream *bs, SVC_NALUHeader *NalHeader)
{
gf_bs_read_int(bs, 1); //reserved_one_bits
NalHeader->idr_pic_flag = gf_bs_read_int(bs, 1); //idr_flag
NalHeader->priority_id = gf_bs_read_int(bs, 6); //priority_id
gf_bs_read_int(bs, 1); //no_inter_layer_pred_flag
NalHeader->dependency_id = gf_bs_read_int(bs, 3); //DependencyId
NalHeader->quality_id = gf_bs_read_int(bs, 4); //quality_id
NalHeader->temporal_id = gf_bs_read_int(bs, 3); //temporal_id
gf_bs_read_int(bs, 1); //use_ref_base_pic_flag
gf_bs_read_int(bs, 1); //discardable_flag
gf_bs_read_int(bs, 1); //output_flag
gf_bs_read_int(bs, 2); //reserved_three_2bits
return 1;
}
static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si)
{
s32 pps_id;
/*s->current_picture.reference= h->nal_ref_idc != 0;*/
/*first_mb_in_slice = */bs_get_ue(bs);
si->slice_type = bs_get_ue(bs);
if (si->slice_type > 9) return -1;
pps_id = bs_get_ue(bs);
if (pps_id>255) return -1;
si->pps = &avc->pps[pps_id];
if (!si->pps->slice_group_count) return -2;
si->sps = &avc->sps[si->pps->sps_id];
if (!si->sps->log2_max_frame_num) return -2;
avc->sps_active_idx = si->pps->sps_id;
si->frame_num = gf_bs_read_int(bs, si->sps->log2_max_frame_num);
si->field_pic_flag = 0;
si->bottom_field_flag = 0;
if (!si->sps->frame_mbs_only_flag) {
si->field_pic_flag = gf_bs_read_int(bs, 1);
if (si->field_pic_flag)
si->bottom_field_flag = gf_bs_read_int(bs, 1);
}
if ((si->nal_unit_type==GF_AVC_NALU_IDR_SLICE) || svc_idr_flag)
si->idr_pic_id = bs_get_ue(bs);
if (si->sps->poc_type==0) {
si->poc_lsb = gf_bs_read_int(bs, si->sps->log2_max_poc_lsb);
if (si->pps->pic_order_present && !si->field_pic_flag) {
si->delta_poc_bottom = bs_get_se(bs);
}
} else if ((si->sps->poc_type==1) && !si->sps->delta_pic_order_always_zero_flag) {
si->delta_poc[0] = bs_get_se(bs);
if ((si->pps->pic_order_present==1) && !si->field_pic_flag)
si->delta_poc[1] = bs_get_se(bs);
}
if (si->pps->redundant_pic_cnt_present) {
si->redundant_pic_cnt = bs_get_ue(bs);
}
return 0;
}
static s32 svc_parse_slice(GF_BitStream *bs, AVCState *avc, AVCSliceInfo *si)
{
s32 pps_id;
/*s->current_picture.reference= h->nal_ref_idc != 0;*/
/*first_mb_in_slice = */bs_get_ue(bs);
si->slice_type = bs_get_ue(bs);
if (si->slice_type > 9) return -1;
pps_id = bs_get_ue(bs);
if (pps_id>255)
return -1;
si->pps = &avc->pps[pps_id];
si->pps->id = pps_id;
if (!si->pps->slice_group_count)
return -2;
si->sps = &avc->sps[si->pps->sps_id + GF_SVC_SSPS_ID_SHIFT];
if (!si->sps->log2_max_frame_num)
return -2;
si->frame_num = gf_bs_read_int(bs, si->sps->log2_max_frame_num);
si->field_pic_flag = 0;
if (si->sps->frame_mbs_only_flag) {
/*s->picture_structure= PICT_FRAME;*/
} else {
si->field_pic_flag = gf_bs_read_int(bs, 1);
if (si->field_pic_flag) si->bottom_field_flag = gf_bs_read_int(bs, 1);
}
if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE || si ->NalHeader.idr_pic_flag)
si->idr_pic_id = bs_get_ue(bs);
if (si->sps->poc_type==0) {
si->poc_lsb = gf_bs_read_int(bs, si->sps->log2_max_poc_lsb);
if (si->pps->pic_order_present && !si->field_pic_flag) {
si->delta_poc_bottom = bs_get_se(bs);
}
} else if ((si->sps->poc_type==1) && !si->sps->delta_pic_order_always_zero_flag) {
si->delta_poc[0] = bs_get_se(bs);
if ((si->pps->pic_order_present==1) && !si->field_pic_flag)
si->delta_poc[1] = bs_get_se(bs);
}
if (si->pps->redundant_pic_cnt_present) {
si->redundant_pic_cnt = bs_get_ue(bs);
}
return 0;
}
static s32 avc_parse_recovery_point_sei(GF_BitStream *bs, AVCState *avc)
{
AVCSeiRecoveryPoint *rp = &avc->sei.recovery_point;
rp->frame_cnt = bs_get_ue(bs);
rp->exact_match_flag = gf_bs_read_int(bs, 1);
rp->broken_link_flag = gf_bs_read_int(bs, 1);
rp->changing_slice_group_idc = gf_bs_read_int(bs, 2);
rp->valid = 1;
return 0;
}
/*for interpretation see ISO 14496-10 N.11084, table D-1*/
static s32 avc_parse_pic_timing_sei(GF_BitStream *bs, AVCState *avc)
{
int i;
int sps_id = avc->sps_active_idx;
const char NumClockTS[] = {1, 1, 1, 2, 2, 3, 3, 2, 3};
AVCSeiPicTiming *pt = &avc->sei.pic_timing;
if (sps_id < 0) {
/*sps_active_idx equals -1 when no sps has been detected. In this case SEI should not be decoded.*/
assert(0);
return 1;
}
if (avc->sps[sps_id].vui.nal_hrd_parameters_present_flag || avc->sps[sps_id].vui.vcl_hrd_parameters_present_flag) { /*CpbDpbDelaysPresentFlag, see 14496-10(2003) E.11*/
gf_bs_read_int(bs, 1+avc->sps[sps_id].vui.hrd.cpb_removal_delay_length_minus1); /*cpb_removal_delay*/
gf_bs_read_int(bs, 1+avc->sps[sps_id].vui.hrd.dpb_output_delay_length_minus1); /*dpb_output_delay*/
}
/*ISO 14496-10 (2003), D.8.2: we need to get pic_struct in order to know if we display top field first or bottom field first*/
if (avc->sps[sps_id].vui.pic_struct_present_flag) {
pt->pic_struct = gf_bs_read_int(bs, 4);
if (pt->pic_struct > 8) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] invalid pic_struct value %d\n", pt->pic_struct));
return 1;
}
for (i=0; i<NumClockTS[pt->pic_struct]; i++) {
if (gf_bs_read_int(bs, 1)) {/*clock_timestamp_flag[i]*/
Bool full_timestamp_flag;
gf_bs_read_int(bs, 2); /*ct_type*/
gf_bs_read_int(bs, 1); /*nuit_field_based_flag*/
gf_bs_read_int(bs, 5); /*counting_type*/
full_timestamp_flag = gf_bs_read_int(bs, 1);/*full_timestamp_flag*/
gf_bs_read_int(bs, 1); /*discontinuity_flag*/
gf_bs_read_int(bs, 1); /*cnt_dropped_flag*/
gf_bs_read_int(bs, 8); /*n_frames*/
if (full_timestamp_flag) {
gf_bs_read_int(bs, 6); /*seconds_value*/
gf_bs_read_int(bs, 6); /*minutes_value*/
gf_bs_read_int(bs, 5); /*hours_value*/
} else {
if (gf_bs_read_int(bs, 1)) { /*seconds_flag*/
gf_bs_read_int(bs, 6); /*seconds_value*/
if (gf_bs_read_int(bs, 1)) { /*minutes_flag*/
gf_bs_read_int(bs, 6); /*minutes_value*/
if (gf_bs_read_int(bs, 1)) { /*hours_flag*/
gf_bs_read_int(bs, 5); /*hours_value*/
}
}
}
if (avc->sps[sps_id].vui.hrd.time_offset_length > 0)
gf_bs_read_int(bs, avc->sps[sps_id].vui.hrd.time_offset_length); /*time_offset*/
}
}
}
}
return 0;
}
static void avc_compute_poc(AVCSliceInfo *si)
{
enum {
AVC_PIC_FRAME,
AVC_PIC_FIELD_TOP,
AVC_PIC_FIELD_BOTTOM,
} pic_type;
s32 field_poc[2] = {0,0};
s32 max_frame_num = 1 << (si->sps->log2_max_frame_num);
/* picture type */
if (si->sps->frame_mbs_only_flag || !si->field_pic_flag) pic_type = AVC_PIC_FRAME;
else if (si->bottom_field_flag) pic_type = AVC_PIC_FIELD_BOTTOM;
else pic_type = AVC_PIC_FIELD_TOP;
/* frame_num_offset */
if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
si->poc_lsb_prev = 0;
si->poc_msb_prev = 0;
si->frame_num_offset = 0;
} else {
if (si->frame_num < si->frame_num_prev)
si->frame_num_offset = si->frame_num_offset_prev + max_frame_num;
else
si->frame_num_offset = si->frame_num_offset_prev;
}
/*ISO 14496-10 N.11084 8.2.1.1*/
if (si->sps->poc_type==0)
{
const u32 max_poc_lsb = 1 << (si->sps->log2_max_poc_lsb);
/*ISO 14496-10 N.11084 eq (8-3)*/
if ((si->poc_lsb < si->poc_lsb_prev) &&
(si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2) )
si->poc_msb = si->poc_msb_prev + max_poc_lsb;
else if ((si->poc_lsb > si->poc_lsb_prev) &&
(si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
si->poc_msb = si->poc_msb_prev - max_poc_lsb;
else
si->poc_msb = si->poc_msb_prev;
/*ISO 14496-10 N.11084 eq (8-4)*/
if (pic_type != AVC_PIC_FIELD_BOTTOM)
field_poc[0] = si->poc_msb + si->poc_lsb;
/*ISO 14496-10 N.11084 eq (8-5)*/
if (pic_type != AVC_PIC_FIELD_TOP) {
if (!si->field_pic_flag)
field_poc[1] = field_poc[0] + si->delta_poc_bottom;
else
field_poc[1] = si->poc_msb + si->poc_lsb;
}
}
/*ISO 14496-10 N.11084 8.2.1.2*/
else if (si->sps->poc_type==1)
{
u32 i;
s32 abs_frame_num, expected_delta_per_poc_cycle, expected_poc;
if (si->sps->poc_cycle_length)
abs_frame_num = si->frame_num_offset + si->frame_num;
else
abs_frame_num = 0;
if (!si->nal_ref_idc && (abs_frame_num > 0)) abs_frame_num--;
expected_delta_per_poc_cycle = 0;
for (i=0; i < si->sps->poc_cycle_length; i++)
expected_delta_per_poc_cycle += si->sps->offset_for_ref_frame[i];
if (abs_frame_num > 0) {
const u32 poc_cycle_cnt = ( abs_frame_num - 1 ) / si->sps->poc_cycle_length;
const u32 frame_num_in_poc_cycle = ( abs_frame_num - 1 ) % si->sps->poc_cycle_length;
expected_poc = poc_cycle_cnt * expected_delta_per_poc_cycle;
for (i = 0; i<=frame_num_in_poc_cycle; i++)
expected_poc += si->sps->offset_for_ref_frame[i];
} else {
expected_poc = 0;
}
if (!si->nal_ref_idc) expected_poc += si->sps->offset_for_non_ref_pic;
field_poc[0] = expected_poc + si->delta_poc[0];
field_poc[1] = field_poc[0] + si->sps->offset_for_top_to_bottom_field;
if (pic_type == AVC_PIC_FRAME) field_poc[1] += si->delta_poc[1];
}
/*ISO 14496-10 N.11084 8.2.1.3*/
else if (si->sps->poc_type== 2)
{
int poc;
if (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
poc = 0;
} else {
const int abs_frame_num = si->frame_num_offset + si->frame_num;
poc = 2 * abs_frame_num;
if (!si->nal_ref_idc) poc -= 1;
}
field_poc[0] = poc;
field_poc[1] = poc;
}
/*ISO 14496-10 N.11084 eq (8-1)*/
if (pic_type == AVC_PIC_FRAME)
si->poc = MIN(field_poc[0], field_poc[1] );
else if (pic_type == AVC_PIC_FIELD_TOP)
si->poc = field_poc[0];
else
si->poc = field_poc[1];
}
GF_EXPORT
s32 gf_media_avc_parse_nalu(GF_BitStream *bs, u32 nal_hdr, AVCState *avc)
{
u8 idr_flag;
s32 slice, ret;
AVCSliceInfo n_state;
slice = 0;
memcpy(&n_state, &avc->s_info, sizeof(AVCSliceInfo));
n_state.nal_unit_type = nal_hdr & 0x1F;
n_state.nal_ref_idc = (nal_hdr>>5) & 0x3;
idr_flag = 0;
switch (n_state.nal_unit_type) {
case GF_AVC_NALU_ACCESS_UNIT:
case GF_AVC_NALU_END_OF_SEQ:
case GF_AVC_NALU_END_OF_STREAM:
ret = 1;
break;
case GF_AVC_NALU_SVC_SLICE:
SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
slice = 1;
// slice buffer - read the info and compare.
/*ret = */svc_parse_slice(bs, avc, &n_state);
if (avc->s_info.nal_ref_idc) {
n_state.poc_lsb_prev = avc->s_info.poc_lsb;
n_state.poc_msb_prev = avc->s_info.poc_msb;
}
if (slice)
avc_compute_poc(&n_state);
if (avc->s_info.poc != n_state.poc) {
memcpy(&avc -> s_info, &n_state, sizeof(AVCSliceInfo));
return 1;
}
memcpy(&avc -> s_info, &n_state, sizeof(AVCSliceInfo));
return 0;
case GF_AVC_NALU_SVC_PREFIX_NALU:
SVC_ReadNal_header_extension(bs, &n_state.NalHeader);
return 0;
case GF_AVC_NALU_NON_IDR_SLICE:
case GF_AVC_NALU_DP_A_SLICE:
case GF_AVC_NALU_DP_B_SLICE:
case GF_AVC_NALU_DP_C_SLICE:
case GF_AVC_NALU_IDR_SLICE:
slice = 1;
/* slice buffer - read the info and compare.*/
ret = avc_parse_slice(bs, avc, idr_flag, &n_state);
if (ret<0) return ret;
ret = 0;
if (
((avc->s_info.nal_unit_type > GF_AVC_NALU_IDR_SLICE) || (avc->s_info.nal_unit_type < GF_AVC_NALU_NON_IDR_SLICE))
&& (avc->s_info.nal_unit_type != GF_AVC_NALU_SVC_SLICE)
) {
break;
}
if (avc->s_info.frame_num != n_state.frame_num) {
ret = 1;
break;
}
if (avc->s_info.field_pic_flag != n_state.field_pic_flag) {
ret = 1;
break;
}
if ((avc->s_info.nal_ref_idc != n_state.nal_ref_idc) &&
(!avc->s_info.nal_ref_idc || !n_state.nal_ref_idc)) {
ret = 1;
break;
}
assert(avc->s_info.sps);
if (avc->s_info.sps->poc_type == n_state.sps->poc_type) {
if (!avc->s_info.sps->poc_type) {
if (!n_state.bottom_field_flag && (avc->s_info.poc_lsb != n_state.poc_lsb)) {
ret = 1;
break;
}
if (avc->s_info.delta_poc_bottom != n_state.delta_poc_bottom) {
ret = 1;
break;
}
} else if (avc->s_info.sps->poc_type==1) {
if (avc->s_info.delta_poc[0] != n_state.delta_poc[0]) {
ret =1;
break;
}
if (avc->s_info.delta_poc[1] != n_state.delta_poc[1]) {
ret = 1;
break;
}
}
}
if (n_state.nal_unit_type == GF_AVC_NALU_IDR_SLICE) {
if (avc->s_info.nal_unit_type != GF_AVC_NALU_IDR_SLICE) { /*IdrPicFlag differs in value*/
ret = 1;
break;
}
else if (avc->s_info.idr_pic_id != n_state.idr_pic_id) { /*both IDR and idr_pic_id differs*/
ret = 1;
break;
}
}
break;
case GF_AVC_NALU_SEQ_PARAM:
case GF_AVC_NALU_PIC_PARAM:
case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
case GF_AVC_NALU_FILLER_DATA:
return 0;
default:
if (avc->s_info.nal_unit_type <= GF_AVC_NALU_IDR_SLICE) ret = 1;
//To detect change of AU when multiple sps and pps in stream
else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEI && avc -> s_info .nal_unit_type == GF_AVC_NALU_SVC_SLICE)
ret = 1;
else if ((nal_hdr & 0x1F) == GF_AVC_NALU_SEQ_PARAM && avc -> s_info .nal_unit_type == GF_AVC_NALU_SVC_SLICE)
ret = 1;
else
ret = 0;
break;
}
/* save _prev values */
if (ret && avc->s_info.sps) {
n_state.frame_num_offset_prev = avc->s_info.frame_num_offset;
if ((avc->s_info.sps->poc_type != 2) || (avc->s_info.nal_ref_idc != 0))
n_state.frame_num_prev = avc->s_info.frame_num;
if (avc->s_info.nal_ref_idc) {
n_state.poc_lsb_prev = avc->s_info.poc_lsb;
n_state.poc_msb_prev = avc->s_info.poc_msb;
}
}
if (slice) avc_compute_poc(&n_state);
memcpy(&avc->s_info, &n_state, sizeof(AVCSliceInfo));
return ret;
}
u32 gf_media_avc_reformat_sei(char *buffer, u32 nal_size, AVCState *avc)
{
u32 ptype, psize, hdr, written, var;
u64 start;
char *new_buffer;
GF_BitStream *bs;
char *sei_without_emulation_bytes = NULL;
u32 sei_without_emulation_bytes_size = 0;
hdr = buffer[0];
if ((hdr & 0x1F) != GF_AVC_NALU_SEI) return 0;
/*PPS still contains emulation bytes*/
sei_without_emulation_bytes = gf_malloc(nal_size + 1/*for SEI null string termination*/);
sei_without_emulation_bytes_size = avc_remove_emulation_bytes(buffer, sei_without_emulation_bytes, nal_size);
bs = gf_bs_new(sei_without_emulation_bytes, sei_without_emulation_bytes_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 8);
new_buffer = (char*)gf_malloc(sizeof(char)*nal_size);
new_buffer[0] = (char) hdr;
written = 1;
/*parse SEI*/
while (gf_bs_available(bs)) {
Bool do_copy;
ptype = 0;
while (gf_bs_peek_bits(bs, 8, 0)==0xFF) {
gf_bs_read_int(bs, 8);
ptype += 255;
}
ptype += gf_bs_read_int(bs, 8);
psize = 0;
while (gf_bs_peek_bits(bs, 8, 0)==0xFF) {
gf_bs_read_int(bs, 8);
psize += 255;
}
psize += gf_bs_read_int(bs, 8);
start = gf_bs_get_position(bs);
do_copy = 1;
if (start+psize >= nal_size) {
if (written == 1) written = 0;
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[avc-h264] SEI user message type %d size error (%d but %d remain), skiping %sSEI message\n", ptype, psize, nal_size-start, written ? "end of " : ""));
break;
}
switch (ptype) {
/*remove SEI messages forbidden in MP4*/
case 3: /*filler data*/
case 10: /*sub_seq info*/
case 11: /*sub_seq_layer char*/
case 12: /*sub_seq char*/
do_copy = 0;
break;
case 5: /*user unregistered */
{
char prev;
prev = sei_without_emulation_bytes[start+psize+1];
sei_without_emulation_bytes[start+psize+1] = 0;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CODING, ("[avc-h264] SEI user message %s\n", sei_without_emulation_bytes+start+16));
sei_without_emulation_bytes[start+psize+1] = prev;
}
break;
case 6: /*recovery point*/
{
GF_BitStream *rp_bs = gf_bs_new(sei_without_emulation_bytes + start, psize, GF_BITSTREAM_READ);
avc_parse_recovery_point_sei(rp_bs, avc);
gf_bs_del(rp_bs);
}
break;
case 1: /*pic_timing*/
{
GF_BitStream *pt_bs = gf_bs_new(sei_without_emulation_bytes + start, psize, GF_BITSTREAM_READ);
avc_parse_pic_timing_sei(pt_bs, avc);
gf_bs_del(pt_bs);
}
break;
case 0: /*buffering period*/
case 2: /*pan scan rect*/
case 4: /*user registered ITU t35*/
case 7: /*def_rec_pic_marking_repetition*/
case 8: /*spare_pic*/
case 9: /*scene info*/
case 13: /*full frame freeze*/
case 14: /*full frame freeze release*/
case 15: /*full frame snapshot*/
case 16: /*progressive refinement segment start*/
case 17: /*progressive refinement segment end*/
case 18: /*motion constrained slice group*/
break;
default: /*reserved*/
do_copy = 0;
break;
}
if (do_copy) {
var = ptype;
while (var>=255) {
new_buffer[written] = (char) 0xff;
written++;
var-=255;
}
new_buffer[written] = (char) var;
written++;
var = psize;
while (var>=255) {
new_buffer[written] = (char) 0xff;
written++;
var-=255;
}
new_buffer[written] = (char) var;
written++;
memcpy(new_buffer+written, sei_without_emulation_bytes+start, sizeof(char) * psize);
written += psize;
}
gf_bs_skip_bytes(bs, (u64) psize);
gf_bs_align(bs);
if (gf_bs_available(bs)<=2) {
if (gf_bs_peek_bits(bs, 8, 0)==0x80) {
new_buffer[written] = (char) 0x80;
written += 1;
}
break;
}
}
gf_bs_del(bs);
gf_free(sei_without_emulation_bytes);
if (written) {
var = avc_emulation_bytes_add_count(new_buffer, written);
if (var) {
if (written+var<=nal_size) {
written = avc_add_emulation_bytes(new_buffer, buffer, written);
} else {
written = 0;
}
} else {
if (written<=nal_size) {
memcpy(buffer, new_buffer, sizeof(char)*written);
} else {
written = 0;
}
}
}
gf_free(new_buffer);
/*if only hdr written ignore*/
return (written>1) ? written : 0;
}
#ifndef GPAC_DISABLE_ISOM
static u8 avc_get_sar_idx(u32 w, u32 h)
{
u32 i;
for (i=0; i<14; i++) {
if ((avc_sar[i].w==w) && (avc_sar[i].h==h)) return i;
}
return 0xFF;
}
GF_Err gf_media_avc_change_par(GF_AVCConfig *avcc, s32 ar_n, s32 ar_d)
{
GF_BitStream *orig, *mod;
AVCState avc;
u32 i, bit_offset, flag;
s32 idx;
GF_AVCConfigSlot *slc;
orig = NULL;
memset(&avc, 0, sizeof(AVCState));
avc.sps_active_idx = -1;
i=0;
while ((slc = (GF_AVCConfigSlot *)gf_list_enum(avcc->sequenceParameterSets, &i))) {
char *no_emulation_buf = NULL;
u32 no_emulation_buf_size = 0, emulation_bytes = 0;
idx = gf_media_avc_read_sps(slc->data, slc->size, &avc, 0, &bit_offset);
if (idx<0) {
if ( orig )
gf_bs_del(orig);
continue;
}
/*SPS still contains emulation bytes*/
no_emulation_buf = gf_malloc((slc->size-1)*sizeof(char));
no_emulation_buf_size = avc_remove_emulation_bytes(slc->data+1, no_emulation_buf, slc->size-1);
orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
gf_bs_read_data(orig, no_emulation_buf, no_emulation_buf_size);
gf_bs_seek(orig, 0);
mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
/*copy over till vui flag*/
assert(bit_offset>=8);
while (bit_offset-8/*bit_offset doesn't take care of the first byte (NALU type)*/) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
bit_offset--;
}
/*check VUI*/
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, 1, 1); /*vui_parameters_present_flag*/
if (flag) {
/*aspect_ratio_info_present_flag*/
if (gf_bs_read_int(orig, 1)) {
s32 aspect_ratio_idc = gf_bs_read_int(orig, 8);
if (aspect_ratio_idc == 255) {
gf_bs_read_int(orig, 16); /*AR num*/
gf_bs_read_int(orig, 16); /*AR den*/
}
}
}
if ((ar_d<0) || (ar_n<0)) {
/*no AR signaled*/
gf_bs_write_int(mod, 0, 1);
} else {
u32 sarx;
gf_bs_write_int(mod, 1, 1);
sarx = avc_get_sar_idx((u32) ar_n, (u32) ar_d);
gf_bs_write_int(mod, sarx, 8);
if (sarx==0xFF) {
gf_bs_write_int(mod, ar_n, 16);
gf_bs_write_int(mod, ar_d, 16);
}
}
/*no VUI in input bitstream, set all vui flags to 0*/
if (!flag) {
gf_bs_write_int(mod, 0, 1); /*overscan_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*video_signal_type_present_flag */
gf_bs_write_int(mod, 0, 1); /*chroma_location_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*timing_info_present_flag*/
gf_bs_write_int(mod, 0, 1); /*nal_hrd_parameters_present*/
gf_bs_write_int(mod, 0, 1); /*vcl_hrd_parameters_present*/
gf_bs_write_int(mod, 0, 1); /*pic_struct_present*/
gf_bs_write_int(mod, 0, 1); /*bitstream_restriction*/
}
/*finally copy over remaining*/
while (gf_bs_bits_available(orig)) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
}
gf_bs_del(orig);
orig = NULL;
gf_free(no_emulation_buf);
/*set anti-emulation*/
gf_bs_get_content(mod, (char **) &no_emulation_buf, &flag);
emulation_bytes = avc_emulation_bytes_add_count(no_emulation_buf, flag);
if (flag+emulation_bytes+1>slc->size)
slc->data = (char*)gf_realloc(slc->data, flag+emulation_bytes+1);
slc->size = avc_add_emulation_bytes(no_emulation_buf, slc->data+1, flag)+1;
gf_bs_del(mod);
gf_free(no_emulation_buf);
}
return GF_OK;
}
#endif
GF_EXPORT
GF_Err gf_avc_get_sps_info(char *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
{
AVCState avc;
s32 idx;
memset(&avc, 0, sizeof(AVCState));
avc.sps_active_idx = -1;
idx = gf_media_avc_read_sps(sps_data, sps_size, &avc, 0, NULL);
if (idx<0) {
return GF_NON_COMPLIANT_BITSTREAM;
}
if (sps_id) *sps_id = idx;
if (width) *width = avc.sps[idx].width;
if (height) *height = avc.sps[idx].height;
if (par_n) *par_n = avc.sps[idx].vui.par_num ? avc.sps[idx].vui.par_num : (u32) -1;
if (par_d) *par_d = avc.sps[idx].vui.par_den ? avc.sps[idx].vui.par_den : (u32) -1;
return GF_OK;
}
GF_EXPORT
GF_Err gf_avc_get_pps_info(char *pps_data, u32 pps_size, u32 *pps_id, u32 *sps_id)
{
GF_BitStream *bs;
char *pps_data_without_emulation_bytes = NULL;
u32 pps_data_without_emulation_bytes_size = 0;
GF_Err e = GF_OK;
/*PPS still contains emulation bytes*/
pps_data_without_emulation_bytes = gf_malloc(pps_size*sizeof(char));
pps_data_without_emulation_bytes_size = avc_remove_emulation_bytes(pps_data, pps_data_without_emulation_bytes, pps_size);
bs = gf_bs_new(pps_data_without_emulation_bytes, pps_data_without_emulation_bytes_size, GF_BITSTREAM_READ);
if (!bs) {
e = GF_NON_COMPLIANT_BITSTREAM;
goto exit;
}
/*nal hdr*/ gf_bs_read_int(bs, 8);
*pps_id = bs_get_ue(bs);
*sps_id = bs_get_ue(bs);
exit:
gf_bs_del(bs);
gf_free(pps_data_without_emulation_bytes);
return e;
}
#ifndef GPAC_DISABLE_HEVC
/**********
HEVC parsing
**********/
Bool gf_media_hevc_slice_is_intra(HEVCState *hevc)
{
switch (hevc->s_info.nal_unit_type) {
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
return GF_TRUE;
default:
return GF_FALSE;
}
}
Bool gf_media_hevc_slice_is_IDR(HEVCState *hevc)
{
if (hevc->sei.recovery_point.valid)
{
hevc->sei.recovery_point.valid = 0;
return GF_TRUE;
}
switch (hevc->s_info.nal_unit_type) {
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
return GF_TRUE;
default:
return GF_FALSE;
}
}
static Bool parse_short_term_ref_pic_set(GF_BitStream *bs, HEVC_SPS *sps, u32 idx_rps)
{
u32 i;
Bool inter_ref_pic_set_prediction_flag = 0;
if (idx_rps != 0)
inter_ref_pic_set_prediction_flag = gf_bs_read_int(bs, 1);
if (inter_ref_pic_set_prediction_flag ) {
HEVC_ReferencePictureSets *ref_ps, *rps;
u32 delta_idx_minus1 = 0;
u32 ref_idx;
u32 delta_rps_sign;
u32 abs_delta_rps_minus1, nb_ref_pics;
s32 deltaRPS;
u32 k = 0, k0 = 0, k1 = 0;
if (idx_rps == sps->num_short_term_ref_pic_sets)
delta_idx_minus1 = bs_get_ue(bs);
assert(delta_idx_minus1 <= idx_rps - 1);
ref_idx = idx_rps - 1 - delta_idx_minus1;
delta_rps_sign = gf_bs_read_int(bs, 1);
abs_delta_rps_minus1 = bs_get_ue(bs);
deltaRPS = (1 - (delta_rps_sign<<1)) * (abs_delta_rps_minus1 + 1);
rps = &sps->rps[idx_rps];
ref_ps = &sps->rps[ref_idx];
nb_ref_pics = ref_ps->num_negative_pics + ref_ps->num_positive_pics;
for (i=0; i<=nb_ref_pics; i++) {
s32 ref_idc;
s32 used_by_curr_pic_flag = gf_bs_read_int(bs, 1);
ref_idc = used_by_curr_pic_flag ? 1 : 0;
if ( !used_by_curr_pic_flag ) {
used_by_curr_pic_flag = gf_bs_read_int(bs, 1);
ref_idc = used_by_curr_pic_flag << 1;
}
if ((ref_idc==1) || (ref_idc== 2)) {
s32 deltaPOC = deltaRPS;
if (i < nb_ref_pics)
deltaPOC += ref_ps->delta_poc[i];
rps->delta_poc[k] = deltaPOC;
if (deltaPOC < 0) k0++;
else k1++;
k++;
}
}
rps->num_negative_pics = k0;
rps->num_positive_pics = k1;
} else {
s32 prev = 0, poc = 0;
sps->rps[idx_rps].num_negative_pics = bs_get_ue(bs);
sps->rps[idx_rps].num_positive_pics = bs_get_ue(bs);
if (sps->rps[idx_rps].num_negative_pics>16)
return GF_FALSE;
if (sps->rps[idx_rps].num_positive_pics>16)
return GF_FALSE;
for (i=0; i<sps->rps[idx_rps].num_negative_pics; i++) {
u32 delta_poc_s0_minus1 = bs_get_ue(bs);
poc = prev - delta_poc_s0_minus1 - 1;
prev = poc;
sps->rps[idx_rps].delta_poc[i] = poc;
/*used_by_curr_pic_s1_flag[ i ] = */gf_bs_read_int(bs, 1);
}
for (i=0; i<sps->rps[idx_rps].num_positive_pics; i++) {
u32 delta_poc_s1_minus1 = bs_get_ue(bs);
poc = prev + delta_poc_s1_minus1 + 1;
prev = poc;
sps->rps[idx_rps].delta_poc[i] = poc;
/*used_by_curr_pic_s1_flag[ i ] = */gf_bs_read_int(bs, 1);
}
}
return GF_TRUE;
}
void hevc_pred_weight_table(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si, HEVC_PPS *pps, HEVC_SPS *sps, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)
{
u32 i, num_ref_idx;
Bool first_pass=GF_TRUE;
u8 luma_weights[20], chroma_weights[20];
u32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;
num_ref_idx = num_ref_idx_l0_active;
/*luma_log2_weight_denom=*/i=bs_get_ue(bs);
if (ChromaArrayType != 0)
/*delta_chroma_log2_weight_denom=*/i=bs_get_se(bs);
parse_weights:
for (i=0; i<num_ref_idx; i++) {
luma_weights[i] = gf_bs_read_int(bs, 1);
//infered to be 0 if not present
chroma_weights[i] = 0;
}
if (ChromaArrayType != 0) {
for (i=0; i<num_ref_idx; i++) {
chroma_weights[i] = gf_bs_read_int(bs, 1);
}
}
for (i=0; i<num_ref_idx; i++) {
if (luma_weights[i]) {
/*delta_luma_weight_l0[ i ]=*/bs_get_se(bs);
/*luma_offset_l0[ i ]=*/bs_get_se(bs);
}
if (chroma_weights[i]) {
/*delta_chroma_weight_l0[ i ][ 0 ]=*/bs_get_se(bs);
/*delta_chroma_offset_l0[ i ][ 0 ]=*/bs_get_se(bs);
/*delta_chroma_weight_l0[ i ][ 1 ]=*/bs_get_se(bs);
/*delta_chroma_offset_l0[ i ][ 1 ]=*/bs_get_se(bs);
}
}
if (si->slice_type==GF_HEVC_SLICE_TYPE_B) {
if (!first_pass) return;
first_pass=GF_FALSE;
num_ref_idx = num_ref_idx_l1_active;
goto parse_weights;
}
}
static
Bool ref_pic_lists_modification(GF_BitStream *bs, u32 slice_type, u32 num_ref_idx_l0_active, u32 num_ref_idx_l1_active)
{
//u32 i;
Bool ref_pic_list_modification_flag_l0 = gf_bs_read_int(bs, 1);
if (ref_pic_list_modification_flag_l0) {
/*for (i=0; i<num_ref_idx_l0_active; i++) {
list_entry_l0[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr())/log(2)));
}*/
return GF_FALSE;
}
if (slice_type == GF_HEVC_SLICE_TYPE_B) {
Bool ref_pic_list_modification_flag_l1 = gf_bs_read_int(bs, 1);
if (ref_pic_list_modification_flag_l1) {
/*for (i=0; i<num_ref_idx_l1_active; i++) {
list_entry_l1[i] = *//*gf_bs_read_int(bs, (u32)ceil(log(getNumPicTotalCurr()) / log(2)));
}*/
return GF_FALSE;
}
}
return GF_TRUE;
}
static
s32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *si)
{
u32 i, j;
u32 num_ref_idx_l0_active=0, num_ref_idx_l1_active=0;
HEVC_PPS *pps;
HEVC_SPS *sps;
s32 pps_id;
Bool RapPicFlag = GF_FALSE;
Bool IDRPicFlag = GF_FALSE;
si->first_slice_segment_in_pic_flag = gf_bs_read_int(bs, 1);
switch (si->nal_unit_type) {
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
IDRPicFlag = GF_TRUE;
RapPicFlag = GF_TRUE;
break;
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
RapPicFlag = GF_TRUE;
break;
}
if (RapPicFlag) {
/*Bool no_output_of_prior_pics_flag = */gf_bs_read_int(bs, 1);
}
pps_id = bs_get_ue(bs);
if (pps_id>=64)
return -1;
pps = &hevc->pps[pps_id];
sps = &hevc->sps[pps->sps_id];
si->sps = sps;
si->pps = pps;
if (!si->first_slice_segment_in_pic_flag && pps->dependent_slice_segments_enabled_flag) {
si->dependent_slice_segment_flag = gf_bs_read_int(bs, 1);
} else {
si->dependent_slice_segment_flag = GF_FALSE;
}
if (!si->first_slice_segment_in_pic_flag) {
si->slice_segment_address = gf_bs_read_int(bs, sps->bitsSliceSegmentAddress);
} else {
si->slice_segment_address = 0;
}
if( !si->dependent_slice_segment_flag ) {
Bool deblocking_filter_override_flag=0;
Bool slice_temporal_mvp_enabled_flag = 0;
Bool slice_sao_luma_flag=0;
Bool slice_sao_chroma_flag=0;
Bool slice_deblocking_filter_disabled_flag=0;
//"slice_reserved_undetermined_flag[]"
gf_bs_read_int(bs, pps->num_extra_slice_header_bits);
si->slice_type = bs_get_ue(bs);
if (si->slice_type == GF_HEVC_SLICE_TYPE_P)
si->slice_type = GF_HEVC_SLICE_TYPE_P;
if(pps->output_flag_present_flag)
/*pic_output_flag = */gf_bs_read_int(bs, 1);
if (sps->separate_colour_plane_flag == 1)
/*colour_plane_id = */gf_bs_read_int(bs, 2);
if (IDRPicFlag) {
si->poc_lsb = 0;
//if not asked to parse full header, abort since we know the poc
if (!hevc->full_slice_header_parse) return 0;
} else {
si->poc_lsb = gf_bs_read_int(bs, sps->log2_max_pic_order_cnt_lsb);
//if not asked to parse full header, abort once we have the poc
if (!hevc->full_slice_header_parse) return 0;
if (/*short_term_ref_pic_set_sps_flag =*/gf_bs_read_int(bs, 1) == 0) {
Bool ret = parse_short_term_ref_pic_set(bs, sps, sps->num_short_term_ref_pic_sets );
if (!ret)
return -1;
} else if( sps->num_short_term_ref_pic_sets > 1 ) {
u32 numbits = 0;
while ( (u32) (1 << numbits) < sps->num_short_term_ref_pic_sets)
numbits++;
if (numbits > 0)
/*s32 short_term_ref_pic_set_idx = */gf_bs_read_int(bs, numbits);
/*else
short_term_ref_pic_set_idx = 0;*/
}
if (sps->long_term_ref_pics_present_flag ) {
u8 DeltaPocMsbCycleLt[32];
u32 num_long_term_sps = 0;
u32 num_long_term_pics = 0;
if (sps->num_long_term_ref_pic_sps > 0 ) {
num_long_term_sps = bs_get_ue(bs);
}
num_long_term_pics = bs_get_ue(bs);
for (i = 0; i < num_long_term_sps + num_long_term_pics; i++ ) {
if( i < num_long_term_sps ) {
if (sps->num_long_term_ref_pic_sps > 1)
/*u8 lt_idx_sps = */gf_bs_read_int(bs, gf_get_bit_size(sps->num_long_term_ref_pic_sps) );
} else {
/*PocLsbLt[ i ] = */ gf_bs_read_int(bs, sps->log2_max_pic_order_cnt_lsb);
/*UsedByCurrPicLt[ i ] = */ gf_bs_read_int(bs, 1);
}
if (/*delta_poc_msb_present_flag[ i ] = */ gf_bs_read_int(bs, 1) ) {
if( i == 0 || i == num_long_term_sps )
DeltaPocMsbCycleLt[i] = bs_get_ue(bs);
else
DeltaPocMsbCycleLt[i] = bs_get_ue(bs) + DeltaPocMsbCycleLt[i-1];
}
}
}
if (sps->temporal_mvp_enable_flag)
slice_temporal_mvp_enabled_flag = gf_bs_read_int(bs, 1);
}
if (sps->sample_adaptive_offset_enabled_flag) {
u32 ChromaArrayType = sps->separate_colour_plane_flag ? 0 : sps->chroma_format_idc;
slice_sao_luma_flag = gf_bs_read_int(bs, 1);
if (ChromaArrayType!=0)
slice_sao_chroma_flag = gf_bs_read_int(bs, 1);
}
if (si->slice_type == GF_HEVC_SLICE_TYPE_P || si->slice_type == GF_HEVC_SLICE_TYPE_B) {
//u32 NumPocTotalCurr;
num_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;
num_ref_idx_l1_active = 0;
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
num_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;
if ( /*num_ref_idx_active_override_flag =*/gf_bs_read_int(bs, 1) ) {
num_ref_idx_l0_active = 1 + bs_get_ue(bs);
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
num_ref_idx_l1_active = 1 + bs_get_ue(bs);
}
if (pps->lists_modification_present_flag /*TODO: && NumPicTotalCurr > 1*/) {
if (!ref_pic_lists_modification(bs, si->slice_type, num_ref_idx_l0_active, num_ref_idx_l1_active)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[hevc] ref_pic_lists_modification( ) not implemented\n"));
return -1;
}
}
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
/*mvd_l1_zero_flag=*/gf_bs_read_int(bs, 1);
if (pps->cabac_init_present_flag)
/*cabac_init_flag=*/gf_bs_read_int(bs, 1);
if (slice_temporal_mvp_enabled_flag) {
// When collocated_from_l0_flag is not present, it is inferred to be equal to 1.
Bool collocated_from_l0_flag = 1;
if (si->slice_type == GF_HEVC_SLICE_TYPE_B)
collocated_from_l0_flag = gf_bs_read_int(bs, 1);
if ( (collocated_from_l0_flag && (num_ref_idx_l0_active>1) )
|| ( !collocated_from_l0_flag && (num_ref_idx_l1_active>1) )
) {
/*collocated_ref_idx=*/bs_get_ue(bs);
}
}
if ( (pps->weighted_pred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_P )
|| ( pps->weighted_bipred_flag && si->slice_type == GF_HEVC_SLICE_TYPE_B)
) {
hevc_pred_weight_table(bs, hevc, si, pps, sps, num_ref_idx_l0_active, num_ref_idx_l1_active);
}
/*five_minus_max_num_merge_cand=*/bs_get_ue(bs);
}
/*slice_qp_delta = */bs_get_se(bs);
if( pps->slice_chroma_qp_offsets_present_flag ) {
/*slice_cb_qp_offset=*/bs_get_se(bs);
/*slice_cr_qp_offset=*/bs_get_se(bs);
}
if ( pps->deblocking_filter_override_enabled_flag ) {
deblocking_filter_override_flag = gf_bs_read_int(bs, 1);
}
if (deblocking_filter_override_flag) {
slice_deblocking_filter_disabled_flag = gf_bs_read_int(bs, 1);
if ( !slice_deblocking_filter_disabled_flag) {
/*slice_beta_offset_div2=*/ bs_get_se(bs);
/*slice_tc_offset_div2=*/bs_get_se(bs);
}
}
if( pps->loop_filter_across_slices_enabled_flag
&& ( slice_sao_luma_flag || slice_sao_chroma_flag || !slice_deblocking_filter_disabled_flag )
) {
/*slice_loop_filter_across_slices_enabled_flag = */gf_bs_read_int(bs, 1);
}
}
//dependent slice segment
else {
//if not asked to parse full header, abort
if (!hevc->full_slice_header_parse) return 0;
}
si->entry_point_start_bits = ((u32)gf_bs_get_position(bs)-1)*8 + gf_bs_get_bit_position(bs);
if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag ) {
u32 num_entry_point_offsets = bs_get_ue(bs);
if ( num_entry_point_offsets > 0) {
u32 offset = bs_get_ue(bs) + 1;
u32 segments = offset >> 4;
s32 remain = (offset & 15);
for (i=0; i<num_entry_point_offsets; i++) {
u32 res = 0;
for (j=0; j<segments; j++) {
res <<= 16;
res += gf_bs_read_int(bs, 16);
}
if (remain) {
res <<= remain;
res += gf_bs_read_int(bs, remain);
}
// entry_point_offset = val + 1; // +1; // +1 to get the size
}
}
}
if (pps->slice_segment_header_extension_present_flag) {
u32 size_ext = bs_get_ue(bs);
while (size_ext) {
gf_bs_read_int(bs, 8);
size_ext--;
}
}
if (gf_bs_read_int(bs, 1) == 0) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("Error parsing slice header: byte_align not found at end of header !\n"));
}
gf_bs_align(bs);
si->payload_start_offset = (s32)gf_bs_get_position(bs);
return 0;
}
static void hevc_compute_poc(HEVCSliceInfo *si)
{
u32 max_poc_lsb = 1 << (si->sps->log2_max_pic_order_cnt_lsb);
/*POC reset for IDR frames, NOT for CRA*/
switch (si->nal_unit_type) {
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
si->poc_lsb_prev = 0;
si->poc_msb_prev = 0;
break;
}
if ((si->poc_lsb < si->poc_lsb_prev) && ( si->poc_lsb_prev - si->poc_lsb >= max_poc_lsb / 2) )
si->poc_msb = si->poc_msb_prev + max_poc_lsb;
else if ((si->poc_lsb > si->poc_lsb_prev) && (si->poc_lsb - si->poc_lsb_prev > max_poc_lsb / 2))
si->poc_msb = si->poc_msb_prev - max_poc_lsb;
else
si->poc_msb = si->poc_msb_prev;
switch (si->nal_unit_type) {
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
si->poc_msb = 0;
break;
}
si->poc = si->poc_msb + si->poc_lsb;
}
static Bool hevc_parse_nal_header(GF_BitStream *bs, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
{
u32 val;
val = gf_bs_read_int(bs, 1);
if (val) return GF_FALSE;
val = gf_bs_read_int(bs, 6);
if (nal_unit_type) *nal_unit_type = val;
val = gf_bs_read_int(bs, 6);
if (layer_id) *layer_id = val;
val = gf_bs_read_int(bs, 3);
if (! val)
return GF_FALSE;
val -= 1;
if (temporal_id) *temporal_id = val;
return GF_TRUE;
}
void profile_tier_level(GF_BitStream *bs, Bool ProfilePresentFlag, u8 MaxNumSubLayersMinus1, HEVC_ProfileTierLevel *ptl)
{
u32 i;
if (ProfilePresentFlag) {
ptl->profile_space = gf_bs_read_int(bs, 2);
ptl->tier_flag = gf_bs_read_int(bs, 1);
ptl->profile_idc = gf_bs_read_int(bs, 5);
ptl->profile_compatibility_flag = gf_bs_read_int(bs, 32);
ptl->general_progressive_source_flag = gf_bs_read_int(bs, 1);
ptl->general_interlaced_source_flag = gf_bs_read_int(bs, 1);
ptl->general_non_packed_constraint_flag = gf_bs_read_int(bs, 1);
ptl->general_frame_only_constraint_flag = gf_bs_read_int(bs, 1);
ptl->general_reserved_44bits = gf_bs_read_long_int(bs, 44);
}
ptl->level_idc = gf_bs_read_int(bs, 8);
for (i=0; i<MaxNumSubLayersMinus1; i++) {
ptl->sub_ptl[i].profile_present_flag = gf_bs_read_int(bs, 1);
ptl->sub_ptl[i].level_present_flag = gf_bs_read_int(bs, 1);
}
if (MaxNumSubLayersMinus1>0) {
for (i=MaxNumSubLayersMinus1; i<8; i++) {
/*reserved_zero_2bits*/gf_bs_read_int(bs, 2);
}
}
for (i=0; i<MaxNumSubLayersMinus1; i++) {
if (ptl->sub_ptl[i].profile_present_flag) {
ptl->sub_ptl[i].profile_space = gf_bs_read_int(bs, 2);
ptl->sub_ptl[i].tier_flag = gf_bs_read_int(bs, 1);
ptl->sub_ptl[i].profile_idc = gf_bs_read_int(bs, 5);
ptl->sub_ptl[i].profile_compatibility_flag = gf_bs_read_int(bs, 32);
/*ptl->sub_ptl[i].progressive_source_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].interlaced_source_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].non_packed_constraint_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].frame_only_constraint_flag =*/ gf_bs_read_int(bs, 1);
/*ptl->sub_ptl[i].reserved_44bits =*/ gf_bs_read_long_int(bs, 44);
}
if (ptl->sub_ptl[i].level_present_flag)
ptl->sub_ptl[i].level_idc = gf_bs_read_int(bs, 8);
}
}
static u32 scalability_type_to_idx(HEVC_VPS *vps, u32 scalability_type)
{
u32 idx = 0, type;
for (type=0; type < scalability_type; type++) {
idx += (vps->scalability_mask[type] ? 1 : 0 );
}
return idx;
}
#define LHVC_VIEW_ORDER_INDEX 1
#define LHVC_SCALABILITY_INDEX 2
static u32 lhvc_get_scalability_id(HEVC_VPS *vps, u32 layer_id_in_vps, u32 scalability_type )
{
u32 idx;
if (!vps->scalability_mask[scalability_type]) return 0;
idx = scalability_type_to_idx(vps, scalability_type);
return vps->dimension_id[layer_id_in_vps][idx];
}
static u32 lhvc_get_view_index(HEVC_VPS *vps, u32 id)
{
return lhvc_get_scalability_id(vps, vps->layer_id_in_vps[id], LHVC_VIEW_ORDER_INDEX);
}
static u32 lhvc_get_num_views(HEVC_VPS *vps)
{
u32 numViews = 1, i;
for (i=0; i<vps->max_layers; i++ ) {
u32 layer_id = vps->layer_id_in_nuh[i];
if (i>0 && ( lhvc_get_view_index( vps, layer_id) != lhvc_get_scalability_id( vps, i-1, LHVC_VIEW_ORDER_INDEX) )) {
numViews++;
}
}
return numViews;
}
static void lhvc_parse_rep_format(HEVC_RepFormat *fmt, GF_BitStream *bs)
{
u8 chroma_bitdepth_present_flag;
fmt->pic_width_luma_samples = gf_bs_read_int(bs, 16);
fmt->pic_height_luma_samples = gf_bs_read_int(bs, 16);
chroma_bitdepth_present_flag = gf_bs_read_int(bs, 1);
if (chroma_bitdepth_present_flag) {
fmt->chroma_format_idc = gf_bs_read_int(bs, 2);
if (fmt->chroma_format_idc == 3)
fmt->separate_colour_plane_flag = gf_bs_read_int(bs, 1);
fmt->bit_depth_luma = 8 + gf_bs_read_int(bs, 4);
fmt->bit_depth_chroma = 8 + gf_bs_read_int(bs, 4);
}
if (/*conformance_window_vps_flag*/ gf_bs_read_int(bs, 1)) {
/*conf_win_vps_left_offset*/bs_get_ue(bs);
/*conf_win_vps_right_offset*/bs_get_ue(bs);
/*conf_win_vps_top_offset*/bs_get_ue(bs);
/*conf_win_vps_bottom_offset*/bs_get_ue(bs);
}
}
static Bool hevc_parse_vps_extension(HEVC_VPS *vps, GF_BitStream *bs)
{
u8 splitting_flag, vps_nuh_layer_id_present_flag, view_id_len;
u32 i, j, num_scalability_types, num_add_olss, num_add_layer_set, num_indepentdent_layers, nb_bits, default_output_layer_idc=0;
u8 dimension_id_len[16], dim_bit_offset[16];
u8 /*avc_base_layer_flag, */NumLayerSets, /*default_one_target_output_layer_flag, */rep_format_idx_present_flag, ols_ids_to_ls_idx;
u8 layer_set_idx_for_ols_minus1[MAX_LHVC_LAYERS];
u8 nb_output_layers_in_output_layer_set[MAX_LHVC_LAYERS+1];
u8 ols_highest_output_layer_id[MAX_LHVC_LAYERS+1];
u32 k,d, r, p, iNuhLId, jNuhLId;
u8 num_direct_ref_layers[64], num_pred_layers[64], num_layers_in_tree_partition[MAX_LHVC_LAYERS];
u8 dependency_flag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS], id_pred_layers[64][MAX_LHVC_LAYERS];
// u8 num_ref_layers[64];
// u8 tree_partition_layer_id[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];
// u8 id_ref_layers[64][MAX_LHVC_LAYERS];
// u8 id_direct_ref_layers[64][MAX_LHVC_LAYERS];
u8 layer_id_in_list_flag[64];
Bool OutputLayerFlag[MAX_LHVC_LAYERS][MAX_LHVC_LAYERS];
vps->vps_extension_found=1;
if ((vps->max_layers > 1) && vps->base_layer_internal_flag)
profile_tier_level(bs, 0, vps->max_sub_layers-1, &vps->ext_ptl[0]);
splitting_flag = gf_bs_read_int(bs, 1);
num_scalability_types = 0;
for (i=0; i<16; i++) {
vps->scalability_mask[i] = gf_bs_read_int(bs, 1);
num_scalability_types += vps->scalability_mask[i];
}
if (num_scalability_types>=16) {
num_scalability_types=16;
}
dimension_id_len[0] = 0;
for (i=0; i<(num_scalability_types - splitting_flag); i++) {
dimension_id_len[i] = 1 + gf_bs_read_int(bs, 3);
}
if (splitting_flag) {
for (i = 0; i < num_scalability_types; i++) {
dim_bit_offset[i] = 0;
for (j = 0; j < i; j++)
dim_bit_offset[i] += dimension_id_len[j];
}
dimension_id_len[num_scalability_types-1] = 1 + (5 - dim_bit_offset[num_scalability_types-1]);
dim_bit_offset[num_scalability_types] = 6;
}
vps_nuh_layer_id_present_flag = gf_bs_read_int(bs, 1);
vps->layer_id_in_nuh[0] = 0;
vps->layer_id_in_vps[0] = 0;
for (i=1; i<vps->max_layers; i++) {
if (vps_nuh_layer_id_present_flag) {
vps->layer_id_in_nuh[i] = gf_bs_read_int(bs, 6);
} else {
vps->layer_id_in_nuh[i] = i;
}
vps->layer_id_in_vps[vps->layer_id_in_nuh[i]] = i;
if (!splitting_flag) {
for (j=0; j<num_scalability_types; j++) {
vps->dimension_id[i][j] = gf_bs_read_int(bs, dimension_id_len[j]);
}
}
}
if (splitting_flag) {
for (i = 0; i<vps->max_layers; i++)
for (j=0; j<num_scalability_types; j++)
vps->dimension_id[i][j] = ((vps->layer_id_in_nuh[i] & ((1 << dim_bit_offset[j+1]) -1)) >> dim_bit_offset[j]);
} else {
for (j=0; j<num_scalability_types; j++)
vps->dimension_id[0][j] = 0;
}
view_id_len = gf_bs_read_int(bs, 4);
if (view_id_len > 0) {
for( i = 0; i < lhvc_get_num_views(vps); i++ ) {
/*m_viewIdVal[i] = */ gf_bs_read_int(bs, view_id_len);
}
}
for (i=1; i<vps->max_layers; i++) {
for (j=0; j<i; j++) {
vps->direct_dependency_flag[i][j] = gf_bs_read_int(bs, 1);
}
}
//we do the test on MAX_LHVC_LAYERS and break in the loop to avoid a wrong GCC 4.8 warning on array bounds
for (i = 0; i < MAX_LHVC_LAYERS; i++) {
if (i >= vps->max_layers) break;
for (j = 0; j < vps->max_layers; j++) {
dependency_flag[i][j] = vps->direct_dependency_flag[i][j];
for (k = 0; k < i; k++)
if (vps->direct_dependency_flag[i][k] && vps->direct_dependency_flag[k][j])
dependency_flag[i][j] = 1;
}
}
for (i = 0; i < vps->max_layers; i++) {
iNuhLId = vps->layer_id_in_nuh[i];
d = r = p = 0;
for (j = 0; j < vps->max_layers; j++) {
jNuhLId = vps->layer_id_in_nuh[j];
if (vps->direct_dependency_flag[i][j]) {
// id_direct_ref_layers[iNuhLId][d] = jNuhLId;
d++;
}
if (dependency_flag[i][j]) {
// id_ref_layers[iNuhLId][r] = jNuhLId;
r++;
}
if (dependency_flag[j][i])
id_pred_layers[iNuhLId][p++] = jNuhLId;
}
num_direct_ref_layers[iNuhLId] = d;
// num_ref_layers[iNuhLId] = r;
num_pred_layers[iNuhLId] = p;
}
memset(layer_id_in_list_flag, 0, 64*sizeof(u8));
k = 0; //num_indepentdent_layers
for (i = 0; i < vps->max_layers; i++) {
iNuhLId = vps->layer_id_in_nuh[i];
if (!num_direct_ref_layers[iNuhLId]) {
u32 h = 1;
//tree_partition_layer_id[k][0] = iNuhLId;
for (j = 0; j < num_pred_layers[iNuhLId]; j++) {
u32 predLId = id_pred_layers[iNuhLId][j];
if (!layer_id_in_list_flag[predLId]) {
//tree_partition_layer_id[k][h++] = predLId;
layer_id_in_list_flag[predLId] = 1;
}
}
num_layers_in_tree_partition[k++] = h;
}
}
num_indepentdent_layers = k;
num_add_layer_set = 0;
if (num_indepentdent_layers > 1)
num_add_layer_set = bs_get_ue(bs);
for (i = 0; i < num_add_layer_set; i++)
for (j = 1; j < num_indepentdent_layers; j++) {
nb_bits =1;
while ((1 << nb_bits) < (num_layers_in_tree_partition[j] + 1))
nb_bits++;
/*highest_layer_idx_plus1[i][j]*/gf_bs_read_int(bs, nb_bits);
}
if (/*vps_sub_layers_max_minus1_present_flag*/gf_bs_read_int(bs, 1)) {
for (i = 0; i < vps->max_layers; i++) {
/*sub_layers_vps_max_minus1[ i ]*/gf_bs_read_int(bs, 3);
}
}
if (/*max_tid_ref_present_flag = */gf_bs_read_int(bs, 1)) {
for (i=0; i<(vps->max_layers-1) ; i++) {
for (j= i+1; j < vps->max_layers; j++) {
if (vps->direct_dependency_flag[j][i])
/*max_tid_il_ref_pics_plus1[ i ][ j ]*/gf_bs_read_int(bs, 3);
}
}
}
/*default_ref_layers_active_flag*/gf_bs_read_int(bs, 1);
vps->num_profile_tier_level = 1+bs_get_ue(bs);
if (vps->num_profile_tier_level > MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of PTLs in VPS %d\n", vps->num_profile_tier_level));
vps->num_profile_tier_level=1;
return GF_FALSE;
}
for (i=vps->base_layer_internal_flag ? 2 : 1; i < vps->num_profile_tier_level; i++) {
Bool vps_profile_present_flag = gf_bs_read_int(bs, 1);
profile_tier_level(bs, vps_profile_present_flag, vps->max_sub_layers-1, &vps->ext_ptl[i-1] );
}
NumLayerSets = vps->num_layer_sets + num_add_layer_set;
num_add_olss = 0;
if (NumLayerSets > 1) {
num_add_olss = bs_get_ue(bs);
default_output_layer_idc = gf_bs_read_int(bs,2);
default_output_layer_idc = default_output_layer_idc < 2 ? default_output_layer_idc : 2;
}
vps->num_output_layer_sets = num_add_olss + NumLayerSets;
layer_set_idx_for_ols_minus1[0] = 1;
vps->output_layer_flag[0][0] = 1;
for (i = 0; i < vps->num_output_layer_sets; i++) {
if ((NumLayerSets > 2) && (i >= NumLayerSets)) {
nb_bits = 1;
while ((1 << nb_bits) < (NumLayerSets - 1))
nb_bits++;
layer_set_idx_for_ols_minus1[i] = gf_bs_read_int(bs, nb_bits);
}
else
layer_set_idx_for_ols_minus1[i] = 0;
ols_ids_to_ls_idx = i < NumLayerSets ? i : layer_set_idx_for_ols_minus1[i] + 1;
if ((i > (vps->num_layer_sets - 1)) || (default_output_layer_idc == 2)) {
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)
vps->output_layer_flag[i][j] = gf_bs_read_int(bs, 1);
}
if ((default_output_layer_idc == 0) || (default_output_layer_idc == 1)) {
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
if ((default_output_layer_idc == 0) || (vps->LayerSetLayerIdList[i][j] == vps->LayerSetLayerIdListMax[i]))
OutputLayerFlag[i][j] = GF_TRUE;
else
OutputLayerFlag[i][j] = GF_FALSE;
}
}
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
if (OutputLayerFlag[i][j]) {
u32 curLayerID, k;
vps->necessary_layers_flag[i][j] = GF_TRUE;
curLayerID = vps->LayerSetLayerIdList[i][j];
for (k = 0; k < j; k++) {
u32 refLayerId = vps->LayerSetLayerIdList[i][k];
if (dependency_flag[vps->layer_id_in_vps[curLayerID]][vps->layer_id_in_vps[refLayerId]])
vps->necessary_layers_flag[i][k] = GF_TRUE;
}
}
}
vps->num_necessary_layers[i] = 0;
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
if (vps->necessary_layers_flag[i][j])
vps->num_necessary_layers[i] += 1;
}
if (i == 0) {
if (vps->base_layer_internal_flag) {
if (vps->max_layers > 1)
vps->profile_tier_level_idx[0][0] = 1;
else
vps->profile_tier_level_idx[0][0] = 0;
}
continue;
}
nb_bits = 1;
while ((u32)(1 << nb_bits) < vps->num_profile_tier_level)
nb_bits++;
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++)
if (vps->necessary_layers_flag[i][j] && vps->num_profile_tier_level)
vps->profile_tier_level_idx[i][j] = gf_bs_read_int(bs, nb_bits);
else
vps->profile_tier_level_idx[i][j] = 0;
nb_output_layers_in_output_layer_set[i] = 0;
for (j = 0; j < vps->num_layers_in_id_list[ols_ids_to_ls_idx]; j++) {
nb_output_layers_in_output_layer_set[i] += OutputLayerFlag[i][j];
if (OutputLayerFlag[i][j]) {
ols_highest_output_layer_id[i] = vps->LayerSetLayerIdList[ols_ids_to_ls_idx][j];
}
}
if (nb_output_layers_in_output_layer_set[i] == 1 && ols_highest_output_layer_id[i] > 0)
vps->alt_output_layer_flag[i] = gf_bs_read_int(bs, 1);
}
vps->num_rep_formats = 1 + bs_get_ue(bs);
if (vps->num_rep_formats > 16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of rep formats in VPS %d\n", vps->num_rep_formats));
vps->num_rep_formats = 0;
return GF_FALSE;
}
for (i = 0; i < vps->num_rep_formats; i++) {
lhvc_parse_rep_format(&vps->rep_formats[i], bs);
}
if (vps->num_rep_formats > 1)
rep_format_idx_present_flag = gf_bs_read_int(bs, 1);
else
rep_format_idx_present_flag = 0;
vps->rep_format_idx[0] = 0;
nb_bits = 1;
while ((u32)(1 << nb_bits) < vps->num_rep_formats)
nb_bits++;
for (i = vps->base_layer_internal_flag ? 1 : 0; i < vps->max_layers; i++) {
if (rep_format_idx_present_flag) {
vps->rep_format_idx[i] = gf_bs_read_int(bs, nb_bits);
}
else {
vps->rep_format_idx[i] = i < vps->num_rep_formats - 1 ? i : vps->num_rep_formats - 1;
}
}
//TODO - we don't use the rest ...
return GF_TRUE;
}
static void sub_layer_hrd_parameters(GF_BitStream *bs, int subLayerId, u32 cpb_cnt, Bool sub_pic_hrd_params_present_flag) {
u32 i;
for (i = 0; i <= cpb_cnt; i++) {
/*bit_rate_value_minus1[i] = */bs_get_ue(bs);
/*cpb_size_value_minus1[i] = */bs_get_ue(bs);
if (sub_pic_hrd_params_present_flag) {
/*cpb_size_du_value_minus1[i] = */bs_get_ue(bs);
/*bit_rate_du_value_minus1[i] = */bs_get_ue(bs);
}
/*cbr_flag[i] = */gf_bs_read_int(bs, 1);
}
}
static void hevc_parse_hrd_parameters(GF_BitStream *bs, Bool commonInfPresentFlag, int maxNumSubLayersMinus1)
{
int i;
Bool nal_hrd_parameters_present_flag = GF_FALSE;
Bool vcl_hrd_parameters_present_flag = GF_FALSE;
Bool sub_pic_hrd_params_present_flag = GF_FALSE;
if (commonInfPresentFlag) {
nal_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
vcl_hrd_parameters_present_flag = gf_bs_read_int(bs, 1);
if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
sub_pic_hrd_params_present_flag = gf_bs_read_int(bs, 1);
if (sub_pic_hrd_params_present_flag) {
/*tick_divisor_minus2 = */gf_bs_read_int(bs, 8);
/*du_cpb_removal_delay_increment_length_minus1 = */gf_bs_read_int(bs, 5);
/*sub_pic_cpb_params_in_pic_timing_sei_flag = */gf_bs_read_int(bs, 1);
/*dpb_output_delay_du_length_minus1 = */gf_bs_read_int(bs, 5);
}
/*bit_rate_scale = */gf_bs_read_int(bs, 4);
/*cpb_size_scale = */gf_bs_read_int(bs, 4);
if (sub_pic_hrd_params_present_flag) {
/*cpb_size_du_scale = */gf_bs_read_int(bs, 4);
}
/*initial_cpb_removal_delay_length_minus1 = */gf_bs_read_int(bs, 5);
/*au_cpb_removal_delay_length_minus1 = */gf_bs_read_int(bs, 5);
/*dpb_output_delay_length_minus1 = */gf_bs_read_int(bs, 5);
}
}
for (i = 0; i <= maxNumSubLayersMinus1; i++) {
Bool fixed_pic_rate_general_flag_i = gf_bs_read_int(bs, 1);
Bool fixed_pic_rate_within_cvs_flag_i = GF_TRUE;
Bool low_delay_hrd_flag_i = GF_FALSE;
u32 cpb_cnt_minus1_i = 0;
if (!fixed_pic_rate_general_flag_i) {
fixed_pic_rate_within_cvs_flag_i = gf_bs_read_int(bs, 1);
}
if (fixed_pic_rate_within_cvs_flag_i)
/*elemental_duration_in_tc_minus1[i] = */bs_get_ue(bs);
else
low_delay_hrd_flag_i = gf_bs_read_int(bs, 1);
if (!low_delay_hrd_flag_i) {
cpb_cnt_minus1_i = bs_get_ue(bs);
}
if (nal_hrd_parameters_present_flag) {
sub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag);
}
if (vcl_hrd_parameters_present_flag) {
sub_layer_hrd_parameters(bs, i, cpb_cnt_minus1_i, sub_pic_hrd_params_present_flag);
}
}
}
static s32 gf_media_hevc_read_vps_bs(GF_BitStream *bs, HEVCState *hevc, Bool stop_at_vps_ext)
{
u8 vps_sub_layer_ordering_info_present_flag, vps_extension_flag;
u32 i, j;
s32 vps_id = -1;
HEVC_VPS *vps;
u8 layer_id_included_flag[MAX_LHVC_LAYERS][64];
//nalu header already parsed
vps_id = gf_bs_read_int(bs, 4);
if (vps_id>=16) return -1;
vps = &hevc->vps[vps_id];
vps->bit_pos_vps_extensions = -1;
if (!vps->state) {
vps->id = vps_id;
vps->state = 1;
}
vps->base_layer_internal_flag = gf_bs_read_int(bs, 1);
vps->base_layer_available_flag = gf_bs_read_int(bs, 1);
vps->max_layers = 1 + gf_bs_read_int(bs, 6);
if (vps->max_layers>MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] sorry, %d layers in VPS but only %d supported\n", vps->max_layers, MAX_LHVC_LAYERS));
return -1;
}
vps->max_sub_layers = gf_bs_read_int(bs, 3) + 1;
vps->temporal_id_nesting = gf_bs_read_int(bs, 1);
/* vps_reserved_ffff_16bits = */ gf_bs_read_int(bs, 16);
profile_tier_level(bs, 1, vps->max_sub_layers-1, &vps->ptl);
vps_sub_layer_ordering_info_present_flag = gf_bs_read_int(bs, 1);
for (i=(vps_sub_layer_ordering_info_present_flag ? 0 : vps->max_sub_layers - 1); i < vps->max_sub_layers; i++) {
/*vps_max_dec_pic_buffering_minus1[i] = */bs_get_ue(bs);
/*vps_max_num_reorder_pics[i] = */bs_get_ue(bs);
/*vps_max_latency_increase_plus1[i] = */bs_get_ue(bs);
}
vps->max_layer_id = gf_bs_read_int(bs, 6);
if (vps->max_layer_id > MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] VPS max layer ID %u but GPAC only supports %u\n", vps->max_layer_id, MAX_LHVC_LAYERS));
return -1;
}
vps->num_layer_sets = bs_get_ue(bs) + 1;
if (vps->num_layer_sets > MAX_LHVC_LAYERS) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Wrong number of layer sets in VPS %d\n", vps->num_layer_sets));
return -1;
}
for (i=1; i < vps->num_layer_sets; i++) {
for (j=0; j <= vps->max_layer_id; j++) {
layer_id_included_flag[ i ][ j ] = gf_bs_read_int(bs, 1);
}
}
vps->num_layers_in_id_list[0] = 1;
for (i = 1; i < vps->num_layer_sets; i++) {
u32 n, m;
n = 0;
for (m = 0; m <= vps->max_layer_id; m++)
if (layer_id_included_flag[i][m]) {
vps->LayerSetLayerIdList[i][n++] = m;
if (vps->LayerSetLayerIdListMax[i] < m)
vps->LayerSetLayerIdListMax[i] = m;
}
vps->num_layers_in_id_list[i] = n;
}
if (/*vps_timing_info_present_flag*/gf_bs_read_int(bs, 1)) {
u32 vps_num_hrd_parameters;
/*u32 vps_num_units_in_tick = */gf_bs_read_int(bs, 32);
/*u32 vps_time_scale = */gf_bs_read_int(bs, 32);
if (/*vps_poc_proportional_to_timing_flag*/gf_bs_read_int(bs, 1)) {
/*vps_num_ticks_poc_diff_one_minus1*/bs_get_ue(bs);
}
vps_num_hrd_parameters = bs_get_ue(bs);
for( i = 0; i < vps_num_hrd_parameters; i++ ) {
Bool cprms_present_flag = GF_TRUE;
/*hrd_layer_set_idx[i] = */bs_get_ue(bs);
if (i>0)
cprms_present_flag = gf_bs_read_int(bs, 1) ;
hevc_parse_hrd_parameters(bs, cprms_present_flag, vps->max_sub_layers - 1);
}
}
if (stop_at_vps_ext) {
return vps_id;
}
vps_extension_flag = gf_bs_read_int(bs, 1);
if (vps_extension_flag ) {
Bool res;
gf_bs_align(bs);
res = hevc_parse_vps_extension(vps, bs);
if (res!=GF_TRUE) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Failed to parse VPS extensions\n"));
return -1;
}
if (/*vps_extension2_flag*/gf_bs_read_int(bs, 1)) {
while (gf_bs_available(bs)) {
/*vps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
}
}
return vps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_vps_ex(char *data, u32 *size, HEVCState *hevc, Bool remove_extensions)
{
GF_BitStream *bs;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
s32 vps_id = -1;
/*still contains emulation bytes*/
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, (*size));
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, (*size), GF_BITSTREAM_READ);
} else {
data_without_emulation_bytes = gf_malloc((*size) * sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, (*size) );
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;
vps_id = gf_media_hevc_read_vps_bs(bs, hevc, remove_extensions);
if (vps_id<0) goto exit;
if (remove_extensions) {
char *new_vps;
u32 new_vps_size, emulation_bytes;
u32 bit_pos = gf_bs_get_bit_offset(bs);
GF_BitStream *w_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_bs_write_u8(w_bs, data[0]);
gf_bs_write_u8(w_bs, data[1]);
gf_bs_write_u8(w_bs, data[2]);
gf_bs_write_u8(w_bs, data[3]);
gf_bs_write_u16(w_bs, 0xFFFF);
gf_bs_seek(bs, 6);
bit_pos-=48;
while (bit_pos) {
u32 v = gf_bs_read_int(bs, 1);
gf_bs_write_int(w_bs, v, 1);
bit_pos--;
}
/*vps extension flag*/
gf_bs_write_int(w_bs, 0, 1);
new_vps=NULL;
gf_bs_get_content(w_bs, &new_vps, &new_vps_size);
gf_bs_del(w_bs);
emulation_bytes = avc_emulation_bytes_add_count(new_vps, new_vps_size);
if (emulation_bytes+new_vps_size > *size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("Buffer too small to rewrite VPS - skipping rewrite\n"));
} else {
*size = avc_add_emulation_bytes(new_vps, data, new_vps_size);
}
}
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return vps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_vps(char *data, u32 size, HEVCState *hevc)
{
return gf_media_hevc_read_vps_ex(data, &size, hevc, GF_FALSE);
}
static void hevc_scaling_list_data(GF_BitStream *bs)
{
u32 i, sizeId, matrixId;
for (sizeId = 0; sizeId < 4; sizeId++) {
for (matrixId=0; matrixId<6; matrixId += (sizeId == 3) ? 3:1 ) {
u32 scaling_list_pred_mode_flag_sizeId_matrixId = gf_bs_read_int(bs, 1);
if( ! scaling_list_pred_mode_flag_sizeId_matrixId ) {
/*scaling_list_pred_matrix_id_delta[ sizeId ][ matrixId ] =*/ bs_get_ue(bs);
} else {
//u32 nextCoef = 8;
u32 coefNum = MIN(64, (1 << (4+(sizeId << 1))));
if ( sizeId > 1 ) {
/*scaling_list_dc_coef_minus8[ sizeId − 2 ][ matrixId ] = */bs_get_se(bs);
}
for (i = 0; i<coefNum; i++) {
/*scaling_list_delta_coef = */bs_get_se(bs);
}
}
}
}
}
static const struct {
u32 w, h;
} hevc_sar[17] =
{
{ 0, 0 }, { 1, 1 }, { 12, 11 }, { 10, 11 },
{ 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
{ 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
{ 64, 33 }, { 160,99 }, { 4,3}, { 3,2}, { 2,1}
};
static s32 gf_media_hevc_read_sps_bs(GF_BitStream *bs, HEVCState *hevc, u8 layer_id, u32 *vui_flag_pos)
{
s32 vps_id, sps_id = -1;
u8 max_sub_layers_minus1, flag;
Bool scaling_list_enable_flag;
u32 i, nb_CTUs, depth;
u32 log2_diff_max_min_luma_coding_block_size;
u32 log2_min_transform_block_size, log2_min_luma_coding_block_size;
Bool sps_sub_layer_ordering_info_present_flag;
HEVC_SPS *sps;
HEVC_VPS *vps;
HEVC_ProfileTierLevel ptl;
u32 sps_ext_or_max_sub_layers_minus1;
Bool multiLayerExtSpsFlag;
if (vui_flag_pos) *vui_flag_pos = 0;
//nalu header already parsed
vps_id = gf_bs_read_int(bs, 4);
if (vps_id>=16) {
return -1;
}
memset(&ptl, 0, sizeof(ptl));
max_sub_layers_minus1 = 0;
sps_ext_or_max_sub_layers_minus1 = 0;
if (layer_id == 0)
max_sub_layers_minus1 = gf_bs_read_int(bs, 3);
else
sps_ext_or_max_sub_layers_minus1 = gf_bs_read_int(bs, 3);
multiLayerExtSpsFlag = (layer_id != 0) && (sps_ext_or_max_sub_layers_minus1 == 7);
if (!multiLayerExtSpsFlag) {
/*temporal_id_nesting_flag = */gf_bs_read_int(bs, 1);
profile_tier_level(bs, 1, max_sub_layers_minus1, &ptl);
}
sps_id = bs_get_ue(bs);
if ((sps_id<0) ||(sps_id>=16)) {
return -1;
}
sps = &hevc->sps[sps_id];
if (!sps->state) {
sps->state = 1;
sps->id = sps_id;
sps->vps_id = vps_id;
}
sps->ptl = ptl;
vps = &hevc->vps[vps_id];
//sps_rep_format_idx = 0;
if (multiLayerExtSpsFlag) {
u8 update_rep_format_flag = gf_bs_read_int(bs, 1);
if (update_rep_format_flag) {
sps->rep_format_idx = gf_bs_read_int(bs, 8);
} else {
sps->rep_format_idx = vps->rep_format_idx[layer_id];
}
sps->width = vps->rep_formats[sps->rep_format_idx].pic_width_luma_samples;
sps->height = vps->rep_formats[sps->rep_format_idx].pic_height_luma_samples;
sps->chroma_format_idc = vps->rep_formats[sps->rep_format_idx].chroma_format_idc;
sps->bit_depth_luma = vps->rep_formats[sps->rep_format_idx].bit_depth_luma;
sps->bit_depth_chroma = vps->rep_formats[sps->rep_format_idx].bit_depth_chroma;
sps->separate_colour_plane_flag = vps->rep_formats[sps->rep_format_idx].separate_colour_plane_flag;
//TODO this is crude ...
sps->ptl = vps->ext_ptl[0];
} else {
sps->chroma_format_idc = bs_get_ue(bs);
if (sps->chroma_format_idc==3)
sps->separate_colour_plane_flag = gf_bs_read_int(bs, 1);
sps->width = bs_get_ue(bs);
sps->height = bs_get_ue(bs);
if (/*conformance_window_flag*/gf_bs_read_int(bs, 1)) {
u32 SubWidthC, SubHeightC;
if (sps->chroma_format_idc==1) {
SubWidthC = SubHeightC = 2;
}
else if (sps->chroma_format_idc==2) {
SubWidthC = 2;
SubHeightC = 1;
} else {
SubWidthC = SubHeightC = 1;
}
sps->cw_left = bs_get_ue(bs);
sps->cw_right = bs_get_ue(bs);
sps->cw_top = bs_get_ue(bs);
sps->cw_bottom = bs_get_ue(bs);
sps->width -= SubWidthC * (sps->cw_left + sps->cw_right);
sps->height -= SubHeightC * (sps->cw_top + sps->cw_bottom);
}
sps->bit_depth_luma = 8 + bs_get_ue(bs);
sps->bit_depth_chroma = 8 + bs_get_ue(bs);
}
sps->log2_max_pic_order_cnt_lsb = 4 + bs_get_ue(bs);
if (!multiLayerExtSpsFlag) {
sps_sub_layer_ordering_info_present_flag = gf_bs_read_int(bs, 1);
for(i=sps_sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i<=max_sub_layers_minus1; i++) {
/*max_dec_pic_buffering = */ bs_get_ue(bs);
/*num_reorder_pics = */ bs_get_ue(bs);
/*max_latency_increase = */ bs_get_ue(bs);
}
}
log2_min_luma_coding_block_size = 3 + bs_get_ue(bs);
log2_diff_max_min_luma_coding_block_size = bs_get_ue(bs);
sps->max_CU_width = ( 1<<(log2_min_luma_coding_block_size + log2_diff_max_min_luma_coding_block_size) );
sps->max_CU_height = ( 1<<(log2_min_luma_coding_block_size + log2_diff_max_min_luma_coding_block_size) );
log2_min_transform_block_size = 2 + bs_get_ue(bs);
/*log2_max_transform_block_size = log2_min_transform_block_size + */bs_get_ue(bs);
depth = 0;
/*u32 max_transform_hierarchy_depth_inter = */bs_get_ue(bs);
/*u32 max_transform_hierarchy_depth_intra = */bs_get_ue(bs);
while( (u32) ( sps->max_CU_width >> log2_diff_max_min_luma_coding_block_size ) > (u32) ( 1 << ( log2_min_transform_block_size + depth ) ) )
{
depth++;
}
sps->max_CU_depth = log2_diff_max_min_luma_coding_block_size + depth;
nb_CTUs = ((sps->width + sps->max_CU_width -1) / sps->max_CU_width) * ((sps->height + sps->max_CU_height-1) / sps->max_CU_height);
sps->bitsSliceSegmentAddress = 0;
while (nb_CTUs > (u32) (1 << sps->bitsSliceSegmentAddress)) {
sps->bitsSliceSegmentAddress++;
}
scaling_list_enable_flag = gf_bs_read_int(bs, 1);
if (scaling_list_enable_flag) {
Bool sps_infer_scaling_list_flag = 0;
/*u8 sps_scaling_list_ref_layer_id = 0;*/
if (multiLayerExtSpsFlag) {
sps_infer_scaling_list_flag = gf_bs_read_int(bs, 1);
}
if (sps_infer_scaling_list_flag) {
/*sps_scaling_list_ref_layer_id = */gf_bs_read_int(bs, 6);
} else {
if (/*sps_scaling_list_data_present_flag=*/gf_bs_read_int(bs, 1) ) {
hevc_scaling_list_data(bs);
}
}
}
/*asymmetric_motion_partitions_enabled_flag= */ gf_bs_read_int(bs, 1);
sps->sample_adaptive_offset_enabled_flag = gf_bs_read_int(bs, 1);
if (/*pcm_enabled_flag= */ gf_bs_read_int(bs, 1) ) {
/*pcm_sample_bit_depth_luma_minus1=*/gf_bs_read_int(bs, 4);
/*pcm_sample_bit_depth_chroma_minus1=*/gf_bs_read_int(bs, 4);
/*log2_min_pcm_luma_coding_block_size_minus3= */ bs_get_ue(bs);
/*log2_diff_max_min_pcm_luma_coding_block_size = */ bs_get_ue(bs);
/*pcm_loop_filter_disable_flag=*/gf_bs_read_int(bs, 1);
}
sps->num_short_term_ref_pic_sets = bs_get_ue(bs);
if (sps->num_short_term_ref_pic_sets>64) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Invalid number of short term reference picture sets %d\n", sps->num_short_term_ref_pic_sets));
return -1;
}
for (i=0; i<sps->num_short_term_ref_pic_sets; i++) {
Bool ret = parse_short_term_ref_pic_set(bs, sps, i);
/*cannot parse short_term_ref_pic_set, skip VUI parsing*/
if (!ret) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] Invalid short_term_ref_pic_set\n"));
return -1;
}
}
sps->long_term_ref_pics_present_flag = gf_bs_read_int(bs, 1);
if (sps->long_term_ref_pics_present_flag) {
sps->num_long_term_ref_pic_sps = bs_get_ue(bs);
for (i=0; i<sps->num_long_term_ref_pic_sps; i++) {
/*lt_ref_pic_poc_lsb_sps=*/gf_bs_read_int(bs, sps->log2_max_pic_order_cnt_lsb);
/*used_by_curr_pic_lt_sps_flag*/gf_bs_read_int(bs, 1);
}
}
sps->temporal_mvp_enable_flag = gf_bs_read_int(bs, 1);
/*strong_intra_smoothing_enable_flag*/gf_bs_read_int(bs, 1);
if (vui_flag_pos)
*vui_flag_pos = (u32) gf_bs_get_bit_offset(bs);
if (/*vui_parameters_present_flag*/gf_bs_read_int(bs, 1)) {
sps->aspect_ratio_info_present_flag = gf_bs_read_int(bs, 1);
if (sps->aspect_ratio_info_present_flag) {
sps->sar_idc = gf_bs_read_int(bs, 8);
if (sps->sar_idc == 255) {
sps->sar_width = gf_bs_read_int(bs, 16);
sps->sar_height = gf_bs_read_int(bs, 16);
} else if (sps->sar_idc<17) {
sps->sar_width = hevc_sar[sps->sar_idc].w;
sps->sar_height = hevc_sar[sps->sar_idc].h;
}
}
if (/*overscan_info_present = */ gf_bs_read_int(bs, 1))
/*overscan_appropriate = */ gf_bs_read_int(bs, 1);
/*video_signal_type_present_flag = */flag = gf_bs_read_int(bs, 1);
if (flag) {
/*video_format = */gf_bs_read_int(bs, 3);
/*video_full_range_flag = */gf_bs_read_int(bs, 1);
if (/*colour_description_present_flag = */gf_bs_read_int(bs, 1)) {
/*colour_primaries = */ gf_bs_read_int(bs, 8);
/* transfer_characteristic = */ gf_bs_read_int(bs, 8);
/* matrix_coeffs = */ gf_bs_read_int(bs, 8);
}
}
if (/*chroma_loc_info_present_flag = */ gf_bs_read_int(bs, 1)) {
/*chroma_sample_loc_type_top_field = */ bs_get_ue(bs);
/*chroma_sample_loc_type_bottom_field = */bs_get_ue(bs);
}
/*neutra_chroma_indication_flag = */gf_bs_read_int(bs, 1);
/*field_seq_flag = */gf_bs_read_int(bs, 1);
/*frame_field_info_present_flag = */gf_bs_read_int(bs, 1);
if (/*default_display_window_flag=*/gf_bs_read_int(bs, 1)) {
/*left_offset = */bs_get_ue(bs);
/*right_offset = */bs_get_ue(bs);
/*top_offset = */bs_get_ue(bs);
/*bottom_offset = */bs_get_ue(bs);
}
sps->has_timing_info = gf_bs_read_int(bs, 1);
if (sps->has_timing_info ) {
sps->num_units_in_tick = gf_bs_read_int(bs, 32);
sps->time_scale = gf_bs_read_int(bs, 32);
sps->poc_proportional_to_timing_flag = gf_bs_read_int(bs, 1);
if (sps->poc_proportional_to_timing_flag)
sps->num_ticks_poc_diff_one_minus1 = bs_get_ue(bs);
if (/*hrd_parameters_present_flag=*/gf_bs_read_int(bs, 1) ) {
// GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[HEVC] HRD param parsing not implemented\n"));
return sps_id;
}
}
if (/*bitstream_restriction_flag=*/gf_bs_read_int(bs, 1)) {
/*tiles_fixed_structure_flag = */gf_bs_read_int(bs, 1);
/*motion_vectors_over_pic_boundaries_flag = */gf_bs_read_int(bs, 1);
/*restricted_ref_pic_lists_flag = */gf_bs_read_int(bs, 1);
/*min_spatial_segmentation_idc = */bs_get_ue(bs);
/*max_bytes_per_pic_denom = */bs_get_ue(bs);
/*max_bits_per_min_cu_denom = */bs_get_ue(bs);
/*log2_max_mv_length_horizontal = */bs_get_ue(bs);
/*log2_max_mv_length_vertical = */bs_get_ue(bs);
}
}
if (/*sps_extension_flag*/gf_bs_read_int(bs, 1)) {
while (gf_bs_available(bs)) {
/*sps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
}
return sps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_sps_ex(char *data, u32 size, HEVCState *hevc, u32 *vui_flag_pos)
{
GF_BitStream *bs;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
s32 sps_id= -1;
u8 layer_id;
if (vui_flag_pos) *vui_flag_pos = 0;
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, size);
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
} else {
/*still contains emulation bytes*/
data_without_emulation_bytes = gf_malloc(size*sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, size);
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, NULL, NULL, &layer_id)) goto exit;
sps_id = gf_media_hevc_read_sps_bs(bs, hevc, layer_id, vui_flag_pos);
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return sps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_sps(char *data, u32 size, HEVCState *hevc)
{
return gf_media_hevc_read_sps_ex(data, size, hevc, NULL);
}
static s32 gf_media_hevc_read_pps_bs(GF_BitStream *bs, HEVCState *hevc)
{
u32 i;
s32 pps_id = -1;
HEVC_PPS *pps;
//NAL header already read
pps_id = bs_get_ue(bs);
if ((pps_id<0) || (pps_id>=64)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong PPS ID %d in PPS\n", pps_id));
return -1;
}
pps = &hevc->pps[pps_id];
if (!pps->state) {
pps->id = pps_id;
pps->state = 1;
}
pps->sps_id = bs_get_ue(bs);
if (pps->sps_id>16) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[HEVC] wrong SPS ID %d in PPS\n", pps->sps_id));
return -1;
}
hevc->sps_active_idx = pps->sps_id; /*set active sps*/
pps->dependent_slice_segments_enabled_flag = gf_bs_read_int(bs, 1);
pps->output_flag_present_flag = gf_bs_read_int(bs, 1);
pps->num_extra_slice_header_bits = gf_bs_read_int(bs, 3);
/*sign_data_hiding_flag = */gf_bs_read_int(bs, 1);
pps->cabac_init_present_flag = gf_bs_read_int(bs, 1);
pps->num_ref_idx_l0_default_active = 1 + bs_get_ue(bs);
pps->num_ref_idx_l1_default_active = 1 + bs_get_ue(bs);
/*pic_init_qp_minus26 = */bs_get_se(bs);
/*constrained_intra_pred_flag = */gf_bs_read_int(bs, 1);
/*transform_skip_enabled_flag = */gf_bs_read_int(bs, 1);
if (/*cu_qp_delta_enabled_flag = */gf_bs_read_int(bs, 1) )
/*diff_cu_qp_delta_depth = */bs_get_ue(bs);
/*pic_cb_qp_offset = */bs_get_se(bs);
/*pic_cr_qp_offset = */bs_get_se(bs);
pps->slice_chroma_qp_offsets_present_flag = gf_bs_read_int(bs, 1);
pps->weighted_pred_flag = gf_bs_read_int(bs, 1);
pps->weighted_bipred_flag = gf_bs_read_int(bs, 1);
/*transquant_bypass_enable_flag = */gf_bs_read_int(bs, 1);
pps->tiles_enabled_flag = gf_bs_read_int(bs, 1);
pps->entropy_coding_sync_enabled_flag = gf_bs_read_int(bs, 1);
if (pps->tiles_enabled_flag) {
pps->num_tile_columns = 1 + bs_get_ue(bs);
pps->num_tile_rows = 1 + bs_get_ue(bs);
pps->uniform_spacing_flag = gf_bs_read_int(bs, 1);
if (!pps->uniform_spacing_flag ) {
for (i=0; i<pps->num_tile_columns-1; i++) {
pps->column_width[i] = 1 + bs_get_ue(bs);
}
for (i=0; i<pps->num_tile_rows-1; i++) {
pps->row_height[i] = 1+bs_get_ue(bs);
}
}
pps->loop_filter_across_tiles_enabled_flag = gf_bs_read_int(bs, 1);
}
pps->loop_filter_across_slices_enabled_flag = gf_bs_read_int(bs, 1);
if( /*deblocking_filter_control_present_flag = */gf_bs_read_int(bs, 1) ) {
pps->deblocking_filter_override_enabled_flag = gf_bs_read_int(bs, 1);
if (! /*pic_disable_deblocking_filter_flag= */gf_bs_read_int(bs, 1) ) {
/*beta_offset_div2 = */bs_get_se(bs);
/*tc_offset_div2 = */bs_get_se(bs);
}
}
if (/*pic_scaling_list_data_present_flag = */gf_bs_read_int(bs, 1) ) {
hevc_scaling_list_data(bs);
}
pps->lists_modification_present_flag = gf_bs_read_int(bs, 1);
/*log2_parallel_merge_level_minus2 = */bs_get_ue(bs);
pps->slice_segment_header_extension_present_flag = gf_bs_read_int(bs, 1);
if ( /*pps_extension_flag= */gf_bs_read_int(bs, 1) ) {
while (gf_bs_available(bs) ) {
/*pps_extension_data_flag */ gf_bs_read_int(bs, 1);
}
}
return pps_id;
}
GF_EXPORT
s32 gf_media_hevc_read_pps(char *data, u32 size, HEVCState *hevc)
{
GF_BitStream *bs;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
s32 pps_id = -1;
/*still contains emulation bytes*/
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, size);
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
} else {
data_without_emulation_bytes = gf_malloc(size*sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, size);
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, NULL, NULL, NULL)) goto exit;
pps_id = gf_media_hevc_read_pps_bs(bs, hevc);
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return pps_id;
}
GF_EXPORT
s32 gf_media_hevc_parse_nalu(char *data, u32 size, HEVCState *hevc, u8 *nal_unit_type, u8 *temporal_id, u8 *layer_id)
{
GF_BitStream *bs=NULL;
char *data_without_emulation_bytes = NULL;
u32 data_without_emulation_bytes_size = 0;
Bool is_slice = GF_FALSE;
s32 ret = -1;
HEVCSliceInfo n_state;
memcpy(&n_state, &hevc->s_info, sizeof(HEVCSliceInfo));
hevc->last_parsed_vps_id = hevc->last_parsed_sps_id = hevc->last_parsed_pps_id = -1;
hevc->s_info.entry_point_start_bits = -1;
hevc->s_info.payload_start_offset = -1;
data_without_emulation_bytes_size = avc_emulation_bytes_remove_count(data, size);
if (!data_without_emulation_bytes_size) {
bs = gf_bs_new(data, size, GF_BITSTREAM_READ);
} else {
/*still contains emulation bytes*/
data_without_emulation_bytes = gf_malloc(size*sizeof(char));
data_without_emulation_bytes_size = avc_remove_emulation_bytes(data, data_without_emulation_bytes, size);
bs = gf_bs_new(data_without_emulation_bytes, data_without_emulation_bytes_size, GF_BITSTREAM_READ);
}
if (!bs) goto exit;
if (! hevc_parse_nal_header(bs, nal_unit_type, temporal_id, layer_id)) goto exit;
n_state.nal_unit_type = *nal_unit_type;
switch (n_state.nal_unit_type) {
case GF_HEVC_NALU_ACCESS_UNIT:
case GF_HEVC_NALU_END_OF_SEQ:
case GF_HEVC_NALU_END_OF_STREAM:
ret = 1;
break;
/*slice_segment_layer_rbsp*/
case GF_HEVC_NALU_SLICE_TRAIL_N:
case GF_HEVC_NALU_SLICE_TRAIL_R:
case GF_HEVC_NALU_SLICE_TSA_N:
case GF_HEVC_NALU_SLICE_TSA_R:
case GF_HEVC_NALU_SLICE_STSA_N:
case GF_HEVC_NALU_SLICE_STSA_R:
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
case GF_HEVC_NALU_SLICE_RADL_N:
case GF_HEVC_NALU_SLICE_RADL_R:
case GF_HEVC_NALU_SLICE_RASL_N:
case GF_HEVC_NALU_SLICE_RASL_R:
is_slice = GF_TRUE;
/* slice - read the info and compare.*/
ret = hevc_parse_slice_segment(bs, hevc, &n_state);
if (ret<0) goto exit;
hevc_compute_poc(&n_state);
ret = 0;
if (hevc->s_info.poc != n_state.poc) {
ret=1;
break;
}
if (n_state.first_slice_segment_in_pic_flag) {
if (!(*layer_id) || (n_state.prev_layer_id_plus1 && ((*layer_id) <= n_state.prev_layer_id_plus1 - 1)) ) {
ret = 1;
break;
}
}
break;
case GF_HEVC_NALU_SEQ_PARAM:
hevc->last_parsed_sps_id = gf_media_hevc_read_sps_bs(bs, hevc, *layer_id, NULL);
ret = 0;
break;
case GF_HEVC_NALU_PIC_PARAM:
hevc->last_parsed_pps_id = gf_media_hevc_read_pps_bs(bs, hevc);
ret = 0;
break;
case GF_HEVC_NALU_VID_PARAM:
hevc->last_parsed_vps_id = gf_media_hevc_read_vps_bs(bs, hevc, GF_FALSE);
ret = 0;
break;
default:
ret = 0;
break;
}
/* save _prev values */
if (ret && hevc->s_info.sps) {
n_state.frame_num_offset_prev = hevc->s_info.frame_num_offset;
n_state.frame_num_prev = hevc->s_info.frame_num;
n_state.poc_lsb_prev = hevc->s_info.poc_lsb;
n_state.poc_msb_prev = hevc->s_info.poc_msb;
n_state.prev_layer_id_plus1 = *layer_id + 1;
}
if (is_slice) hevc_compute_poc(&n_state);
memcpy(&hevc->s_info, &n_state, sizeof(HEVCSliceInfo));
exit:
if (bs) gf_bs_del(bs);
if (data_without_emulation_bytes) gf_free(data_without_emulation_bytes);
return ret;
}
static u8 hevc_get_sar_idx(u32 w, u32 h)
{
u32 i;
for (i=0; i<14; i++) {
if ((avc_sar[i].w==w) && (avc_sar[i].h==h)) return i;
}
return 0xFF;
}
GF_Err gf_media_hevc_change_par(GF_HEVCConfig *hvcc, s32 ar_n, s32 ar_d)
{
GF_BitStream *orig, *mod;
HEVCState hevc;
u32 i, bit_offset, flag;
s32 idx;
GF_HEVCParamArray *spss;
GF_AVCConfigSlot *slc;
orig = NULL;
memset(&hevc, 0, sizeof(HEVCState));
hevc.sps_active_idx = -1;
i=0;
spss = NULL;
while ((spss = (GF_HEVCParamArray *)gf_list_enum(hvcc->param_array, &i))) {
if (spss->type==GF_HEVC_NALU_SEQ_PARAM)
break;
spss = NULL;
}
if (!spss) return GF_NON_COMPLIANT_BITSTREAM;
i=0;
while ((slc = (GF_AVCConfigSlot *)gf_list_enum(spss->nalus, &i))) {
char *no_emulation_buf = NULL;
u32 no_emulation_buf_size = 0, emulation_bytes = 0;
/*SPS may still contains emulation bytes*/
no_emulation_buf = gf_malloc((slc->size)*sizeof(char));
no_emulation_buf_size = avc_remove_emulation_bytes(slc->data, no_emulation_buf, slc->size);
idx = gf_media_hevc_read_sps_ex(no_emulation_buf, no_emulation_buf_size, &hevc, &bit_offset);
if (idx<0) {
if ( orig )
gf_bs_del(orig);
gf_free(no_emulation_buf);
continue;
}
orig = gf_bs_new(no_emulation_buf, no_emulation_buf_size, GF_BITSTREAM_READ);
mod = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
/*copy over till vui flag*/
assert(bit_offset >= 0);
while (bit_offset) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
bit_offset--;
}
/*check VUI*/
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, 1, 1); /*vui_parameters_present_flag*/
if (flag) {
/*aspect_ratio_info_present_flag*/
if (gf_bs_read_int(orig, 1)) {
s32 aspect_ratio_idc = gf_bs_read_int(orig, 8);
if (aspect_ratio_idc == 255) {
gf_bs_read_int(orig, 16); /*AR num*/
gf_bs_read_int(orig, 16); /*AR den*/
}
}
}
if ((ar_d<0) || (ar_n<0)) {
/*no AR signaled*/
gf_bs_write_int(mod, 0, 1);
} else {
u32 sarx;
gf_bs_write_int(mod, 1, 1);
sarx = hevc_get_sar_idx((u32) ar_n, (u32) ar_d);
gf_bs_write_int(mod, sarx, 8);
if (sarx==0xFF) {
gf_bs_write_int(mod, ar_n, 16);
gf_bs_write_int(mod, ar_d, 16);
}
}
/*no VUI in input bitstream, set all vui flags to 0*/
if (!flag) {
gf_bs_write_int(mod, 0, 1); /*overscan_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*video_signal_type_present_flag */
gf_bs_write_int(mod, 0, 1); /*chroma_location_info_present_flag */
gf_bs_write_int(mod, 0, 1); /*neutra_chroma_indication_flag */;
gf_bs_write_int(mod, 0, 1); /*field_seq_flag */;
gf_bs_write_int(mod, 0, 1); /*frame_field_info_present_flag*/;
gf_bs_write_int(mod, 0, 1); /*default_display_window_flag*/;
gf_bs_write_int(mod, 0, 1); /*timing_info_present_flag*/
gf_bs_write_int(mod, 0, 1); /*bitstream_restriction*/
}
/*finally copy over remaining*/
while (gf_bs_bits_available(orig)) {
flag = gf_bs_read_int(orig, 1);
gf_bs_write_int(mod, flag, 1);
}
gf_bs_del(orig);
orig = NULL;
gf_free(no_emulation_buf);
/*set anti-emulation*/
gf_bs_get_content(mod, (char **) &no_emulation_buf, &no_emulation_buf_size);
emulation_bytes = avc_emulation_bytes_add_count(no_emulation_buf, no_emulation_buf_size);
if (no_emulation_buf_size + emulation_bytes > slc->size)
slc->data = (char*)gf_realloc(slc->data, no_emulation_buf_size + emulation_bytes);
slc->size = avc_add_emulation_bytes(no_emulation_buf, slc->data, no_emulation_buf_size);
gf_bs_del(mod);
gf_free(no_emulation_buf);
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_hevc_get_sps_info_with_state(HEVCState *hevc, char *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
{
s32 idx;
idx = gf_media_hevc_read_sps(sps_data, sps_size, hevc);
if (idx<0) {
return GF_NON_COMPLIANT_BITSTREAM;
}
if (sps_id) *sps_id = idx;
if (width) *width = hevc->sps[idx].width;
if (height) *height = hevc->sps[idx].height;
if (par_n) *par_n = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_width : (u32) -1;
if (par_d) *par_d = hevc->sps[idx].aspect_ratio_info_present_flag ? hevc->sps[idx].sar_height : (u32) -1;
return GF_OK;
}
GF_EXPORT
GF_Err gf_hevc_get_sps_info(char *sps_data, u32 sps_size, u32 *sps_id, u32 *width, u32 *height, s32 *par_n, s32 *par_d)
{
HEVCState hevc;
memset(&hevc, 0, sizeof(HEVCState));
hevc.sps_active_idx = -1;
return gf_hevc_get_sps_info_with_state(&hevc, sps_data, sps_size, sps_id, width, height, par_n, par_d);
}
#endif //GPAC_DISABLE_HEVC
static u32 AC3_FindSyncCode(u8 *buf, u32 buflen)
{
u32 end = buflen - 6;
u32 offset = 0;
while (offset <= end) {
if (buf[offset] == 0x0b && buf[offset + 1] == 0x77) {
return offset;
}
offset++;
}
return buflen;
}
static Bool AC3_FindSyncCodeBS(GF_BitStream *bs)
{
u8 b1;
u64 pos = gf_bs_get_position(bs);
u64 end = gf_bs_get_size(bs) - 6;
pos += 1;
b1 = gf_bs_read_u8(bs);
while (pos <= end) {
u8 b2 = gf_bs_read_u8(bs);
if ((b1 == 0x0b) && (b2==0x77)) {
gf_bs_seek(bs, pos-1);
return GF_TRUE;
}
pos++;
b1 = b2;
}
return GF_FALSE;
}
static const u32 ac3_sizecod_to_bitrate[] = {
32000, 40000, 48000, 56000, 64000, 80000, 96000,
112000, 128000, 160000, 192000, 224000, 256000,
320000, 384000, 448000, 512000, 576000, 640000
};
static const u32 ac3_sizecod2_to_framesize[] = {
96, 120, 144, 168, 192, 240, 288, 336, 384, 480, 576, 672,
768, 960, 1152, 1344, 1536, 1728, 1920
};
static const u32 ac3_sizecod1_to_framesize[] = {
69, 87, 104, 121, 139, 174, 208, 243, 278, 348, 417, 487,
557, 696, 835, 975, 1114, 1253, 1393
};
static const u32 ac3_sizecod0_to_framesize[] = {
64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448,
512, 640, 768, 896, 1024, 1152, 1280
};
static const u32 ac3_mod_to_chans[] = {
2, 1, 2, 3, 3, 4, 4, 5
};
GF_EXPORT
u32 gf_ac3_get_channels(u32 acmod)
{
u32 nb_ch;
nb_ch = ac3_mod_to_chans[acmod];
return nb_ch;
}
GF_EXPORT
u32 gf_ac3_get_bitrate(u32 brcode)
{
return ac3_sizecod_to_bitrate[brcode];
}
Bool gf_ac3_parser(u8 *buf, u32 buflen, u32 *pos, GF_AC3Header *hdr, Bool full_parse)
{
GF_BitStream *bs;
Bool ret;
if (buflen < 6) return GF_FALSE;
(*pos) = AC3_FindSyncCode(buf, buflen);
if (*pos >= buflen) return GF_FALSE;
bs = gf_bs_new((const char*)(buf+*pos), buflen, GF_BITSTREAM_READ);
ret = gf_ac3_parser_bs(bs, hdr, full_parse);
gf_bs_del(bs);
return ret;
}
GF_EXPORT
Bool gf_ac3_parser_bs(GF_BitStream *bs, GF_AC3Header *hdr, Bool full_parse)
{
u32 fscod, frmsizecod, bsid, ac3_mod, freq, framesize, bsmod, syncword;
u64 pos;
if (!hdr || (gf_bs_available(bs) < 6)) return GF_FALSE;
if (!AC3_FindSyncCodeBS(bs)) return GF_FALSE;
pos = gf_bs_get_position(bs);
syncword = gf_bs_read_u16(bs);
if (syncword != 0x0B77) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\n", syncword));
return GF_FALSE;
}
gf_bs_read_u16(bs); //crc1
fscod = gf_bs_read_int(bs, 2);
frmsizecod = gf_bs_read_int(bs, 6);
bsid = gf_bs_read_int(bs, 5);
bsmod = gf_bs_read_int(bs, 3);
ac3_mod = gf_bs_read_int(bs, 3);
hdr->bitrate = ac3_sizecod_to_bitrate[frmsizecod / 2];
if (bsid > 8) hdr->bitrate = hdr->bitrate >> (bsid - 8);
switch (fscod) {
case 0:
freq = 48000;
framesize = ac3_sizecod0_to_framesize[frmsizecod / 2] * 2;
break;
case 1:
freq = 44100;
framesize = (ac3_sizecod1_to_framesize[frmsizecod / 2] + (frmsizecod & 0x1)) * 2;
break;
case 2:
freq = 32000;
framesize = ac3_sizecod2_to_framesize[frmsizecod / 2] * 2;
break;
default:
return GF_FALSE;
}
hdr->sample_rate = freq;
hdr->framesize = framesize;
if (full_parse) {
hdr->bsid = bsid;
hdr->bsmod = bsmod;
hdr->acmod = ac3_mod;
hdr->lfon = 0;
hdr->fscod = fscod;
hdr->brcode = frmsizecod / 2;
}
hdr->channels = ac3_mod_to_chans[ac3_mod];
if ((ac3_mod & 0x1) && (ac3_mod != 1)) gf_bs_read_int(bs, 2);
if (ac3_mod & 0x4) gf_bs_read_int(bs, 2);
if (ac3_mod == 0x2) gf_bs_read_int(bs, 2);
/*LFEon*/
if (gf_bs_read_int(bs, 1)) {
hdr->channels += 1;
hdr->lfon = 1;
}
gf_bs_seek(bs, pos);
return GF_TRUE;
}
GF_EXPORT
Bool gf_eac3_parser_bs(GF_BitStream *bs, GF_AC3Header *hdr, Bool full_parse)
{
u32 fscod, bsid, ac3_mod, freq, framesize, syncword, substreamid, lfon, channels, numblkscod;
u64 pos;
restart:
if (!hdr || (gf_bs_available(bs) < 6))
return GF_FALSE;
if (!AC3_FindSyncCodeBS(bs))
return GF_FALSE;
pos = gf_bs_get_position(bs);
framesize = 0;
numblkscod = 0;
block:
syncword = gf_bs_read_u16(bs);
if (syncword != 0x0B77) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[E-AC3] Wrong sync word detected (0x%X - expecting 0x0B77).\n", syncword));
return GF_FALSE;
}
gf_bs_read_int(bs, 2); //strmtyp
substreamid = gf_bs_read_int(bs, 3);
framesize += gf_bs_read_int(bs, 11);
fscod = gf_bs_read_int(bs, 2);
if (fscod == 0x3) {
fscod = gf_bs_read_int(bs, 2);
numblkscod += 6;
} else {
numblkscod += gf_bs_read_int(bs, 2);
}
assert(numblkscod <= 9);
if ((hdr->substreams >> substreamid) & 0x1) {
if (!substreamid) {
hdr->framesize = framesize;
if (numblkscod < 6) { //we need 6 blocks to make a sample
gf_bs_seek(bs, pos+2*framesize);
if ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))
return GF_FALSE;
goto block;
}
gf_bs_seek(bs, pos);
return GF_TRUE;
} else {
GF_LOG(GF_LOG_INFO, GF_LOG_CODING, ("[E-AC3] Detected sample in substream id=%u. Skipping.\n", substreamid));
gf_bs_seek(bs, pos+framesize);
goto restart;
}
}
hdr->substreams |= (1 << substreamid);
switch (fscod) {
case 0:
freq = 48000;
break;
case 1:
freq = 44100;
break;
case 2:
freq = 32000;
break;
default:
return GF_FALSE;
}
ac3_mod = gf_bs_read_int(bs, 3);
lfon = gf_bs_read_int(bs, 1);
bsid = gf_bs_read_int(bs, 5);
if (!substreamid && (bsid!=16/*E-AC3*/))
return GF_FALSE;
channels = ac3_mod_to_chans[ac3_mod];
if (lfon)
channels += 1;
if (substreamid) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("[E-AC3] Detected additional %u channels in substream id=%u - may not be handled correctly. Skipping.\n", channels, substreamid));
gf_bs_seek(bs, pos+framesize);
goto restart;
} else {
hdr->bitrate = 0;
hdr->sample_rate = freq;
hdr->framesize = framesize;
hdr->lfon = lfon;
hdr->channels = channels;
if (full_parse) {
hdr->bsid = bsid;
hdr->bsmod = 0;
hdr->acmod = ac3_mod;
hdr->fscod = fscod;
hdr->brcode = 0;
}
}
if (numblkscod < 6) { //we need 6 blocks to make a sample
gf_bs_seek(bs, pos+2*framesize);
if ((gf_bs_available(bs) < 6) || !AC3_FindSyncCodeBS(bs))
return GF_FALSE;
goto block;
}
gf_bs_seek(bs, pos);
return GF_TRUE;
}
#endif /*GPAC_DISABLE_AV_PARSERS*/
#if !defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)
/*
Vorbis parser
*/
static u32 vorbis_book_maptype1_quantvals(u32 entries, u32 dim)
{
u32 vals = (u32) floor(pow(entries, 1.0/dim));
while(1) {
u32 acc=1;
u32 acc1=1;
u32 i;
for (i=0; i<dim; i++) {
acc*=vals;
acc1*=vals+1;
}
if(acc<=entries && acc1>entries) return (vals);
else {
if (acc>entries) vals--;
else vals++;
}
}
}
u32 _ilog_(u32 v)
{
u32 ret=0;
while(v) {
ret++;
v>>=1;
}
return(ret);
}
static u32 ilog(u32 v)
{
u32 ret=0;
if(v) --v;
while(v) {
ret++;
v>>=1;
}
return (ret);
}
static u32 icount(u32 v)
{
u32 ret=0;
while(v) {
ret += v&1;
v>>=1;
}
return(ret);
}
GF_EXPORT
Bool gf_vorbis_parse_header(GF_VorbisParser *vp, char *data, u32 data_len)
{
u32 pack_type, i, j, k, times, nb_part, nb_books, nb_modes;
char szNAME[8];
oggpack_buffer opb;
oggpack_readinit(&opb, (u8*)data, data_len);
pack_type = oggpack_read(&opb, 8);
i=0;
while (i<6) {
szNAME[i] = oggpack_read(&opb, 8);
i++;
}
szNAME[i] = 0;
if (strcmp(szNAME, "vorbis")) return vp->is_init = 0;
switch (pack_type) {
case 0x01:
vp->version = oggpack_read(&opb, 32);
if (vp->version!=0) return 0;
vp->channels = oggpack_read(&opb, 8);
vp->sample_rate = oggpack_read(&opb, 32);
vp->max_r = oggpack_read(&opb, 32);
vp->avg_r = oggpack_read(&opb, 32);
vp->low_r = oggpack_read(&opb, 32);
vp->min_block = 1<<oggpack_read(&opb, 4);
vp->max_block = 1<<oggpack_read(&opb, 4);
if (vp->sample_rate < 1) return vp->is_init = 0;
if (vp->channels < 1) return vp->is_init = 0;
if (vp->min_block<8) return vp->is_init = 0;
if (vp->max_block < vp->min_block) return vp->is_init = 0;
if (oggpack_read(&opb, 1) != 1) return vp->is_init = 0;
vp->is_init = 1;
return 1;
case 0x03:
/*trash comments*/
vp->is_init ++;
return 1;
case 0x05:
/*need at least bitstream header to make sure we're parsing the right thing*/
if (!vp->is_init) return 0;
break;
default:
vp->is_init = 0;
return 0;
}
/*OK parse codebook*/
nb_books = oggpack_read(&opb, 8) + 1;
/*skip vorbis static books*/
for (i=0; i<nb_books; i++) {
u32 j, map_type, qb, qq;
u32 entries, dim;
oggpack_read(&opb, 24);
dim = oggpack_read(&opb, 16);
entries = oggpack_read(&opb, 24);
if ( (s32) entries < 0) entries = 0;
if (oggpack_read(&opb, 1) == 0) {
if (oggpack_read(&opb, 1)) {
for (j=0; j<entries; j++) {
if (oggpack_read(&opb, 1)) {
oggpack_read(&opb, 5);
}
}
} else {
for (j=0; j<entries; j++)
oggpack_read(&opb, 5);
}
} else {
oggpack_read(&opb, 5);
for (j=0; j<entries;) {
u32 num = oggpack_read(&opb, _ilog_(entries-j));
for (k=0; k<num && j<entries; k++, j++) {
}
}
}
switch ((map_type=oggpack_read(&opb, 4))) {
case 0:
break;
case 1:
case 2:
oggpack_read(&opb, 32);
oggpack_read(&opb, 32);
qq = oggpack_read(&opb, 4)+1;
oggpack_read(&opb, 1);
if (map_type==1) qb = vorbis_book_maptype1_quantvals(entries, dim);
else if (map_type==2) qb = entries * dim;
else qb = 0;
for (j=0; j<qb; j++) oggpack_read(&opb, qq);
break;
}
}
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) oggpack_read(&opb, 16);
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) {
u32 type = oggpack_read(&opb, 16);
if (type) {
u32 *parts, *class_dims, count, rangebits;
u32 max_class = 0;
nb_part = oggpack_read(&opb, 5);
parts = (u32*)gf_malloc(sizeof(u32) * nb_part);
for (j=0; j<nb_part; j++) {
parts[j] = oggpack_read(&opb, 4);
if (max_class<parts[j]) max_class = parts[j];
}
class_dims = (u32*)gf_malloc(sizeof(u32) * (max_class+1));
for (j=0; j<max_class+1; j++) {
u32 class_sub;
class_dims[j] = oggpack_read(&opb, 3) + 1;
class_sub = oggpack_read(&opb, 2);
if (class_sub) oggpack_read(&opb, 8);
for (k=0; k < (u32) (1<<class_sub); k++) oggpack_read(&opb, 8);
}
oggpack_read(&opb, 2);
rangebits=oggpack_read(&opb, 4);
count = 0;
for (j=0,k=0; j<nb_part; j++) {
count+=class_dims[parts[j]];
for (; k<count; k++) oggpack_read(&opb, rangebits);
}
gf_free(parts);
gf_free(class_dims);
} else {
u32 j, nb_books;
oggpack_read(&opb, 8+16+16+6+8);
nb_books = oggpack_read(&opb, 4)+1;
for (j=0; j<nb_books; j++) oggpack_read(&opb, 8);
}
}
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) {
u32 acc = 0;
oggpack_read(&opb, 16);/*type*/
oggpack_read(&opb, 24);
oggpack_read(&opb,24);
oggpack_read(&opb,24);
nb_part = oggpack_read(&opb, 6)+1;
oggpack_read(&opb, 8);
for (j=0; j<nb_part; j++) {
u32 cascade = oggpack_read(&opb, 3);
if (oggpack_read(&opb, 1)) cascade |= (oggpack_read(&opb, 5)<<3);
acc += icount(cascade);
}
for (j=0; j<acc; j++) oggpack_read(&opb, 8);
}
times = oggpack_read(&opb, 6)+1;
for (i=0; i<times; i++) {
u32 sub_maps = 1;
oggpack_read(&opb, 16);
if (oggpack_read(&opb, 1)) sub_maps = oggpack_read(&opb, 4)+1;
if (oggpack_read(&opb, 1)) {
u32 nb_steps = oggpack_read(&opb, 8)+1;
for (j=0; j<nb_steps; j++) {
oggpack_read(&opb, ilog(vp->channels));
oggpack_read(&opb, ilog(vp->channels));
}
}
oggpack_read(&opb, 2);
if (sub_maps>1) {
for(j=0; j<vp->channels; j++) oggpack_read(&opb, 4);
}
for (j=0; j<sub_maps; j++) {
oggpack_read(&opb, 8);
oggpack_read(&opb, 8);
oggpack_read(&opb, 8);
}
}
nb_modes = oggpack_read(&opb, 6)+1;
for (i=0; i<nb_modes; i++) {
vp->mode_flag[i] = oggpack_read(&opb, 1);
oggpack_read(&opb, 16);
oggpack_read(&opb, 16);
oggpack_read(&opb, 8);
}
vp->modebits = 0;
j = nb_modes;
while(j>1) {
vp->modebits++;
j>>=1;
}
return 1;
}
GF_EXPORT
u32 gf_vorbis_check_frame(GF_VorbisParser *vp, char *data, u32 data_length)
{
s32 block_size;
oggpack_buffer opb;
if (!vp->is_init) return 0;
oggpack_readinit(&opb, (unsigned char*)data, data_length);
/*not audio*/
if (oggpack_read(&opb, 1) !=0) return 0;
block_size = oggpack_read(&opb, vp->modebits);
if (block_size == -1) return 0;
return ((vp->mode_flag[block_size]) ? vp->max_block : vp->min_block) / (2);
}
#endif /*!defined(GPAC_DISABLE_AV_PARSERS) && !defined (GPAC_DISABLE_OGG)*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_651_2 |
crossvul-cpp_data_good_2133_0 | /***************************************************************************
* Copyright (C) 2010-2012 by Bruno Prémont <bonbons@linux-vserver.org> *
* *
* Based on Logitech G13 driver (v0.4) *
* Copyright (C) 2009 by Rick L. Vinyard, Jr. <rvinyard@cs.nmsu.edu> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, version 2 of the License. *
* *
* This driver 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 see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include <linux/hid.h>
#include <linux/hid-debug.h>
#include <linux/input.h>
#include "hid-ids.h"
#include <linux/fb.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include "hid-picolcd.h"
/* Input device
*
* The PicoLCD has an IR receiver header, a built-in keypad with 5 keys
* and header for 4x4 key matrix. The built-in keys are part of the matrix.
*/
static const unsigned short def_keymap[PICOLCD_KEYS] = {
KEY_RESERVED, /* none */
KEY_BACK, /* col 4 + row 1 */
KEY_HOMEPAGE, /* col 3 + row 1 */
KEY_RESERVED, /* col 2 + row 1 */
KEY_RESERVED, /* col 1 + row 1 */
KEY_SCROLLUP, /* col 4 + row 2 */
KEY_OK, /* col 3 + row 2 */
KEY_SCROLLDOWN, /* col 2 + row 2 */
KEY_RESERVED, /* col 1 + row 2 */
KEY_RESERVED, /* col 4 + row 3 */
KEY_RESERVED, /* col 3 + row 3 */
KEY_RESERVED, /* col 2 + row 3 */
KEY_RESERVED, /* col 1 + row 3 */
KEY_RESERVED, /* col 4 + row 4 */
KEY_RESERVED, /* col 3 + row 4 */
KEY_RESERVED, /* col 2 + row 4 */
KEY_RESERVED, /* col 1 + row 4 */
};
/* Find a given report */
struct hid_report *picolcd_report(int id, struct hid_device *hdev, int dir)
{
struct list_head *feature_report_list = &hdev->report_enum[dir].report_list;
struct hid_report *report = NULL;
list_for_each_entry(report, feature_report_list, list) {
if (report->id == id)
return report;
}
hid_warn(hdev, "No report with id 0x%x found\n", id);
return NULL;
}
/* Submit a report and wait for a reply from device - if device fades away
* or does not respond in time, return NULL */
struct picolcd_pending *picolcd_send_and_wait(struct hid_device *hdev,
int report_id, const u8 *raw_data, int size)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
struct picolcd_pending *work;
struct hid_report *report = picolcd_out_report(report_id, hdev);
unsigned long flags;
int i, j, k;
if (!report || !data)
return NULL;
if (data->status & PICOLCD_FAILED)
return NULL;
work = kzalloc(sizeof(*work), GFP_KERNEL);
if (!work)
return NULL;
init_completion(&work->ready);
work->out_report = report;
work->in_report = NULL;
work->raw_size = 0;
mutex_lock(&data->mutex);
spin_lock_irqsave(&data->lock, flags);
for (i = k = 0; i < report->maxfield; i++)
for (j = 0; j < report->field[i]->report_count; j++) {
hid_set_field(report->field[i], j, k < size ? raw_data[k] : 0);
k++;
}
if (data->status & PICOLCD_FAILED) {
kfree(work);
work = NULL;
} else {
data->pending = work;
hid_hw_request(data->hdev, report, HID_REQ_SET_REPORT);
spin_unlock_irqrestore(&data->lock, flags);
wait_for_completion_interruptible_timeout(&work->ready, HZ*2);
spin_lock_irqsave(&data->lock, flags);
data->pending = NULL;
}
spin_unlock_irqrestore(&data->lock, flags);
mutex_unlock(&data->mutex);
return work;
}
/*
* input class device
*/
static int picolcd_raw_keypad(struct picolcd_data *data,
struct hid_report *report, u8 *raw_data, int size)
{
/*
* Keypad event
* First and second data bytes list currently pressed keys,
* 0x00 means no key and at most 2 keys may be pressed at same time
*/
int i, j;
/* determine newly pressed keys */
for (i = 0; i < size; i++) {
unsigned int key_code;
if (raw_data[i] == 0)
continue;
for (j = 0; j < sizeof(data->pressed_keys); j++)
if (data->pressed_keys[j] == raw_data[i])
goto key_already_down;
for (j = 0; j < sizeof(data->pressed_keys); j++)
if (data->pressed_keys[j] == 0) {
data->pressed_keys[j] = raw_data[i];
break;
}
input_event(data->input_keys, EV_MSC, MSC_SCAN, raw_data[i]);
if (raw_data[i] < PICOLCD_KEYS)
key_code = data->keycode[raw_data[i]];
else
key_code = KEY_UNKNOWN;
if (key_code != KEY_UNKNOWN) {
dbg_hid(PICOLCD_NAME " got key press for %u:%d",
raw_data[i], key_code);
input_report_key(data->input_keys, key_code, 1);
}
input_sync(data->input_keys);
key_already_down:
continue;
}
/* determine newly released keys */
for (j = 0; j < sizeof(data->pressed_keys); j++) {
unsigned int key_code;
if (data->pressed_keys[j] == 0)
continue;
for (i = 0; i < size; i++)
if (data->pressed_keys[j] == raw_data[i])
goto key_still_down;
input_event(data->input_keys, EV_MSC, MSC_SCAN, data->pressed_keys[j]);
if (data->pressed_keys[j] < PICOLCD_KEYS)
key_code = data->keycode[data->pressed_keys[j]];
else
key_code = KEY_UNKNOWN;
if (key_code != KEY_UNKNOWN) {
dbg_hid(PICOLCD_NAME " got key release for %u:%d",
data->pressed_keys[j], key_code);
input_report_key(data->input_keys, key_code, 0);
}
input_sync(data->input_keys);
data->pressed_keys[j] = 0;
key_still_down:
continue;
}
return 1;
}
static int picolcd_check_version(struct hid_device *hdev)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
struct picolcd_pending *verinfo;
int ret = 0;
if (!data)
return -ENODEV;
verinfo = picolcd_send_and_wait(hdev, REPORT_VERSION, NULL, 0);
if (!verinfo) {
hid_err(hdev, "no version response from PicoLCD\n");
return -ENODEV;
}
if (verinfo->raw_size == 2) {
data->version[0] = verinfo->raw_data[1];
data->version[1] = verinfo->raw_data[0];
if (data->status & PICOLCD_BOOTLOADER) {
hid_info(hdev, "PicoLCD, bootloader version %d.%d\n",
verinfo->raw_data[1], verinfo->raw_data[0]);
} else {
hid_info(hdev, "PicoLCD, firmware version %d.%d\n",
verinfo->raw_data[1], verinfo->raw_data[0]);
}
} else {
hid_err(hdev, "confused, got unexpected version response from PicoLCD\n");
ret = -EINVAL;
}
kfree(verinfo);
return ret;
}
/*
* Reset our device and wait for answer to VERSION request
*/
int picolcd_reset(struct hid_device *hdev)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
struct hid_report *report = picolcd_out_report(REPORT_RESET, hdev);
unsigned long flags;
int error;
if (!data || !report || report->maxfield != 1)
return -ENODEV;
spin_lock_irqsave(&data->lock, flags);
if (hdev->product == USB_DEVICE_ID_PICOLCD_BOOTLOADER)
data->status |= PICOLCD_BOOTLOADER;
/* perform the reset */
hid_set_field(report->field[0], 0, 1);
if (data->status & PICOLCD_FAILED) {
spin_unlock_irqrestore(&data->lock, flags);
return -ENODEV;
}
hid_hw_request(hdev, report, HID_REQ_SET_REPORT);
spin_unlock_irqrestore(&data->lock, flags);
error = picolcd_check_version(hdev);
if (error)
return error;
picolcd_resume_lcd(data);
picolcd_resume_backlight(data);
picolcd_fb_refresh(data);
picolcd_leds_set(data);
return 0;
}
/*
* The "operation_mode" sysfs attribute
*/
static ssize_t picolcd_operation_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct picolcd_data *data = dev_get_drvdata(dev);
if (data->status & PICOLCD_BOOTLOADER)
return snprintf(buf, PAGE_SIZE, "[bootloader] lcd\n");
else
return snprintf(buf, PAGE_SIZE, "bootloader [lcd]\n");
}
static ssize_t picolcd_operation_mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct picolcd_data *data = dev_get_drvdata(dev);
struct hid_report *report = NULL;
size_t cnt = count;
int timeout = data->opmode_delay;
unsigned long flags;
if (cnt >= 3 && strncmp("lcd", buf, 3) == 0) {
if (data->status & PICOLCD_BOOTLOADER)
report = picolcd_out_report(REPORT_EXIT_FLASHER, data->hdev);
buf += 3;
cnt -= 3;
} else if (cnt >= 10 && strncmp("bootloader", buf, 10) == 0) {
if (!(data->status & PICOLCD_BOOTLOADER))
report = picolcd_out_report(REPORT_EXIT_KEYBOARD, data->hdev);
buf += 10;
cnt -= 10;
}
if (!report || report->maxfield != 1)
return -EINVAL;
while (cnt > 0 && (buf[cnt-1] == '\n' || buf[cnt-1] == '\r'))
cnt--;
if (cnt != 0)
return -EINVAL;
spin_lock_irqsave(&data->lock, flags);
hid_set_field(report->field[0], 0, timeout & 0xff);
hid_set_field(report->field[0], 1, (timeout >> 8) & 0xff);
hid_hw_request(data->hdev, report, HID_REQ_SET_REPORT);
spin_unlock_irqrestore(&data->lock, flags);
return count;
}
static DEVICE_ATTR(operation_mode, 0644, picolcd_operation_mode_show,
picolcd_operation_mode_store);
/*
* The "operation_mode_delay" sysfs attribute
*/
static ssize_t picolcd_operation_mode_delay_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct picolcd_data *data = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%hu\n", data->opmode_delay);
}
static ssize_t picolcd_operation_mode_delay_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct picolcd_data *data = dev_get_drvdata(dev);
unsigned u;
if (sscanf(buf, "%u", &u) != 1)
return -EINVAL;
if (u > 30000)
return -EINVAL;
else
data->opmode_delay = u;
return count;
}
static DEVICE_ATTR(operation_mode_delay, 0644, picolcd_operation_mode_delay_show,
picolcd_operation_mode_delay_store);
/*
* Handle raw report as sent by device
*/
static int picolcd_raw_event(struct hid_device *hdev,
struct hid_report *report, u8 *raw_data, int size)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
unsigned long flags;
int ret = 0;
if (!data)
return 1;
if (size > 64) {
hid_warn(hdev, "invalid size value (%d) for picolcd raw event\n",
size);
return 0;
}
if (report->id == REPORT_KEY_STATE) {
if (data->input_keys)
ret = picolcd_raw_keypad(data, report, raw_data+1, size-1);
} else if (report->id == REPORT_IR_DATA) {
ret = picolcd_raw_cir(data, report, raw_data+1, size-1);
} else {
spin_lock_irqsave(&data->lock, flags);
/*
* We let the caller of picolcd_send_and_wait() check if the
* report we got is one of the expected ones or not.
*/
if (data->pending) {
memcpy(data->pending->raw_data, raw_data+1, size-1);
data->pending->raw_size = size-1;
data->pending->in_report = report;
complete(&data->pending->ready);
}
spin_unlock_irqrestore(&data->lock, flags);
}
picolcd_debug_raw_event(data, hdev, report, raw_data, size);
return 1;
}
#ifdef CONFIG_PM
static int picolcd_suspend(struct hid_device *hdev, pm_message_t message)
{
if (PMSG_IS_AUTO(message))
return 0;
picolcd_suspend_backlight(hid_get_drvdata(hdev));
dbg_hid(PICOLCD_NAME " device ready for suspend\n");
return 0;
}
static int picolcd_resume(struct hid_device *hdev)
{
int ret;
ret = picolcd_resume_backlight(hid_get_drvdata(hdev));
if (ret)
dbg_hid(PICOLCD_NAME " restoring backlight failed: %d\n", ret);
return 0;
}
static int picolcd_reset_resume(struct hid_device *hdev)
{
int ret;
ret = picolcd_reset(hdev);
if (ret)
dbg_hid(PICOLCD_NAME " resetting our device failed: %d\n", ret);
ret = picolcd_fb_reset(hid_get_drvdata(hdev), 0);
if (ret)
dbg_hid(PICOLCD_NAME " restoring framebuffer content failed: %d\n", ret);
ret = picolcd_resume_lcd(hid_get_drvdata(hdev));
if (ret)
dbg_hid(PICOLCD_NAME " restoring lcd failed: %d\n", ret);
ret = picolcd_resume_backlight(hid_get_drvdata(hdev));
if (ret)
dbg_hid(PICOLCD_NAME " restoring backlight failed: %d\n", ret);
picolcd_leds_set(hid_get_drvdata(hdev));
return 0;
}
#endif
/* initialize keypad input device */
static int picolcd_init_keys(struct picolcd_data *data,
struct hid_report *report)
{
struct hid_device *hdev = data->hdev;
struct input_dev *idev;
int error, i;
if (!report)
return -ENODEV;
if (report->maxfield != 1 || report->field[0]->report_count != 2 ||
report->field[0]->report_size != 8) {
hid_err(hdev, "unsupported KEY_STATE report\n");
return -EINVAL;
}
idev = input_allocate_device();
if (idev == NULL) {
hid_err(hdev, "failed to allocate input device\n");
return -ENOMEM;
}
input_set_drvdata(idev, hdev);
memcpy(data->keycode, def_keymap, sizeof(def_keymap));
idev->name = hdev->name;
idev->phys = hdev->phys;
idev->uniq = hdev->uniq;
idev->id.bustype = hdev->bus;
idev->id.vendor = hdev->vendor;
idev->id.product = hdev->product;
idev->id.version = hdev->version;
idev->dev.parent = &hdev->dev;
idev->keycode = &data->keycode;
idev->keycodemax = PICOLCD_KEYS;
idev->keycodesize = sizeof(data->keycode[0]);
input_set_capability(idev, EV_MSC, MSC_SCAN);
set_bit(EV_REP, idev->evbit);
for (i = 0; i < PICOLCD_KEYS; i++)
input_set_capability(idev, EV_KEY, data->keycode[i]);
error = input_register_device(idev);
if (error) {
hid_err(hdev, "error registering the input device\n");
input_free_device(idev);
return error;
}
data->input_keys = idev;
return 0;
}
static void picolcd_exit_keys(struct picolcd_data *data)
{
struct input_dev *idev = data->input_keys;
data->input_keys = NULL;
if (idev)
input_unregister_device(idev);
}
static int picolcd_probe_lcd(struct hid_device *hdev, struct picolcd_data *data)
{
int error;
/* Setup keypad input device */
error = picolcd_init_keys(data, picolcd_in_report(REPORT_KEY_STATE, hdev));
if (error)
goto err;
/* Setup CIR input device */
error = picolcd_init_cir(data, picolcd_in_report(REPORT_IR_DATA, hdev));
if (error)
goto err;
/* Set up the framebuffer device */
error = picolcd_init_framebuffer(data);
if (error)
goto err;
/* Setup lcd class device */
error = picolcd_init_lcd(data, picolcd_out_report(REPORT_CONTRAST, hdev));
if (error)
goto err;
/* Setup backlight class device */
error = picolcd_init_backlight(data, picolcd_out_report(REPORT_BRIGHTNESS, hdev));
if (error)
goto err;
/* Setup the LED class devices */
error = picolcd_init_leds(data, picolcd_out_report(REPORT_LED_STATE, hdev));
if (error)
goto err;
picolcd_init_devfs(data, picolcd_out_report(REPORT_EE_READ, hdev),
picolcd_out_report(REPORT_EE_WRITE, hdev),
picolcd_out_report(REPORT_READ_MEMORY, hdev),
picolcd_out_report(REPORT_WRITE_MEMORY, hdev),
picolcd_out_report(REPORT_RESET, hdev));
return 0;
err:
picolcd_exit_leds(data);
picolcd_exit_backlight(data);
picolcd_exit_lcd(data);
picolcd_exit_framebuffer(data);
picolcd_exit_cir(data);
picolcd_exit_keys(data);
return error;
}
static int picolcd_probe_bootloader(struct hid_device *hdev, struct picolcd_data *data)
{
picolcd_init_devfs(data, NULL, NULL,
picolcd_out_report(REPORT_BL_READ_MEMORY, hdev),
picolcd_out_report(REPORT_BL_WRITE_MEMORY, hdev), NULL);
return 0;
}
static int picolcd_probe(struct hid_device *hdev,
const struct hid_device_id *id)
{
struct picolcd_data *data;
int error = -ENOMEM;
dbg_hid(PICOLCD_NAME " hardware probe...\n");
/*
* Let's allocate the picolcd data structure, set some reasonable
* defaults, and associate it with the device
*/
data = kzalloc(sizeof(struct picolcd_data), GFP_KERNEL);
if (data == NULL) {
hid_err(hdev, "can't allocate space for Minibox PicoLCD device data\n");
error = -ENOMEM;
goto err_no_cleanup;
}
spin_lock_init(&data->lock);
mutex_init(&data->mutex);
data->hdev = hdev;
data->opmode_delay = 5000;
if (hdev->product == USB_DEVICE_ID_PICOLCD_BOOTLOADER)
data->status |= PICOLCD_BOOTLOADER;
hid_set_drvdata(hdev, data);
/* Parse the device reports and start it up */
error = hid_parse(hdev);
if (error) {
hid_err(hdev, "device report parse failed\n");
goto err_cleanup_data;
}
error = hid_hw_start(hdev, 0);
if (error) {
hid_err(hdev, "hardware start failed\n");
goto err_cleanup_data;
}
error = hid_hw_open(hdev);
if (error) {
hid_err(hdev, "failed to open input interrupt pipe for key and IR events\n");
goto err_cleanup_hid_hw;
}
error = device_create_file(&hdev->dev, &dev_attr_operation_mode_delay);
if (error) {
hid_err(hdev, "failed to create sysfs attributes\n");
goto err_cleanup_hid_ll;
}
error = device_create_file(&hdev->dev, &dev_attr_operation_mode);
if (error) {
hid_err(hdev, "failed to create sysfs attributes\n");
goto err_cleanup_sysfs1;
}
if (data->status & PICOLCD_BOOTLOADER)
error = picolcd_probe_bootloader(hdev, data);
else
error = picolcd_probe_lcd(hdev, data);
if (error)
goto err_cleanup_sysfs2;
dbg_hid(PICOLCD_NAME " activated and initialized\n");
return 0;
err_cleanup_sysfs2:
device_remove_file(&hdev->dev, &dev_attr_operation_mode);
err_cleanup_sysfs1:
device_remove_file(&hdev->dev, &dev_attr_operation_mode_delay);
err_cleanup_hid_ll:
hid_hw_close(hdev);
err_cleanup_hid_hw:
hid_hw_stop(hdev);
err_cleanup_data:
kfree(data);
err_no_cleanup:
hid_set_drvdata(hdev, NULL);
return error;
}
static void picolcd_remove(struct hid_device *hdev)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
unsigned long flags;
dbg_hid(PICOLCD_NAME " hardware remove...\n");
spin_lock_irqsave(&data->lock, flags);
data->status |= PICOLCD_FAILED;
spin_unlock_irqrestore(&data->lock, flags);
picolcd_exit_devfs(data);
device_remove_file(&hdev->dev, &dev_attr_operation_mode);
device_remove_file(&hdev->dev, &dev_attr_operation_mode_delay);
hid_hw_close(hdev);
hid_hw_stop(hdev);
/* Shortcut potential pending reply that will never arrive */
spin_lock_irqsave(&data->lock, flags);
if (data->pending)
complete(&data->pending->ready);
spin_unlock_irqrestore(&data->lock, flags);
/* Cleanup LED */
picolcd_exit_leds(data);
/* Clean up the framebuffer */
picolcd_exit_backlight(data);
picolcd_exit_lcd(data);
picolcd_exit_framebuffer(data);
/* Cleanup input */
picolcd_exit_cir(data);
picolcd_exit_keys(data);
hid_set_drvdata(hdev, NULL);
mutex_destroy(&data->mutex);
/* Finally, clean up the picolcd data itself */
kfree(data);
}
static const struct hid_device_id picolcd_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD) },
{ HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_PICOLCD_BOOTLOADER) },
{ }
};
MODULE_DEVICE_TABLE(hid, picolcd_devices);
static struct hid_driver picolcd_driver = {
.name = "hid-picolcd",
.id_table = picolcd_devices,
.probe = picolcd_probe,
.remove = picolcd_remove,
.raw_event = picolcd_raw_event,
#ifdef CONFIG_PM
.suspend = picolcd_suspend,
.resume = picolcd_resume,
.reset_resume = picolcd_reset_resume,
#endif
};
module_hid_driver(picolcd_driver);
MODULE_DESCRIPTION("Minibox graphics PicoLCD Driver");
MODULE_LICENSE("GPL v2");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2133_0 |
crossvul-cpp_data_bad_346_1 | /*
* Support for ePass2003 smart cards
*
* Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com>
* Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_SM /* empty file without SM enabled */
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table epass2003_atrs[] = {
/* This is a FIPS certified card using SCP01 security messaging. */
{"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e",
"FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00",
"FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL },
{NULL, NULL, NULL, 0, 0, NULL}
};
static struct sc_card_operations *iso_ops = NULL;
static struct sc_card_operations epass2003_ops;
static struct sc_card_driver epass2003_drv = {
"epass2003",
"epass2003",
&epass2003_ops,
NULL, 0, NULL
};
#define KEY_TYPE_AES 0x01 /* FIPS mode */
#define KEY_TYPE_DES 0x02 /* Non-FIPS mode */
#define KEY_LEN_AES 16
#define KEY_LEN_DES 8
#define KEY_LEN_DES3 24
#define HASH_LEN 24
static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID };
/*0x00:plain; 0x01:scp01 sm*/
#define SM_PLAIN 0x00
#define SM_SCP01 0x01
static unsigned char g_init_key_enc[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_init_key_mac[16] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10
};
static unsigned char g_random[8] = {
0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40
};
typedef struct epass2003_exdata_st {
unsigned char sm; /* SM_PLAIN or SM_SCP01 */
unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */
unsigned char sk_enc[16]; /* encrypt session key */
unsigned char sk_mac[16]; /* mac session key */
unsigned char icv_mac[16]; /* instruction counter vector(for sm) */
unsigned char currAlg; /* current Alg */
unsigned int ecAlgFlags; /* Ec Alg mechanism type*/
} epass2003_exdata;
#define REVERSE_ORDER4(x) ( \
((unsigned long)x & 0xFF000000)>> 24 | \
((unsigned long)x & 0x00FF0000)>> 8 | \
((unsigned long)x & 0x0000FF00)<< 8 | \
((unsigned long)x & 0x000000FF)<< 24)
static const struct sc_card_error epass2003_errors[] = {
{ 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" },
{ 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" },
{ 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" },
{ 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" },
{ 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" },
{ 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"},
{ 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"},
{ 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"},
{ 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" },
{ 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" },
{ 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" },
{ 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" },
{ 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" },
{ 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" },
{ 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" },
{ 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" },
{ 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" },
{ 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" },
{ 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" },
{ 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" },
{ 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" },
{ 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" },
{ 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" },
{ 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" },
{ 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" },
{ 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" },
{ 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" },
{ 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" },
{ 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" },
{ 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" },
{ 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" },
{ 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" },
{ 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"},
{ 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"},
{ 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" },
{ 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" },
{ 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" },
{ 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" },
{ 0x9000,SC_SUCCESS, NULL }
};
static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu);
static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out);
int epass2003_refresh(struct sc_card *card);
static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType);
static int
epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]);
int i;
/* Handle special cases here */
if (sw1 == 0x6C) {
sc_log(card->ctx, "Wrong length; correct length is %d", sw2);
return SC_ERROR_WRONG_LENGTH;
}
for (i = 0; i < err_count; i++) {
if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) {
sc_log(card->ctx, "%s", epass2003_errors[i].errorstr);
return epass2003_errors[i].errorno;
}
}
sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2);
return SC_ERROR_CARD_CMD_FAILED;
}
static int
sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu)
{
int r = sc_transmit_apdu(card, apdu);
if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2)))
{
epass2003_refresh(card);
r = sc_transmit_apdu(card, apdu);
}
return r;
}
static int
openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_EncryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv,
const unsigned char *input, size_t length, unsigned char *output)
{
int r = SC_ERROR_INTERNAL;
EVP_CIPHER_CTX * ctx = NULL;
int outl = 0;
int outl_tmp = 0;
unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 };
memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto out;
EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_DecryptUpdate(ctx, output, &outl, input, length))
goto out;
if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp))
goto out;
r = SC_SUCCESS;
out:
if (ctx)
EVP_CIPHER_CTX_free(ctx);
return r;
}
static int
aes128_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output);
}
static int
aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output);
}
static int
des3_encrypt_ecb(const unsigned char *key, int keysize,
const unsigned char *input, int length, unsigned char *output)
{
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output);
}
static int
des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
unsigned char bKey[24] = { 0 };
if (keysize == 16) {
memcpy(&bKey[0], key, 16);
memcpy(&bKey[16], key, 8);
}
else {
memcpy(&bKey[0], key, 24);
}
return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output);
}
static int
des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_enc(EVP_des_cbc(), key, iv, input, length, output);
}
static int
des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH],
const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dec(EVP_des_cbc(), key, iv, input, length, output);
}
static int
openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length,
unsigned char *output)
{
int r = 0;
EVP_MD_CTX *ctx = NULL;
unsigned outl = 0;
ctx = EVP_MD_CTX_create();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
EVP_MD_CTX_init(ctx);
EVP_DigestInit_ex(ctx, digest, NULL);
if (!EVP_DigestUpdate(ctx, input, length)) {
r = SC_ERROR_INTERNAL;
goto err;
}
if (!EVP_DigestFinal_ex(ctx, output, &outl)) {
r = SC_ERROR_INTERNAL;
goto err;
}
r = SC_SUCCESS;
err:
if (ctx)
EVP_MD_CTX_destroy(ctx);
return r;
}
static int
sha1_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha1(), input, length, output);
}
static int
sha256_digest(const unsigned char *input, size_t length, unsigned char *output)
{
return openssl_dig(EVP_sha256(), input, length, output);
}
static int
gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac,
unsigned char *result, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned char data[256] = { 0 };
unsigned char tmp_sm;
unsigned long blocksize = 0;
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = sizeof(g_random);
apdu.data = g_random; /* host random */
apdu.le = apdu.resplen = 28;
apdu.resp = result; /* card random is result[12~19] */
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "gen_init_key failed");
/* Step 1 - Generate Derivation data */
memcpy(data, &result[16], 4);
memcpy(&data[4], g_random, 4);
memcpy(&data[8], &result[12], 4);
memcpy(&data[12], &g_random[4], 4);
/* Step 2,3 - Create S-ENC/S-MAC Session Key */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
else {
des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc);
des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac);
}
memcpy(data, g_random, 8);
memcpy(&data[8], &result[12], 8);
data[16] = 0x80;
blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
memset(&data[17], 0x00, blocksize - 1);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram);
/* verify card cryptogram */
if (0 != memcmp(&cryptogram[16], &result[20], 8))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type)
{
int r;
struct sc_apdu apdu;
unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8);
unsigned char data[256] = { 0 };
unsigned char cryptogram[256] = { 0 }; /* host cryptogram */
unsigned char iv[16] = { 0 };
unsigned char mac[256] = { 0 };
unsigned long i;
unsigned char tmp_sm;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
memcpy(data, ran_key, 8);
memcpy(&data[8], g_random, 8);
data[16] = 0x80;
memset(&data[17], 0x00, blocksize - 1);
memset(iv, 0, 16);
/* calculate host cryptogram */
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
} else {
des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize,
cryptogram);
}
memset(data, 0, sizeof(data));
memcpy(data, "\x84\x82\x03\x00\x10", 5);
memcpy(&data[5], &cryptogram[16], 8);
memcpy(&data[13], "\x80\x00\x00", 3);
/* calculate mac icv */
memset(iv, 0x00, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 0;
} else {
des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac);
i = 8;
}
/* save mac icv */
memset(exdata->icv_mac, 0x00, 16);
memcpy(exdata->icv_mac, &mac[i], 8);
/* verify host cryptogram */
memcpy(data, &cryptogram[16], 8);
memcpy(&data[8], &mac[i], 8);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00);
apdu.cla = 0x84;
apdu.lc = apdu.datalen = 16;
apdu.data = data;
tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = epass2003_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
LOG_TEST_RET(card->ctx, r,
"APDU verify_init_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r,
"verify_init_key failed");
return r;
}
static int
mutual_auth(struct sc_card *card, unsigned char *key_enc,
unsigned char *key_mac)
{
struct sc_context *ctx = card->ctx;
int r;
unsigned char result[256] = { 0 };
unsigned char ran_key[8] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(ctx);
r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype);
LOG_TEST_RET(ctx, r, "gen_init_key failed");
memcpy(ran_key, &result[12], 8);
r = verify_init_key(card, ran_key, exdata->smtype);
LOG_TEST_RET(ctx, r, "verify_init_key failed");
LOG_FUNC_RETURN(ctx, r);
}
int
epass2003_refresh(struct sc_card *card)
{
int r = SC_SUCCESS;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (exdata->sm) {
card->sm_ctx.sm_mode = 0;
r = mutual_auth(card, g_init_key_enc, g_init_key_mac);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
LOG_TEST_RET(card->ctx, r, "mutual_auth failed");
}
return r;
}
/* Data(TLV)=0x87|L|0x01+Cipher */
static int
construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf,
unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char pad[4096] = { 0 };
size_t pad_len;
size_t tlv_more; /* increased tlv length */
unsigned char iv[16] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* padding */
apdu_buf[block_size] = 0x87;
memcpy(pad, apdu->data, apdu->lc);
pad[apdu->lc] = 0x80;
if ((apdu->lc + 1) % block_size)
pad_len = ((apdu->lc + 1) / block_size + 1) * block_size;
else
pad_len = apdu->lc + 1;
/* encode Lc' */
if (pad_len > 0x7E) {
/* Lc' > 0x7E, use extended APDU */
apdu_buf[block_size + 1] = 0x82;
apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100);
apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100);
apdu_buf[block_size + 4] = 0x01;
tlv_more = 5;
}
else {
apdu_buf[block_size + 1] = (unsigned char)pad_len + 1;
apdu_buf[block_size + 2] = 0x01;
tlv_more = 3;
}
memcpy(data_tlv, &apdu_buf[block_size], tlv_more);
/* encrypt Data */
if (KEY_TYPE_AES == key_type)
aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
else
des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more);
memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len);
*data_tlv_len = tlv_more + pad_len;
return 0;
}
/* Le(TLV)=0x97|L|Le */
static int
construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len,
unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
*(apdu_buf + block_size + data_tlv_len) = 0x97;
if (apdu->le > 0x7F) {
/* Le' > 0x7E, use extended APDU */
*(apdu_buf + block_size + data_tlv_len + 1) = 2;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100);
*(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100);
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4);
*le_tlv_len = 4;
}
else {
*(apdu_buf + block_size + data_tlv_len + 1) = 1;
*(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le;
memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3);
*le_tlv_len = 3;
}
return 0;
}
/* MAC(TLV)=0x8e|0x08|MAC */
static int
construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
/* According to GlobalPlatform Card Specification's SCP01
* encode APDU from
* CLA INS P1 P2 [Lc] Data [Le]
* to
* CLA INS P1 P2 Lc' Data' [Le]
* where
* Data'=Data(TLV)+Le(TLV)+MAC(TLV) */
static int
encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm,
unsigned char *apdu_buf, size_t * apdu_buf_len)
{
size_t block_size = 0;
unsigned char dataTLV[4096] = { 0 };
size_t data_tlv_len = 0;
unsigned char le_tlv[256] = { 0 };
size_t le_tlv_len = 0;
size_t mac_tlv_len = 10;
size_t tmp_lc = 0;
size_t tmp_le = 0;
unsigned char mac_tlv[256] = { 0 };
epass2003_exdata *exdata = NULL;
mac_tlv[0] = 0x8E;
mac_tlv[1] = 8;
/* size_t plain_le = 0; */
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata*)card->drv_data;
block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8);
sm->cse = SC_APDU_CASE_4_SHORT;
apdu_buf[0] = (unsigned char)plain->cla;
apdu_buf[1] = (unsigned char)plain->ins;
apdu_buf[2] = (unsigned char)plain->p1;
apdu_buf[3] = (unsigned char)plain->p2;
/* plain_le = plain->le; */
/* padding */
apdu_buf[4] = 0x80;
memset(&apdu_buf[5], 0x00, block_size - 5);
/* Data -> Data' */
if (plain->lc != 0)
if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype))
return -1;
if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0))
if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv,
&le_tlv_len, exdata->smtype))
return -1;
if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype))
return -1;
memset(apdu_buf + 4, 0, *apdu_buf_len - 4);
sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len;
if (sm->lc > 0xFF) {
sm->cse = SC_APDU_CASE_4_EXT;
apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000);
apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100);
apdu_buf[6] = (unsigned char)((sm->lc) % 0x100);
tmp_lc = 3;
}
else {
apdu_buf[4] = (unsigned char)sm->lc;
tmp_lc = 1;
}
memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len);
memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len);
memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen);
*apdu_buf_len = 0;
if (4 == le_tlv_len) {
sm->cse = SC_APDU_CASE_4_EXT;
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100);
*(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100);
tmp_le = 2;
}
else if (3 == le_tlv_len) {
*(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le;
tmp_le = 1;
}
*apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le;
/* sm->le = calc_le(plain_le); */
return 0;
}
static int
epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm)
{
unsigned char buf[4096] = { 0 }; /* APDU buffer */
size_t buf_len = sizeof(buf);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
if (exdata->sm)
plain->cla |= 0x0C;
sm->cse = plain->cse;
sm->cla = plain->cla;
sm->ins = plain->ins;
sm->p1 = plain->p1;
sm->p2 = plain->p2;
sm->lc = plain->lc;
sm->le = plain->le;
sm->control = plain->control;
sm->flags = plain->flags;
switch (sm->cla & 0x0C) {
case 0x00:
case 0x04:
sm->datalen = plain->datalen;
memcpy((void *)sm->data, plain->data, plain->datalen);
sm->resplen = plain->resplen;
memcpy(sm->resp, plain->resp, plain->resplen);
break;
case 0x0C:
memset(buf, 0, sizeof(buf));
if (0 != encode_apdu(card, plain, sm, buf, &buf_len))
return SC_ERROR_CARD_CMD_FAILED;
break;
default:
return SC_ERROR_INCORRECT_PARAMETERS;
}
return SC_SUCCESS;
}
/* According to GlobalPlatform Card Specification's SCP01
* decrypt APDU response from
* ResponseData' SW1 SW2
* to
* ResponseData SW1 SW2
* where
* ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV)
* where
* Data(TLV)=0x87|L|Cipher
* SW12(TLV)=0x99|0x02|SW1+SW2
* MAC(TLV)=0x8e|0x08|MAC */
static int
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
static int
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_sm_free_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
if (!sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*sm_apdu))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (plain)
rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain);
if ((*sm_apdu)->data) {
unsigned char * p = (unsigned char *)((*sm_apdu)->data);
free(p);
}
if ((*sm_apdu)->resp) {
free((*sm_apdu)->resp);
}
free(*sm_apdu);
*sm_apdu = NULL;
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_sm_get_wrapped_apdu(struct sc_card *card,
struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu *apdu = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (!plain || !sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
*sm_apdu = NULL;
//construct new SM apdu from original apdu
apdu = calloc(1, sizeof(struct sc_apdu));
if (!apdu) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->data) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE);
if (!apdu->resp) {
rv = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE;
apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE;
rv = epass2003_sm_wrap_apdu(card, plain, apdu);
if (rv) {
rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu);
if (rv < 0)
goto err;
}
*sm_apdu = apdu;
apdu = NULL;
err:
if (apdu) {
free((unsigned char *) apdu->data);
free(apdu->resp);
free(apdu);
apdu = NULL;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = sc_transmit_apdu_t(card, apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return r;
}
static int
get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t resplen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type);
apdu.resp = resp;
apdu.le = 0;
apdu.resplen = resplen;
if (0x86 == type) {
/* No SM temporarily */
unsigned char tmp_sm = exdata->sm;
exdata->sm = SM_PLAIN;
r = sc_transmit_apdu(card, &apdu);
exdata->sm = tmp_sm;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
}
LOG_TEST_RET(card->ctx, r, "APDU get_data failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get_data failed");
memcpy(data, resp, datalen);
return r;
}
/* card driver functions */
static int epass2003_match_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = _sc_match_atr(card, epass2003_atrs, &card->type);
if (r < 0)
return 0;
return 1;
}
static int
epass2003_init(struct sc_card *card)
{
unsigned int flags;
unsigned int ext_flags;
unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
size_t datalen = SC_MAX_APDU_BUFFER_SIZE;
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
card->name = "epass2003";
card->cla = 0x00;
exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata));
if (!exdata)
return SC_ERROR_OUT_OF_MEMORY;
card->drv_data = exdata;
exdata->sm = SM_SCP01;
/* decide FIPS/Non-FIPS mode */
if (SC_SUCCESS != get_data(card, 0x86, data, datalen))
return SC_ERROR_INVALID_CARD;
if (0x01 == data[2])
exdata->smtype = KEY_TYPE_AES;
else
exdata->smtype = KEY_TYPE_DES;
if (0x84 == data[14]) {
if (0x00 == data[16]) {
exdata->sm = SM_PLAIN;
}
}
/* mutual authentication */
card->max_recv_size = 0xD8;
card->max_send_size = 0xE8;
card->sm_ctx.ops.open = epass2003_refresh;
card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu;
card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu;
/* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */
epass2003_refresh(card);
card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
//set EC Alg Flags
flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW;
ext_flags = 0;
_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_finish(sc_card_t *card)
{
epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data;
if (exdata)
free(exdata);
return SC_SUCCESS;
}
/* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the
* same DF, so use hook functions to increase/decrease FID by 0x20 */
static int
epass2003_hook_path(struct sc_path *path, int inc)
{
u8 fid_h = path->value[path->len - 2];
u8 fid_l = path->value[path->len - 1];
switch (fid_h) {
case 0x29:
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
if (inc)
fid_l = fid_l * FID_STEP;
else
fid_l = fid_l / FID_STEP;
path->value[path->len - 1] = fid_l;
return 1;
default:
break;
}
return 0;
}
static void
epass2003_hook_file(struct sc_file *file, int inc)
{
int fidl = file->id & 0xff;
int fidh = file->id & 0xff00;
if (epass2003_hook_path(&file->path, inc)) {
if (inc)
file->id = fidh + fidl * FID_STEP;
else
file->id = fidh + fidl / FID_STEP;
}
}
static int
epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out)
{
struct sc_apdu apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen;
sc_file_t *file = NULL;
epass2003_hook_path(in_path, 1);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 0;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.p2 = 0; /* first record, return FCI */
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 0;
}
else {
apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */
/* Not allowed to select private key file, so fake fci. */
/* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */
apdu.resplen = 0x18;
memcpy(apdu.resp,
"\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff",
apdu.resplen);
apdu.resp[9] = path[1];
apdu.sw1 = 0x90;
apdu.sw2 = 0x00;
}
else {
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
}
if (file_out == NULL) {
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(card->ctx, 0);
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(card->ctx, r);
if (apdu.resplen < 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
switch (apdu.resp[0]) {
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
if (card->ops->process_fci == NULL) {
sc_file_free(file);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
if ((size_t) apdu.resp[1] + 2 <= apdu.resplen)
card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]);
epass2003_hook_file(file, 0);
*file_out = file;
break;
case 0x00: /* proprietary coding */
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
return 0;
}
static int
epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo,
sc_file_t ** file_out)
{
int r;
sc_file_t *file = 0;
sc_path_t path;
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_FILE_ID;
path.value[0] = id_hi;
path.value[1] = id_lo;
path.len = 2;
r = epass2003_select_fid_(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
if (file && file->type == SC_FILE_TYPE_DF) {
card->cache.current_path.type = SC_PATH_TYPE_PATH;
card->cache.current_path.value[0] = 0x3f;
card->cache.current_path.value[1] = 0x00;
if (id_hi == 0x3f && id_lo == 0x00) {
card->cache.current_path.len = 2;
}
else {
card->cache.current_path.len = 4;
card->cache.current_path.value[2] = id_hi;
card->cache.current_path.value[3] = id_lo;
}
}
if (file_out)
*file_out = file;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out)
{
int r = 0;
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_path.len == in_path->len
&& memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) {
if (file_out) {
*file_out = sc_file_new();
if (!file_out)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
}
else {
r = iso_ops->select_file(card, in_path, file_out);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
/* update cache */
card->cache.current_path.type = SC_PATH_TYPE_DF_NAME;
card->cache.current_path.len = in_path->len;
memcpy(card->cache.current_path.value, in_path->value, in_path->len);
}
if (file_out) {
sc_file_t *file = *file_out;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->path.len = 0;
file->size = 0;
/* AID */
memcpy(file->name, in_path->value, in_path->len);
file->namelen = in_path->len;
file->id = 0x0000;
}
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len,
sc_file_t ** file_out)
{
u8 n_pathbuf[SC_MAX_PATH_SIZE];
const u8 *path = pathbuf;
size_t pathlen = len;
int bMatch = -1;
unsigned int i;
int r;
if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* if pathlen == 6 then the first FID must be MF (== 3F00) */
if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00))
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
/* unify path (the first FID should be MF) */
if (path[0] != 0x3f || path[1] != 0x00) {
n_pathbuf[0] = 0x3f;
n_pathbuf[1] = 0x00;
for (i = 0; i < pathlen; i++)
n_pathbuf[i + 2] = pathbuf[i];
path = n_pathbuf;
pathlen += 2;
}
/* check current working directory */
if (card->cache.valid
&& card->cache.current_path.type == SC_PATH_TYPE_PATH
&& card->cache.current_path.len >= 2
&& card->cache.current_path.len <= pathlen) {
bMatch = 0;
for (i = 0; i < card->cache.current_path.len; i += 2)
if (card->cache.current_path.value[i] == path[i]
&& card->cache.current_path.value[i + 1] == path[i + 1])
bMatch += 2;
}
if (card->cache.valid && bMatch > 2) {
if (pathlen - bMatch == 2) {
/* we are in the right directory */
return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out);
}
else if (pathlen - bMatch > 2) {
/* two more steps to go */
sc_path_t new_path;
/* first step: change directory */
r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
new_path.type = SC_PATH_TYPE_PATH;
new_path.len = pathlen - bMatch - 2;
memcpy(new_path.value, &(path[bMatch + 2]), new_path.len);
/* final step: select file */
return epass2003_select_file(card, &new_path, file_out);
}
else { /* if (bMatch - pathlen == 0) */
/* done: we are already in the
* requested directory */
sc_log(card->ctx, "cache hit\n");
/* copy file info (if necessary) */
if (file_out) {
sc_file_t *file = sc_file_new();
if (!file)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
file->id = (path[pathlen - 2] << 8) + path[pathlen - 1];
file->path = card->cache.current_path;
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
file->size = 0;
file->namelen = 0;
file->magic = SC_FILE_MAGIC;
*file_out = file;
}
/* nothing left to do */
return SC_SUCCESS;
}
}
else {
/* no usable cache */
for (i = 0; i < pathlen - 2; i += 2) {
r = epass2003_select_fid(card, path[i], path[i + 1], NULL);
LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed");
}
return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out);
}
}
static int
epass2003_select_file(struct sc_card *card, const sc_path_t * in_path,
sc_file_t ** file_out)
{
int r;
char pbuf[SC_MAX_PATH_STRING_SIZE];
LOG_FUNC_CALLED(card->ctx);
r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (r != SC_SUCCESS)
pbuf[0] = '\0';
sc_log(card->ctx,
"current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n",
card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ?
"aid" : "path",
card->cache.valid ? "valid" : "invalid", pbuf,
card->cache.current_path.len);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (in_path->len != 2)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out);
case SC_PATH_TYPE_DF_NAME:
return epass2003_select_aid(card, in_path, file_out);
case SC_PATH_TYPE_PATH:
return epass2003_select_path(card, in_path->value, in_path->len, file_out);
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
}
static int
epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num)
{
struct sc_apdu apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 *p;
unsigned short fid = 0;
int r, locked = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0);
p = sbuf;
*p++ = 0x80; /* algorithm reference */
*p++ = 0x01;
*p++ = 0x84;
*p++ = 0x81;
*p++ = 0x02;
fid = 0x2900;
fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff));
*p++ = fid >> 8;
*p++ = fid & 0xff;
r = p - sbuf;
apdu.lc = r;
apdu.datalen = r;
apdu.data = sbuf;
if (env->algorithm == SC_ALGORITHM_EC)
{
apdu.p2 = 0xB6;
exdata->currAlg = SC_ALGORITHM_EC;
if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
sbuf[2] = 0x91;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1;
}
else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
sbuf[2] = 0x92;
exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256;
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags);
goto err;
}
}
else if(env->algorithm == SC_ALGORITHM_RSA)
{
exdata->currAlg = SC_ALGORITHM_RSA;
apdu.p2 = 0xB8;
sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags);
}
else
{
sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm);
}
if (se_num > 0) {
r = sc_lock(card);
LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
locked = 1;
}
if (apdu.datalen != 0) {
r = sc_transmit_apdu_t(card, &apdu);
if (r) {
sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r));
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r) {
sc_log(card->ctx, "%s: Card returned error", sc_strerror(r));
goto err;
}
}
if (se_num <= 0)
return 0;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num);
r = sc_transmit_apdu_t(card, &apdu);
sc_unlock(card);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
err:
if (locked)
sc_unlock(card);
return r;
}
static int
epass2003_restore_security_env(struct sc_card *card, int se_num)
{
LOG_FUNC_CALLED(card->ctx);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
epass2003_exdata *exdata = NULL;
LOG_FUNC_CALLED(card->ctx);
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if(exdata->currAlg == SC_ALGORITHM_EC)
{
if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x14;
apdu.datalen = 0x14;
}
else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256);
LOG_TEST_RET(card->ctx, r, "hash_data failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A);
apdu.data = sbuf;
apdu.lc = 0x20;
apdu.datalen = 0x20;
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
else if(exdata->currAlg == SC_ALGORITHM_RSA)
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
else
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
memcpy(sbuf, data, datalen);
apdu.data = sbuf;
apdu.lc = datalen;
apdu.datalen = datalen;
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
LOG_FUNC_RETURN(card->ctx, len);
}
LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int
acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e)
{
if (e == NULL)
return SC_ERROR_OBJECT_NOT_FOUND;
switch (e->method) {
case SC_AC_NONE:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE);
case SC_AC_NEVER:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE);
default:
LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS);
}
static int
epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen)
{
sc_context_t *ctx = card->ctx;
size_t taglen, len = buflen;
const u8 *tag = NULL, *p = buf;
sc_log(ctx, "processing FCI bytes");
tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen);
if (tag != NULL && taglen == 2) {
file->id = (tag[0] << 8) | tag[1];
sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]);
}
tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen);
if (tag != NULL && taglen > 0 && taglen < 3) {
file->size = tag[0];
if (taglen == 2)
file->size = (file->size << 8) + tag[1];
sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u",
file->size);
}
if (tag == NULL) {
tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen);
if (tag != NULL && taglen >= 2) {
int bytes = (tag[0] << 8) + tag[1];
sc_log(ctx, " bytes in file: %d", bytes);
file->size = bytes;
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen);
if (tag != NULL) {
if (taglen > 0) {
unsigned char byte = tag[0];
const char *type;
if (byte == 0x38) {
type = "DF";
file->type = SC_FILE_TYPE_DF;
}
else if (0x01 <= byte && byte <= 0x07) {
type = "working EF";
file->type = SC_FILE_TYPE_WORKING_EF;
switch (byte) {
case 0x01:
file->ef_structure = SC_FILE_EF_TRANSPARENT;
break;
case 0x02:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x04:
file->ef_structure = SC_FILE_EF_LINEAR_FIXED;
break;
case 0x03:
case 0x05:
case 0x06:
case 0x07:
break;
default:
break;
}
}
else if (0x10 == byte) {
type = "BSO";
file->type = SC_FILE_TYPE_BSO;
}
else if (0x11 <= byte) {
type = "internal EF";
file->type = SC_FILE_TYPE_INTERNAL_EF;
switch (byte) {
case 0x11:
break;
case 0x12:
break;
default:
break;
}
}
else {
type = "unknown";
file->type = SC_FILE_TYPE_INTERNAL_EF;
}
sc_log(ctx, "type %s, EF structure %d", type, byte);
}
}
tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen);
if (tag != NULL && taglen > 0 && taglen <= 16) {
memcpy(file->name, tag, taglen);
file->namelen = taglen;
sc_log_hex(ctx, "File name", file->name, file->namelen);
if (!file->type)
file->type = SC_FILE_TYPE_DF;
}
tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
else
file->prop_attr_len = 0;
tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen);
if (tag != NULL && taglen)
sc_file_set_prop_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen);
if (tag != NULL && taglen)
sc_file_set_sec_attr(file, tag, taglen);
tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen);
if (tag != NULL && taglen == 1) {
if (tag[0] == 0x01)
file->status = SC_FILE_STATUS_CREATION;
else if (tag[0] == 0x07 || tag[0] == 0x05)
file->status = SC_FILE_STATUS_ACTIVATED;
else if (tag[0] == 0x06 || tag[0] == 0x04)
file->status = SC_FILE_STATUS_INVALIDATED;
}
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
epass2003_construct_fci(struct sc_card *card, const sc_file_t * file,
u8 * out, size_t * outlen)
{
u8 *p = out;
u8 buf[64];
unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
int rv;
unsigned ii;
if (*outlen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*p++ = 0x62;
p++;
if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->type == SC_FILE_TYPE_DF) {
buf[0] = 0x38;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
buf[0] = file->ef_structure & 7;
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
buf[1] = 0x00;
buf[2] = 0x00;
buf[3] = 0x40; /* record length */
buf[4] = 0x00; /* record count */
sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
buf[0] = 0x11;
buf[1] = 0x00;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = 0x12;
buf[1] = 0x00;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = 0x10;
buf[1] = 0x00;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen != 0) {
sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p);
}
else {
return SC_ERROR_INVALID_ARGUMENTS;
}
}
if (file->type == SC_FILE_TYPE_DF) {
unsigned char data[2] = {0x00, 0x7F};
/* 127 files at most */
sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_BSO) {
buf[0] = file->size & 0xff;
sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p);
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p);
}
}
if (file->sec_attr_len) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p);
}
else {
sc_log(card->ctx, "SC_FILE_ACL");
if (file->type == SC_FILE_TYPE_DF) {
ops[0] = SC_AC_OP_LIST_FILES;
ops[1] = SC_AC_OP_CREATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_WORKING_EF) {
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED
|| file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_WRITE;
ops[3] = SC_AC_OP_DELETE;
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
}
else if (file->type == SC_FILE_TYPE_BSO) {
ops[0] = SC_AC_OP_UPDATE;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT ||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) {
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
ops[0] = SC_AC_OP_READ;
ops[1] = SC_AC_OP_UPDATE;
ops[2] = SC_AC_OP_CRYPTO;
ops[3] = SC_AC_OP_DELETE;
}
}
else {
return SC_ERROR_NOT_SUPPORTED;
}
for (ii = 0; ii < sizeof(ops); ii++) {
const struct sc_acl_entry *entry;
buf[ii] = 0xFF;
if (ops[ii] == 0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
rv = acl_to_ac_byte(card, entry);
LOG_TEST_RET(card->ctx, rv, "Invalid ACL");
buf[ii] = rv;
}
sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x13;
}
}
/* VT ??? */
if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC||
file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) {
unsigned char data[2] = {0x00, 0x66};
sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p);
if(file->size == 256)
{
out[4]= 0x14;
}
}
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int
epass2003_create_file(struct sc_card *card, sc_file_t * file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
struct sc_apdu apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
epass2003_hook_file(file, 1);
if (card->ops->construct_fci == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
r = epass2003_construct_fci(card, file, sbuf, &len);
LOG_TEST_RET(card->ctx, r, "construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong");
epass2003_hook_file(file, 0);
return r;
}
static int
epass2003_delete_file(struct sc_card *card, const sc_path_t * path)
{
int r;
u8 sbuf[2];
struct sc_apdu apdu;
LOG_FUNC_CALLED(card->ctx);
r = sc_select_file(card, path, NULL);
epass2003_hook_path((struct sc_path *)path, 1);
if (r == SC_SUCCESS) {
sbuf[0] = path->value[path->len - 2];
sbuf[1] = path->value[path->len - 1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Delete file failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen)
{
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 };
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00);
apdu.cla = 0x80;
apdu.le = 0;
apdu.resplen = sizeof(rbuf);
apdu.resp = rbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Card returned error");
if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0)
LOG_FUNC_RETURN(card->ctx, 0);
buflen = buflen < apdu.resplen ? buflen : apdu.resplen;
memcpy(buf, rbuf, buflen);
LOG_FUNC_RETURN(card->ctx, buflen);
}
static int
internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor,
sc_pkcs15_bignum_t data)
{
int r;
struct sc_apdu apdu;
u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
sbuff[0] = ((fid & 0xff00) >> 8);
sbuff[1] = (fid & 0x00ff);
memcpy(&sbuff[2], data.data, data.len);
// sc_mem_reverse(&sbuff[2], data.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2 + data.len;
apdu.data = sbuff;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa)
{
int r;
LOG_FUNC_CALLED(card->ctx);
r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus);
LOG_TEST_RET(card->ctx, r, "write n failed");
r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d);
LOG_TEST_RET(card->ctx, r, "write d failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType)
{
if ((NULL == data) || (NULL == hash))
return SC_ERROR_INVALID_ARGUMENTS;
if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1)
{
unsigned char data_hash[24] = { 0 };
size_t len = 0;
sha1_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[20], &len, 4);
memcpy(hash, data_hash, 24);
}
else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256)
{
unsigned char data_hash[36] = { 0 };
size_t len = 0;
sha256_digest(data, datalen, data_hash);
len = REVERSE_ORDER4(datalen);
memcpy(&data_hash[32], &len, 4);
memcpy(hash, data_hash, 36);
}
else
{
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
}
static int
install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
unsigned char useac, unsigned char modifyac, unsigned char EC,
unsigned char *data, unsigned long dataLen)
{
int r;
struct sc_apdu apdu;
unsigned char isapp = 0x00; /* appendable */
unsigned char tmp_data[256] = { 0 };
tmp_data[0] = ktype;
tmp_data[1] = kid;
tmp_data[2] = useac;
tmp_data[3] = modifyac;
tmp_data[8] = 0xFF;
if (0x04 == ktype || 0x06 == ktype) {
tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO;
tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO);
tmp_data[9] = (EC << 4) | EC;
}
memcpy(&tmp_data[10], data, dataLen);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 10 + dataLen;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "install_secret_key failed");
return r;
}
static int
internal_install_pre(struct sc_card *card)
{
int r;
/* init key for enc */
r = install_secret_key(card, 0x01, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_enc, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
/* init key for mac */
r = install_secret_key(card, 0x02, 0x00,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE,
0, g_init_key_mac, 16);
LOG_TEST_RET(card->ctx, r, "Install init key failed");
return r;
}
/* use external auth secret as pin */
static int
internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin)
{
int r;
unsigned char hash[HASH_LEN] = { 0 };
r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid,
pin->key_data.es_secret.ac[0],
pin->key_data.es_secret.ac[1],
pin->key_data.es_secret.EC, hash, HASH_LEN);
LOG_TEST_RET(card->ctx, r, "Install failed");
return r;
}
static int
epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data)
{
LOG_FUNC_CALLED(card->ctx);
if (data->type & SC_EPASS2003_KEY) {
if (data->type == SC_EPASS2003_KEY_RSA)
return internal_write_rsa_key(card, data->key_data.es_key.fid,
data->key_data.es_key.rsa);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
} else if (data->type & SC_EPASS2003_SECRET) {
if (data->type == SC_EPASS2003_SECRET_PRE)
return internal_install_pre(card);
else if (data->type == SC_EPASS2003_SECRET_PIN)
return internal_install_pin(card, data);
else
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
else {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data)
{
int r;
size_t len = data->key_length;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 };
LOG_FUNC_CALLED(card->ctx);
if(len == 256)
{
sbuf[0] = 0x02;
}
else
{
sbuf[0] = 0x01;
}
sbuf[1] = (u8) ((len >> 8) & 0xff);
sbuf[2] = (u8) (len & 0xff);
sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF);
sbuf[4] = (u8) ((data->prkey_id) & 0xFF);
sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF);
sbuf[6] = (u8) ((data->pukey_id) & 0xFF);
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.lc = apdu.datalen = 7;
apdu.data = sbuf;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "generate keypair failed");
/* read public key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00);
if(len == 256)
{
apdu.p1 = 0x00;
}
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 2;
apdu.data = &sbuf[5];
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x00;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "get pukey failed");
if (len < apdu.resplen)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
data->modulus = (u8 *) malloc(len);
if (!data->modulus)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(data->modulus, rbuf, len);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_erase_card(struct sc_card *card)
{
int r;
LOG_FUNC_CALLED(card->ctx);
sc_invalidate_cache(card);
r = sc_delete_file(card, sc_get_mf_path());
LOG_TEST_RET(card->ctx, r, "delete MF failed");
LOG_FUNC_RETURN(card->ctx, r);
}
static int
epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial)
{
u8 rbuf[8];
size_t rbuf_len = sizeof(rbuf);
LOG_FUNC_CALLED(card->ctx);
if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len))
return SC_ERROR_CARD_CMD_FAILED;
card->serialnr.len = serial->len = 8;
memcpy(card->serialnr.value, rbuf, 8);
memcpy(serial->value, rbuf, 8);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd is %0lx", cmd);
switch (cmd) {
case SC_CARDCTL_ENTERSAFE_WRITE_KEY:
return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr);
case SC_CARDCTL_ENTERSAFE_GENERATE_KEY:
return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr);
case SC_CARDCTL_ERASE_CARD:
return epass2003_erase_card(card);
case SC_CARDCTL_GET_SERIALNR:
return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
static void
internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num)
{
pin->encoding = SC_PIN_ENCODING_ASCII;
pin->min_length = 4;
pin->max_length = 16;
pin->pad_length = 16;
pin->offset = 5 + num * 16;
pin->pad_char = 0x00;
}
static int
get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries)
{
unsigned char maxcounter[2] = { 0 };
static const sc_path_t file_path = {
{0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6,
0,
0,
SC_PATH_TYPE_PATH,
{{0}, 0}
};
int ret;
ret = sc_select_file(card, &file_path, NULL);
LOG_TEST_RET(card->ctx, ret, "select max counter file failed");
ret = sc_read_binary(card, 0, maxcounter, 2, 0);
LOG_TEST_RET(card->ctx, ret, "read max counter file failed");
*maxtries = maxcounter[0];
return SC_SUCCESS;
}
static int
get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid);
apdu.resp = NULL;
apdu.resplen = 0;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed");
if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) {
*retries = (apdu.sw2 & 0x0f);
r = SC_SUCCESS;
}
else {
LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed");
r = SC_ERROR_CARD_CMD_FAILED;
}
return r;
}
static int
epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
u8 rbuf[16];
size_t out_len;
int r;
LOG_FUNC_CALLED(card->ctx);
r = iso_ops->get_challenge(card, rbuf, sizeof rbuf);
LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed");
if (len < (size_t) r) {
out_len = len;
} else {
out_len = (size_t) r;
}
memcpy(rnd, rbuf, out_len);
LOG_FUNC_RETURN(card->ctx, (int) out_len);
}
static int
external_key_auth(struct sc_card *card, unsigned char kid,
unsigned char *data, size_t datalen)
{
int r;
struct sc_apdu apdu;
unsigned char random[16] = { 0 };
unsigned char tmp_data[16] = { 0 };
unsigned char hash[HASH_LEN] = { 0 };
unsigned char iv[16] = { 0 };
r = sc_get_challenge(card, random, 8);
LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed");
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid);
apdu.lc = apdu.datalen = 8;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "external_key_auth failed");
return r;
}
static int
update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid,
const unsigned char *data, unsigned long datalen)
{
int r;
struct sc_apdu apdu;
unsigned char hash[HASH_LEN] = { 0 };
unsigned char tmp_data[256] = { 0 };
unsigned char maxtries = 0;
r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1);
LOG_TEST_RET(card->ctx, r, "hash data failed");
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
tmp_data[0] = (maxtries << 4) | maxtries;
memcpy(&tmp_data[1], hash, HASH_LEN);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid);
apdu.cla = 0x80;
apdu.lc = apdu.datalen = 1 + HASH_LEN;
apdu.data = tmp_data;
r = sc_transmit_apdu_t(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, r, "update_secret_key failed");
return r;
}
/* use external auth secret as pin */
static int
epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r;
u8 kid;
u8 retries = 0;
u8 pin_low = 3;
unsigned char maxtries = 0;
LOG_FUNC_CALLED(card->ctx);
internal_sanitize_pin_info(&data->pin1, 0);
internal_sanitize_pin_info(&data->pin2, 1);
data->flags |= SC_PIN_CMD_NEED_PADDING;
kid = data->pin_reference;
/* get pin retries */
if (data->cmd == SC_PIN_CMD_GET_INFO) {
r = get_external_key_retries(card, 0x80 | kid, &retries);
if (r == SC_SUCCESS) {
data->pin1.tries_left = retries;
if (tries_left)
*tries_left = retries;
r = get_external_key_maxtries(card, &maxtries);
LOG_TEST_RET(card->ctx, r, "get max counter failed");
data->pin1.max_tries = maxtries;
}
//remove below code, because the old implement only return PIN retries, now modify the code and return PIN status
// return r;
}
else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */
r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data,
data->pin1.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */
r = update_secret_key(card, 0x04, kid, data->pin2.data,
(unsigned long)data->pin2.len);
LOG_TEST_RET(card->ctx, r, "verify pin failed");
}
else {
r = external_key_auth(card, kid, (unsigned char *)data->pin1.data,
data->pin1.len);
get_external_key_retries(card, 0x80 | kid, &retries);
if (retries < pin_low)
sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries);
}
LOG_TEST_RET(card->ctx, r, "verify pin failed");
if (r == SC_SUCCESS)
{
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
}
return r;
}
static struct sc_card_driver *sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL)
iso_ops = iso_drv->ops;
epass2003_ops = *iso_ops;
epass2003_ops.match_card = epass2003_match_card;
epass2003_ops.init = epass2003_init;
epass2003_ops.finish = epass2003_finish;
epass2003_ops.write_binary = NULL;
epass2003_ops.write_record = NULL;
epass2003_ops.select_file = epass2003_select_file;
epass2003_ops.get_response = NULL;
epass2003_ops.restore_security_env = epass2003_restore_security_env;
epass2003_ops.set_security_env = epass2003_set_security_env;
epass2003_ops.decipher = epass2003_decipher;
epass2003_ops.compute_signature = epass2003_decipher;
epass2003_ops.create_file = epass2003_create_file;
epass2003_ops.delete_file = epass2003_delete_file;
epass2003_ops.list_files = epass2003_list_files;
epass2003_ops.card_ctl = epass2003_card_ctl;
epass2003_ops.process_fci = epass2003_process_fci;
epass2003_ops.construct_fci = epass2003_construct_fci;
epass2003_ops.pin_cmd = epass2003_pin_cmd;
epass2003_ops.check_sw = epass2003_check_sw;
epass2003_ops.get_challenge = epass2003_get_challenge;
return &epass2003_drv;
}
struct sc_card_driver *sc_get_epass2003_driver(void)
{
return sc_get_driver();
}
#endif /* #ifdef ENABLE_OPENSSL */
#endif /* #ifdef ENABLE_SM */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_1 |
crossvul-cpp_data_bad_5263_0 | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sterling Hughes <sterling@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_CURL
#include <stdio.h>
#include <string.h>
#ifdef PHP_WIN32
#include <winsock2.h>
#include <sys/types.h>
#endif
#include <curl/curl.h>
#include <curl/easy.h>
/* As of curl 7.11.1 this is no longer defined inside curl.h */
#ifndef HttpPost
#define HttpPost curl_httppost
#endif
/* {{{ cruft for thread safe SSL crypto locks */
#if defined(ZTS) && defined(HAVE_CURL_SSL)
# ifdef PHP_WIN32
# define PHP_CURL_NEED_OPENSSL_TSL
# include <openssl/crypto.h>
# else /* !PHP_WIN32 */
# if defined(HAVE_CURL_OPENSSL)
# if defined(HAVE_OPENSSL_CRYPTO_H)
# define PHP_CURL_NEED_OPENSSL_TSL
# include <openssl/crypto.h>
# else
# warning \
"libcurl was compiled with OpenSSL support, but configure could not find " \
"openssl/crypto.h; thus no SSL crypto locking callbacks will be set, which may " \
"cause random crashes on SSL requests"
# endif
# elif defined(HAVE_CURL_GNUTLS)
# if defined(HAVE_GCRYPT_H)
# define PHP_CURL_NEED_GNUTLS_TSL
# include <gcrypt.h>
# else
# warning \
"libcurl was compiled with GnuTLS support, but configure could not find " \
"gcrypt.h; thus no SSL crypto locking callbacks will be set, which may " \
"cause random crashes on SSL requests"
# endif
# else
# warning \
"libcurl was compiled with SSL support, but configure could not determine which" \
"library was used; thus no SSL crypto locking callbacks will be set, which may " \
"cause random crashes on SSL requests"
# endif /* HAVE_CURL_OPENSSL || HAVE_CURL_GNUTLS */
# endif /* PHP_WIN32 */
#endif /* ZTS && HAVE_CURL_SSL */
/* }}} */
#define SMART_STR_PREALLOC 4096
#include "zend_smart_str.h"
#include "ext/standard/info.h"
#include "ext/standard/file.h"
#include "ext/standard/url.h"
#include "php_curl.h"
int le_curl;
int le_curl_multi_handle;
int le_curl_share_handle;
#ifdef PHP_CURL_NEED_OPENSSL_TSL /* {{{ */
static MUTEX_T *php_curl_openssl_tsl = NULL;
static void php_curl_ssl_lock(int mode, int n, const char * file, int line)
{
if (mode & CRYPTO_LOCK) {
tsrm_mutex_lock(php_curl_openssl_tsl[n]);
} else {
tsrm_mutex_unlock(php_curl_openssl_tsl[n]);
}
}
static unsigned long php_curl_ssl_id(void)
{
return (unsigned long) tsrm_thread_id();
}
#endif
/* }}} */
#ifdef PHP_CURL_NEED_GNUTLS_TSL /* {{{ */
static int php_curl_ssl_mutex_create(void **m)
{
if (*((MUTEX_T *) m) = tsrm_mutex_alloc()) {
return SUCCESS;
} else {
return FAILURE;
}
}
static int php_curl_ssl_mutex_destroy(void **m)
{
tsrm_mutex_free(*((MUTEX_T *) m));
return SUCCESS;
}
static int php_curl_ssl_mutex_lock(void **m)
{
return tsrm_mutex_lock(*((MUTEX_T *) m));
}
static int php_curl_ssl_mutex_unlock(void **m)
{
return tsrm_mutex_unlock(*((MUTEX_T *) m));
}
static struct gcry_thread_cbs php_curl_gnutls_tsl = {
GCRY_THREAD_OPTION_USER,
NULL,
php_curl_ssl_mutex_create,
php_curl_ssl_mutex_destroy,
php_curl_ssl_mutex_lock,
php_curl_ssl_mutex_unlock
};
#endif
/* }}} */
static void _php_curl_close_ex(php_curl *ch);
static void _php_curl_close(zend_resource *rsrc);
#define SAVE_CURL_ERROR(__handle, __err) (__handle)->err.no = (int) __err;
#define CAAL(s, v) add_assoc_long_ex(return_value, s, sizeof(s) - 1, (zend_long) v);
#define CAAD(s, v) add_assoc_double_ex(return_value, s, sizeof(s) - 1, (double) v);
#define CAAS(s, v) add_assoc_string_ex(return_value, s, sizeof(s) - 1, (char *) (v ? v : ""));
#define CAASTR(s, v) add_assoc_str_ex(return_value, s, sizeof(s) - 1, \
v ? zend_string_copy(v) : ZSTR_EMPTY_ALLOC());
#define CAAZ(s, v) add_assoc_zval_ex(return_value, s, sizeof(s) -1 , (zval *) v);
#if defined(PHP_WIN32) || defined(__GNUC__)
# define php_curl_ret(__ret) RETVAL_FALSE; return __ret;
#else
# define php_curl_ret(__ret) RETVAL_FALSE; return;
#endif
static int php_curl_option_str(php_curl *ch, zend_long option, const char *str, const int len, zend_bool make_copy)
{
CURLcode error = CURLE_OK;
if (strlen(str) != len) {
php_error_docref(NULL, E_WARNING, "Curl option contains invalid characters (\\0)");
return FAILURE;
}
#if LIBCURL_VERSION_NUM >= 0x071100
if (make_copy) {
#endif
char *copystr;
/* Strings passed to libcurl as 'char *' arguments, are copied by the library since 7.17.0 */
copystr = estrndup(str, len);
error = curl_easy_setopt(ch->cp, option, copystr);
zend_llist_add_element(&ch->to_free->str, ©str);
#if LIBCURL_VERSION_NUM >= 0x071100
} else {
error = curl_easy_setopt(ch->cp, option, str);
}
#endif
SAVE_CURL_ERROR(ch, error)
return error == CURLE_OK ? SUCCESS : FAILURE;
}
static int php_curl_option_url(php_curl *ch, const char *url, const int len) /* {{{ */
{
/* Disable file:// if open_basedir are used */
if (PG(open_basedir) && *PG(open_basedir)) {
#if LIBCURL_VERSION_NUM >= 0x071304
curl_easy_setopt(ch->cp, CURLOPT_PROTOCOLS, CURLPROTO_ALL & ~CURLPROTO_FILE);
#else
php_url *uri;
if (!(uri = php_url_parse_ex(url, len))) {
php_error_docref(NULL, E_WARNING, "Invalid URL '%s'", url);
return FAILURE;
}
if (uri->scheme && !strncasecmp("file", uri->scheme, sizeof("file"))) {
php_error_docref(NULL, E_WARNING, "Protocol 'file' disabled in cURL");
php_url_free(uri);
return FAILURE;
}
php_url_free(uri);
#endif
}
return php_curl_option_str(ch, CURLOPT_URL, url, len, 0);
}
/* }}} */
void _php_curl_verify_handlers(php_curl *ch, int reporterror) /* {{{ */
{
php_stream *stream;
ZEND_ASSERT(ch && ch->handlers);
if (!Z_ISUNDEF(ch->handlers->std_err)) {
stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->std_err, NULL, php_file_le_stream(), php_file_le_pstream());
if (stream == NULL) {
if (reporterror) {
php_error_docref(NULL, E_WARNING, "CURLOPT_STDERR resource has gone away, resetting to stderr");
}
zval_ptr_dtor(&ch->handlers->std_err);
ZVAL_UNDEF(&ch->handlers->std_err);
curl_easy_setopt(ch->cp, CURLOPT_STDERR, stderr);
}
}
if (ch->handlers->read && !Z_ISUNDEF(ch->handlers->read->stream)) {
stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->read->stream, NULL, php_file_le_stream(), php_file_le_pstream());
if (stream == NULL) {
if (reporterror) {
php_error_docref(NULL, E_WARNING, "CURLOPT_INFILE resource has gone away, resetting to default");
}
zval_ptr_dtor(&ch->handlers->read->stream);
ZVAL_UNDEF(&ch->handlers->read->stream);
ch->handlers->read->res = NULL;
ch->handlers->read->fp = 0;
curl_easy_setopt(ch->cp, CURLOPT_INFILE, (void *) ch);
}
}
if (ch->handlers->write_header && !Z_ISUNDEF(ch->handlers->write_header->stream)) {
stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->write_header->stream, NULL, php_file_le_stream(), php_file_le_pstream());
if (stream == NULL) {
if (reporterror) {
php_error_docref(NULL, E_WARNING, "CURLOPT_WRITEHEADER resource has gone away, resetting to default");
}
zval_ptr_dtor(&ch->handlers->write_header->stream);
ZVAL_UNDEF(&ch->handlers->write_header->stream);
ch->handlers->write_header->fp = 0;
ch->handlers->write_header->method = PHP_CURL_IGNORE;
curl_easy_setopt(ch->cp, CURLOPT_WRITEHEADER, (void *) ch);
}
}
if (ch->handlers->write && !Z_ISUNDEF(ch->handlers->write->stream)) {
stream = (php_stream *)zend_fetch_resource2_ex(&ch->handlers->write->stream, NULL, php_file_le_stream(), php_file_le_pstream());
if (stream == NULL) {
if (reporterror) {
php_error_docref(NULL, E_WARNING, "CURLOPT_FILE resource has gone away, resetting to default");
}
zval_ptr_dtor(&ch->handlers->write->stream);
ZVAL_UNDEF(&ch->handlers->write->stream);
ch->handlers->write->fp = 0;
ch->handlers->write->method = PHP_CURL_STDOUT;
curl_easy_setopt(ch->cp, CURLOPT_FILE, (void *) ch);
}
}
return;
}
/* }}} */
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_version, 0, 0, 0)
ZEND_ARG_INFO(0, version)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_init, 0, 0, 0)
ZEND_ARG_INFO(0, url)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_copy_handle, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_setopt, 0)
ZEND_ARG_INFO(0, ch)
ZEND_ARG_INFO(0, option)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_setopt_array, 0)
ZEND_ARG_INFO(0, ch)
ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_exec, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_getinfo, 0, 0, 1)
ZEND_ARG_INFO(0, ch)
ZEND_ARG_INFO(0, option)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_error, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_errno, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_close, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
#if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */
ZEND_BEGIN_ARG_INFO(arginfo_curl_reset, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
#endif
#if LIBCURL_VERSION_NUM > 0x070f03 /* 7.15.4 */
ZEND_BEGIN_ARG_INFO(arginfo_curl_escape, 0)
ZEND_ARG_INFO(0, ch)
ZEND_ARG_INFO(0, str)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_unescape, 0)
ZEND_ARG_INFO(0, ch)
ZEND_ARG_INFO(0, str)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_setopt, 0)
ZEND_ARG_INFO(0, sh)
ZEND_ARG_INFO(0, option)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_init, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_add_handle, 0)
ZEND_ARG_INFO(0, mh)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_remove_handle, 0)
ZEND_ARG_INFO(0, mh)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_multi_select, 0, 0, 1)
ZEND_ARG_INFO(0, mh)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_multi_exec, 0, 0, 1)
ZEND_ARG_INFO(0, mh)
ZEND_ARG_INFO(1, still_running)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_getcontent, 0)
ZEND_ARG_INFO(0, ch)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_curl_multi_info_read, 0, 0, 1)
ZEND_ARG_INFO(0, mh)
ZEND_ARG_INFO(1, msgs_in_queue)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_close, 0)
ZEND_ARG_INFO(0, mh)
ZEND_END_ARG_INFO()
#if LIBCURL_VERSION_NUM >= 0x070c00 /* Available since 7.12.0 */
ZEND_BEGIN_ARG_INFO(arginfo_curl_strerror, 0)
ZEND_ARG_INFO(0, errornum)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_multi_strerror, 0)
ZEND_ARG_INFO(0, errornum)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO(arginfo_curl_share_init, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_share_close, 0)
ZEND_ARG_INFO(0, sh)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_curl_share_setopt, 0)
ZEND_ARG_INFO(0, sh)
ZEND_ARG_INFO(0, option)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
#if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */
ZEND_BEGIN_ARG_INFO(arginfo_curl_pause, 0)
ZEND_ARG_INFO(0, ch)
ZEND_ARG_INFO(0, bitmask)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO_EX(arginfo_curlfile_create, 0, 0, 1)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, mimetype)
ZEND_ARG_INFO(0, postname)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ curl_functions[]
*/
const zend_function_entry curl_functions[] = {
PHP_FE(curl_init, arginfo_curl_init)
PHP_FE(curl_copy_handle, arginfo_curl_copy_handle)
PHP_FE(curl_version, arginfo_curl_version)
PHP_FE(curl_setopt, arginfo_curl_setopt)
PHP_FE(curl_setopt_array, arginfo_curl_setopt_array)
PHP_FE(curl_exec, arginfo_curl_exec)
PHP_FE(curl_getinfo, arginfo_curl_getinfo)
PHP_FE(curl_error, arginfo_curl_error)
PHP_FE(curl_errno, arginfo_curl_errno)
PHP_FE(curl_close, arginfo_curl_close)
#if LIBCURL_VERSION_NUM >= 0x070c00 /* 7.12.0 */
PHP_FE(curl_strerror, arginfo_curl_strerror)
PHP_FE(curl_multi_strerror, arginfo_curl_multi_strerror)
#endif
#if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */
PHP_FE(curl_reset, arginfo_curl_reset)
#endif
#if LIBCURL_VERSION_NUM >= 0x070f04 /* 7.15.4 */
PHP_FE(curl_escape, arginfo_curl_escape)
PHP_FE(curl_unescape, arginfo_curl_unescape)
#endif
#if LIBCURL_VERSION_NUM >= 0x071200 /* 7.18.0 */
PHP_FE(curl_pause, arginfo_curl_pause)
#endif
PHP_FE(curl_multi_init, arginfo_curl_multi_init)
PHP_FE(curl_multi_add_handle, arginfo_curl_multi_add_handle)
PHP_FE(curl_multi_remove_handle, arginfo_curl_multi_remove_handle)
PHP_FE(curl_multi_select, arginfo_curl_multi_select)
PHP_FE(curl_multi_exec, arginfo_curl_multi_exec)
PHP_FE(curl_multi_getcontent, arginfo_curl_multi_getcontent)
PHP_FE(curl_multi_info_read, arginfo_curl_multi_info_read)
PHP_FE(curl_multi_close, arginfo_curl_multi_close)
#if LIBCURL_VERSION_NUM >= 0x070f04 /* 7.15.4 */
PHP_FE(curl_multi_setopt, arginfo_curl_multi_setopt)
#endif
PHP_FE(curl_share_init, arginfo_curl_share_init)
PHP_FE(curl_share_close, arginfo_curl_share_close)
PHP_FE(curl_share_setopt, arginfo_curl_share_setopt)
PHP_FE(curl_file_create, arginfo_curlfile_create)
PHP_FE_END
};
/* }}} */
/* {{{ curl_module_entry
*/
zend_module_entry curl_module_entry = {
STANDARD_MODULE_HEADER,
"curl",
curl_functions,
PHP_MINIT(curl),
PHP_MSHUTDOWN(curl),
NULL,
NULL,
PHP_MINFO(curl),
PHP_CURL_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_CURL
ZEND_GET_MODULE (curl)
#endif
/* {{{ PHP_INI_BEGIN */
PHP_INI_BEGIN()
PHP_INI_ENTRY("curl.cainfo", "", PHP_INI_SYSTEM, NULL)
PHP_INI_END()
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(curl)
{
curl_version_info_data *d;
char **p;
char str[1024];
size_t n = 0;
d = curl_version_info(CURLVERSION_NOW);
php_info_print_table_start();
php_info_print_table_row(2, "cURL support", "enabled");
php_info_print_table_row(2, "cURL Information", d->version);
sprintf(str, "%d", d->age);
php_info_print_table_row(2, "Age", str);
/* To update on each new cURL release using src/main.c in cURL sources */
if (d->features) {
struct feat {
const char *name;
int bitmask;
};
unsigned int i;
static const struct feat feats[] = {
#if LIBCURL_VERSION_NUM >= 0x070a07 /* 7.10.7 */
{"AsynchDNS", CURL_VERSION_ASYNCHDNS},
#endif
#if LIBCURL_VERSION_NUM >= 0x070f04 /* 7.15.4 */
{"CharConv", CURL_VERSION_CONV},
#endif
#if LIBCURL_VERSION_NUM >= 0x070a06 /* 7.10.6 */
{"Debug", CURL_VERSION_DEBUG},
{"GSS-Negotiate", CURL_VERSION_GSSNEGOTIATE},
#endif
#if LIBCURL_VERSION_NUM >= 0x070c00 /* 7.12.0 */
{"IDN", CURL_VERSION_IDN},
#endif
{"IPv6", CURL_VERSION_IPV6},
{"krb4", CURL_VERSION_KERBEROS4},
#if LIBCURL_VERSION_NUM >= 0x070b01 /* 7.11.1 */
{"Largefile", CURL_VERSION_LARGEFILE},
#endif
{"libz", CURL_VERSION_LIBZ},
#if LIBCURL_VERSION_NUM >= 0x070a06 /* 7.10.6 */
{"NTLM", CURL_VERSION_NTLM},
#endif
#if LIBCURL_VERSION_NUM >= 0x071600 /* 7.22.0 */
{"NTLMWB", CURL_VERSION_NTLM_WB},
#endif
#if LIBCURL_VERSION_NUM >= 0x070a08 /* 7.10.8 */
{"SPNEGO", CURL_VERSION_SPNEGO},
#endif
{"SSL", CURL_VERSION_SSL},
#if LIBCURL_VERSION_NUM >= 0x070d02 /* 7.13.2 */
{"SSPI", CURL_VERSION_SSPI},
#endif
#if LIBCURL_VERSION_NUM >= 0x071504 /* 7.21.4 */
{"TLS-SRP", CURL_VERSION_TLSAUTH_SRP},
#endif
#if LIBCURL_VERSION_NUM >= 0x072100 /* 7.33.0 */
{"HTTP2", CURL_VERSION_HTTP2},
#endif
#if LIBCURL_VERSION_NUM >= 0x072600 /* 7.38.0 */
{"GSSAPI", CURL_VERSION_GSSAPI},
#endif
#if LIBCURL_VERSION_NUM >= 0x072800 /* 7.40.0 */
{"KERBEROS5", CURL_VERSION_KERBEROS5},
{"UNIX_SOCKETS", CURL_VERSION_UNIX_SOCKETS},
#endif
#if LIBCURL_VERSION_NUM >= 0x072f00 /* 7.47.0 */
{"PSL", CURL_VERSION_PSL},
#endif
{NULL, 0}
};
php_info_print_table_row(1, "Features");
for(i=0; i<sizeof(feats)/sizeof(feats[0]); i++) {
if (feats[i].name) {
php_info_print_table_row(2, feats[i].name, d->features & feats[i].bitmask ? "Yes" : "No");
}
}
}
n = 0;
p = (char **) d->protocols;
while (*p != NULL) {
n += sprintf(str + n, "%s%s", *p, *(p + 1) != NULL ? ", " : "");
p++;
}
php_info_print_table_row(2, "Protocols", str);
php_info_print_table_row(2, "Host", d->host);
if (d->ssl_version) {
php_info_print_table_row(2, "SSL Version", d->ssl_version);
}
if (d->libz_version) {
php_info_print_table_row(2, "ZLib Version", d->libz_version);
}
#if defined(CURLVERSION_SECOND) && CURLVERSION_NOW >= CURLVERSION_SECOND
if (d->ares) {
php_info_print_table_row(2, "ZLib Version", d->ares);
}
#endif
#if defined(CURLVERSION_THIRD) && CURLVERSION_NOW >= CURLVERSION_THIRD
if (d->libidn) {
php_info_print_table_row(2, "libIDN Version", d->libidn);
}
#endif
#if LIBCURL_VERSION_NUM >= 0x071300
if (d->iconv_ver_num) {
php_info_print_table_row(2, "IconV Version", d->iconv_ver_num);
}
if (d->libssh_version) {
php_info_print_table_row(2, "libSSH Version", d->libssh_version);
}
#endif
php_info_print_table_end();
}
/* }}} */
#define REGISTER_CURL_CONSTANT(__c) REGISTER_LONG_CONSTANT(#__c, __c, CONST_CS | CONST_PERSISTENT)
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(curl)
{
le_curl = zend_register_list_destructors_ex(_php_curl_close, NULL, "curl", module_number);
le_curl_multi_handle = zend_register_list_destructors_ex(_php_curl_multi_close, NULL, "curl_multi", module_number);
le_curl_share_handle = zend_register_list_destructors_ex(_php_curl_share_close, NULL, "curl_share", module_number);
REGISTER_INI_ENTRIES();
/* See http://curl.haxx.se/lxr/source/docs/libcurl/symbols-in-versions
or curl src/docs/libcurl/symbols-in-versions for a (almost) complete list
of options and which version they were introduced */
/* Constants for curl_setopt() */
REGISTER_CURL_CONSTANT(CURLOPT_AUTOREFERER);
REGISTER_CURL_CONSTANT(CURLOPT_BINARYTRANSFER);
REGISTER_CURL_CONSTANT(CURLOPT_BUFFERSIZE);
REGISTER_CURL_CONSTANT(CURLOPT_CAINFO);
REGISTER_CURL_CONSTANT(CURLOPT_CAPATH);
REGISTER_CURL_CONSTANT(CURLOPT_CONNECTTIMEOUT);
REGISTER_CURL_CONSTANT(CURLOPT_COOKIE);
REGISTER_CURL_CONSTANT(CURLOPT_COOKIEFILE);
REGISTER_CURL_CONSTANT(CURLOPT_COOKIEJAR);
REGISTER_CURL_CONSTANT(CURLOPT_COOKIESESSION);
REGISTER_CURL_CONSTANT(CURLOPT_CRLF);
REGISTER_CURL_CONSTANT(CURLOPT_CUSTOMREQUEST);
REGISTER_CURL_CONSTANT(CURLOPT_DNS_CACHE_TIMEOUT);
REGISTER_CURL_CONSTANT(CURLOPT_DNS_USE_GLOBAL_CACHE);
REGISTER_CURL_CONSTANT(CURLOPT_EGDSOCKET);
REGISTER_CURL_CONSTANT(CURLOPT_ENCODING);
REGISTER_CURL_CONSTANT(CURLOPT_FAILONERROR);
REGISTER_CURL_CONSTANT(CURLOPT_FILE);
REGISTER_CURL_CONSTANT(CURLOPT_FILETIME);
REGISTER_CURL_CONSTANT(CURLOPT_FOLLOWLOCATION);
REGISTER_CURL_CONSTANT(CURLOPT_FORBID_REUSE);
REGISTER_CURL_CONSTANT(CURLOPT_FRESH_CONNECT);
REGISTER_CURL_CONSTANT(CURLOPT_FTPAPPEND);
REGISTER_CURL_CONSTANT(CURLOPT_FTPLISTONLY);
REGISTER_CURL_CONSTANT(CURLOPT_FTPPORT);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_USE_EPRT);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_USE_EPSV);
REGISTER_CURL_CONSTANT(CURLOPT_HEADER);
REGISTER_CURL_CONSTANT(CURLOPT_HEADERFUNCTION);
REGISTER_CURL_CONSTANT(CURLOPT_HTTP200ALIASES);
REGISTER_CURL_CONSTANT(CURLOPT_HTTPGET);
REGISTER_CURL_CONSTANT(CURLOPT_HTTPHEADER);
REGISTER_CURL_CONSTANT(CURLOPT_HTTPPROXYTUNNEL);
REGISTER_CURL_CONSTANT(CURLOPT_HTTP_VERSION);
REGISTER_CURL_CONSTANT(CURLOPT_INFILE);
REGISTER_CURL_CONSTANT(CURLOPT_INFILESIZE);
REGISTER_CURL_CONSTANT(CURLOPT_INTERFACE);
REGISTER_CURL_CONSTANT(CURLOPT_KRB4LEVEL);
REGISTER_CURL_CONSTANT(CURLOPT_LOW_SPEED_LIMIT);
REGISTER_CURL_CONSTANT(CURLOPT_LOW_SPEED_TIME);
REGISTER_CURL_CONSTANT(CURLOPT_MAXCONNECTS);
REGISTER_CURL_CONSTANT(CURLOPT_MAXREDIRS);
REGISTER_CURL_CONSTANT(CURLOPT_NETRC);
REGISTER_CURL_CONSTANT(CURLOPT_NOBODY);
REGISTER_CURL_CONSTANT(CURLOPT_NOPROGRESS);
REGISTER_CURL_CONSTANT(CURLOPT_NOSIGNAL);
REGISTER_CURL_CONSTANT(CURLOPT_PORT);
REGISTER_CURL_CONSTANT(CURLOPT_POST);
REGISTER_CURL_CONSTANT(CURLOPT_POSTFIELDS);
REGISTER_CURL_CONSTANT(CURLOPT_POSTQUOTE);
REGISTER_CURL_CONSTANT(CURLOPT_PREQUOTE);
REGISTER_CURL_CONSTANT(CURLOPT_PRIVATE);
REGISTER_CURL_CONSTANT(CURLOPT_PROGRESSFUNCTION);
REGISTER_CURL_CONSTANT(CURLOPT_PROXY);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYPORT);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYTYPE);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYUSERPWD);
REGISTER_CURL_CONSTANT(CURLOPT_PUT);
REGISTER_CURL_CONSTANT(CURLOPT_QUOTE);
REGISTER_CURL_CONSTANT(CURLOPT_RANDOM_FILE);
REGISTER_CURL_CONSTANT(CURLOPT_RANGE);
REGISTER_CURL_CONSTANT(CURLOPT_READDATA);
REGISTER_CURL_CONSTANT(CURLOPT_READFUNCTION);
REGISTER_CURL_CONSTANT(CURLOPT_REFERER);
REGISTER_CURL_CONSTANT(CURLOPT_RESUME_FROM);
REGISTER_CURL_CONSTANT(CURLOPT_RETURNTRANSFER);
REGISTER_CURL_CONSTANT(CURLOPT_SHARE);
REGISTER_CURL_CONSTANT(CURLOPT_SSLCERT);
REGISTER_CURL_CONSTANT(CURLOPT_SSLCERTPASSWD);
REGISTER_CURL_CONSTANT(CURLOPT_SSLCERTTYPE);
REGISTER_CURL_CONSTANT(CURLOPT_SSLENGINE);
REGISTER_CURL_CONSTANT(CURLOPT_SSLENGINE_DEFAULT);
REGISTER_CURL_CONSTANT(CURLOPT_SSLKEY);
REGISTER_CURL_CONSTANT(CURLOPT_SSLKEYPASSWD);
REGISTER_CURL_CONSTANT(CURLOPT_SSLKEYTYPE);
REGISTER_CURL_CONSTANT(CURLOPT_SSLVERSION);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_CIPHER_LIST);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_VERIFYHOST);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_VERIFYPEER);
REGISTER_CURL_CONSTANT(CURLOPT_STDERR);
REGISTER_CURL_CONSTANT(CURLOPT_TELNETOPTIONS);
REGISTER_CURL_CONSTANT(CURLOPT_TIMECONDITION);
REGISTER_CURL_CONSTANT(CURLOPT_TIMEOUT);
REGISTER_CURL_CONSTANT(CURLOPT_TIMEVALUE);
REGISTER_CURL_CONSTANT(CURLOPT_TRANSFERTEXT);
REGISTER_CURL_CONSTANT(CURLOPT_UNRESTRICTED_AUTH);
REGISTER_CURL_CONSTANT(CURLOPT_UPLOAD);
REGISTER_CURL_CONSTANT(CURLOPT_URL);
REGISTER_CURL_CONSTANT(CURLOPT_USERAGENT);
REGISTER_CURL_CONSTANT(CURLOPT_USERPWD);
REGISTER_CURL_CONSTANT(CURLOPT_VERBOSE);
REGISTER_CURL_CONSTANT(CURLOPT_WRITEFUNCTION);
REGISTER_CURL_CONSTANT(CURLOPT_WRITEHEADER);
/* */
REGISTER_CURL_CONSTANT(CURLE_ABORTED_BY_CALLBACK);
REGISTER_CURL_CONSTANT(CURLE_BAD_CALLING_ORDER);
REGISTER_CURL_CONSTANT(CURLE_BAD_CONTENT_ENCODING);
REGISTER_CURL_CONSTANT(CURLE_BAD_DOWNLOAD_RESUME);
REGISTER_CURL_CONSTANT(CURLE_BAD_FUNCTION_ARGUMENT);
REGISTER_CURL_CONSTANT(CURLE_BAD_PASSWORD_ENTERED);
REGISTER_CURL_CONSTANT(CURLE_COULDNT_CONNECT);
REGISTER_CURL_CONSTANT(CURLE_COULDNT_RESOLVE_HOST);
REGISTER_CURL_CONSTANT(CURLE_COULDNT_RESOLVE_PROXY);
REGISTER_CURL_CONSTANT(CURLE_FAILED_INIT);
REGISTER_CURL_CONSTANT(CURLE_FILE_COULDNT_READ_FILE);
REGISTER_CURL_CONSTANT(CURLE_FTP_ACCESS_DENIED);
REGISTER_CURL_CONSTANT(CURLE_FTP_BAD_DOWNLOAD_RESUME);
REGISTER_CURL_CONSTANT(CURLE_FTP_CANT_GET_HOST);
REGISTER_CURL_CONSTANT(CURLE_FTP_CANT_RECONNECT);
REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_GET_SIZE);
REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_RETR_FILE);
REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_SET_ASCII);
REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_SET_BINARY);
REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_STOR_FILE);
REGISTER_CURL_CONSTANT(CURLE_FTP_COULDNT_USE_REST);
REGISTER_CURL_CONSTANT(CURLE_FTP_PARTIAL_FILE);
REGISTER_CURL_CONSTANT(CURLE_FTP_PORT_FAILED);
REGISTER_CURL_CONSTANT(CURLE_FTP_QUOTE_ERROR);
REGISTER_CURL_CONSTANT(CURLE_FTP_USER_PASSWORD_INCORRECT);
REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_227_FORMAT);
REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_PASS_REPLY);
REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_PASV_REPLY);
REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_SERVER_REPLY);
REGISTER_CURL_CONSTANT(CURLE_FTP_WEIRD_USER_REPLY);
REGISTER_CURL_CONSTANT(CURLE_FTP_WRITE_ERROR);
REGISTER_CURL_CONSTANT(CURLE_FUNCTION_NOT_FOUND);
REGISTER_CURL_CONSTANT(CURLE_GOT_NOTHING);
REGISTER_CURL_CONSTANT(CURLE_HTTP_NOT_FOUND);
REGISTER_CURL_CONSTANT(CURLE_HTTP_PORT_FAILED);
REGISTER_CURL_CONSTANT(CURLE_HTTP_POST_ERROR);
REGISTER_CURL_CONSTANT(CURLE_HTTP_RANGE_ERROR);
REGISTER_CURL_CONSTANT(CURLE_HTTP_RETURNED_ERROR);
REGISTER_CURL_CONSTANT(CURLE_LDAP_CANNOT_BIND);
REGISTER_CURL_CONSTANT(CURLE_LDAP_SEARCH_FAILED);
REGISTER_CURL_CONSTANT(CURLE_LIBRARY_NOT_FOUND);
REGISTER_CURL_CONSTANT(CURLE_MALFORMAT_USER);
REGISTER_CURL_CONSTANT(CURLE_OBSOLETE);
REGISTER_CURL_CONSTANT(CURLE_OK);
REGISTER_CURL_CONSTANT(CURLE_OPERATION_TIMEDOUT);
REGISTER_CURL_CONSTANT(CURLE_OPERATION_TIMEOUTED);
REGISTER_CURL_CONSTANT(CURLE_OUT_OF_MEMORY);
REGISTER_CURL_CONSTANT(CURLE_PARTIAL_FILE);
REGISTER_CURL_CONSTANT(CURLE_READ_ERROR);
REGISTER_CURL_CONSTANT(CURLE_RECV_ERROR);
REGISTER_CURL_CONSTANT(CURLE_SEND_ERROR);
REGISTER_CURL_CONSTANT(CURLE_SHARE_IN_USE);
REGISTER_CURL_CONSTANT(CURLE_SSL_CACERT);
REGISTER_CURL_CONSTANT(CURLE_SSL_CERTPROBLEM);
REGISTER_CURL_CONSTANT(CURLE_SSL_CIPHER);
REGISTER_CURL_CONSTANT(CURLE_SSL_CONNECT_ERROR);
REGISTER_CURL_CONSTANT(CURLE_SSL_ENGINE_NOTFOUND);
REGISTER_CURL_CONSTANT(CURLE_SSL_ENGINE_SETFAILED);
REGISTER_CURL_CONSTANT(CURLE_SSL_PEER_CERTIFICATE);
REGISTER_CURL_CONSTANT(CURLE_TELNET_OPTION_SYNTAX);
REGISTER_CURL_CONSTANT(CURLE_TOO_MANY_REDIRECTS);
REGISTER_CURL_CONSTANT(CURLE_UNKNOWN_TELNET_OPTION);
REGISTER_CURL_CONSTANT(CURLE_UNSUPPORTED_PROTOCOL);
REGISTER_CURL_CONSTANT(CURLE_URL_MALFORMAT);
REGISTER_CURL_CONSTANT(CURLE_URL_MALFORMAT_USER);
REGISTER_CURL_CONSTANT(CURLE_WRITE_ERROR);
/* cURL info constants */
REGISTER_CURL_CONSTANT(CURLINFO_CONNECT_TIME);
REGISTER_CURL_CONSTANT(CURLINFO_CONTENT_LENGTH_DOWNLOAD);
REGISTER_CURL_CONSTANT(CURLINFO_CONTENT_LENGTH_UPLOAD);
REGISTER_CURL_CONSTANT(CURLINFO_CONTENT_TYPE);
REGISTER_CURL_CONSTANT(CURLINFO_EFFECTIVE_URL);
REGISTER_CURL_CONSTANT(CURLINFO_FILETIME);
REGISTER_CURL_CONSTANT(CURLINFO_HEADER_OUT);
REGISTER_CURL_CONSTANT(CURLINFO_HEADER_SIZE);
REGISTER_CURL_CONSTANT(CURLINFO_HTTP_CODE);
REGISTER_CURL_CONSTANT(CURLINFO_LASTONE);
REGISTER_CURL_CONSTANT(CURLINFO_NAMELOOKUP_TIME);
REGISTER_CURL_CONSTANT(CURLINFO_PRETRANSFER_TIME);
REGISTER_CURL_CONSTANT(CURLINFO_PRIVATE);
REGISTER_CURL_CONSTANT(CURLINFO_REDIRECT_COUNT);
REGISTER_CURL_CONSTANT(CURLINFO_REDIRECT_TIME);
REGISTER_CURL_CONSTANT(CURLINFO_REQUEST_SIZE);
REGISTER_CURL_CONSTANT(CURLINFO_SIZE_DOWNLOAD);
REGISTER_CURL_CONSTANT(CURLINFO_SIZE_UPLOAD);
REGISTER_CURL_CONSTANT(CURLINFO_SPEED_DOWNLOAD);
REGISTER_CURL_CONSTANT(CURLINFO_SPEED_UPLOAD);
REGISTER_CURL_CONSTANT(CURLINFO_SSL_VERIFYRESULT);
REGISTER_CURL_CONSTANT(CURLINFO_STARTTRANSFER_TIME);
REGISTER_CURL_CONSTANT(CURLINFO_TOTAL_TIME);
/* Other */
REGISTER_CURL_CONSTANT(CURLMSG_DONE);
REGISTER_CURL_CONSTANT(CURLVERSION_NOW);
/* Curl Multi Constants */
REGISTER_CURL_CONSTANT(CURLM_BAD_EASY_HANDLE);
REGISTER_CURL_CONSTANT(CURLM_BAD_HANDLE);
REGISTER_CURL_CONSTANT(CURLM_CALL_MULTI_PERFORM);
REGISTER_CURL_CONSTANT(CURLM_INTERNAL_ERROR);
REGISTER_CURL_CONSTANT(CURLM_OK);
REGISTER_CURL_CONSTANT(CURLM_OUT_OF_MEMORY);
#if LIBCURL_VERSION_NUM >= 0x072001 /* Available since 7.32.1 */
REGISTER_CURL_CONSTANT(CURLM_ADDED_ALREADY);
#endif
/* Curl proxy constants */
REGISTER_CURL_CONSTANT(CURLPROXY_HTTP);
REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS4);
REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS5);
/* Curl Share constants */
REGISTER_CURL_CONSTANT(CURLSHOPT_NONE);
REGISTER_CURL_CONSTANT(CURLSHOPT_SHARE);
REGISTER_CURL_CONSTANT(CURLSHOPT_UNSHARE);
/* Curl Http Version constants (CURLOPT_HTTP_VERSION) */
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_1_0);
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_1_1);
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_NONE);
/* Curl Lock constants */
REGISTER_CURL_CONSTANT(CURL_LOCK_DATA_COOKIE);
REGISTER_CURL_CONSTANT(CURL_LOCK_DATA_DNS);
REGISTER_CURL_CONSTANT(CURL_LOCK_DATA_SSL_SESSION);
/* Curl NETRC constants (CURLOPT_NETRC) */
REGISTER_CURL_CONSTANT(CURL_NETRC_IGNORED);
REGISTER_CURL_CONSTANT(CURL_NETRC_OPTIONAL);
REGISTER_CURL_CONSTANT(CURL_NETRC_REQUIRED);
/* Curl SSL Version constants (CURLOPT_SSLVERSION) */
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_DEFAULT);
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_SSLv2);
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_SSLv3);
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1);
/* Curl TIMECOND constants (CURLOPT_TIMECONDITION) */
REGISTER_CURL_CONSTANT(CURL_TIMECOND_IFMODSINCE);
REGISTER_CURL_CONSTANT(CURL_TIMECOND_IFUNMODSINCE);
REGISTER_CURL_CONSTANT(CURL_TIMECOND_LASTMOD);
REGISTER_CURL_CONSTANT(CURL_TIMECOND_NONE);
/* Curl version constants */
REGISTER_CURL_CONSTANT(CURL_VERSION_IPV6);
REGISTER_CURL_CONSTANT(CURL_VERSION_KERBEROS4);
REGISTER_CURL_CONSTANT(CURL_VERSION_LIBZ);
REGISTER_CURL_CONSTANT(CURL_VERSION_SSL);
#if LIBCURL_VERSION_NUM >= 0x070a06 /* Available since 7.10.6 */
REGISTER_CURL_CONSTANT(CURLOPT_HTTPAUTH);
/* http authentication options */
REGISTER_CURL_CONSTANT(CURLAUTH_ANY);
REGISTER_CURL_CONSTANT(CURLAUTH_ANYSAFE);
REGISTER_CURL_CONSTANT(CURLAUTH_BASIC);
REGISTER_CURL_CONSTANT(CURLAUTH_DIGEST);
REGISTER_CURL_CONSTANT(CURLAUTH_GSSNEGOTIATE);
REGISTER_CURL_CONSTANT(CURLAUTH_NONE);
REGISTER_CURL_CONSTANT(CURLAUTH_NTLM);
#endif
#if LIBCURL_VERSION_NUM >= 0x070a07 /* Available since 7.10.7 */
REGISTER_CURL_CONSTANT(CURLINFO_HTTP_CONNECTCODE);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_CREATE_MISSING_DIRS);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYAUTH);
#endif
#if LIBCURL_VERSION_NUM >= 0x070a08 /* Available since 7.10.8 */
REGISTER_CURL_CONSTANT(CURLE_FILESIZE_EXCEEDED);
REGISTER_CURL_CONSTANT(CURLE_LDAP_INVALID_URL);
REGISTER_CURL_CONSTANT(CURLINFO_HTTPAUTH_AVAIL);
REGISTER_CURL_CONSTANT(CURLINFO_RESPONSE_CODE);
REGISTER_CURL_CONSTANT(CURLINFO_PROXYAUTH_AVAIL);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_RESPONSE_TIMEOUT);
REGISTER_CURL_CONSTANT(CURLOPT_IPRESOLVE);
REGISTER_CURL_CONSTANT(CURLOPT_MAXFILESIZE);
REGISTER_CURL_CONSTANT(CURL_IPRESOLVE_V4);
REGISTER_CURL_CONSTANT(CURL_IPRESOLVE_V6);
REGISTER_CURL_CONSTANT(CURL_IPRESOLVE_WHATEVER);
#endif
#if LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */
REGISTER_CURL_CONSTANT(CURLE_FTP_SSL_FAILED);
REGISTER_CURL_CONSTANT(CURLFTPSSL_ALL);
REGISTER_CURL_CONSTANT(CURLFTPSSL_CONTROL);
REGISTER_CURL_CONSTANT(CURLFTPSSL_NONE);
REGISTER_CURL_CONSTANT(CURLFTPSSL_TRY);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_SSL);
REGISTER_CURL_CONSTANT(CURLOPT_NETRC_FILE);
#endif
#if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */
REGISTER_CURL_CONSTANT(CURLFTPAUTH_DEFAULT);
REGISTER_CURL_CONSTANT(CURLFTPAUTH_SSL);
REGISTER_CURL_CONSTANT(CURLFTPAUTH_TLS);
REGISTER_CURL_CONSTANT(CURLOPT_FTPSSLAUTH);
#endif
#if LIBCURL_VERSION_NUM >= 0x070d00 /* Available since 7.13.0 */
REGISTER_CURL_CONSTANT(CURLOPT_FTP_ACCOUNT);
#endif
#if LIBCURL_VERSION_NUM >= 0x070b02 /* Available since 7.11.2 */
REGISTER_CURL_CONSTANT(CURLOPT_TCP_NODELAY);
#endif
#if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */
REGISTER_CURL_CONSTANT(CURLINFO_OS_ERRNO);
#endif
#if LIBCURL_VERSION_NUM >= 0x070c03 /* Available since 7.12.3 */
REGISTER_CURL_CONSTANT(CURLINFO_NUM_CONNECTS);
REGISTER_CURL_CONSTANT(CURLINFO_SSL_ENGINES);
#endif
#if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */
REGISTER_CURL_CONSTANT(CURLINFO_COOKIELIST);
REGISTER_CURL_CONSTANT(CURLOPT_COOKIELIST);
REGISTER_CURL_CONSTANT(CURLOPT_IGNORE_CONTENT_LENGTH);
#endif
#if LIBCURL_VERSION_NUM >= 0x070f00 /* Available since 7.15.0 */
REGISTER_CURL_CONSTANT(CURLOPT_FTP_SKIP_PASV_IP);
#endif
#if LIBCURL_VERSION_NUM >= 0x070f01 /* Available since 7.15.1 */
REGISTER_CURL_CONSTANT(CURLOPT_FTP_FILEMETHOD);
#endif
#if LIBCURL_VERSION_NUM >= 0x070f02 /* Available since 7.15.2 */
REGISTER_CURL_CONSTANT(CURLOPT_CONNECT_ONLY);
REGISTER_CURL_CONSTANT(CURLOPT_LOCALPORT);
REGISTER_CURL_CONSTANT(CURLOPT_LOCALPORTRANGE);
#endif
#if LIBCURL_VERSION_NUM >= 0x070f03 /* Available since 7.15.3 */
REGISTER_CURL_CONSTANT(CURLFTPMETHOD_MULTICWD);
REGISTER_CURL_CONSTANT(CURLFTPMETHOD_NOCWD);
REGISTER_CURL_CONSTANT(CURLFTPMETHOD_SINGLECWD);
#endif
#if LIBCURL_VERSION_NUM >= 0x070f04 /* Available since 7.15.4 */
REGISTER_CURL_CONSTANT(CURLINFO_FTP_ENTRY_PATH);
#endif
#if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */
REGISTER_CURL_CONSTANT(CURLOPT_FTP_ALTERNATIVE_TO_USER);
REGISTER_CURL_CONSTANT(CURLOPT_MAX_RECV_SPEED_LARGE);
REGISTER_CURL_CONSTANT(CURLOPT_MAX_SEND_SPEED_LARGE);
#endif
#if LIBCURL_VERSION_NUM >= 0x071000 /* Available since 7.16.0 */
REGISTER_CURL_CONSTANT(CURLE_SSL_CACERT_BADFILE);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_SESSIONID_CACHE);
REGISTER_CURL_CONSTANT(CURLMOPT_PIPELINING);
#endif
#if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */
REGISTER_CURL_CONSTANT(CURLE_SSH);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_SSL_CCC);
REGISTER_CURL_CONSTANT(CURLOPT_SSH_AUTH_TYPES);
REGISTER_CURL_CONSTANT(CURLOPT_SSH_PRIVATE_KEYFILE);
REGISTER_CURL_CONSTANT(CURLOPT_SSH_PUBLIC_KEYFILE);
REGISTER_CURL_CONSTANT(CURLFTPSSL_CCC_ACTIVE);
REGISTER_CURL_CONSTANT(CURLFTPSSL_CCC_NONE);
REGISTER_CURL_CONSTANT(CURLFTPSSL_CCC_PASSIVE);
#endif
#if LIBCURL_VERSION_NUM >= 0x071002 /* Available since 7.16.2 */
REGISTER_CURL_CONSTANT(CURLOPT_CONNECTTIMEOUT_MS);
REGISTER_CURL_CONSTANT(CURLOPT_HTTP_CONTENT_DECODING);
REGISTER_CURL_CONSTANT(CURLOPT_HTTP_TRANSFER_DECODING);
REGISTER_CURL_CONSTANT(CURLOPT_TIMEOUT_MS);
#endif
#if LIBCURL_VERSION_NUM >= 0x071003 /* Available since 7.16.3 */
REGISTER_CURL_CONSTANT(CURLMOPT_MAXCONNECTS);
#endif
#if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */
REGISTER_CURL_CONSTANT(CURLOPT_KRBLEVEL);
REGISTER_CURL_CONSTANT(CURLOPT_NEW_DIRECTORY_PERMS);
REGISTER_CURL_CONSTANT(CURLOPT_NEW_FILE_PERMS);
#endif
#if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */
REGISTER_CURL_CONSTANT(CURLOPT_APPEND);
REGISTER_CURL_CONSTANT(CURLOPT_DIRLISTONLY);
REGISTER_CURL_CONSTANT(CURLOPT_USE_SSL);
/* Curl SSL Constants */
REGISTER_CURL_CONSTANT(CURLUSESSL_ALL);
REGISTER_CURL_CONSTANT(CURLUSESSL_CONTROL);
REGISTER_CURL_CONSTANT(CURLUSESSL_NONE);
REGISTER_CURL_CONSTANT(CURLUSESSL_TRY);
#endif
#if LIBCURL_VERSION_NUM >= 0x071101 /* Available since 7.17.1 */
REGISTER_CURL_CONSTANT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5);
#endif
#if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */
REGISTER_CURL_CONSTANT(CURLOPT_PROXY_TRANSFER_MODE);
REGISTER_CURL_CONSTANT(CURLPAUSE_ALL);
REGISTER_CURL_CONSTANT(CURLPAUSE_CONT);
REGISTER_CURL_CONSTANT(CURLPAUSE_RECV);
REGISTER_CURL_CONSTANT(CURLPAUSE_RECV_CONT);
REGISTER_CURL_CONSTANT(CURLPAUSE_SEND);
REGISTER_CURL_CONSTANT(CURLPAUSE_SEND_CONT);
REGISTER_CURL_CONSTANT(CURL_READFUNC_PAUSE);
REGISTER_CURL_CONSTANT(CURL_WRITEFUNC_PAUSE);
REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS4A);
REGISTER_CURL_CONSTANT(CURLPROXY_SOCKS5_HOSTNAME);
#endif
#if LIBCURL_VERSION_NUM >= 0x071202 /* Available since 7.18.2 */
REGISTER_CURL_CONSTANT(CURLINFO_REDIRECT_URL);
#endif
#if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */
REGISTER_CURL_CONSTANT(CURLINFO_APPCONNECT_TIME);
REGISTER_CURL_CONSTANT(CURLINFO_PRIMARY_IP);
REGISTER_CURL_CONSTANT(CURLOPT_ADDRESS_SCOPE);
REGISTER_CURL_CONSTANT(CURLOPT_CRLFILE);
REGISTER_CURL_CONSTANT(CURLOPT_ISSUERCERT);
REGISTER_CURL_CONSTANT(CURLOPT_KEYPASSWD);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_ANY);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_DEFAULT);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_HOST);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_KEYBOARD);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_NONE);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_PASSWORD);
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_PUBLICKEY);
#endif
#if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */
REGISTER_CURL_CONSTANT(CURLINFO_CERTINFO);
REGISTER_CURL_CONSTANT(CURLOPT_CERTINFO);
REGISTER_CURL_CONSTANT(CURLOPT_PASSWORD);
REGISTER_CURL_CONSTANT(CURLOPT_POSTREDIR);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYPASSWORD);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYUSERNAME);
REGISTER_CURL_CONSTANT(CURLOPT_USERNAME);
REGISTER_CURL_CONSTANT(CURL_REDIR_POST_301);
REGISTER_CURL_CONSTANT(CURL_REDIR_POST_302);
REGISTER_CURL_CONSTANT(CURL_REDIR_POST_ALL);
#endif
#if LIBCURL_VERSION_NUM >= 0x071303 /* Available since 7.19.3 */
REGISTER_CURL_CONSTANT(CURLAUTH_DIGEST_IE);
#endif
#if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */
REGISTER_CURL_CONSTANT(CURLINFO_CONDITION_UNMET);
REGISTER_CURL_CONSTANT(CURLOPT_NOPROXY);
REGISTER_CURL_CONSTANT(CURLOPT_PROTOCOLS);
REGISTER_CURL_CONSTANT(CURLOPT_REDIR_PROTOCOLS);
REGISTER_CURL_CONSTANT(CURLOPT_SOCKS5_GSSAPI_NEC);
REGISTER_CURL_CONSTANT(CURLOPT_SOCKS5_GSSAPI_SERVICE);
REGISTER_CURL_CONSTANT(CURLOPT_TFTP_BLKSIZE);
REGISTER_CURL_CONSTANT(CURLPROTO_ALL);
REGISTER_CURL_CONSTANT(CURLPROTO_DICT);
REGISTER_CURL_CONSTANT(CURLPROTO_FILE);
REGISTER_CURL_CONSTANT(CURLPROTO_FTP);
REGISTER_CURL_CONSTANT(CURLPROTO_FTPS);
REGISTER_CURL_CONSTANT(CURLPROTO_HTTP);
REGISTER_CURL_CONSTANT(CURLPROTO_HTTPS);
REGISTER_CURL_CONSTANT(CURLPROTO_LDAP);
REGISTER_CURL_CONSTANT(CURLPROTO_LDAPS);
REGISTER_CURL_CONSTANT(CURLPROTO_SCP);
REGISTER_CURL_CONSTANT(CURLPROTO_SFTP);
REGISTER_CURL_CONSTANT(CURLPROTO_TELNET);
REGISTER_CURL_CONSTANT(CURLPROTO_TFTP);
REGISTER_CURL_CONSTANT(CURLPROXY_HTTP_1_0);
REGISTER_CURL_CONSTANT(CURLFTP_CREATE_DIR);
REGISTER_CURL_CONSTANT(CURLFTP_CREATE_DIR_NONE);
REGISTER_CURL_CONSTANT(CURLFTP_CREATE_DIR_RETRY);
#endif
#if LIBCURL_VERSION_NUM >= 0x071306 /* Available since 7.19.6 */
REGISTER_CURL_CONSTANT(CURLOPT_SSH_KNOWNHOSTS);
#endif
#if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */
REGISTER_CURL_CONSTANT(CURLINFO_RTSP_CLIENT_CSEQ);
REGISTER_CURL_CONSTANT(CURLINFO_RTSP_CSEQ_RECV);
REGISTER_CURL_CONSTANT(CURLINFO_RTSP_SERVER_CSEQ);
REGISTER_CURL_CONSTANT(CURLINFO_RTSP_SESSION_ID);
REGISTER_CURL_CONSTANT(CURLOPT_FTP_USE_PRET);
REGISTER_CURL_CONSTANT(CURLOPT_MAIL_FROM);
REGISTER_CURL_CONSTANT(CURLOPT_MAIL_RCPT);
REGISTER_CURL_CONSTANT(CURLOPT_RTSP_CLIENT_CSEQ);
REGISTER_CURL_CONSTANT(CURLOPT_RTSP_REQUEST);
REGISTER_CURL_CONSTANT(CURLOPT_RTSP_SERVER_CSEQ);
REGISTER_CURL_CONSTANT(CURLOPT_RTSP_SESSION_ID);
REGISTER_CURL_CONSTANT(CURLOPT_RTSP_STREAM_URI);
REGISTER_CURL_CONSTANT(CURLOPT_RTSP_TRANSPORT);
REGISTER_CURL_CONSTANT(CURLPROTO_IMAP);
REGISTER_CURL_CONSTANT(CURLPROTO_IMAPS);
REGISTER_CURL_CONSTANT(CURLPROTO_POP3);
REGISTER_CURL_CONSTANT(CURLPROTO_POP3S);
REGISTER_CURL_CONSTANT(CURLPROTO_RTSP);
REGISTER_CURL_CONSTANT(CURLPROTO_SMTP);
REGISTER_CURL_CONSTANT(CURLPROTO_SMTPS);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_ANNOUNCE);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_DESCRIBE);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_GET_PARAMETER);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_OPTIONS);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_PAUSE);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_PLAY);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_RECEIVE);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_RECORD);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_SET_PARAMETER);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_SETUP);
REGISTER_CURL_CONSTANT(CURL_RTSPREQ_TEARDOWN);
#endif
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
REGISTER_CURL_CONSTANT(CURLINFO_LOCAL_IP);
REGISTER_CURL_CONSTANT(CURLINFO_LOCAL_PORT);
REGISTER_CURL_CONSTANT(CURLINFO_PRIMARY_PORT);
REGISTER_CURL_CONSTANT(CURLOPT_FNMATCH_FUNCTION);
REGISTER_CURL_CONSTANT(CURLOPT_WILDCARDMATCH);
REGISTER_CURL_CONSTANT(CURLPROTO_RTMP);
REGISTER_CURL_CONSTANT(CURLPROTO_RTMPE);
REGISTER_CURL_CONSTANT(CURLPROTO_RTMPS);
REGISTER_CURL_CONSTANT(CURLPROTO_RTMPT);
REGISTER_CURL_CONSTANT(CURLPROTO_RTMPTE);
REGISTER_CURL_CONSTANT(CURLPROTO_RTMPTS);
REGISTER_CURL_CONSTANT(CURL_FNMATCHFUNC_FAIL);
REGISTER_CURL_CONSTANT(CURL_FNMATCHFUNC_MATCH);
REGISTER_CURL_CONSTANT(CURL_FNMATCHFUNC_NOMATCH);
#endif
#if LIBCURL_VERSION_NUM >= 0x071502 /* Available since 7.21.2 */
REGISTER_CURL_CONSTANT(CURLPROTO_GOPHER);
#endif
#if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */
REGISTER_CURL_CONSTANT(CURLAUTH_ONLY);
REGISTER_CURL_CONSTANT(CURLOPT_RESOLVE);
#endif
#if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */
REGISTER_CURL_CONSTANT(CURLOPT_TLSAUTH_PASSWORD);
REGISTER_CURL_CONSTANT(CURLOPT_TLSAUTH_TYPE);
REGISTER_CURL_CONSTANT(CURLOPT_TLSAUTH_USERNAME);
REGISTER_CURL_CONSTANT(CURL_TLSAUTH_SRP);
#endif
#if LIBCURL_VERSION_NUM >= 0x071506 /* Available since 7.21.6 */
REGISTER_CURL_CONSTANT(CURLOPT_ACCEPT_ENCODING);
REGISTER_CURL_CONSTANT(CURLOPT_TRANSFER_ENCODING);
#endif
#if LIBCURL_VERSION_NUM >= 0x071600 /* Available since 7.22.0 */
REGISTER_CURL_CONSTANT(CURLAUTH_NTLM_WB);
REGISTER_CURL_CONSTANT(CURLGSSAPI_DELEGATION_FLAG);
REGISTER_CURL_CONSTANT(CURLGSSAPI_DELEGATION_POLICY_FLAG);
REGISTER_CURL_CONSTANT(CURLOPT_GSSAPI_DELEGATION);
#endif
#if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */
REGISTER_CURL_CONSTANT(CURLOPT_ACCEPTTIMEOUT_MS);
REGISTER_CURL_CONSTANT(CURLOPT_DNS_SERVERS);
#endif
#if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */
REGISTER_CURL_CONSTANT(CURLOPT_MAIL_AUTH);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_OPTIONS);
REGISTER_CURL_CONSTANT(CURLOPT_TCP_KEEPALIVE);
REGISTER_CURL_CONSTANT(CURLOPT_TCP_KEEPIDLE);
REGISTER_CURL_CONSTANT(CURLOPT_TCP_KEEPINTVL);
REGISTER_CURL_CONSTANT(CURLSSLOPT_ALLOW_BEAST);
#endif
#if LIBCURL_VERSION_NUM >= 0x071901 /* Available since 7.25.1 */
REGISTER_CURL_CONSTANT(CURL_REDIR_POST_303);
#endif
#if LIBCURL_VERSION_NUM >= 0x071c00 /* Available since 7.28.0 */
REGISTER_CURL_CONSTANT(CURLSSH_AUTH_AGENT);
#endif
#if LIBCURL_VERSION_NUM >= 0x071e00 /* Available since 7.30.0 */
REGISTER_CURL_CONSTANT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE);
REGISTER_CURL_CONSTANT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE);
REGISTER_CURL_CONSTANT(CURLMOPT_MAX_HOST_CONNECTIONS);
REGISTER_CURL_CONSTANT(CURLMOPT_MAX_PIPELINE_LENGTH);
REGISTER_CURL_CONSTANT(CURLMOPT_MAX_TOTAL_CONNECTIONS);
#endif
#if LIBCURL_VERSION_NUM >= 0x071f00 /* Available since 7.31.0 */
REGISTER_CURL_CONSTANT(CURLOPT_SASL_IR);
#endif
#if LIBCURL_VERSION_NUM >= 0x072100 /* Available since 7.33.0 */
REGISTER_CURL_CONSTANT(CURLOPT_DNS_INTERFACE);
REGISTER_CURL_CONSTANT(CURLOPT_DNS_LOCAL_IP4);
REGISTER_CURL_CONSTANT(CURLOPT_DNS_LOCAL_IP6);
REGISTER_CURL_CONSTANT(CURLOPT_XOAUTH2_BEARER);
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2_0);
REGISTER_CURL_CONSTANT(CURL_VERSION_HTTP2);
#endif
#if LIBCURL_VERSION_NUM >= 0x072200 /* Available since 7.34.0 */
REGISTER_CURL_CONSTANT(CURLOPT_LOGIN_OPTIONS);
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1_0);
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1_1);
REGISTER_CURL_CONSTANT(CURL_SSLVERSION_TLSv1_2);
#endif
#if LIBCURL_VERSION_NUM >= 0x072400 /* Available since 7.36.0 */
REGISTER_CURL_CONSTANT(CURLOPT_EXPECT_100_TIMEOUT_MS);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_ENABLE_ALPN);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_ENABLE_NPN);
#endif
#if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */
REGISTER_CURL_CONSTANT(CURLHEADER_SEPARATE);
REGISTER_CURL_CONSTANT(CURLHEADER_UNIFIED);
REGISTER_CURL_CONSTANT(CURLOPT_HEADEROPT);
REGISTER_CURL_CONSTANT(CURLOPT_PROXYHEADER);
#endif
#if LIBCURL_VERSION_NUM >= 0x072600 /* Available since 7.38.0 */
REGISTER_CURL_CONSTANT(CURLAUTH_NEGOTIATE);
#endif
#if LIBCURL_VERSION_NUM >= 0x072700 /* Available since 7.39.0 */
REGISTER_CURL_CONSTANT(CURLOPT_PINNEDPUBLICKEY);
#endif
#if LIBCURL_VERSION_NUM >= 0x072800 /* Available since 7.40.0 */
REGISTER_CURL_CONSTANT(CURLOPT_UNIX_SOCKET_PATH);
REGISTER_CURL_CONSTANT(CURLPROTO_SMB);
REGISTER_CURL_CONSTANT(CURLPROTO_SMBS);
#endif
#if LIBCURL_VERSION_NUM >= 0x072900 /* Available since 7.41.0 */
REGISTER_CURL_CONSTANT(CURLOPT_SSL_VERIFYSTATUS);
#endif
#if LIBCURL_VERSION_NUM >= 0x072a00 /* Available since 7.42.0 */
REGISTER_CURL_CONSTANT(CURLOPT_PATH_AS_IS);
REGISTER_CURL_CONSTANT(CURLOPT_SSL_FALSESTART);
#endif
#if LIBCURL_VERSION_NUM >= 0x072b00 /* Available since 7.43.0 */
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2);
REGISTER_CURL_CONSTANT(CURLOPT_PIPEWAIT);
REGISTER_CURL_CONSTANT(CURLOPT_PROXY_SERVICE_NAME);
REGISTER_CURL_CONSTANT(CURLOPT_SERVICE_NAME);
REGISTER_CURL_CONSTANT(CURLPIPE_NOTHING);
REGISTER_CURL_CONSTANT(CURLPIPE_HTTP1);
REGISTER_CURL_CONSTANT(CURLPIPE_MULTIPLEX);
#endif
#if LIBCURL_VERSION_NUM >= 0x072c00 /* Available since 7.44.0 */
REGISTER_CURL_CONSTANT(CURLSSLOPT_NO_REVOKE);
#endif
#if LIBCURL_VERSION_NUM >= 0x072d00 /* Available since 7.45.0 */
REGISTER_CURL_CONSTANT(CURLOPT_DEFAULT_PROTOCOL);
#endif
#if LIBCURL_VERSION_NUM >= 0x072e00 /* Available since 7.46.0 */
REGISTER_CURL_CONSTANT(CURLOPT_STREAM_WEIGHT);
#endif
#if LIBCURL_VERSION_NUM >= 0x072f00 /* Available since 7.47.0 */
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2TLS);
#endif
#if LIBCURL_VERSION_NUM >= 0x073000 /* Available since 7.48.0 */
REGISTER_CURL_CONSTANT(CURLOPT_TFTP_NO_OPTIONS);
#endif
#if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */
REGISTER_CURL_CONSTANT(CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE);
REGISTER_CURL_CONSTANT(CURLOPT_CONNECT_TO);
REGISTER_CURL_CONSTANT(CURLOPT_TCP_FASTOPEN);
#endif
#if CURLOPT_FTPASCII != 0
REGISTER_CURL_CONSTANT(CURLOPT_FTPASCII);
#endif
#if CURLOPT_MUTE != 0
REGISTER_CURL_CONSTANT(CURLOPT_MUTE);
#endif
#if CURLOPT_PASSWDFUNCTION != 0
REGISTER_CURL_CONSTANT(CURLOPT_PASSWDFUNCTION);
#endif
REGISTER_CURL_CONSTANT(CURLOPT_SAFE_UPLOAD);
#ifdef PHP_CURL_NEED_OPENSSL_TSL
if (!CRYPTO_get_id_callback()) {
int i, c = CRYPTO_num_locks();
php_curl_openssl_tsl = malloc(c * sizeof(MUTEX_T));
if (!php_curl_openssl_tsl) {
return FAILURE;
}
for (i = 0; i < c; ++i) {
php_curl_openssl_tsl[i] = tsrm_mutex_alloc();
}
CRYPTO_set_id_callback(php_curl_ssl_id);
CRYPTO_set_locking_callback(php_curl_ssl_lock);
}
#endif
#ifdef PHP_CURL_NEED_GNUTLS_TSL
gcry_control(GCRYCTL_SET_THREAD_CBS, &php_curl_gnutls_tsl);
#endif
if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) {
return FAILURE;
}
curlfile_register_class();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(curl)
{
curl_global_cleanup();
#ifdef PHP_CURL_NEED_OPENSSL_TSL
if (php_curl_openssl_tsl) {
int i, c = CRYPTO_num_locks();
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < c; ++i) {
tsrm_mutex_free(php_curl_openssl_tsl[i]);
}
free(php_curl_openssl_tsl);
php_curl_openssl_tsl = NULL;
}
#endif
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ curl_write_nothing
* Used as a work around. See _php_curl_close_ex
*/
static size_t curl_write_nothing(char *data, size_t size, size_t nmemb, void *ctx)
{
return size * nmemb;
}
/* }}} */
/* {{{ curl_write
*/
static size_t curl_write(char *data, size_t size, size_t nmemb, void *ctx)
{
php_curl *ch = (php_curl *) ctx;
php_curl_write *t = ch->handlers->write;
size_t length = size * nmemb;
#if PHP_CURL_DEBUG
fprintf(stderr, "curl_write() called\n");
fprintf(stderr, "data = %s, size = %d, nmemb = %d, ctx = %x\n", data, size, nmemb, ctx);
#endif
switch (t->method) {
case PHP_CURL_STDOUT:
PHPWRITE(data, length);
break;
case PHP_CURL_FILE:
return fwrite(data, size, nmemb, t->fp);
case PHP_CURL_RETURN:
if (length > 0) {
smart_str_appendl(&t->buf, data, (int) length);
}
break;
case PHP_CURL_USER: {
zval argv[2];
zval retval;
int error;
zend_fcall_info fci;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
ZVAL_STRINGL(&argv[1], data, length);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.object = NULL;
ZVAL_COPY_VALUE(&fci.function_name, &t->func_name);
fci.retval = &retval;
fci.param_count = 2;
fci.params = argv;
fci.no_separation = 0;
fci.symbol_table = NULL;
ch->in_callback = 1;
error = zend_call_function(&fci, &t->fci_cache);
ch->in_callback = 0;
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_WRITEFUNCTION");
length = -1;
} else if (!Z_ISUNDEF(retval)) {
_php_curl_verify_handlers(ch, 1);
length = zval_get_long(&retval);
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
break;
}
}
return length;
}
/* }}} */
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
/* {{{ curl_fnmatch
*/
static int curl_fnmatch(void *ctx, const char *pattern, const char *string)
{
php_curl *ch = (php_curl *) ctx;
php_curl_fnmatch *t = ch->handlers->fnmatch;
int rval = CURL_FNMATCHFUNC_FAIL;
switch (t->method) {
case PHP_CURL_USER: {
zval argv[3];
zval retval;
int error;
zend_fcall_info fci;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
ZVAL_STRING(&argv[1], pattern);
ZVAL_STRING(&argv[2], string);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
ZVAL_COPY_VALUE(&fci.function_name, &t->func_name);
fci.object = NULL;
fci.retval = &retval;
fci.param_count = 3;
fci.params = argv;
fci.no_separation = 0;
fci.symbol_table = NULL;
ch->in_callback = 1;
error = zend_call_function(&fci, &t->fci_cache);
ch->in_callback = 0;
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_FNMATCH_FUNCTION");
} else if (!Z_ISUNDEF(retval)) {
_php_curl_verify_handlers(ch, 1);
rval = zval_get_long(&retval);
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
zval_ptr_dtor(&argv[2]);
break;
}
}
return rval;
}
/* }}} */
#endif
/* {{{ curl_progress
*/
static size_t curl_progress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
php_curl *ch = (php_curl *)clientp;
php_curl_progress *t = ch->handlers->progress;
size_t rval = 0;
#if PHP_CURL_DEBUG
fprintf(stderr, "curl_progress() called\n");
fprintf(stderr, "clientp = %x, dltotal = %f, dlnow = %f, ultotal = %f, ulnow = %f\n", clientp, dltotal, dlnow, ultotal, ulnow);
#endif
switch (t->method) {
case PHP_CURL_USER: {
zval argv[5];
zval retval;
int error;
zend_fcall_info fci;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
ZVAL_LONG(&argv[1], (zend_long)dltotal);
ZVAL_LONG(&argv[2], (zend_long)dlnow);
ZVAL_LONG(&argv[3], (zend_long)ultotal);
ZVAL_LONG(&argv[4], (zend_long)ulnow);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
ZVAL_COPY_VALUE(&fci.function_name, &t->func_name);
fci.object = NULL;
fci.retval = &retval;
fci.param_count = 5;
fci.params = argv;
fci.no_separation = 0;
fci.symbol_table = NULL;
ch->in_callback = 1;
error = zend_call_function(&fci, &t->fci_cache);
ch->in_callback = 0;
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_PROGRESSFUNCTION");
} else if (!Z_ISUNDEF(retval)) {
_php_curl_verify_handlers(ch, 1);
if (0 != zval_get_long(&retval)) {
rval = 1;
}
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
zval_ptr_dtor(&argv[2]);
zval_ptr_dtor(&argv[3]);
zval_ptr_dtor(&argv[4]);
break;
}
}
return rval;
}
/* }}} */
/* {{{ curl_read
*/
static size_t curl_read(char *data, size_t size, size_t nmemb, void *ctx)
{
php_curl *ch = (php_curl *)ctx;
php_curl_read *t = ch->handlers->read;
int length = 0;
switch (t->method) {
case PHP_CURL_DIRECT:
if (t->fp) {
length = fread(data, size, nmemb, t->fp);
}
break;
case PHP_CURL_USER: {
zval argv[3];
zval retval;
int error;
zend_fcall_info fci;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
if (t->res) {
ZVAL_RES(&argv[1], t->res);
Z_ADDREF(argv[1]);
} else {
ZVAL_NULL(&argv[1]);
}
ZVAL_LONG(&argv[2], (int)size * nmemb);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
ZVAL_COPY_VALUE(&fci.function_name, &t->func_name);
fci.object = NULL;
fci.retval = &retval;
fci.param_count = 3;
fci.params = argv;
fci.no_separation = 0;
fci.symbol_table = NULL;
ch->in_callback = 1;
error = zend_call_function(&fci, &t->fci_cache);
ch->in_callback = 0;
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_READFUNCTION");
#if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */
length = CURL_READFUNC_ABORT;
#endif
} else if (!Z_ISUNDEF(retval)) {
_php_curl_verify_handlers(ch, 1);
if (Z_TYPE(retval) == IS_STRING) {
length = MIN((int) (size * nmemb), Z_STRLEN(retval));
memcpy(data, Z_STRVAL(retval), length);
}
zval_ptr_dtor(&retval);
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
zval_ptr_dtor(&argv[2]);
break;
}
}
return length;
}
/* }}} */
/* {{{ curl_write_header
*/
static size_t curl_write_header(char *data, size_t size, size_t nmemb, void *ctx)
{
php_curl *ch = (php_curl *) ctx;
php_curl_write *t = ch->handlers->write_header;
size_t length = size * nmemb;
switch (t->method) {
case PHP_CURL_STDOUT:
/* Handle special case write when we're returning the entire transfer
*/
if (ch->handlers->write->method == PHP_CURL_RETURN && length > 0) {
smart_str_appendl(&ch->handlers->write->buf, data, (int) length);
} else {
PHPWRITE(data, length);
}
break;
case PHP_CURL_FILE:
return fwrite(data, size, nmemb, t->fp);
case PHP_CURL_USER: {
zval argv[2];
zval retval;
int error;
zend_fcall_info fci;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
ZVAL_STRINGL(&argv[1], data, length);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
ZVAL_COPY_VALUE(&fci.function_name, &t->func_name);
fci.symbol_table = NULL;
fci.object = NULL;
fci.retval = &retval;
fci.param_count = 2;
fci.params = argv;
fci.no_separation = 0;
ch->in_callback = 1;
error = zend_call_function(&fci, &t->fci_cache);
ch->in_callback = 0;
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_HEADERFUNCTION");
length = -1;
} else if (!Z_ISUNDEF(retval)) {
_php_curl_verify_handlers(ch, 1);
length = zval_get_long(&retval);
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
break;
}
case PHP_CURL_IGNORE:
return length;
default:
return -1;
}
return length;
}
/* }}} */
static int curl_debug(CURL *cp, curl_infotype type, char *buf, size_t buf_len, void *ctx) /* {{{ */
{
php_curl *ch = (php_curl *)ctx;
if (type == CURLINFO_HEADER_OUT) {
if (ch->header.str) {
zend_string_release(ch->header.str);
}
if (buf_len > 0) {
ch->header.str = zend_string_init(buf, buf_len, 0);
}
}
return 0;
}
/* }}} */
#if CURLOPT_PASSWDFUNCTION != 0
/* {{{ curl_passwd
*/
static size_t curl_passwd(void *ctx, char *prompt, char *buf, int buflen)
{
php_curl *ch = (php_curl *) ctx;
zval *func = &ch->handlers->passwd;
zval argv[3];
zval retval;
int error;
int ret = -1;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
ZVAL_STRING(&argv[1], prompt);
ZVAL_LONG(&argv[2], buflen);
error = call_user_function(EG(function_table), NULL, func, &retval, 2, argv);
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_PASSWDFUNCTION");
} else if (Z_TYPE(retval) == IS_STRING) {
if (Z_STRLEN(retval) > buflen) {
php_error_docref(NULL, E_WARNING, "Returned password is too long for libcurl to handle");
} else {
memcpy(buf, Z_STRVAL(retval), Z_STRLEN(retval) + 1);
}
} else {
php_error_docref(NULL, E_WARNING, "User handler '%s' did not return a string", Z_STRVAL_P(func));
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
zval_ptr_dtor(&argv[2]);
zval_ptr_dtor(&retval);
return ret;
}
/* }}} */
#endif
/* {{{ curl_free_string
*/
static void curl_free_string(void **string)
{
efree((char *)*string);
}
/* }}} */
/* {{{ curl_free_post
*/
static void curl_free_post(void **post)
{
curl_formfree((struct HttpPost *)*post);
}
/* }}} */
/* {{{ curl_free_slist
*/
static void curl_free_slist(zval *el)
{
curl_slist_free_all(((struct curl_slist *)Z_PTR_P(el)));
}
/* }}} */
/* {{{ proto array curl_version([int version])
Return cURL version information. */
PHP_FUNCTION(curl_version)
{
curl_version_info_data *d;
zend_long uversion = CURLVERSION_NOW;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &uversion) == FAILURE) {
return;
}
d = curl_version_info(uversion);
if (d == NULL) {
RETURN_FALSE;
}
array_init(return_value);
CAAL("version_number", d->version_num);
CAAL("age", d->age);
CAAL("features", d->features);
CAAL("ssl_version_number", d->ssl_version_num);
CAAS("version", d->version);
CAAS("host", d->host);
CAAS("ssl_version", d->ssl_version);
CAAS("libz_version", d->libz_version);
/* Add an array of protocols */
{
char **p = (char **) d->protocols;
zval protocol_list;
array_init(&protocol_list);
while (*p != NULL) {
add_next_index_string(&protocol_list, *p);
p++;
}
CAAZ("protocols", &protocol_list);
}
}
/* }}} */
/* {{{ alloc_curl_handle
*/
static php_curl *alloc_curl_handle()
{
php_curl *ch = ecalloc(1, sizeof(php_curl));
ch->to_free = ecalloc(1, sizeof(struct _php_curl_free));
ch->handlers = ecalloc(1, sizeof(php_curl_handlers));
ch->handlers->write = ecalloc(1, sizeof(php_curl_write));
ch->handlers->write_header = ecalloc(1, sizeof(php_curl_write));
ch->handlers->read = ecalloc(1, sizeof(php_curl_read));
ch->handlers->progress = NULL;
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
ch->handlers->fnmatch = NULL;
#endif
ch->clone = emalloc(sizeof(uint32_t));
*ch->clone = 1;
memset(&ch->err, 0, sizeof(struct _php_curl_error));
zend_llist_init(&ch->to_free->str, sizeof(char *), (llist_dtor_func_t)curl_free_string, 0);
zend_llist_init(&ch->to_free->post, sizeof(struct HttpPost *), (llist_dtor_func_t)curl_free_post, 0);
ch->to_free->slist = emalloc(sizeof(HashTable));
zend_hash_init(ch->to_free->slist, 4, NULL, curl_free_slist, 0);
return ch;
}
/* }}} */
#if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */
/* {{{ create_certinfo
*/
static void create_certinfo(struct curl_certinfo *ci, zval *listcode)
{
int i;
if (ci) {
zval certhash;
for (i=0; i<ci->num_of_certs; i++) {
struct curl_slist *slist;
array_init(&certhash);
for (slist = ci->certinfo[i]; slist; slist = slist->next) {
int len;
char s[64];
char *tmp;
strncpy(s, slist->data, 64);
tmp = memchr(s, ':', 64);
if(tmp) {
*tmp = '\0';
len = strlen(s);
add_assoc_string(&certhash, s, &slist->data[len+1]);
} else {
php_error_docref(NULL, E_WARNING, "Could not extract hash key from certificate info");
}
}
add_next_index_zval(listcode, &certhash);
}
}
}
/* }}} */
#endif
/* {{{ _php_curl_set_default_options()
Set default options for a handle */
static void _php_curl_set_default_options(php_curl *ch)
{
char *cainfo;
curl_easy_setopt(ch->cp, CURLOPT_NOPROGRESS, 1);
curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 0);
curl_easy_setopt(ch->cp, CURLOPT_ERRORBUFFER, ch->err.str);
curl_easy_setopt(ch->cp, CURLOPT_WRITEFUNCTION, curl_write);
curl_easy_setopt(ch->cp, CURLOPT_FILE, (void *) ch);
curl_easy_setopt(ch->cp, CURLOPT_READFUNCTION, curl_read);
curl_easy_setopt(ch->cp, CURLOPT_INFILE, (void *) ch);
curl_easy_setopt(ch->cp, CURLOPT_HEADERFUNCTION, curl_write_header);
curl_easy_setopt(ch->cp, CURLOPT_WRITEHEADER, (void *) ch);
#if !defined(ZTS)
curl_easy_setopt(ch->cp, CURLOPT_DNS_USE_GLOBAL_CACHE, 1);
#endif
curl_easy_setopt(ch->cp, CURLOPT_DNS_CACHE_TIMEOUT, 120);
curl_easy_setopt(ch->cp, CURLOPT_MAXREDIRS, 20); /* prevent infinite redirects */
cainfo = INI_STR("openssl.cafile");
if (!(cainfo && cainfo[0] != '\0')) {
cainfo = INI_STR("curl.cainfo");
}
if (cainfo && cainfo[0] != '\0') {
curl_easy_setopt(ch->cp, CURLOPT_CAINFO, cainfo);
}
#if defined(ZTS)
curl_easy_setopt(ch->cp, CURLOPT_NOSIGNAL, 1);
#endif
}
/* }}} */
/* {{{ proto resource curl_init([string url])
Initialize a cURL session */
PHP_FUNCTION(curl_init)
{
php_curl *ch;
CURL *cp;
char *url = NULL;
size_t url_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &url, &url_len) == FAILURE) {
return;
}
cp = curl_easy_init();
if (!cp) {
php_error_docref(NULL, E_WARNING, "Could not initialize a new cURL handle");
RETURN_FALSE;
}
ch = alloc_curl_handle();
ch->cp = cp;
ch->handlers->write->method = PHP_CURL_STDOUT;
ch->handlers->read->method = PHP_CURL_DIRECT;
ch->handlers->write_header->method = PHP_CURL_IGNORE;
_php_curl_set_default_options(ch);
if (url) {
if (php_curl_option_url(ch, url, url_len) == FAILURE) {
_php_curl_close_ex(ch);
RETURN_FALSE;
}
}
ZVAL_RES(return_value, zend_register_resource(ch, le_curl));
ch->res = Z_RES_P(return_value);
}
/* }}} */
/* {{{ proto resource curl_copy_handle(resource ch)
Copy a cURL handle along with all of it's preferences */
PHP_FUNCTION(curl_copy_handle)
{
CURL *cp;
zval *zid;
php_curl *ch, *dupch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
cp = curl_easy_duphandle(ch->cp);
if (!cp) {
php_error_docref(NULL, E_WARNING, "Cannot duplicate cURL handle");
RETURN_FALSE;
}
dupch = alloc_curl_handle();
dupch->cp = cp;
Z_ADDREF_P(zid);
if (!Z_ISUNDEF(ch->handlers->write->stream)) {
Z_ADDREF(ch->handlers->write->stream);
}
dupch->handlers->write->stream = ch->handlers->write->stream;
dupch->handlers->write->method = ch->handlers->write->method;
if (!Z_ISUNDEF(ch->handlers->read->stream)) {
Z_ADDREF(ch->handlers->read->stream);
}
dupch->handlers->read->stream = ch->handlers->read->stream;
dupch->handlers->read->method = ch->handlers->read->method;
dupch->handlers->write_header->method = ch->handlers->write_header->method;
if (!Z_ISUNDEF(ch->handlers->write_header->stream)) {
Z_ADDREF(ch->handlers->write_header->stream);
}
dupch->handlers->write_header->stream = ch->handlers->write_header->stream;
dupch->handlers->write->fp = ch->handlers->write->fp;
dupch->handlers->write_header->fp = ch->handlers->write_header->fp;
dupch->handlers->read->fp = ch->handlers->read->fp;
dupch->handlers->read->res = ch->handlers->read->res;
#if CURLOPT_PASSWDDATA != 0
if (!Z_ISUNDEF(ch->handlers->passwd)) {
ZVAL_COPY(&dupch->handlers->passwd, &ch->handlers->passwd);
curl_easy_setopt(ch->cp, CURLOPT_PASSWDDATA, (void *) dupch);
}
#endif
if (!Z_ISUNDEF(ch->handlers->write->func_name)) {
ZVAL_COPY(&dupch->handlers->write->func_name, &ch->handlers->write->func_name);
}
if (!Z_ISUNDEF(ch->handlers->read->func_name)) {
ZVAL_COPY(&dupch->handlers->read->func_name, &ch->handlers->read->func_name);
}
if (!Z_ISUNDEF(ch->handlers->write_header->func_name)) {
ZVAL_COPY(&dupch->handlers->write_header->func_name, &ch->handlers->write_header->func_name);
}
curl_easy_setopt(dupch->cp, CURLOPT_ERRORBUFFER, dupch->err.str);
curl_easy_setopt(dupch->cp, CURLOPT_FILE, (void *) dupch);
curl_easy_setopt(dupch->cp, CURLOPT_INFILE, (void *) dupch);
curl_easy_setopt(dupch->cp, CURLOPT_WRITEHEADER, (void *) dupch);
if (ch->handlers->progress) {
dupch->handlers->progress = ecalloc(1, sizeof(php_curl_progress));
if (!Z_ISUNDEF(ch->handlers->progress->func_name)) {
ZVAL_COPY(&dupch->handlers->progress->func_name, &ch->handlers->progress->func_name);
}
dupch->handlers->progress->method = ch->handlers->progress->method;
curl_easy_setopt(dupch->cp, CURLOPT_PROGRESSDATA, (void *) dupch);
}
/* Available since 7.21.0 */
#if LIBCURL_VERSION_NUM >= 0x071500
if (ch->handlers->fnmatch) {
dupch->handlers->fnmatch = ecalloc(1, sizeof(php_curl_fnmatch));
if (!Z_ISUNDEF(ch->handlers->fnmatch->func_name)) {
ZVAL_COPY(&dupch->handlers->fnmatch->func_name, &ch->handlers->fnmatch->func_name);
}
dupch->handlers->fnmatch->method = ch->handlers->fnmatch->method;
curl_easy_setopt(dupch->cp, CURLOPT_FNMATCH_DATA, (void *) dupch);
}
#endif
efree(dupch->to_free->slist);
efree(dupch->to_free);
dupch->to_free = ch->to_free;
efree(dupch->clone);
dupch->clone = ch->clone;
/* Keep track of cloned copies to avoid invoking curl destructors for every clone */
(*ch->clone)++;
ZVAL_RES(return_value, zend_register_resource(dupch, le_curl));
dupch->res = Z_RES_P(return_value);
}
/* }}} */
static int _php_curl_setopt(php_curl *ch, zend_long option, zval *zvalue) /* {{{ */
{
CURLcode error = CURLE_OK;
zend_long lval;
ZVAL_DEREF(zvalue);
switch (option) {
/* Long options */
case CURLOPT_SSL_VERIFYHOST:
lval = zval_get_long(zvalue);
if (lval == 1) {
#if LIBCURL_VERSION_NUM <= 0x071c00 /* 7.28.0 */
php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST with value 1 is deprecated and will be removed as of libcurl 7.28.1. It is recommended to use value 2 instead");
#else
php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST no longer accepts the value 1, value 2 will be used instead");
error = curl_easy_setopt(ch->cp, option, 2);
break;
#endif
}
case CURLOPT_AUTOREFERER:
case CURLOPT_BUFFERSIZE:
case CURLOPT_CONNECTTIMEOUT:
case CURLOPT_COOKIESESSION:
case CURLOPT_CRLF:
case CURLOPT_DNS_CACHE_TIMEOUT:
case CURLOPT_DNS_USE_GLOBAL_CACHE:
case CURLOPT_FAILONERROR:
case CURLOPT_FILETIME:
case CURLOPT_FORBID_REUSE:
case CURLOPT_FRESH_CONNECT:
case CURLOPT_FTP_USE_EPRT:
case CURLOPT_FTP_USE_EPSV:
case CURLOPT_HEADER:
case CURLOPT_HTTPGET:
case CURLOPT_HTTPPROXYTUNNEL:
case CURLOPT_HTTP_VERSION:
case CURLOPT_INFILESIZE:
case CURLOPT_LOW_SPEED_LIMIT:
case CURLOPT_LOW_SPEED_TIME:
case CURLOPT_MAXCONNECTS:
case CURLOPT_MAXREDIRS:
case CURLOPT_NETRC:
case CURLOPT_NOBODY:
case CURLOPT_NOPROGRESS:
case CURLOPT_NOSIGNAL:
case CURLOPT_PORT:
case CURLOPT_POST:
case CURLOPT_PROXYPORT:
case CURLOPT_PROXYTYPE:
case CURLOPT_PUT:
case CURLOPT_RESUME_FROM:
case CURLOPT_SSLVERSION:
case CURLOPT_SSL_VERIFYPEER:
case CURLOPT_TIMECONDITION:
case CURLOPT_TIMEOUT:
case CURLOPT_TIMEVALUE:
case CURLOPT_TRANSFERTEXT:
case CURLOPT_UNRESTRICTED_AUTH:
case CURLOPT_UPLOAD:
case CURLOPT_VERBOSE:
#if LIBCURL_VERSION_NUM >= 0x070a06 /* Available since 7.10.6 */
case CURLOPT_HTTPAUTH:
#endif
#if LIBCURL_VERSION_NUM >= 0x070a07 /* Available since 7.10.7 */
case CURLOPT_FTP_CREATE_MISSING_DIRS:
case CURLOPT_PROXYAUTH:
#endif
#if LIBCURL_VERSION_NUM >= 0x070a08 /* Available since 7.10.8 */
case CURLOPT_FTP_RESPONSE_TIMEOUT:
case CURLOPT_IPRESOLVE:
case CURLOPT_MAXFILESIZE:
#endif
#if LIBCURL_VERSION_NUM >= 0x070b02 /* Available since 7.11.2 */
case CURLOPT_TCP_NODELAY:
#endif
#if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */
case CURLOPT_FTPSSLAUTH:
#endif
#if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */
case CURLOPT_IGNORE_CONTENT_LENGTH:
#endif
#if LIBCURL_VERSION_NUM >= 0x070f00 /* Available since 7.15.0 */
case CURLOPT_FTP_SKIP_PASV_IP:
#endif
#if LIBCURL_VERSION_NUM >= 0x070f01 /* Available since 7.15.1 */
case CURLOPT_FTP_FILEMETHOD:
#endif
#if LIBCURL_VERSION_NUM >= 0x070f02 /* Available since 7.15.2 */
case CURLOPT_CONNECT_ONLY:
case CURLOPT_LOCALPORT:
case CURLOPT_LOCALPORTRANGE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071000 /* Available since 7.16.0 */
case CURLOPT_SSL_SESSIONID_CACHE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */
case CURLOPT_FTP_SSL_CCC:
case CURLOPT_SSH_AUTH_TYPES:
#endif
#if LIBCURL_VERSION_NUM >= 0x071002 /* Available since 7.16.2 */
case CURLOPT_CONNECTTIMEOUT_MS:
case CURLOPT_HTTP_CONTENT_DECODING:
case CURLOPT_HTTP_TRANSFER_DECODING:
case CURLOPT_TIMEOUT_MS:
#endif
#if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */
case CURLOPT_NEW_DIRECTORY_PERMS:
case CURLOPT_NEW_FILE_PERMS:
#endif
#if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */
case CURLOPT_USE_SSL:
#elif LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */
case CURLOPT_FTP_SSL:
#endif
#if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */
case CURLOPT_APPEND:
case CURLOPT_DIRLISTONLY:
#else
case CURLOPT_FTPAPPEND:
case CURLOPT_FTPLISTONLY:
#endif
#if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */
case CURLOPT_PROXY_TRANSFER_MODE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */
case CURLOPT_ADDRESS_SCOPE:
#endif
#if LIBCURL_VERSION_NUM > 0x071301 /* Available since 7.19.1 */
case CURLOPT_CERTINFO:
#endif
#if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */
case CURLOPT_PROTOCOLS:
case CURLOPT_REDIR_PROTOCOLS:
case CURLOPT_SOCKS5_GSSAPI_NEC:
case CURLOPT_TFTP_BLKSIZE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */
case CURLOPT_FTP_USE_PRET:
case CURLOPT_RTSP_CLIENT_CSEQ:
case CURLOPT_RTSP_REQUEST:
case CURLOPT_RTSP_SERVER_CSEQ:
#endif
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
case CURLOPT_WILDCARDMATCH:
#endif
#if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */
case CURLOPT_TLSAUTH_TYPE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071600 /* Available since 7.22.0 */
case CURLOPT_GSSAPI_DELEGATION:
#endif
#if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */
case CURLOPT_ACCEPTTIMEOUT_MS:
#endif
#if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */
case CURLOPT_SSL_OPTIONS:
case CURLOPT_TCP_KEEPALIVE:
case CURLOPT_TCP_KEEPIDLE:
case CURLOPT_TCP_KEEPINTVL:
#endif
#if LIBCURL_VERSION_NUM >= 0x071f00 /* Available since 7.31.0 */
case CURLOPT_SASL_IR:
#endif
#if LIBCURL_VERSION_NUM >= 0x072400 /* Available since 7.36.0 */
case CURLOPT_EXPECT_100_TIMEOUT_MS:
case CURLOPT_SSL_ENABLE_ALPN:
case CURLOPT_SSL_ENABLE_NPN:
#endif
#if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */
case CURLOPT_HEADEROPT:
#endif
#if LIBCURL_VERSION_NUM >= 0x072900 /* Available since 7.41.0 */
case CURLOPT_SSL_VERIFYSTATUS:
#endif
#if LIBCURL_VERSION_NUM >= 0x072a00 /* Available since 7.42.0 */
case CURLOPT_PATH_AS_IS:
case CURLOPT_SSL_FALSESTART:
#endif
#if LIBCURL_VERSION_NUM >= 0x072b00 /* Available since 7.43.0 */
case CURLOPT_PIPEWAIT:
#endif
#if LIBCURL_VERSION_NUM >= 0x072e00 /* Available since 7.46.0 */
case CURLOPT_STREAM_WEIGHT:
#endif
#if LIBCURL_VERSION_NUM >= 0x073000 /* Available since 7.48.0 */
case CURLOPT_TFTP_NO_OPTIONS:
#endif
#if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */
case CURLOPT_TCP_FASTOPEN:
#endif
#if CURLOPT_MUTE != 0
case CURLOPT_MUTE:
#endif
lval = zval_get_long(zvalue);
#if LIBCURL_VERSION_NUM >= 0x71304
if ((option == CURLOPT_PROTOCOLS || option == CURLOPT_REDIR_PROTOCOLS) &&
(PG(open_basedir) && *PG(open_basedir)) && (lval & CURLPROTO_FILE)) {
php_error_docref(NULL, E_WARNING, "CURLPROTO_FILE cannot be activated when an open_basedir is set");
return 1;
}
#endif
# if defined(ZTS)
if (option == CURLOPT_DNS_USE_GLOBAL_CACHE) {
php_error_docref(NULL, E_WARNING, "CURLOPT_DNS_USE_GLOBAL_CACHE cannot be activated when thread safety is enabled");
return 1;
}
# endif
error = curl_easy_setopt(ch->cp, option, lval);
break;
case CURLOPT_SAFE_UPLOAD:
lval = zval_get_long(zvalue);
if (lval == 0) {
php_error_docref(NULL, E_WARNING, "Disabling safe uploads is no longer supported");
return FAILURE;
}
break;
/* String options */
case CURLOPT_CAINFO:
case CURLOPT_CAPATH:
case CURLOPT_COOKIE:
case CURLOPT_EGDSOCKET:
case CURLOPT_INTERFACE:
case CURLOPT_PROXY:
case CURLOPT_PROXYUSERPWD:
case CURLOPT_REFERER:
case CURLOPT_SSLCERTTYPE:
case CURLOPT_SSLENGINE:
case CURLOPT_SSLENGINE_DEFAULT:
case CURLOPT_SSLKEY:
case CURLOPT_SSLKEYPASSWD:
case CURLOPT_SSLKEYTYPE:
case CURLOPT_SSL_CIPHER_LIST:
case CURLOPT_USERAGENT:
case CURLOPT_USERPWD:
#if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */
case CURLOPT_COOKIELIST:
#endif
#if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */
case CURLOPT_FTP_ALTERNATIVE_TO_USER:
#endif
#if LIBCURL_VERSION_NUM >= 0x071101 /* Available since 7.17.1 */
case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
#endif
#if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */
case CURLOPT_PASSWORD:
case CURLOPT_PROXYPASSWORD:
case CURLOPT_PROXYUSERNAME:
case CURLOPT_USERNAME:
#endif
#if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */
case CURLOPT_NOPROXY:
case CURLOPT_SOCKS5_GSSAPI_SERVICE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */
case CURLOPT_MAIL_FROM:
case CURLOPT_RTSP_STREAM_URI:
case CURLOPT_RTSP_TRANSPORT:
#endif
#if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */
case CURLOPT_TLSAUTH_PASSWORD:
case CURLOPT_TLSAUTH_USERNAME:
#endif
#if LIBCURL_VERSION_NUM >= 0x071506 /* Available since 7.21.6 */
case CURLOPT_ACCEPT_ENCODING:
case CURLOPT_TRANSFER_ENCODING:
#else
case CURLOPT_ENCODING:
#endif
#if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */
case CURLOPT_DNS_SERVERS:
#endif
#if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */
case CURLOPT_MAIL_AUTH:
#endif
#if LIBCURL_VERSION_NUM >= 0x072200 /* Available since 7.34.0 */
case CURLOPT_LOGIN_OPTIONS:
#endif
#if LIBCURL_VERSION_NUM >= 0x072700 /* Available since 7.39.0 */
case CURLOPT_PINNEDPUBLICKEY:
#endif
#if LIBCURL_VERSION_NUM >= 0x072b00 /* Available since 7.43.0 */
case CURLOPT_PROXY_SERVICE_NAME:
case CURLOPT_SERVICE_NAME:
#endif
#if LIBCURL_VERSION_NUM >= 0x072d00 /* Available since 7.45.0 */
case CURLOPT_DEFAULT_PROTOCOL:
#endif
{
zend_string *str = zval_get_string(zvalue);
int ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 0);
zend_string_release(str);
return ret;
}
/* Curl nullable string options */
case CURLOPT_CUSTOMREQUEST:
case CURLOPT_FTPPORT:
case CURLOPT_RANGE:
#if LIBCURL_VERSION_NUM >= 0x070d00 /* Available since 7.13.0 */
case CURLOPT_FTP_ACCOUNT:
#endif
#if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */
case CURLOPT_RTSP_SESSION_ID:
#endif
#if LIBCURL_VERSION_NUM >= 0x072100 /* Available since 7.33.0 */
case CURLOPT_DNS_INTERFACE:
case CURLOPT_DNS_LOCAL_IP4:
case CURLOPT_DNS_LOCAL_IP6:
case CURLOPT_XOAUTH2_BEARER:
#endif
#if LIBCURL_VERSION_NUM >= 0x072800 /* Available since 7.40.0 */
case CURLOPT_UNIX_SOCKET_PATH:
#endif
#if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */
case CURLOPT_KRBLEVEL:
#else
case CURLOPT_KRB4LEVEL:
#endif
{
if (Z_ISNULL_P(zvalue)) {
error = curl_easy_setopt(ch->cp, option, NULL);
} else {
zend_string *str = zval_get_string(zvalue);
int ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 0);
zend_string_release(str);
return ret;
}
break;
}
/* Curl private option */
case CURLOPT_PRIVATE:
{
zend_string *str = zval_get_string(zvalue);
int ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 1);
zend_string_release(str);
return ret;
}
/* Curl url option */
case CURLOPT_URL:
{
zend_string *str = zval_get_string(zvalue);
int ret = php_curl_option_url(ch, ZSTR_VAL(str), ZSTR_LEN(str));
zend_string_release(str);
return ret;
}
/* Curl file handle options */
case CURLOPT_FILE:
case CURLOPT_INFILE:
case CURLOPT_STDERR:
case CURLOPT_WRITEHEADER: {
FILE *fp = NULL;
php_stream *what = NULL;
if (Z_TYPE_P(zvalue) != IS_NULL) {
what = (php_stream *)zend_fetch_resource2_ex(zvalue, "File-Handle", php_file_le_stream(), php_file_le_pstream());
if (!what) {
return FAILURE;
}
if (FAILURE == php_stream_cast(what, PHP_STREAM_AS_STDIO, (void *) &fp, REPORT_ERRORS)) {
return FAILURE;
}
if (!fp) {
return FAILURE;
}
}
error = CURLE_OK;
switch (option) {
case CURLOPT_FILE:
if (!what) {
if (!Z_ISUNDEF(ch->handlers->write->stream)) {
zval_ptr_dtor(&ch->handlers->write->stream);
ZVAL_UNDEF(&ch->handlers->write->stream);
}
ch->handlers->write->fp = NULL;
ch->handlers->write->method = PHP_CURL_STDOUT;
} else if (what->mode[0] != 'r' || what->mode[1] == '+') {
zval_ptr_dtor(&ch->handlers->write->stream);
ch->handlers->write->fp = fp;
ch->handlers->write->method = PHP_CURL_FILE;
ZVAL_COPY(&ch->handlers->write->stream, zvalue);
} else {
php_error_docref(NULL, E_WARNING, "the provided file handle is not writable");
return FAILURE;
}
break;
case CURLOPT_WRITEHEADER:
if (!what) {
if (!Z_ISUNDEF(ch->handlers->write_header->stream)) {
zval_ptr_dtor(&ch->handlers->write_header->stream);
ZVAL_UNDEF(&ch->handlers->write_header->stream);
}
ch->handlers->write_header->fp = NULL;
ch->handlers->write_header->method = PHP_CURL_IGNORE;
} else if (what->mode[0] != 'r' || what->mode[1] == '+') {
zval_ptr_dtor(&ch->handlers->write_header->stream);
ch->handlers->write_header->fp = fp;
ch->handlers->write_header->method = PHP_CURL_FILE;
ZVAL_COPY(&ch->handlers->write_header->stream, zvalue);;
} else {
php_error_docref(NULL, E_WARNING, "the provided file handle is not writable");
return FAILURE;
}
break;
case CURLOPT_INFILE:
if (!what) {
if (!Z_ISUNDEF(ch->handlers->read->stream)) {
zval_ptr_dtor(&ch->handlers->read->stream);
ZVAL_UNDEF(&ch->handlers->read->stream);
}
ch->handlers->read->fp = NULL;
ch->handlers->read->res = NULL;
} else {
zval_ptr_dtor(&ch->handlers->read->stream);
ch->handlers->read->fp = fp;
ch->handlers->read->res = Z_RES_P(zvalue);
ZVAL_COPY(&ch->handlers->read->stream, zvalue);
}
break;
case CURLOPT_STDERR:
if (!what) {
if (!Z_ISUNDEF(ch->handlers->std_err)) {
zval_ptr_dtor(&ch->handlers->std_err);
ZVAL_UNDEF(&ch->handlers->std_err);
}
} else if (what->mode[0] != 'r' || what->mode[1] == '+') {
zval_ptr_dtor(&ch->handlers->std_err);
ZVAL_COPY(&ch->handlers->std_err, zvalue);
} else {
php_error_docref(NULL, E_WARNING, "the provided file handle is not writable");
return FAILURE;
}
/* break omitted intentionally */
default:
error = curl_easy_setopt(ch->cp, option, fp);
break;
}
break;
}
/* Curl linked list options */
case CURLOPT_HTTP200ALIASES:
case CURLOPT_HTTPHEADER:
case CURLOPT_POSTQUOTE:
case CURLOPT_PREQUOTE:
case CURLOPT_QUOTE:
case CURLOPT_TELNETOPTIONS:
#if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */
case CURLOPT_MAIL_RCPT:
#endif
#if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */
case CURLOPT_RESOLVE:
#endif
#if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */
case CURLOPT_PROXYHEADER:
#endif
#if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */
case CURLOPT_CONNECT_TO:
#endif
{
zval *current;
HashTable *ph;
zend_string *val;
struct curl_slist *slist = NULL;
ph = HASH_OF(zvalue);
if (!ph) {
char *name = NULL;
switch (option) {
case CURLOPT_HTTPHEADER:
name = "CURLOPT_HTTPHEADER";
break;
case CURLOPT_QUOTE:
name = "CURLOPT_QUOTE";
break;
case CURLOPT_HTTP200ALIASES:
name = "CURLOPT_HTTP200ALIASES";
break;
case CURLOPT_POSTQUOTE:
name = "CURLOPT_POSTQUOTE";
break;
case CURLOPT_PREQUOTE:
name = "CURLOPT_PREQUOTE";
break;
case CURLOPT_TELNETOPTIONS:
name = "CURLOPT_TELNETOPTIONS";
break;
#if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */
case CURLOPT_MAIL_RCPT:
name = "CURLOPT_MAIL_RCPT";
break;
#endif
#if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */
case CURLOPT_RESOLVE:
name = "CURLOPT_RESOLVE";
break;
#endif
#if LIBCURL_VERSION_NUM >= 0x072500 /* Available since 7.37.0 */
case CURLOPT_PROXYHEADER:
name = "CURLOPT_PROXYHEADER";
break;
#endif
#if LIBCURL_VERSION_NUM >= 0x073100 /* Available since 7.49.0 */
case CURLOPT_CONNECT_TO:
name = "CURLOPT_CONNECT_TO";
break;
#endif
}
php_error_docref(NULL, E_WARNING, "You must pass either an object or an array with the %s argument", name);
return FAILURE;
}
ZEND_HASH_FOREACH_VAL(ph, current) {
ZVAL_DEREF(current);
val = zval_get_string(current);
slist = curl_slist_append(slist, ZSTR_VAL(val));
zend_string_release(val);
if (!slist) {
php_error_docref(NULL, E_WARNING, "Could not build curl_slist");
return 1;
}
} ZEND_HASH_FOREACH_END();
if (slist) {
if ((*ch->clone) == 1) {
zend_hash_index_update_ptr(ch->to_free->slist, option, slist);
} else {
zend_hash_next_index_insert_ptr(ch->to_free->slist, slist);
}
}
error = curl_easy_setopt(ch->cp, option, slist);
break;
}
case CURLOPT_BINARYTRANSFER:
/* Do nothing, just backward compatibility */
break;
case CURLOPT_FOLLOWLOCATION:
lval = zval_get_long(zvalue);
#if LIBCURL_VERSION_NUM < 0x071304
if (PG(open_basedir) && *PG(open_basedir)) {
if (lval != 0) {
php_error_docref(NULL, E_WARNING, "CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set");
return FAILURE;
}
}
#endif
error = curl_easy_setopt(ch->cp, option, lval);
break;
case CURLOPT_HEADERFUNCTION:
if (!Z_ISUNDEF(ch->handlers->write_header->func_name)) {
zval_ptr_dtor(&ch->handlers->write_header->func_name);
ch->handlers->write_header->fci_cache = empty_fcall_info_cache;
}
ZVAL_COPY(&ch->handlers->write_header->func_name, zvalue);
ch->handlers->write_header->method = PHP_CURL_USER;
break;
case CURLOPT_POSTFIELDS:
if (Z_TYPE_P(zvalue) == IS_ARRAY || Z_TYPE_P(zvalue) == IS_OBJECT) {
zval *current;
HashTable *postfields;
zend_string *string_key;
zend_ulong num_key;
struct HttpPost *first = NULL;
struct HttpPost *last = NULL;
CURLFORMcode form_error;
postfields = HASH_OF(zvalue);
if (!postfields) {
php_error_docref(NULL, E_WARNING, "Couldn't get HashTable in CURLOPT_POSTFIELDS");
return FAILURE;
}
ZEND_HASH_FOREACH_KEY_VAL(postfields, num_key, string_key, current) {
zend_string *postval;
/* Pretend we have a string_key here */
if (!string_key) {
string_key = zend_long_to_str(num_key);
} else {
zend_string_addref(string_key);
}
ZVAL_DEREF(current);
if (Z_TYPE_P(current) == IS_OBJECT &&
instanceof_function(Z_OBJCE_P(current), curl_CURLFile_class)) {
/* new-style file upload */
zval *prop, rv;
char *type = NULL, *filename = NULL;
prop = zend_read_property(curl_CURLFile_class, current, "name", sizeof("name")-1, 0, &rv);
if (Z_TYPE_P(prop) != IS_STRING) {
php_error_docref(NULL, E_WARNING, "Invalid filename for key %s", ZSTR_VAL(string_key));
} else {
postval = Z_STR_P(prop);
if (php_check_open_basedir(ZSTR_VAL(postval))) {
return 1;
}
prop = zend_read_property(curl_CURLFile_class, current, "mime", sizeof("mime")-1, 0, &rv);
if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) {
type = Z_STRVAL_P(prop);
}
prop = zend_read_property(curl_CURLFile_class, current, "postname", sizeof("postname")-1, 0, &rv);
if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) {
filename = Z_STRVAL_P(prop);
}
form_error = curl_formadd(&first, &last,
CURLFORM_COPYNAME, ZSTR_VAL(string_key),
CURLFORM_NAMELENGTH, ZSTR_LEN(string_key),
CURLFORM_FILENAME, filename ? filename : ZSTR_VAL(postval),
CURLFORM_CONTENTTYPE, type ? type : "application/octet-stream",
CURLFORM_FILE, ZSTR_VAL(postval),
CURLFORM_END);
if (form_error != CURL_FORMADD_OK) {
/* Not nice to convert between enums but we only have place for one error type */
error = (CURLcode)form_error;
}
}
zend_string_release(string_key);
continue;
}
postval = zval_get_string(current);
/* The arguments after _NAMELENGTH and _CONTENTSLENGTH
* must be explicitly cast to long in curl_formadd
* use since curl needs a long not an int. */
form_error = curl_formadd(&first, &last,
CURLFORM_COPYNAME, ZSTR_VAL(string_key),
CURLFORM_NAMELENGTH, ZSTR_LEN(string_key),
CURLFORM_COPYCONTENTS, ZSTR_VAL(postval),
CURLFORM_CONTENTSLENGTH, ZSTR_LEN(postval),
CURLFORM_END);
if (form_error != CURL_FORMADD_OK) {
/* Not nice to convert between enums but we only have place for one error type */
error = (CURLcode)form_error;
}
zend_string_release(postval);
zend_string_release(string_key);
} ZEND_HASH_FOREACH_END();
SAVE_CURL_ERROR(ch, error);
if (error != CURLE_OK) {
return FAILURE;
}
if ((*ch->clone) == 1) {
zend_llist_clean(&ch->to_free->post);
}
zend_llist_add_element(&ch->to_free->post, &first);
error = curl_easy_setopt(ch->cp, CURLOPT_HTTPPOST, first);
} else {
#if LIBCURL_VERSION_NUM >= 0x071101
zend_string *str = zval_get_string(zvalue);
/* with curl 7.17.0 and later, we can use COPYPOSTFIELDS, but we have to provide size before */
error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, ZSTR_LEN(str));
error = curl_easy_setopt(ch->cp, CURLOPT_COPYPOSTFIELDS, ZSTR_VAL(str));
zend_string_release(str);
#else
char *post = NULL;
zend_string *str = zval_get_string(zvalue);
post = estrndup(ZSTR_VAL(str), ZSTR_LEN(str));
zend_llist_add_element(&ch->to_free->str, &post);
curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDS, post);
error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, ZSTR_LEN(str));
zend_string_release(str);
#endif
}
break;
case CURLOPT_PROGRESSFUNCTION:
curl_easy_setopt(ch->cp, CURLOPT_PROGRESSFUNCTION, curl_progress);
curl_easy_setopt(ch->cp, CURLOPT_PROGRESSDATA, ch);
if (ch->handlers->progress == NULL) {
ch->handlers->progress = ecalloc(1, sizeof(php_curl_progress));
} else if (!Z_ISUNDEF(ch->handlers->progress->func_name)) {
zval_ptr_dtor(&ch->handlers->progress->func_name);
ch->handlers->progress->fci_cache = empty_fcall_info_cache;
}
ZVAL_COPY(&ch->handlers->progress->func_name, zvalue);
ch->handlers->progress->method = PHP_CURL_USER;
break;
case CURLOPT_READFUNCTION:
if (!Z_ISUNDEF(ch->handlers->read->func_name)) {
zval_ptr_dtor(&ch->handlers->read->func_name);
ch->handlers->read->fci_cache = empty_fcall_info_cache;
}
ZVAL_COPY(&ch->handlers->read->func_name, zvalue);
ch->handlers->read->method = PHP_CURL_USER;
break;
case CURLOPT_RETURNTRANSFER:
lval = zval_get_long(zvalue);
if (lval) {
ch->handlers->write->method = PHP_CURL_RETURN;
} else {
ch->handlers->write->method = PHP_CURL_STDOUT;
}
break;
case CURLOPT_WRITEFUNCTION:
if (!Z_ISUNDEF(ch->handlers->write->func_name)) {
zval_ptr_dtor(&ch->handlers->write->func_name);
ch->handlers->write->fci_cache = empty_fcall_info_cache;
}
ZVAL_COPY(&ch->handlers->write->func_name, zvalue);
ch->handlers->write->method = PHP_CURL_USER;
break;
#if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */
case CURLOPT_MAX_RECV_SPEED_LARGE:
case CURLOPT_MAX_SEND_SPEED_LARGE:
lval = zval_get_long(zvalue);
error = curl_easy_setopt(ch->cp, option, (curl_off_t)lval);
break;
#endif
#if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */
case CURLOPT_POSTREDIR:
lval = zval_get_long(zvalue);
error = curl_easy_setopt(ch->cp, CURLOPT_POSTREDIR, lval & CURL_REDIR_POST_ALL);
break;
#endif
#if CURLOPT_PASSWDFUNCTION != 0
case CURLOPT_PASSWDFUNCTION:
zval_ptr_dtor(&ch->handlers->passwd);
ZVAL_COPY(&ch->handlers->passwd, zvalue);
error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDFUNCTION, curl_passwd);
error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDDATA, (void *) ch);
break;
#endif
/* the following options deal with files, therefore the open_basedir check
* is required.
*/
case CURLOPT_COOKIEFILE:
case CURLOPT_COOKIEJAR:
case CURLOPT_RANDOM_FILE:
case CURLOPT_SSLCERT:
#if LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */
case CURLOPT_NETRC_FILE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */
case CURLOPT_SSH_PRIVATE_KEYFILE:
case CURLOPT_SSH_PUBLIC_KEYFILE:
#endif
#if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */
case CURLOPT_CRLFILE:
case CURLOPT_ISSUERCERT:
#endif
#if LIBCURL_VERSION_NUM >= 0x071306 /* Available since 7.19.6 */
case CURLOPT_SSH_KNOWNHOSTS:
#endif
{
zend_string *str = zval_get_string(zvalue);
int ret;
if (ZSTR_LEN(str) && php_check_open_basedir(ZSTR_VAL(str))) {
zend_string_release(str);
return FAILURE;
}
ret = php_curl_option_str(ch, option, ZSTR_VAL(str), ZSTR_LEN(str), 0);
zend_string_release(str);
return ret;
}
case CURLINFO_HEADER_OUT:
lval = zval_get_long(zvalue);
if (lval == 1) {
curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, curl_debug);
curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, (void *)ch);
curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 1);
} else {
curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, NULL);
curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, NULL);
curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 0);
}
break;
case CURLOPT_SHARE:
{
php_curlsh *sh;
if ((sh = (php_curlsh *)zend_fetch_resource_ex(zvalue, le_curl_share_handle_name, le_curl_share_handle))) {
curl_easy_setopt(ch->cp, CURLOPT_SHARE, sh->share);
}
}
break;
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
case CURLOPT_FNMATCH_FUNCTION:
curl_easy_setopt(ch->cp, CURLOPT_FNMATCH_FUNCTION, curl_fnmatch);
curl_easy_setopt(ch->cp, CURLOPT_FNMATCH_DATA, ch);
if (ch->handlers->fnmatch == NULL) {
ch->handlers->fnmatch = ecalloc(1, sizeof(php_curl_fnmatch));
} else if (!Z_ISUNDEF(ch->handlers->fnmatch->func_name)) {
zval_ptr_dtor(&ch->handlers->fnmatch->func_name);
ch->handlers->fnmatch->fci_cache = empty_fcall_info_cache;
}
ZVAL_COPY(&ch->handlers->fnmatch->func_name, zvalue);
ch->handlers->fnmatch->method = PHP_CURL_USER;
break;
#endif
}
SAVE_CURL_ERROR(ch, error);
if (error != CURLE_OK) {
return FAILURE;
} else {
return SUCCESS;
}
}
/* }}} */
/* {{{ proto bool curl_setopt(resource ch, int option, mixed value)
Set an option for a cURL transfer */
PHP_FUNCTION(curl_setopt)
{
zval *zid, *zvalue;
zend_long options;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlz", &zid, &options, &zvalue) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if (options <= 0 && options != CURLOPT_SAFE_UPLOAD) {
php_error_docref(NULL, E_WARNING, "Invalid curl configuration option");
RETURN_FALSE;
}
if (_php_curl_setopt(ch, options, zvalue) == SUCCESS) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto bool curl_setopt_array(resource ch, array options)
Set an array of option for a cURL transfer */
PHP_FUNCTION(curl_setopt_array)
{
zval *zid, *arr, *entry;
php_curl *ch;
zend_ulong option;
zend_string *string_key;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ra", &zid, &arr) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(arr), option, string_key, entry) {
if (string_key) {
php_error_docref(NULL, E_WARNING,
"Array keys must be CURLOPT constants or equivalent integer values");
RETURN_FALSE;
}
if (_php_curl_setopt(ch, (zend_long) option, entry) == FAILURE) {
RETURN_FALSE;
}
} ZEND_HASH_FOREACH_END();
RETURN_TRUE;
}
/* }}} */
/* {{{ _php_curl_cleanup_handle(ch)
Cleanup an execution phase */
void _php_curl_cleanup_handle(php_curl *ch)
{
smart_str_free(&ch->handlers->write->buf);
if (ch->header.str) {
zend_string_release(ch->header.str);
ch->header.str = NULL;
}
memset(ch->err.str, 0, CURL_ERROR_SIZE + 1);
ch->err.no = 0;
}
/* }}} */
/* {{{ proto bool curl_exec(resource ch)
Perform a cURL session */
PHP_FUNCTION(curl_exec)
{
CURLcode error;
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
_php_curl_verify_handlers(ch, 1);
_php_curl_cleanup_handle(ch);
error = curl_easy_perform(ch->cp);
SAVE_CURL_ERROR(ch, error);
/* CURLE_PARTIAL_FILE is returned by HEAD requests */
if (error != CURLE_OK && error != CURLE_PARTIAL_FILE) {
smart_str_free(&ch->handlers->write->buf);
RETURN_FALSE;
}
if (!Z_ISUNDEF(ch->handlers->std_err)) {
php_stream *stream;
stream = (php_stream*)zend_fetch_resource2_ex(&ch->handlers->std_err, NULL, php_file_le_stream(), php_file_le_pstream());
if (stream) {
php_stream_flush(stream);
}
}
if (ch->handlers->write->method == PHP_CURL_RETURN && ch->handlers->write->buf.s) {
smart_str_0(&ch->handlers->write->buf);
RETURN_STR_COPY(ch->handlers->write->buf.s);
}
/* flush the file handle, so any remaining data is synched to disk */
if (ch->handlers->write->method == PHP_CURL_FILE && ch->handlers->write->fp) {
fflush(ch->handlers->write->fp);
}
if (ch->handlers->write_header->method == PHP_CURL_FILE && ch->handlers->write_header->fp) {
fflush(ch->handlers->write_header->fp);
}
if (ch->handlers->write->method == PHP_CURL_RETURN) {
RETURN_EMPTY_STRING();
} else {
RETURN_TRUE;
}
}
/* }}} */
/* {{{ proto mixed curl_getinfo(resource ch [, int option])
Get information regarding a specific transfer */
PHP_FUNCTION(curl_getinfo)
{
zval *zid;
php_curl *ch;
zend_long option = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zid, &option) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if (ZEND_NUM_ARGS() < 2) {
char *s_code;
/* libcurl expects long datatype. So far no cases are known where
it would be an issue. Using zend_long would truncate a 64-bit
var on Win64, so the exact long datatype fits everywhere, as
long as there's no 32-bit int overflow. */
long l_code;
double d_code;
#if LIBCURL_VERSION_NUM > 0x071301
struct curl_certinfo *ci = NULL;
zval listcode;
#endif
array_init(return_value);
if (curl_easy_getinfo(ch->cp, CURLINFO_EFFECTIVE_URL, &s_code) == CURLE_OK) {
CAAS("url", s_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_CONTENT_TYPE, &s_code) == CURLE_OK) {
if (s_code != NULL) {
CAAS("content_type", s_code);
} else {
zval retnull;
ZVAL_NULL(&retnull);
CAAZ("content_type", &retnull);
}
}
if (curl_easy_getinfo(ch->cp, CURLINFO_HTTP_CODE, &l_code) == CURLE_OK) {
CAAL("http_code", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_HEADER_SIZE, &l_code) == CURLE_OK) {
CAAL("header_size", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_REQUEST_SIZE, &l_code) == CURLE_OK) {
CAAL("request_size", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_FILETIME, &l_code) == CURLE_OK) {
CAAL("filetime", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_SSL_VERIFYRESULT, &l_code) == CURLE_OK) {
CAAL("ssl_verify_result", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_REDIRECT_COUNT, &l_code) == CURLE_OK) {
CAAL("redirect_count", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_TOTAL_TIME, &d_code) == CURLE_OK) {
CAAD("total_time", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_NAMELOOKUP_TIME, &d_code) == CURLE_OK) {
CAAD("namelookup_time", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_CONNECT_TIME, &d_code) == CURLE_OK) {
CAAD("connect_time", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_PRETRANSFER_TIME, &d_code) == CURLE_OK) {
CAAD("pretransfer_time", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_SIZE_UPLOAD, &d_code) == CURLE_OK) {
CAAD("size_upload", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_SIZE_DOWNLOAD, &d_code) == CURLE_OK) {
CAAD("size_download", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_SPEED_DOWNLOAD, &d_code) == CURLE_OK) {
CAAD("speed_download", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_SPEED_UPLOAD, &d_code) == CURLE_OK) {
CAAD("speed_upload", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d_code) == CURLE_OK) {
CAAD("download_content_length", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_CONTENT_LENGTH_UPLOAD, &d_code) == CURLE_OK) {
CAAD("upload_content_length", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_STARTTRANSFER_TIME, &d_code) == CURLE_OK) {
CAAD("starttransfer_time", d_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_REDIRECT_TIME, &d_code) == CURLE_OK) {
CAAD("redirect_time", d_code);
}
#if LIBCURL_VERSION_NUM >= 0x071202 /* Available since 7.18.2 */
if (curl_easy_getinfo(ch->cp, CURLINFO_REDIRECT_URL, &s_code) == CURLE_OK) {
CAAS("redirect_url", s_code);
}
#endif
#if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */
if (curl_easy_getinfo(ch->cp, CURLINFO_PRIMARY_IP, &s_code) == CURLE_OK) {
CAAS("primary_ip", s_code);
}
#endif
#if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */
if (curl_easy_getinfo(ch->cp, CURLINFO_CERTINFO, &ci) == CURLE_OK) {
array_init(&listcode);
create_certinfo(ci, &listcode);
CAAZ("certinfo", &listcode);
}
#endif
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
if (curl_easy_getinfo(ch->cp, CURLINFO_PRIMARY_PORT, &l_code) == CURLE_OK) {
CAAL("primary_port", l_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_LOCAL_IP, &s_code) == CURLE_OK) {
CAAS("local_ip", s_code);
}
if (curl_easy_getinfo(ch->cp, CURLINFO_LOCAL_PORT, &l_code) == CURLE_OK) {
CAAL("local_port", l_code);
}
#endif
if (ch->header.str) {
CAASTR("request_header", ch->header.str);
}
} else {
switch (option) {
case CURLINFO_HEADER_OUT:
if (ch->header.str) {
RETURN_STR_COPY(ch->header.str);
} else {
RETURN_FALSE;
}
#if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */
case CURLINFO_CERTINFO: {
struct curl_certinfo *ci = NULL;
array_init(return_value);
if (curl_easy_getinfo(ch->cp, CURLINFO_CERTINFO, &ci) == CURLE_OK) {
create_certinfo(ci, return_value);
} else {
RETURN_FALSE;
}
break;
}
#endif
default: {
int type = CURLINFO_TYPEMASK & option;
switch (type) {
case CURLINFO_STRING:
{
char *s_code = NULL;
if (curl_easy_getinfo(ch->cp, option, &s_code) == CURLE_OK && s_code) {
RETURN_STRING(s_code);
} else {
RETURN_FALSE;
}
break;
}
case CURLINFO_LONG:
{
zend_long code = 0;
if (curl_easy_getinfo(ch->cp, option, &code) == CURLE_OK) {
RETURN_LONG(code);
} else {
RETURN_FALSE;
}
break;
}
case CURLINFO_DOUBLE:
{
double code = 0.0;
if (curl_easy_getinfo(ch->cp, option, &code) == CURLE_OK) {
RETURN_DOUBLE(code);
} else {
RETURN_FALSE;
}
break;
}
#if LIBCURL_VERSION_NUM >= 0x070c03 /* Available since 7.12.3 */
case CURLINFO_SLIST:
{
struct curl_slist *slist;
array_init(return_value);
if (curl_easy_getinfo(ch->cp, option, &slist) == CURLE_OK) {
while (slist) {
add_next_index_string(return_value, slist->data);
slist = slist->next;
}
curl_slist_free_all(slist);
} else {
RETURN_FALSE;
}
break;
}
#endif
default:
RETURN_FALSE;
}
}
}
}
}
/* }}} */
/* {{{ proto string curl_error(resource ch)
Return a string contain the last error for the current session */
PHP_FUNCTION(curl_error)
{
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
ch->err.str[CURL_ERROR_SIZE] = 0;
RETURN_STRING(ch->err.str);
}
/* }}} */
/* {{{ proto int curl_errno(resource ch)
Return an integer containing the last error number */
PHP_FUNCTION(curl_errno)
{
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
RETURN_LONG(ch->err.no);
}
/* }}} */
/* {{{ proto void curl_close(resource ch)
Close a cURL session */
PHP_FUNCTION(curl_close)
{
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if (ch->in_callback) {
php_error_docref(NULL, E_WARNING, "Attempt to close cURL handle from a callback");
return;
}
if (Z_REFCOUNT_P(zid) <= 2) {
zend_list_close(Z_RES_P(zid));
}
}
/* }}} */
/* {{{ _php_curl_close_ex()
List destructor for curl handles */
static void _php_curl_close_ex(php_curl *ch)
{
#if PHP_CURL_DEBUG
fprintf(stderr, "DTOR CALLED, ch = %x\n", ch);
#endif
_php_curl_verify_handlers(ch, 0);
/*
* Libcurl is doing connection caching. When easy handle is cleaned up,
* if the handle was previously used by the curl_multi_api, the connection
* remains open un the curl multi handle is cleaned up. Some protocols are
* sending content like the FTP one, and libcurl try to use the
* WRITEFUNCTION or the HEADERFUNCTION. Since structures used in those
* callback are freed, we need to use an other callback to which avoid
* segfaults.
*
* Libcurl commit d021f2e8a00 fix this issue and should be part of 7.28.2
*/
curl_easy_setopt(ch->cp, CURLOPT_HEADERFUNCTION, curl_write_nothing);
curl_easy_setopt(ch->cp, CURLOPT_WRITEFUNCTION, curl_write_nothing);
curl_easy_cleanup(ch->cp);
/* cURL destructors should be invoked only by last curl handle */
if (--(*ch->clone) == 0) {
zend_llist_clean(&ch->to_free->str);
zend_llist_clean(&ch->to_free->post);
zend_hash_destroy(ch->to_free->slist);
efree(ch->to_free->slist);
efree(ch->to_free);
efree(ch->clone);
}
smart_str_free(&ch->handlers->write->buf);
zval_ptr_dtor(&ch->handlers->write->func_name);
zval_ptr_dtor(&ch->handlers->read->func_name);
zval_ptr_dtor(&ch->handlers->write_header->func_name);
#if CURLOPT_PASSWDFUNCTION != 0
zval_ptr_dtor(&ch->handlers->passwd);
#endif
zval_ptr_dtor(&ch->handlers->std_err);
if (ch->header.str) {
zend_string_release(ch->header.str);
}
zval_ptr_dtor(&ch->handlers->write_header->stream);
zval_ptr_dtor(&ch->handlers->write->stream);
zval_ptr_dtor(&ch->handlers->read->stream);
efree(ch->handlers->write);
efree(ch->handlers->write_header);
efree(ch->handlers->read);
if (ch->handlers->progress) {
zval_ptr_dtor(&ch->handlers->progress->func_name);
efree(ch->handlers->progress);
}
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
if (ch->handlers->fnmatch) {
zval_ptr_dtor(&ch->handlers->fnmatch->func_name);
efree(ch->handlers->fnmatch);
}
#endif
efree(ch->handlers);
efree(ch);
}
/* }}} */
/* {{{ _php_curl_close()
List destructor for curl handles */
static void _php_curl_close(zend_resource *rsrc)
{
php_curl *ch = (php_curl *) rsrc->ptr;
_php_curl_close_ex(ch);
}
/* }}} */
#if LIBCURL_VERSION_NUM >= 0x070c00 /* Available since 7.12.0 */
/* {{{ proto bool curl_strerror(int code)
return string describing error code */
PHP_FUNCTION(curl_strerror)
{
zend_long code;
const char *str;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &code) == FAILURE) {
return;
}
str = curl_easy_strerror(code);
if (str) {
RETURN_STRING(str);
} else {
RETURN_NULL();
}
}
/* }}} */
#endif
#if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */
/* {{{ _php_curl_reset_handlers()
Reset all handlers of a given php_curl */
static void _php_curl_reset_handlers(php_curl *ch)
{
if (!Z_ISUNDEF(ch->handlers->write->stream)) {
zval_ptr_dtor(&ch->handlers->write->stream);
ZVAL_UNDEF(&ch->handlers->write->stream);
}
ch->handlers->write->fp = NULL;
ch->handlers->write->method = PHP_CURL_STDOUT;
if (!Z_ISUNDEF(ch->handlers->write_header->stream)) {
zval_ptr_dtor(&ch->handlers->write_header->stream);
ZVAL_UNDEF(&ch->handlers->write_header->stream);
}
ch->handlers->write_header->fp = NULL;
ch->handlers->write_header->method = PHP_CURL_IGNORE;
if (!Z_ISUNDEF(ch->handlers->read->stream)) {
zval_ptr_dtor(&ch->handlers->read->stream);
ZVAL_UNDEF(&ch->handlers->read->stream);
}
ch->handlers->read->fp = NULL;
ch->handlers->read->res = NULL;
ch->handlers->read->method = PHP_CURL_DIRECT;
if (!Z_ISUNDEF(ch->handlers->std_err)) {
zval_ptr_dtor(&ch->handlers->std_err);
ZVAL_UNDEF(&ch->handlers->std_err);
}
if (ch->handlers->progress) {
zval_ptr_dtor(&ch->handlers->progress->func_name);
efree(ch->handlers->progress);
ch->handlers->progress = NULL;
}
#if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */
if (ch->handlers->fnmatch) {
zval_ptr_dtor(&ch->handlers->fnmatch->func_name);
efree(ch->handlers->fnmatch);
ch->handlers->fnmatch = NULL;
}
#endif
}
/* }}} */
/* {{{ proto void curl_reset(resource ch)
Reset all options of a libcurl session handle */
PHP_FUNCTION(curl_reset)
{
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if (ch->in_callback) {
php_error_docref(NULL, E_WARNING, "Attempt to reset cURL handle from a callback");
return;
}
curl_easy_reset(ch->cp);
_php_curl_reset_handlers(ch);
_php_curl_set_default_options(ch);
}
/* }}} */
#endif
#if LIBCURL_VERSION_NUM > 0x070f03 /* 7.15.4 */
/* {{{ proto void curl_escape(resource ch, string str)
URL encodes the given string */
PHP_FUNCTION(curl_escape)
{
char *str = NULL, *res = NULL;
size_t str_len = 0;
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if ((res = curl_easy_escape(ch->cp, str, str_len))) {
RETVAL_STRING(res);
curl_free(res);
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto void curl_unescape(resource ch, string str)
URL decodes the given string */
PHP_FUNCTION(curl_unescape)
{
char *str = NULL, *out = NULL;
size_t str_len = 0;
int out_len;
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if (str_len > INT_MAX) {
RETURN_FALSE;
}
if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) {
RETVAL_STRINGL(out, out_len);
curl_free(out);
} else {
RETURN_FALSE;
}
}
/* }}} */
#endif
#if LIBCURL_VERSION_NUM >= 0x071200 /* 7.18.0 */
/* {{{ proto void curl_pause(resource ch, int bitmask)
pause and unpause a connection */
PHP_FUNCTION(curl_pause)
{
zend_long bitmask;
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zid, &bitmask) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
RETURN_LONG(curl_easy_pause(ch->cp, bitmask));
}
/* }}} */
#endif
#endif /* HAVE_CURL */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: fdm=marker
* vim: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5263_0 |
crossvul-cpp_data_bad_5762_0 | /*
* Luminary Micro Stellaris Ethernet Controller
*
* Copyright (c) 2007 CodeSourcery.
* Written by Paul Brook
*
* This code is licensed under the GPL.
*/
#include "hw/sysbus.h"
#include "net/net.h"
#include <zlib.h>
//#define DEBUG_STELLARIS_ENET 1
#ifdef DEBUG_STELLARIS_ENET
#define DPRINTF(fmt, ...) \
do { printf("stellaris_enet: " fmt , ## __VA_ARGS__); } while (0)
#define BADF(fmt, ...) \
do { fprintf(stderr, "stellaris_enet: error: " fmt , ## __VA_ARGS__); exit(1);} while (0)
#else
#define DPRINTF(fmt, ...) do {} while(0)
#define BADF(fmt, ...) \
do { fprintf(stderr, "stellaris_enet: error: " fmt , ## __VA_ARGS__);} while (0)
#endif
#define SE_INT_RX 0x01
#define SE_INT_TXER 0x02
#define SE_INT_TXEMP 0x04
#define SE_INT_FOV 0x08
#define SE_INT_RXER 0x10
#define SE_INT_MD 0x20
#define SE_INT_PHY 0x40
#define SE_RCTL_RXEN 0x01
#define SE_RCTL_AMUL 0x02
#define SE_RCTL_PRMS 0x04
#define SE_RCTL_BADCRC 0x08
#define SE_RCTL_RSTFIFO 0x10
#define SE_TCTL_TXEN 0x01
#define SE_TCTL_PADEN 0x02
#define SE_TCTL_CRC 0x04
#define SE_TCTL_DUPLEX 0x08
#define TYPE_STELLARIS_ENET "stellaris_enet"
#define STELLARIS_ENET(obj) \
OBJECT_CHECK(stellaris_enet_state, (obj), TYPE_STELLARIS_ENET)
typedef struct {
SysBusDevice parent_obj;
uint32_t ris;
uint32_t im;
uint32_t rctl;
uint32_t tctl;
uint32_t thr;
uint32_t mctl;
uint32_t mdv;
uint32_t mtxd;
uint32_t mrxd;
uint32_t np;
int tx_fifo_len;
uint8_t tx_fifo[2048];
/* Real hardware has a 2k fifo, which works out to be at most 31 packets.
We implement a full 31 packet fifo. */
struct {
uint8_t data[2048];
int len;
} rx[31];
int rx_fifo_offset;
int next_packet;
NICState *nic;
NICConf conf;
qemu_irq irq;
MemoryRegion mmio;
} stellaris_enet_state;
static void stellaris_enet_update(stellaris_enet_state *s)
{
qemu_set_irq(s->irq, (s->ris & s->im) != 0);
}
/* Return the data length of the packet currently being assembled
* in the TX fifo.
*/
static inline int stellaris_txpacket_datalen(stellaris_enet_state *s)
{
return s->tx_fifo[0] | (s->tx_fifo[1] << 8);
}
/* Return true if the packet currently in the TX FIFO is complete,
* ie the FIFO holds enough bytes for the data length, ethernet header,
* payload and optionally CRC.
*/
static inline bool stellaris_txpacket_complete(stellaris_enet_state *s)
{
int framelen = stellaris_txpacket_datalen(s);
framelen += 16;
if (!(s->tctl & SE_TCTL_CRC)) {
framelen += 4;
}
/* Cover the corner case of a 2032 byte payload with auto-CRC disabled:
* this requires more bytes than will fit in the FIFO. It's not totally
* clear how the h/w handles this, but if using threshold-based TX
* it will definitely try to transmit something.
*/
framelen = MIN(framelen, ARRAY_SIZE(s->tx_fifo));
return s->tx_fifo_len >= framelen;
}
/* Return true if the TX FIFO threshold is enabled and the FIFO
* has filled enough to reach it.
*/
static inline bool stellaris_tx_thr_reached(stellaris_enet_state *s)
{
return (s->thr < 0x3f &&
(s->tx_fifo_len >= 4 * (s->thr * 8 + 1)));
}
/* Send the packet currently in the TX FIFO */
static void stellaris_enet_send(stellaris_enet_state *s)
{
int framelen = stellaris_txpacket_datalen(s);
/* Ethernet header is in the FIFO but not in the datacount.
* We don't implement explicit CRC, so just ignore any
* CRC value in the FIFO.
*/
framelen += 14;
if ((s->tctl & SE_TCTL_PADEN) && framelen < 60) {
memset(&s->tx_fifo[framelen + 2], 0, 60 - framelen);
framelen = 60;
}
/* This MIN will have no effect unless the FIFO data is corrupt
* (eg bad data from an incoming migration); otherwise the check
* on the datalen at the start of writing the data into the FIFO
* will have caught this. Silently write a corrupt half-packet,
* which is what the hardware does in FIFO underrun situations.
*/
framelen = MIN(framelen, ARRAY_SIZE(s->tx_fifo) - 2);
qemu_send_packet(qemu_get_queue(s->nic), s->tx_fifo + 2, framelen);
s->tx_fifo_len = 0;
s->ris |= SE_INT_TXEMP;
stellaris_enet_update(s);
DPRINTF("Done TX\n");
}
/* TODO: Implement MAC address filtering. */
static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
int n;
uint8_t *p;
uint32_t crc;
if ((s->rctl & SE_RCTL_RXEN) == 0)
return -1;
if (s->np >= 31) {
DPRINTF("Packet dropped\n");
return -1;
}
DPRINTF("Received packet len=%zu\n", size);
n = s->next_packet + s->np;
if (n >= 31)
n -= 31;
s->np++;
s->rx[n].len = size + 6;
p = s->rx[n].data;
*(p++) = (size + 6);
*(p++) = (size + 6) >> 8;
memcpy (p, buf, size);
p += size;
crc = crc32(~0, buf, size);
*(p++) = crc;
*(p++) = crc >> 8;
*(p++) = crc >> 16;
*(p++) = crc >> 24;
/* Clear the remaining bytes in the last word. */
if ((size & 3) != 2) {
memset(p, 0, (6 - size) & 3);
}
s->ris |= SE_INT_RX;
stellaris_enet_update(s);
return size;
}
static int stellaris_enet_can_receive(NetClientState *nc)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
if ((s->rctl & SE_RCTL_RXEN) == 0)
return 1;
return (s->np < 31);
}
static uint64_t stellaris_enet_read(void *opaque, hwaddr offset,
unsigned size)
{
stellaris_enet_state *s = (stellaris_enet_state *)opaque;
uint32_t val;
switch (offset) {
case 0x00: /* RIS */
DPRINTF("IRQ status %02x\n", s->ris);
return s->ris;
case 0x04: /* IM */
return s->im;
case 0x08: /* RCTL */
return s->rctl;
case 0x0c: /* TCTL */
return s->tctl;
case 0x10: /* DATA */
{
uint8_t *rx_fifo;
if (s->np == 0) {
BADF("RX underflow\n");
return 0;
}
rx_fifo = s->rx[s->next_packet].data + s->rx_fifo_offset;
val = rx_fifo[0] | (rx_fifo[1] << 8) | (rx_fifo[2] << 16)
| (rx_fifo[3] << 24);
s->rx_fifo_offset += 4;
if (s->rx_fifo_offset >= s->rx[s->next_packet].len) {
s->rx_fifo_offset = 0;
s->next_packet++;
if (s->next_packet >= 31)
s->next_packet = 0;
s->np--;
DPRINTF("RX done np=%d\n", s->np);
}
return val;
}
case 0x14: /* IA0 */
return s->conf.macaddr.a[0] | (s->conf.macaddr.a[1] << 8)
| (s->conf.macaddr.a[2] << 16)
| ((uint32_t)s->conf.macaddr.a[3] << 24);
case 0x18: /* IA1 */
return s->conf.macaddr.a[4] | (s->conf.macaddr.a[5] << 8);
case 0x1c: /* THR */
return s->thr;
case 0x20: /* MCTL */
return s->mctl;
case 0x24: /* MDV */
return s->mdv;
case 0x28: /* MADD */
return 0;
case 0x2c: /* MTXD */
return s->mtxd;
case 0x30: /* MRXD */
return s->mrxd;
case 0x34: /* NP */
return s->np;
case 0x38: /* TR */
return 0;
case 0x3c: /* Undocuented: Timestamp? */
return 0;
default:
hw_error("stellaris_enet_read: Bad offset %x\n", (int)offset);
return 0;
}
}
static void stellaris_enet_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
stellaris_enet_state *s = (stellaris_enet_state *)opaque;
switch (offset) {
case 0x00: /* IACK */
s->ris &= ~value;
DPRINTF("IRQ ack %02" PRIx64 "/%02x\n", value, s->ris);
stellaris_enet_update(s);
/* Clearing TXER also resets the TX fifo. */
if (value & SE_INT_TXER) {
s->tx_fifo_len = 0;
}
break;
case 0x04: /* IM */
DPRINTF("IRQ mask %02" PRIx64 "/%02x\n", value, s->ris);
s->im = value;
stellaris_enet_update(s);
break;
case 0x08: /* RCTL */
s->rctl = value;
if (value & SE_RCTL_RSTFIFO) {
s->np = 0;
s->rx_fifo_offset = 0;
stellaris_enet_update(s);
}
break;
case 0x0c: /* TCTL */
s->tctl = value;
break;
case 0x10: /* DATA */
if (s->tx_fifo_len == 0) {
/* The first word is special, it contains the data length */
int framelen = value & 0xffff;
if (framelen > 2032) {
DPRINTF("TX frame too long (%d)\n", framelen);
s->ris |= SE_INT_TXER;
stellaris_enet_update(s);
break;
}
}
if (s->tx_fifo_len + 4 <= ARRAY_SIZE(s->tx_fifo)) {
s->tx_fifo[s->tx_fifo_len++] = value;
s->tx_fifo[s->tx_fifo_len++] = value >> 8;
s->tx_fifo[s->tx_fifo_len++] = value >> 16;
s->tx_fifo[s->tx_fifo_len++] = value >> 24;
}
if (stellaris_tx_thr_reached(s) && stellaris_txpacket_complete(s)) {
stellaris_enet_send(s);
}
break;
case 0x14: /* IA0 */
s->conf.macaddr.a[0] = value;
s->conf.macaddr.a[1] = value >> 8;
s->conf.macaddr.a[2] = value >> 16;
s->conf.macaddr.a[3] = value >> 24;
break;
case 0x18: /* IA1 */
s->conf.macaddr.a[4] = value;
s->conf.macaddr.a[5] = value >> 8;
break;
case 0x1c: /* THR */
s->thr = value;
break;
case 0x20: /* MCTL */
s->mctl = value;
break;
case 0x24: /* MDV */
s->mdv = value;
break;
case 0x28: /* MADD */
/* ignored. */
break;
case 0x2c: /* MTXD */
s->mtxd = value & 0xff;
break;
case 0x38: /* TR */
if (value & 1) {
stellaris_enet_send(s);
}
break;
case 0x30: /* MRXD */
case 0x34: /* NP */
/* Ignored. */
case 0x3c: /* Undocuented: Timestamp? */
/* Ignored. */
break;
default:
hw_error("stellaris_enet_write: Bad offset %x\n", (int)offset);
}
}
static const MemoryRegionOps stellaris_enet_ops = {
.read = stellaris_enet_read,
.write = stellaris_enet_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static void stellaris_enet_reset(stellaris_enet_state *s)
{
s->mdv = 0x80;
s->rctl = SE_RCTL_BADCRC;
s->im = SE_INT_PHY | SE_INT_MD | SE_INT_RXER | SE_INT_FOV | SE_INT_TXEMP
| SE_INT_TXER | SE_INT_RX;
s->thr = 0x3f;
s->tx_fifo_len = 0;
}
static void stellaris_enet_save(QEMUFile *f, void *opaque)
{
stellaris_enet_state *s = (stellaris_enet_state *)opaque;
int i;
qemu_put_be32(f, s->ris);
qemu_put_be32(f, s->im);
qemu_put_be32(f, s->rctl);
qemu_put_be32(f, s->tctl);
qemu_put_be32(f, s->thr);
qemu_put_be32(f, s->mctl);
qemu_put_be32(f, s->mdv);
qemu_put_be32(f, s->mtxd);
qemu_put_be32(f, s->mrxd);
qemu_put_be32(f, s->np);
qemu_put_be32(f, s->tx_fifo_len);
qemu_put_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));
for (i = 0; i < 31; i++) {
qemu_put_be32(f, s->rx[i].len);
qemu_put_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));
}
qemu_put_be32(f, s->next_packet);
qemu_put_be32(f, s->rx_fifo_offset);
}
static int stellaris_enet_load(QEMUFile *f, void *opaque, int version_id)
{
stellaris_enet_state *s = (stellaris_enet_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->ris = qemu_get_be32(f);
s->im = qemu_get_be32(f);
s->rctl = qemu_get_be32(f);
s->tctl = qemu_get_be32(f);
s->thr = qemu_get_be32(f);
s->mctl = qemu_get_be32(f);
s->mdv = qemu_get_be32(f);
s->mtxd = qemu_get_be32(f);
s->mrxd = qemu_get_be32(f);
s->np = qemu_get_be32(f);
s->tx_fifo_len = qemu_get_be32(f);
qemu_get_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));
for (i = 0; i < 31; i++) {
s->rx[i].len = qemu_get_be32(f);
qemu_get_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));
}
s->next_packet = qemu_get_be32(f);
s->rx_fifo_offset = qemu_get_be32(f);
return 0;
}
static void stellaris_enet_cleanup(NetClientState *nc)
{
stellaris_enet_state *s = qemu_get_nic_opaque(nc);
s->nic = NULL;
}
static NetClientInfo net_stellaris_enet_info = {
.type = NET_CLIENT_OPTIONS_KIND_NIC,
.size = sizeof(NICState),
.can_receive = stellaris_enet_can_receive,
.receive = stellaris_enet_receive,
.cleanup = stellaris_enet_cleanup,
};
static int stellaris_enet_init(SysBusDevice *sbd)
{
DeviceState *dev = DEVICE(sbd);
stellaris_enet_state *s = STELLARIS_ENET(dev);
memory_region_init_io(&s->mmio, OBJECT(s), &stellaris_enet_ops, s,
"stellaris_enet", 0x1000);
sysbus_init_mmio(sbd, &s->mmio);
sysbus_init_irq(sbd, &s->irq);
qemu_macaddr_default_if_unset(&s->conf.macaddr);
s->nic = qemu_new_nic(&net_stellaris_enet_info, &s->conf,
object_get_typename(OBJECT(dev)), dev->id, s);
qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);
stellaris_enet_reset(s);
register_savevm(dev, "stellaris_enet", -1, 1,
stellaris_enet_save, stellaris_enet_load, s);
return 0;
}
static void stellaris_enet_unrealize(DeviceState *dev, Error **errp)
{
stellaris_enet_state *s = STELLARIS_ENET(dev);
unregister_savevm(DEVICE(s), "stellaris_enet", s);
memory_region_destroy(&s->mmio);
}
static Property stellaris_enet_properties[] = {
DEFINE_NIC_PROPERTIES(stellaris_enet_state, conf),
DEFINE_PROP_END_OF_LIST(),
};
static void stellaris_enet_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
k->init = stellaris_enet_init;
dc->unrealize = stellaris_enet_unrealize;
dc->props = stellaris_enet_properties;
}
static const TypeInfo stellaris_enet_info = {
.name = TYPE_STELLARIS_ENET,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(stellaris_enet_state),
.class_init = stellaris_enet_class_init,
};
static void stellaris_enet_register_types(void)
{
type_register_static(&stellaris_enet_info);
}
type_init(stellaris_enet_register_types)
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5762_0 |
crossvul-cpp_data_bad_343_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_343_7 |
crossvul-cpp_data_good_341_0 | /*
* card-cac.c: Support for CAC from NIST SP800-73
* card-default.c: Support for cards with no driver
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
* Copyright (C) 2016 - 2018, Red Hat, Inc.
*
* CAC driver author: Robert Relyea <rrelyea@redhat.com>
* Further work: Jakub Jelen <jjelen@redhat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef ENABLE_OPENSSL
/* openssl only needed for card administration */
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#endif /* ENABLE_OPENSSL */
#include "internal.h"
#include "simpletlv.h"
#include "cardctl.h"
#ifdef ENABLE_ZLIB
#include "compression.h"
#endif
#include "iso7816.h"
#define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */
/*
* CAC hardware and APDU constants
*/
#define CAC_MAX_CHUNK_SIZE 240
#define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */
#define CAC_INS_READ_FILE 0x52 /* read a TL or V file */
#define CAC_INS_GET_ACR 0x4c
#define CAC_INS_GET_PROPERTIES 0x56
#define CAC_P1_STEP 0x80
#define CAC_P1_FINAL 0x00
#define CAC_FILE_TAG 1
#define CAC_FILE_VALUE 2
/* TAGS in a TL file */
#define CAC_TAG_CERTIFICATE 0x70
#define CAC_TAG_CERTINFO 0x71
#define CAC_TAG_MSCUID 0x72
#define CAC_TAG_CUID 0xF0
#define CAC_TAG_CC_VERSION_NUMBER 0xF1
#define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2
#define CAC_TAG_CARDURL 0xF3
#define CAC_TAG_PKCS15 0xF4
#define CAC_TAG_ACCESS_CONTROL 0xF6
#define CAC_TAG_DATA_MODEL 0xF5
#define CAC_TAG_CARD_APDU 0xF7
#define CAC_TAG_REDIRECTION 0xFA
#define CAC_TAG_CAPABILITY_TUPLES 0xFB
#define CAC_TAG_STATUS_TUPLES 0xFC
#define CAC_TAG_NEXT_CCC 0xFD
#define CAC_TAG_ERROR_CODES 0xFE
#define CAC_TAG_APPLET_FAMILY 0x01
#define CAC_TAG_NUMBER_APPLETS 0x94
#define CAC_TAG_APPLET_ENTRY 0x93
#define CAC_TAG_APPLET_AID 0x92
#define CAC_TAG_APPLET_INFORMATION 0x01
#define CAC_TAG_NUMBER_OF_OBJECTS 0x40
#define CAC_TAG_TV_BUFFER 0x50
#define CAC_TAG_PKI_OBJECT 0x51
#define CAC_TAG_OBJECT_ID 0x41
#define CAC_TAG_BUFFER_PROPERTIES 0x42
#define CAC_TAG_PKI_PROPERTIES 0x43
#define CAC_APP_TYPE_GENERAL 0x01
#define CAC_APP_TYPE_SKI 0x02
#define CAC_APP_TYPE_PKI 0x04
#define CAC_ACR_ACR 0x00
#define CAC_ACR_APPLET_OBJECT 0x10
#define CAC_ACR_AMP 0x20
#define CAC_ACR_SERVICE 0x21
/* hardware data structures (returned in the CCC) */
/* part of the card_url */
typedef struct cac_access_profile {
u8 GCACR_listID;
u8 GCACR_readTagListACRID;
u8 GCACR_updatevalueACRID;
u8 GCACR_readvalueACRID;
u8 GCACR_createACRID;
u8 GCACR_deleteACRID;
u8 CryptoACR_listID;
u8 CryptoACR_getChallengeACRID;
u8 CryptoACR_internalAuthenicateACRID;
u8 CryptoACR_pkiComputeACRID;
u8 CryptoACR_readTagListACRID;
u8 CryptoACR_updatevalueACRID;
u8 CryptoACR_readvalueACRID;
u8 CryptoACR_createACRID;
u8 CryptoACR_deleteACRID;
} cac_access_profile_t;
/* part of the card url */
typedef struct cac_access_key_info {
u8 keyFileID[2];
u8 keynumber;
} cac_access_key_info_t;
typedef struct cac_card_url {
u8 rid[5];
u8 cardApplicationType;
u8 objectID[2];
u8 applicationID[2];
cac_access_profile_t accessProfile;
u8 pinID; /* not used for VM cards */
cac_access_key_info_t accessKeyInfo; /* not used for VM cards */
u8 keyCryptoAlgorithm; /* not used for VM cards */
} cac_card_url_t;
typedef struct cac_cuid {
u8 gsc_rid[5];
u8 manufacturer_id;
u8 card_type;
u8 card_id;
} cac_cuid_t;
/* data structures to store meta data about CAC objects */
typedef struct cac_object {
const char *name;
int fd;
sc_path_t path;
} cac_object_t;
#define CAC_MAX_OBJECTS 16
typedef struct {
/* OID has two bytes */
unsigned char oid[2];
/* Format is NOT SimpleTLV? */
unsigned char simpletlv;
/* Is certificate object and private key is initialized */
unsigned char privatekey;
} cac_properties_object_t;
typedef struct {
unsigned int num_objects;
cac_properties_object_t objects[CAC_MAX_OBJECTS];
} cac_properties_t;
/*
* Flags for Current Selected Object Type
* CAC files are TLV files, with TL and V separated. For generic
* containers we reintegrate the TL anv V portions into a single
* file to read. Certs are also TLV files, but pkcs15 wants the
* actual certificate. At select time we know the patch which tells
* us what time of files we want to read. We remember that type
* so that read_binary can do the appropriate processing.
*/
#define CAC_OBJECT_TYPE_CERT 1
#define CAC_OBJECT_TYPE_TLV_FILE 4
#define CAC_OBJECT_TYPE_GENERIC 5
/*
* CAC private data per card state
*/
typedef struct cac_private_data {
int object_type; /* select set this so we know how to read the file */
int cert_next; /* index number for the next certificate found in the list */
u8 *cache_buf; /* cached version of the currently selected file */
size_t cache_buf_len; /* length of the cached selected file */
int cached; /* is the cached selected file valid */
cac_cuid_t cuid; /* card unique ID from the CCC */
u8 *cac_id; /* card serial number */
size_t cac_id_len; /* card serial number len */
list_t pki_list; /* list of pki containers */
cac_object_t *pki_current; /* current pki object _ctl function */
list_t general_list; /* list of general containers */
cac_object_t *general_current; /* current object for _ctl function */
sc_path_t *aca_path; /* ACA path to be selected before pin verification */
} cac_private_data_t;
#define CAC_DATA(card) ((cac_private_data_t*)card->drv_data)
int cac_list_compare_path(const void *a, const void *b)
{
if (a == NULL || b == NULL)
return 1;
return memcmp( &((cac_object_t *) a)->path,
&((cac_object_t *) b)->path, sizeof(sc_path_t));
}
/* For SimCList autocopy, we need to know the size of the data elements */
size_t cac_list_meter(const void *el) {
return sizeof(cac_object_t);
}
static cac_private_data_t *cac_new_private_data(void)
{
cac_private_data_t *priv;
priv = calloc(1, sizeof(cac_private_data_t));
if (!priv)
return NULL;
list_init(&priv->pki_list);
list_attributes_comparator(&priv->pki_list, cac_list_compare_path);
list_attributes_copy(&priv->pki_list, cac_list_meter, 1);
list_init(&priv->general_list);
list_attributes_comparator(&priv->general_list, cac_list_compare_path);
list_attributes_copy(&priv->general_list, cac_list_meter, 1);
/* set other fields as appropriate */
return priv;
}
static void cac_free_private_data(cac_private_data_t *priv)
{
free(priv->cac_id);
free(priv->cache_buf);
free(priv->aca_path);
list_destroy(&priv->pki_list);
list_destroy(&priv->general_list);
free(priv);
return;
}
static int cac_add_object_to_list(list_t *list, const cac_object_t *object)
{
if (list_append(list, object) < 0)
return SC_ERROR_UNKNOWN;
return SC_SUCCESS;
}
/*
* Set up the normal CAC paths
*/
#define CAC_TO_AID(x) x, sizeof(x)-1
#define CAC_2_RID "\xA0\x00\x00\x01\x16"
#define CAC_1_RID "\xA0\x00\x00\x00\x79"
static const sc_path_t cac_ACA_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x10\x00") }
};
static const sc_path_t cac_CCC_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_2_RID "\xDB\x00") }
};
#define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */
/* default certificate labels for the CAC card */
static const char *cac_labels[MAX_CAC_SLOTS] = {
"CAC ID Certificate",
"CAC Email Signature Certificate",
"CAC Email Encryption Certificate",
"CAC Cert 4",
"CAC Cert 5",
"CAC Cert 6",
"CAC Cert 7",
"CAC Cert 8",
"CAC Cert 9",
"CAC Cert 10",
"CAC Cert 11",
"CAC Cert 12",
"CAC Cert 13",
"CAC Cert 14",
"CAC Cert 15",
"CAC Cert 16"
};
/* template for a CAC pki object */
static const cac_object_t cac_cac_pki_obj = {
"CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x01\x00") } }
};
/* template for emulated cuid */
static const cac_cuid_t cac_cac_cuid = {
{ 0xa0, 0x00, 0x00, 0x00, 0x79 },
2, 2, 0
};
/*
* CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0.
* doubles as a source for CAC-2 labels.
*/
static const cac_object_t cac_objects[] = {
{ "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x00") }}},
{ "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x01") }}},
{ "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x02") }}},
{ "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x03") }}},
{ "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFD") }}},
{ "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFE") }}},
};
static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]);
/*
* use the object id to find our object info on the object in our CAC-1 list
*/
static const cac_object_t *cac_find_obj_by_id(unsigned short object_id)
{
int i;
for (i = 0; i < cac_object_count; i++) {
if (cac_objects[i].fd == object_id) {
return &cac_objects[i];
}
}
return NULL;
}
/*
* Lookup the path in the pki list to see if it is a cert path
*/
static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path)
{
cac_object_t test_obj;
test_obj.path = *in_path;
test_obj.path.index = 0;
test_obj.path.count = 0;
return (list_contains(&priv->pki_list, &test_obj) != 0);
}
/*
* Send a command and receive data.
*
* A caller may provide a buffer, and length to read. If not provided,
* an internal 4096 byte buffer is used, and a copy is returned to the
* caller. that need to be freed by the caller.
*
* modelled after a similar function in card-piv.c
*/
static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2,
const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf,
size_t * recvbuflen)
{
int r;
sc_apdu_t apdu;
u8 rbufinitbuf[CAC_MAX_SIZE];
u8 *rbuf;
size_t rbuflen;
unsigned int apdu_case = SC_APDU_CASE_1;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
ins, p1, p2, sendbuflen, card->max_send_size,
card->max_recv_size);
rbuf = rbufinitbuf;
rbuflen = sizeof(rbufinitbuf);
/* if caller provided a buffer and length */
if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
rbuf = *recvbuf;
rbuflen = *recvbuflen;
}
if (recvbuf) {
if (sendbuf)
apdu_case = SC_APDU_CASE_4_SHORT;
else
apdu_case = SC_APDU_CASE_2_SHORT;
} else if (sendbuf)
apdu_case = SC_APDU_CASE_3_SHORT;
sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
apdu.lc = sendbuflen;
apdu.datalen = sendbuflen;
apdu.data = sendbuf;
if (recvbuf) {
apdu.resp = rbuf;
apdu.le = (rbuflen > 255) ? 255 : rbuflen;
apdu.resplen = rbuflen;
} else {
apdu.resp = rbuf;
apdu.le = 0;
apdu.resplen = 0;
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
apdu.flags, apdu.le, apdu.resplen, apdu.resp);
/* with new adpu.c and chaining, this actually reads the whole object */
r = sc_transmit_apdu(card, &apdu);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
r, apdu.resplen, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error ");
goto err;
}
if (recvbuflen) {
if (recvbuf && *recvbuf == NULL) {
*recvbuf = malloc(apdu.resplen);
if (*recvbuf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*recvbuf, rbuf, apdu.resplen);
}
*recvbuflen = apdu.resplen;
r = *recvbuflen;
}
err:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Get ACR of currently ACA applet identified by the acr_type
* 5.3.3.5 Get ACR APDU
*/
static int
cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len)
{
u8 *out = NULL;
/* XXX assuming it will not be longer than 255 B */
size_t len = 256;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* for simplicity we support only ACR without arguments now */
if (acr_type != 0x00 && acr_type != 0x10
&& acr_type != 0x20 && acr_type != 0x21) {
return SC_ERROR_INVALID_ARGUMENTS;
}
r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out);
*out_len = len;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_buf = NULL;
*out_len = 0;
return r;
}
/*
* Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file
*/
#define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff)
#define LOW_BYTE_OF_SHORT(x) ((x) & 0xff)
static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len)
{
u8 params[2];
u8 count[2];
u8 *out = NULL;
u8 *out_ptr;
size_t offset = 0;
size_t size = 0;
size_t left = 0;
size_t len;
int r;
params[0] = file_type;
params[1] = 2;
/* get the size */
len = sizeof(count);
out_ptr = count;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, ¶ms[0], sizeof(params), &out_ptr, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
left = size = lebytes2ushort(count);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)",
len, out_ptr, &count, count[0], count[1], size, size);
out = out_ptr = malloc(size);
if (out == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto fail;
}
for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) {
len = MIN(left, CAC_MAX_CHUNK_SIZE);
params[1] = len;
r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset),
¶ms[0], sizeof(params), &out_ptr, &len);
/* if there is no data, assume there is no file */
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0) {
goto fail;
}
}
*out_len = size;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_len = 0;
return r;
}
/*
* Callers of this may be expecting a certificate,
* select file will have saved the object type for us
* as well as set that we want the cert from the object.
*/
static int cac_read_binary(sc_card_t *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
cac_private_data_t * priv = CAC_DATA(card);
int r = 0;
u8 *tl = NULL, *val = NULL;
u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start;
u8 *cert_ptr;
size_t tl_len, val_len, tlv_len;
size_t len, tl_head_len, cert_len;
u8 cert_type, tag;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* if we didn't return it all last time, return the remainder */
if (priv->cached) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (idx > priv->cache_buf_len) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED);
}
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len);
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
priv->cache_buf_len = 0;
}
if (priv->object_type <= 0)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0) {
goto done;
}
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
switch (priv->object_type) {
case CAC_OBJECT_TYPE_TLV_FILE:
tlv_len = tl_len + val_len;
priv->cache_buf = malloc(tlv_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = tlv_len;
for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
tl_len >= 2 && tlv_len > 0;
val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
/* get the tag and the length */
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = (tl_ptr - tl_start);
sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
tlv_len -= tl_head_len;
tl_len -= tl_head_len;
/* don't crash on bad data */
if (val_len < len) {
len = val_len;
}
/* if we run out of return space, truncate */
if (tlv_len < len) {
len = tlv_len;
}
memcpy(tlv_ptr, val_ptr, len);
}
break;
case CAC_OBJECT_TYPE_CERT:
/* read file */
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
" obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
val_len, val_len);
cert_len = 0;
cert_ptr = NULL;
cert_type = 0;
for (tl_ptr = tl, val_ptr = val; tl_len >= 2;
val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = tl_ptr - tl_start;
/* incomplete value */
if (val_len < len)
break;
if (tag == CAC_TAG_CERTIFICATE) {
cert_len = len;
cert_ptr = val_ptr;
}
if (tag == CAC_TAG_CERTINFO) {
if ((len >= 1) && (val_len >=1)) {
cert_type = *val_ptr;
}
}
if (tag == CAC_TAG_MSCUID) {
sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
}
if ((val_len < len) || (tl_len < tl_head_len)) {
break;
}
}
/* if the info byte is 1, then the cert is compressed, decompress it */
if ((cert_type & 0x3) == 1) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len,
cert_ptr, cert_len, COMPRESSION_AUTO);
#else
sc_log(card->ctx, "CAC compression not supported, no zlib");
r = SC_ERROR_NOT_SUPPORTED;
#endif
if (r)
goto done;
} else if (cert_len > 0) {
priv->cache_buf = malloc(cert_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = cert_len;
memcpy(priv->cache_buf, cert_ptr, cert_len);
} else {
sc_log(card->ctx, "Can't read zero-length certificate");
goto done;
}
break;
case CAC_OBJECT_TYPE_GENERIC:
/* TODO
* We have some two buffers in unknown encoding that we
* need to present in PKCS#15 layer.
*/
default:
/* Unknown object type */
sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
r = SC_ERROR_INTERNAL;
goto done;
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
priv->cached = 1;
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
r = len;
done:
if (tl)
free(tl);
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* CAC driver is read only */
static int cac_write_binary(sc_card_t *card, unsigned int idx,
const u8 *buf, size_t count, unsigned long flags)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
/* initialize getting a list and return the number of elements in the list */
static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp)
{
*countp = list_size(list);
list_iterator_start(list);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
/* finalize the list iterator */
static int cac_final_iterator(list_t *list)
{
list_iterator_stop(list);
return SC_SUCCESS;
}
/* fill in the obj_info for the current object on the list and advance to the next object */
static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info)
{
memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t));
if (*entry == NULL) {
return SC_ERROR_FILE_END_REACHED;
}
obj_info->path = (*entry)->path;
obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */
obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff;
obj_info->id.value[1] = (*entry)->fd & 0xff;
obj_info->id.len = 2;
strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, serial->len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (priv->aca_path) {
*path = *priv->aca_path;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
cac_private_data_t * priv = CAC_DATA(card);
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
if (priv == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
switch(cmd) {
case SC_CARDCTL_CAC_GET_ACA_PATH:
return cac_get_ACA_path(card, (sc_path_t *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS:
return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr);
case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS:
return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT:
return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT:
return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS:
return cac_final_iterator(&priv->general_list);
case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS:
return cac_final_iterator(&priv->pki_list);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
/* CAC requires 8 byte response */
u8 rbuf[8];
u8 *rbufp = &rbuf[0];
size_t out_len = sizeof rbuf;
int r;
LOG_FUNC_CALLED(card->ctx);
r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len);
LOG_TEST_RET(card->ctx, r, "Could not get challenge");
if (len < out_len) {
out_len = len;
}
memcpy(rnd, rbuf, out_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len);
}
static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
env->flags, env->operation, env->algorithm,
env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
env->key_ref_len);
if (env->algorithm != SC_ALGORITHM_RSA) {
r = SC_ERROR_NO_CARD_SUPPORT;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int cac_restore_security_env(sc_card_t *card, int se_num)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_rsa_op(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
u8 *outp, *rbuf;
size_t rbuflen, outplen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
datalen, outlen);
outp = out;
outplen = outlen;
/* Not strictly necessary. This code requires the caller to have selected the correct PKI container
* and authenticated to that container with the verifyPin command... All of this under the reader lock.
* The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just
* different sets of APDU's that need to be called), so this call is really a little bit of paranoia */
r = sc_lock(card);
if (r != SC_SUCCESS)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
rbuf = NULL;
rbuflen = 0;
for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) {
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0,
data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen);
if (r < 0) {
break;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
outp += n;
outplen -= n;
}
free(rbuf);
rbuf = NULL;
rbuflen = 0;
}
if (r < 0) {
goto err;
}
rbuf = NULL;
rbuflen = 0;
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen);
if (r < 0) {
goto err;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
/*outp += n; unused */
outplen -= n;
}
free(rbuf);
rbuf = NULL;
r = outlen-outplen;
err:
sc_unlock(card);
if (r < 0) {
sc_mem_clear(out, outlen);
}
if (rbuf) {
free(rbuf);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int cac_compute_signature(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_decipher(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_parse_properties_object(sc_card_t *card, u8 type,
u8 *data, size_t data_len, cac_properties_object_t *object)
{
size_t len;
u8 *val, *val_end, tag;
int parsed = 0;
if (data_len < 11)
return -1;
/* Initilize: non-PKI applet */
object->privatekey = 0;
val = data;
val_end = data + data_len;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_OBJECT_ID:
if (len != 2) {
sc_log(card->ctx, "TAG: Object ID: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]);
memcpy(&object->oid, val, 2);
parsed++;
break;
case CAC_TAG_BUFFER_PROPERTIES:
if (len != 5) {
sc_log(card->ctx, "TAG: Buffer Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* First byte is "Type of Tag Supported" */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Buffer Properties: Type of Tag Supported = 0x%02x",
val[0]);
object->simpletlv = val[0];
parsed++;
break;
case CAC_TAG_PKI_PROPERTIES:
/* 4th byte is "Private Key Initialized" */
if (len != 4) {
sc_log(card->ctx, "TAG: PKI Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
if (type != CAC_TAG_PKI_OBJECT) {
sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object");
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Properties: Private Key Initialized = 0x%02x",
val[2]);
object->privatekey = val[2];
parsed++;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)",tag );
break;
}
}
if (parsed < 2)
return SC_ERROR_INVALID_DATA;
return SC_SUCCESS;
}
static int cac_get_properties(sc_card_t *card, cac_properties_t *prop)
{
u8 *rbuf = NULL;
size_t rbuflen = 0, len;
u8 *val, *val_end, tag;
size_t i = 0;
int r;
prop->num_objects = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0,
&rbuf, &rbuflen);
if (r < 0)
return r;
val = rbuf;
val_end = val + rbuflen;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_INFORMATION:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%0x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_OF_OBJECTS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num objects: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num objects = %hhd", *val);
/* make sure we do not overrun buffer */
prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS);
break;
case CAC_TAG_TV_BUFFER:
if (len != 17) {
sc_log(card->ctx, "TAG: TV Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
case CAC_TAG_PKI_OBJECT:
if (len != 17) {
sc_log(card->ctx, "TAG: PKI Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
default:
/* ignore tags we don't understand */
sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%"
SC_FORMAT_LEN_SIZE_T"u", tag, len);
break;
}
}
free(rbuf);
/* sanity */
if (i != prop->num_objects)
sc_log(card->ctx, "The announced number of objects (%u) "
"did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)",
prop->num_objects, i);
prop->num_objects = i;
return SC_SUCCESS;
}
/*
* CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more
* of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead
* of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS
* if it doesn't like anything about the select, so we always 'request' FCI for CAC1
*
* The rest is just copied from iso7816_select_file
*/
static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type)
{
struct sc_context *ctx;
struct sc_apdu apdu;
unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen, pathtype;
struct sc_file *file = NULL;
cac_private_data_t * priv = CAC_DATA(card);
assert(card != NULL && in_path != NULL);
ctx = card->ctx;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
pathtype = in_path->type;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
in_path->aid.value[0], in_path->aid.value[1],
in_path->aid.value[2], in_path->aid.value[3],
in_path->aid.value[4], in_path->aid.value[5],
in_path->aid.value[6], in_path->aid.len, in_path->value[0],
in_path->value[1], in_path->value[2], in_path->value[3],
in_path->len, in_path->type, in_path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
file_out, in_path->index, in_path->count);
/* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override.
* we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file
* a flag that says 'no, really this path is fine'. We only need to do this for private keys */
if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
if (pathlen > 2) {
path += 2;
pathlen -= 2;
}
}
/* CAC has multiple different type of objects that aren't PKCS #15. When we read
* them we need convert them to something PKCS #15 would understand. Find the object
* and object type here:
*/
if (priv) { /* don't record anything if we haven't been initialized yet */
priv->object_type = CAC_OBJECT_TYPE_GENERIC;
if (cac_is_cert(priv, in_path)) {
priv->object_type = CAC_OBJECT_TYPE_CERT;
}
/* forget any old cached values */
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
}
priv->cache_buf_len = 0;
priv->cached = 0;
}
if (in_path->aid.len) {
if (!pathlen) {
memcpy(path, in_path->aid.value, in_path->aid.len);
pathlen = in_path->aid.len;
pathtype = SC_PATH_TYPE_DF_NAME;
} else {
/* First, select the application */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
apdu.data = in_path->aid.value;
apdu.datalen = in_path->aid.len;
apdu.lc = in_path->aid.len;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
switch (pathtype) {
/* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select.
* Unfortunately we'd also need to update the caching code as well. For now just
* use FILE_ID and change p1 here */
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 2;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
if (file_out != NULL) {
apdu.p2 = 0; /* first record, return FCI */
}
else {
apdu.p2 = 0x0C;
}
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
if (file_out == NULL) {
/* For some cards 'SELECT' can be only with request to return FCI/FCP. */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) {
apdu.p2 = 0x00;
apdu.resplen = sizeof(buf);
if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_FUNC_RETURN(ctx, r);
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
/* This needs to come after the applet selection */
if (priv && in_path->len >= 2) {
/* get applet properties to know if we can treat the
* buffer as SimpleLTV and if we have PKI applet.
*
* Do this only if we select applets for reading
* (not during driver initialization)
*/
cac_properties_t prop;
size_t i = -1;
r = cac_get_properties(card, &prop);
if (r == SC_SUCCESS) {
for (i = 0; i < prop.num_objects; i++) {
sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x",
prop.objects[i].oid[0], prop.objects[i].oid[1],
in_path->value[0], in_path->value[1]);
if (memcmp(prop.objects[i].oid,
in_path->value, 2) == 0)
break;
}
}
if (i < prop.num_objects) {
if (prop.objects[i].privatekey)
priv->object_type = CAC_OBJECT_TYPE_CERT;
else if (prop.objects[i].simpletlv == 0)
priv->object_type = CAC_OBJECT_TYPE_TLV_FILE;
}
}
/* CAC cards never return FCI, fake one */
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
*file_out = file;
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
return cac_select_file_by_type(card, in_path, file_out, card->type);
}
static int cac_finish(sc_card_t *card)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
cac_free_private_data(priv);
}
return SC_SUCCESS;
}
/* select the Card Capabilities Container on CAC-2 */
static int cac_select_CCC(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II);
}
/* Select ACA in non-standard location */
static int cac_select_ACA(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II);
}
static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len)
{
if (len < 10) {
return SC_ERROR_INVALID_DATA;
}
sc_mem_clear(path, sizeof(sc_path_t));
memcpy(path->aid.value, &val->rid, sizeof(val->rid));
memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID));
path->aid.len = sizeof(val->rid) + sizeof(val->applicationID);
memcpy(path->value, &val->objectID, sizeof(val->objectID));
path->len = sizeof(val->objectID);
path->type = SC_PATH_TYPE_FILE_ID;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
path->aid.value[0], path->aid.value[1], path->aid.value[2],
path->aid.value[3], path->aid.value[4], path->aid.value[5],
path->aid.value[6], path->aid.len, path->value[0],
path->value[1], path->len, path->type, path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u",
val->rid[0], val->rid[1], val->rid[2], val->rid[3],
val->rid[4], sizeof(val->rid), val->applicationID[0],
val->applicationID[1], sizeof(val->applicationID),
val->objectID[0], val->objectID[1], sizeof(val->objectID));
return SC_SUCCESS;
}
static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len)
{
cac_object_t new_object;
cac_properties_t prop;
size_t i;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Search for PKI applets (7 B). Ignore generic objects for now */
if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0
&& memcmp(aid, CAC_1_RID "\x00", 6) != 0))
return SC_SUCCESS;
sc_mem_clear(&new_object.path, sizeof(sc_path_t));
memcpy(new_object.path.aid.value, aid, aid_len);
new_object.path.aid.len = aid_len;
/* Call without OID set will just select the AID without subseqent
* OID selection, which we need to figure out just now
*/
cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II);
r = cac_get_properties(card, &prop);
if (r < 0)
return SC_ERROR_INTERNAL;
for (i = 0; i < prop.num_objects; i++) {
/* don't fail just because we have more certs than we can support */
if (priv->cert_next >= MAX_CAC_SLOTS)
return SC_SUCCESS;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"ACA: pki_object found, cert_next=%d (%s), privkey=%d",
priv->cert_next, cac_labels[priv->cert_next],
prop.objects[i].privatekey);
/* If the private key is not initialized, we can safely
* ignore this object here, but increase the pointer to follow
* the certificate labels
*/
if (!prop.objects[i].privatekey) {
priv->cert_next++;
continue;
}
/* OID here has always 2B */
memcpy(new_object.path.value, &prop.objects[i].oid, 2);
new_object.path.len = 2;
new_object.path.type = SC_PATH_TYPE_FILE_ID;
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
}
return SC_SUCCESS;
}
static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len)
{
cac_object_t new_object;
const cac_object_t *obj;
unsigned short object_id;
int r;
r = cac_path_from_cardurl(card, &new_object.path, val, len);
if (r != SC_SUCCESS) {
return r;
}
switch (val->cardApplicationType) {
case CAC_APP_TYPE_PKI:
/* we don't want to overflow the cac_label array. This test could
* go way if we create a label function that will create a unique label
* from a cert index.
*/
if (priv->cert_next >= MAX_CAC_SLOTS)
break; /* don't fail just because we have more certs than we can support */
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name);
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
break;
case CAC_APP_TYPE_GENERAL:
object_id = bebytes2ushort(val->objectID);
obj = cac_find_obj_by_id(object_id);
if (obj == NULL)
break; /* don't fail just because we don't recognize the object */
new_object.name = obj->name;
new_object.fd = 0;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name);
cac_add_object_to_list(&priv->general_list, &new_object);
break;
case CAC_APP_TYPE_SKI:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found");
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType);
/* don't fail just because there is an unknown object in the CCC */
break;
}
return SC_SUCCESS;
}
static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len)
{
size_t card_id_len;
if (len < sizeof(cac_cuid_t)) {
return SC_ERROR_INVALID_DATA;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid)));
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type);
card_id_len = len - (&val->card_id - (u8 *)val);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)",
sc_dump_hex(&val->card_id, card_id_len),
card_id_len);
priv->cuid = *val;
priv->cac_id = malloc(card_id_len);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
memcpy(priv->cac_id, &val->card_id, card_id_len);
priv->cac_id_len = card_id_len;
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv);
static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl,
size_t tl_len, u8 *val, size_t val_len)
{
size_t len = 0;
u8 *tl_end = tl + tl_len;
u8 *val_end = val + val_len;
sc_path_t new_path;
int r;
for (; (tl < tl_end) && (val< val_end); val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_CUID:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID");
r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len);
if (r < 0)
return r;
break;
case CAC_TAG_CC_VERSION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: CC Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: CC Version = 0x%02x", *val);
break;
case CAC_TAG_GRAMMAR_VERION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: Grammar Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Grammar Version = 0x%02x", *val);
break;
case CAC_TAG_CARDURL:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL");
r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len);
if (r < 0)
return r;
break;
/*
* The following are really for file systems cards. This code only cares about CAC VM cards
*/
case CAC_TAG_PKCS15:
if (len != 1) {
sc_log(card->ctx, "TAG: PKCS15: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* TODO should verify that this is '0'. If it's not
* zero, we should drop out of here and let the PKCS 15
* code handle this card */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val);
break;
case CAC_TAG_DATA_MODEL:
case CAC_TAG_CARD_APDU:
case CAC_TAG_CAPABILITY_TUPLES:
case CAC_TAG_STATUS_TUPLES:
case CAC_TAG_REDIRECTION:
case CAC_TAG_ERROR_CODES:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag);
break;
case CAC_TAG_ACCESS_CONTROL:
/* TODO handle access control later */
sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len);
break;
case CAC_TAG_NEXT_CCC:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC");
r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len);
if (r < 0)
return r;
r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II);
if (r < 0)
return r;
r = cac_process_CCC(card, priv);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag );
break;
}
}
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv)
{
u8 *tl = NULL, *val = NULL;
size_t tl_len, val_len;
int r;
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0)
goto done;
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len);
done:
if (tl)
free(tl);
if (val)
free(val);
return r;
}
/* Service Applet Table (Table 5-21) should list all the applets on the
* card, which is a good start if we don't have CCC
*/
static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv,
u8 *val, size_t val_len)
{
size_t len = 0;
u8 *val_end = val + val_len;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
for (; val < val_end; val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_FAMILY:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%02x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_APPLETS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num applets: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num applets = %hhd", *val);
break;
case CAC_TAG_APPLET_ENTRY:
/* Make sure we match the outer length */
if (len < 3 || val[2] != len - 3) {
sc_log(card->ctx, "TAG: Applet Entry: "
"bad length (%"SC_FORMAT_LEN_SIZE_T
"u) or length of internal buffer", len);
break;
}
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Entry: AID", &val[3], val[2]);
/* This is SimpleTLV prefixed with applet ID (1B) */
r = cac_parse_aid(card, priv, &val[3], val[2]);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)", tag);
break;
}
}
return SC_SUCCESS;
}
/* select a CAC pki applet by index */
static int cac_select_pki_applet(sc_card_t *card, int index)
{
sc_path_t applet_path = cac_cac_pki_obj.path;
applet_path.aid.value[applet_path.aid.len-1] = index;
return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II);
}
/*
* Find the first existing CAC applet. If none found, then this isn't a CAC
*/
static int cac_find_first_pki_applet(sc_card_t *card, int *index_out)
{
int r, i;
for (i = 0; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
/* Try to read first two bytes of the buffer to
* make sure it is not just malfunctioning card
*/
u8 params[2] = {CAC_FILE_TAG, 2};
u8 data[2], *out_ptr = data;
size_t len = 2;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0,
¶ms[0], sizeof(params), &out_ptr, &len);
if (r != 2)
continue;
*index_out = i;
return SC_SUCCESS;
}
}
return SC_ERROR_OBJECT_NOT_FOUND;
}
/*
* This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets
*/
static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv)
{
int r, i;
cac_object_t pki_obj = cac_cac_pki_obj;
u8 buf[100];
u8 *val;
size_t val_len;
/* populate PKI objects */
for (i = index; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
pki_obj.name = cac_labels[i];
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name);
pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
pki_obj.fd = i+1; /* don't use id of zero */
cac_add_object_to_list(&priv->pki_list, &pki_obj);
}
}
/* populate non-PKI objects */
for (i=0; i < cac_object_count; i++) {
r = cac_select_file_by_type(card, &cac_objects[i].path, NULL,
SC_CARD_TYPE_CAC_II);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: obj_object found, cert_next=%d (%s),",
i, cac_objects[i].name);
cac_add_object_to_list(&priv->general_list, &cac_objects[i]);
}
}
/*
* create a cuid to simulate the cac 2 cuid.
*/
priv->cuid = cac_cac_cuid;
/* create a serial number by hashing the first 100 bytes of the
* first certificate on the card */
r = cac_select_pki_applet(card, index);
if (r < 0) {
return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
}
val = buf;
val_len = cac_read_binary(card, 0, val, sizeof(buf), 0);
if (val_len > 0) {
priv->cac_id = malloc(20);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
#ifdef ENABLE_OPENSSL
SHA1(val, val_len, priv->cac_id);
priv->cac_id_len = 20;
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"cuid", priv->cac_id, priv->cac_id_len);
#else
sc_log(card->ctx, "OpenSSL Required");
return SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
}
return SC_SUCCESS;
}
static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv)
{
int r;
u8 *val = NULL;
size_t val_len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Assuming ACA is already selected */
r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_ACA_service(card, priv, val, val_len);
if (r == SC_SUCCESS) {
priv->aca_path = malloc(sizeof(sc_path_t));
if (!priv->aca_path) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t));
}
done:
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Look for a CAC card. If it exists, initialize our data structures
*/
static int cac_find_and_initialize(sc_card_t *card, int initialize)
{
int r, index;
cac_private_data_t *priv = NULL;
/* already initialized? */
if (card->drv_data) {
return SC_SUCCESS;
}
/* is this a CAC-2 specified in NIST Interagency Report 6887 -
* "Government Smart Card Interoperability Specification v2.1 July 2003" */
r = cac_select_CCC(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2");
if (!initialize) /* match card only */
return r;
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
r = cac_process_CCC(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* Even some ALT tokens can be missing CCC so we should try with ACA */
r = cac_select_ACA(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
r = cac_process_ACA(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* is this a CAC Alt token without any accompanying structures */
r = cac_find_first_pki_applet(card, &index);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
card->drv_data = priv; /* needed for the read_binary() */
r = cac_populate_cac_alt(card, index, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
return r;
}
card->drv_data = NULL; /* reset on failure */
}
if (priv) {
cac_free_private_data(priv);
}
return r;
}
/* NOTE: returns a bool, 1 card matches, 0 it does not */
static int cac_match_card(sc_card_t *card)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
r = cac_find_and_initialize(card, 0);
return (r == SC_SUCCESS); /* never match */
}
static int cac_init(sc_card_t *card)
{
int r;
unsigned long flags;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_find_and_initialize(card, 1);
if (r < 0) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD);
}
flags = SC_ALGORITHM_RSA_RAW;
_sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
_sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
_sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
/* CAC, like PIV needs Extra validation of (new) PIN during
* a PIN change request, to ensure it's not outside the
* FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2
* (6 character minimum) requirements.
*/
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (data->cmd == SC_PIN_CMD_CHANGE) {
int i = 0;
if (data->pin2.len < 6) {
return SC_ERROR_INVALID_PIN_LENGTH;
}
for(i=0; i < data->pin2.len; ++i) {
if (!isdigit(data->pin2.data[i])) {
return SC_ERROR_INVALID_DATA;
}
}
}
return iso_drv->ops->pin_cmd(card, data, tries_left);
}
static struct sc_card_operations cac_ops;
static struct sc_card_driver cac_drv = {
"Common Access Card (CAC)",
"cac",
&cac_ops,
NULL, 0, NULL
};
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
cac_ops = *iso_drv->ops;
cac_ops.match_card = cac_match_card;
cac_ops.init = cac_init;
cac_ops.finish = cac_finish;
cac_ops.select_file = cac_select_file; /* need to record object type */
cac_ops.get_challenge = cac_get_challenge;
cac_ops.read_binary = cac_read_binary;
cac_ops.write_binary = cac_write_binary;
cac_ops.set_security_env = cac_set_security_env;
cac_ops.restore_security_env = cac_restore_security_env;
cac_ops.compute_signature = cac_compute_signature;
cac_ops.decipher = cac_decipher;
cac_ops.card_ctl = cac_card_ctl;
cac_ops.pin_cmd = cac_pin_cmd;
return &cac_drv;
}
struct sc_card_driver * sc_get_cac_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_341_0 |
crossvul-cpp_data_good_3020_2 | /*
* Copyright (c) 2014-2015 Hisilicon Limited.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/cdev.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <asm/cacheflush.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/of_irq.h>
#include <linux/spinlock.h>
#include "hns_dsaf_main.h"
#include "hns_dsaf_ppe.h"
#include "hns_dsaf_rcb.h"
#define RCB_COMMON_REG_OFFSET 0x80000
#define TX_RING 0
#define RX_RING 1
#define RCB_RESET_WAIT_TIMES 30
#define RCB_RESET_TRY_TIMES 10
/* Because default mtu is 1500, rcb buffer size is set to 2048 enough */
#define RCB_DEFAULT_BUFFER_SIZE 2048
/**
*hns_rcb_wait_fbd_clean - clean fbd
*@qs: ring struct pointer array
*@qnum: num of array
*@flag: tx or rx flag
*/
void hns_rcb_wait_fbd_clean(struct hnae_queue **qs, int q_num, u32 flag)
{
int i, wait_cnt;
u32 fbd_num;
for (wait_cnt = i = 0; i < q_num; wait_cnt++) {
usleep_range(200, 300);
fbd_num = 0;
if (flag & RCB_INT_FLAG_TX)
fbd_num += dsaf_read_dev(qs[i],
RCB_RING_TX_RING_FBDNUM_REG);
if (flag & RCB_INT_FLAG_RX)
fbd_num += dsaf_read_dev(qs[i],
RCB_RING_RX_RING_FBDNUM_REG);
if (!fbd_num)
i++;
if (wait_cnt >= 10000)
break;
}
if (i < q_num)
dev_err(qs[i]->handle->owner_dev,
"queue(%d) wait fbd(%d) clean fail!!\n", i, fbd_num);
}
/**
*hns_rcb_reset_ring_hw - ring reset
*@q: ring struct pointer
*/
void hns_rcb_reset_ring_hw(struct hnae_queue *q)
{
u32 wait_cnt;
u32 try_cnt = 0;
u32 could_ret;
u32 tx_fbd_num;
while (try_cnt++ < RCB_RESET_TRY_TIMES) {
usleep_range(100, 200);
tx_fbd_num = dsaf_read_dev(q, RCB_RING_TX_RING_FBDNUM_REG);
if (tx_fbd_num)
continue;
dsaf_write_dev(q, RCB_RING_PREFETCH_EN_REG, 0);
dsaf_write_dev(q, RCB_RING_T0_BE_RST, 1);
msleep(20);
could_ret = dsaf_read_dev(q, RCB_RING_COULD_BE_RST);
wait_cnt = 0;
while (!could_ret && (wait_cnt < RCB_RESET_WAIT_TIMES)) {
dsaf_write_dev(q, RCB_RING_T0_BE_RST, 0);
dsaf_write_dev(q, RCB_RING_T0_BE_RST, 1);
msleep(20);
could_ret = dsaf_read_dev(q, RCB_RING_COULD_BE_RST);
wait_cnt++;
}
dsaf_write_dev(q, RCB_RING_T0_BE_RST, 0);
if (could_ret)
break;
}
if (try_cnt >= RCB_RESET_TRY_TIMES)
dev_err(q->dev->dev, "port%d reset ring fail\n",
hns_ae_get_vf_cb(q->handle)->port_index);
}
/**
*hns_rcb_int_ctrl_hw - rcb irq enable control
*@q: hnae queue struct pointer
*@flag:ring flag tx or rx
*@mask:mask
*/
void hns_rcb_int_ctrl_hw(struct hnae_queue *q, u32 flag, u32 mask)
{
u32 int_mask_en = !!mask;
if (flag & RCB_INT_FLAG_TX) {
dsaf_write_dev(q, RCB_RING_INTMSK_TXWL_REG, int_mask_en);
dsaf_write_dev(q, RCB_RING_INTMSK_TX_OVERTIME_REG,
int_mask_en);
}
if (flag & RCB_INT_FLAG_RX) {
dsaf_write_dev(q, RCB_RING_INTMSK_RXWL_REG, int_mask_en);
dsaf_write_dev(q, RCB_RING_INTMSK_RX_OVERTIME_REG,
int_mask_en);
}
}
void hns_rcb_int_clr_hw(struct hnae_queue *q, u32 flag)
{
if (flag & RCB_INT_FLAG_TX) {
dsaf_write_dev(q, RCB_RING_INTSTS_TX_RING_REG, 1);
dsaf_write_dev(q, RCB_RING_INTSTS_TX_OVERTIME_REG, 1);
}
if (flag & RCB_INT_FLAG_RX) {
dsaf_write_dev(q, RCB_RING_INTSTS_RX_RING_REG, 1);
dsaf_write_dev(q, RCB_RING_INTSTS_RX_OVERTIME_REG, 1);
}
}
void hns_rcbv2_int_ctrl_hw(struct hnae_queue *q, u32 flag, u32 mask)
{
u32 int_mask_en = !!mask;
if (flag & RCB_INT_FLAG_TX)
dsaf_write_dev(q, RCB_RING_INTMSK_TXWL_REG, int_mask_en);
if (flag & RCB_INT_FLAG_RX)
dsaf_write_dev(q, RCB_RING_INTMSK_RXWL_REG, int_mask_en);
}
void hns_rcbv2_int_clr_hw(struct hnae_queue *q, u32 flag)
{
if (flag & RCB_INT_FLAG_TX)
dsaf_write_dev(q, RCBV2_TX_RING_INT_STS_REG, 1);
if (flag & RCB_INT_FLAG_RX)
dsaf_write_dev(q, RCBV2_RX_RING_INT_STS_REG, 1);
}
/**
*hns_rcb_ring_enable_hw - enable ring
*@ring: rcb ring
*/
void hns_rcb_ring_enable_hw(struct hnae_queue *q, u32 val)
{
dsaf_write_dev(q, RCB_RING_PREFETCH_EN_REG, !!val);
}
void hns_rcb_start(struct hnae_queue *q, u32 val)
{
hns_rcb_ring_enable_hw(q, val);
}
/**
*hns_rcb_common_init_commit_hw - make rcb common init completed
*@rcb_common: rcb common device
*/
void hns_rcb_common_init_commit_hw(struct rcb_common_cb *rcb_common)
{
wmb(); /* Sync point before breakpoint */
dsaf_write_dev(rcb_common, RCB_COM_CFG_SYS_FSH_REG, 1);
wmb(); /* Sync point after breakpoint */
}
/* hns_rcb_set_tx_ring_bs - init rcb ring buf size regester
*@q: hnae_queue
*@buf_size: buffer size set to hw
*/
void hns_rcb_set_tx_ring_bs(struct hnae_queue *q, u32 buf_size)
{
u32 bd_size_type = hns_rcb_buf_size2type(buf_size);
dsaf_write_dev(q, RCB_RING_TX_RING_BD_LEN_REG,
bd_size_type);
}
/* hns_rcb_set_rx_ring_bs - init rcb ring buf size regester
*@q: hnae_queue
*@buf_size: buffer size set to hw
*/
void hns_rcb_set_rx_ring_bs(struct hnae_queue *q, u32 buf_size)
{
u32 bd_size_type = hns_rcb_buf_size2type(buf_size);
dsaf_write_dev(q, RCB_RING_RX_RING_BD_LEN_REG,
bd_size_type);
}
/**
*hns_rcb_ring_init - init rcb ring
*@ring_pair: ring pair control block
*@ring_type: ring type, RX_RING or TX_RING
*/
static void hns_rcb_ring_init(struct ring_pair_cb *ring_pair, int ring_type)
{
struct hnae_queue *q = &ring_pair->q;
struct hnae_ring *ring =
(ring_type == RX_RING) ? &q->rx_ring : &q->tx_ring;
dma_addr_t dma = ring->desc_dma_addr;
if (ring_type == RX_RING) {
dsaf_write_dev(q, RCB_RING_RX_RING_BASEADDR_L_REG,
(u32)dma);
dsaf_write_dev(q, RCB_RING_RX_RING_BASEADDR_H_REG,
(u32)((dma >> 31) >> 1));
hns_rcb_set_rx_ring_bs(q, ring->buf_size);
dsaf_write_dev(q, RCB_RING_RX_RING_BD_NUM_REG,
ring_pair->port_id_in_comm);
dsaf_write_dev(q, RCB_RING_RX_RING_PKTLINE_REG,
ring_pair->port_id_in_comm);
} else {
dsaf_write_dev(q, RCB_RING_TX_RING_BASEADDR_L_REG,
(u32)dma);
dsaf_write_dev(q, RCB_RING_TX_RING_BASEADDR_H_REG,
(u32)((dma >> 31) >> 1));
hns_rcb_set_tx_ring_bs(q, ring->buf_size);
dsaf_write_dev(q, RCB_RING_TX_RING_BD_NUM_REG,
ring_pair->port_id_in_comm);
dsaf_write_dev(q, RCB_RING_TX_RING_PKTLINE_REG,
ring_pair->port_id_in_comm + HNS_RCB_TX_PKTLINE_OFFSET);
}
}
/**
*hns_rcb_init_hw - init rcb hardware
*@ring: rcb ring
*/
void hns_rcb_init_hw(struct ring_pair_cb *ring)
{
hns_rcb_ring_init(ring, RX_RING);
hns_rcb_ring_init(ring, TX_RING);
}
/**
*hns_rcb_set_port_desc_cnt - set rcb port description num
*@rcb_common: rcb_common device
*@port_idx:port index
*@desc_cnt:BD num
*/
static void hns_rcb_set_port_desc_cnt(struct rcb_common_cb *rcb_common,
u32 port_idx, u32 desc_cnt)
{
dsaf_write_dev(rcb_common, RCB_CFG_BD_NUM_REG + port_idx * 4,
desc_cnt);
}
static void hns_rcb_set_port_timeout(
struct rcb_common_cb *rcb_common, u32 port_idx, u32 timeout)
{
if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) {
dsaf_write_dev(rcb_common, RCB_CFG_OVERTIME_REG,
timeout * HNS_RCB_CLK_FREQ_MHZ);
} else if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) {
if (timeout > HNS_RCB_DEF_GAP_TIME_USECS)
dsaf_write_dev(rcb_common,
RCB_PORT_INT_GAPTIME_REG + port_idx * 4,
HNS_RCB_DEF_GAP_TIME_USECS);
else
dsaf_write_dev(rcb_common,
RCB_PORT_INT_GAPTIME_REG + port_idx * 4,
timeout);
dsaf_write_dev(rcb_common,
RCB_PORT_CFG_OVERTIME_REG + port_idx * 4,
timeout);
} else {
dsaf_write_dev(rcb_common,
RCB_PORT_CFG_OVERTIME_REG + port_idx * 4,
timeout);
}
}
static int hns_rcb_common_get_port_num(struct rcb_common_cb *rcb_common)
{
if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev))
return HNS_RCB_SERVICE_NW_ENGINE_NUM;
else
return HNS_RCB_DEBUG_NW_ENGINE_NUM;
}
/*clr rcb comm exception irq**/
static void hns_rcb_comm_exc_irq_en(
struct rcb_common_cb *rcb_common, int en)
{
u32 clr_vlue = 0xfffffffful;
u32 msk_vlue = en ? 0 : 0xfffffffful;
/* clr int*/
dsaf_write_dev(rcb_common, RCB_COM_INTSTS_ECC_ERR_REG, clr_vlue);
dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_RING_STS, clr_vlue);
dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_BD_RINT_STS, clr_vlue);
dsaf_write_dev(rcb_common, RCB_COM_RINT_TX_PKT_REG, clr_vlue);
dsaf_write_dev(rcb_common, RCB_COM_AXI_ERR_STS, clr_vlue);
/*en msk*/
dsaf_write_dev(rcb_common, RCB_COM_INTMASK_ECC_ERR_REG, msk_vlue);
dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_INTMASK_RING, msk_vlue);
/*for tx bd neednot cacheline, so msk sf_txring_fbd_intmask (bit 1)**/
dsaf_write_dev(rcb_common, RCB_COM_SF_CFG_INTMASK_BD, msk_vlue | 2);
dsaf_write_dev(rcb_common, RCB_COM_INTMSK_TX_PKT_REG, msk_vlue);
dsaf_write_dev(rcb_common, RCB_COM_AXI_WR_ERR_INTMASK, msk_vlue);
}
/**
*hns_rcb_common_init_hw - init rcb common hardware
*@rcb_common: rcb_common device
*retuen 0 - success , negative --fail
*/
int hns_rcb_common_init_hw(struct rcb_common_cb *rcb_common)
{
u32 reg_val;
int i;
int port_num = hns_rcb_common_get_port_num(rcb_common);
hns_rcb_comm_exc_irq_en(rcb_common, 0);
reg_val = dsaf_read_dev(rcb_common, RCB_COM_CFG_INIT_FLAG_REG);
if (0x1 != (reg_val & 0x1)) {
dev_err(rcb_common->dsaf_dev->dev,
"RCB_COM_CFG_INIT_FLAG_REG reg = 0x%x\n", reg_val);
return -EBUSY;
}
for (i = 0; i < port_num; i++) {
hns_rcb_set_port_desc_cnt(rcb_common, i, rcb_common->desc_num);
hns_rcb_set_rx_coalesced_frames(
rcb_common, i, HNS_RCB_DEF_RX_COALESCED_FRAMES);
if (!AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver) &&
!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev))
hns_rcb_set_tx_coalesced_frames(
rcb_common, i, HNS_RCB_DEF_TX_COALESCED_FRAMES);
hns_rcb_set_port_timeout(
rcb_common, i, HNS_RCB_DEF_COALESCED_USECS);
}
dsaf_write_dev(rcb_common, RCB_COM_CFG_ENDIAN_REG,
HNS_RCB_COMMON_ENDIAN);
if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) {
dsaf_write_dev(rcb_common, RCB_COM_CFG_FNA_REG, 0x0);
dsaf_write_dev(rcb_common, RCB_COM_CFG_FA_REG, 0x1);
} else {
dsaf_set_dev_bit(rcb_common, RCBV2_COM_CFG_USER_REG,
RCB_COM_CFG_FNA_B, false);
dsaf_set_dev_bit(rcb_common, RCBV2_COM_CFG_USER_REG,
RCB_COM_CFG_FA_B, true);
dsaf_set_dev_bit(rcb_common, RCBV2_COM_CFG_TSO_MODE_REG,
RCB_COM_TSO_MODE_B, HNS_TSO_MODE_8BD_32K);
}
return 0;
}
int hns_rcb_buf_size2type(u32 buf_size)
{
int bd_size_type;
switch (buf_size) {
case 512:
bd_size_type = HNS_BD_SIZE_512_TYPE;
break;
case 1024:
bd_size_type = HNS_BD_SIZE_1024_TYPE;
break;
case 2048:
bd_size_type = HNS_BD_SIZE_2048_TYPE;
break;
case 4096:
bd_size_type = HNS_BD_SIZE_4096_TYPE;
break;
default:
bd_size_type = -EINVAL;
}
return bd_size_type;
}
static void hns_rcb_ring_get_cfg(struct hnae_queue *q, int ring_type)
{
struct hnae_ring *ring;
struct rcb_common_cb *rcb_common;
struct ring_pair_cb *ring_pair_cb;
u16 desc_num, mdnum_ppkt;
bool irq_idx, is_ver1;
ring_pair_cb = container_of(q, struct ring_pair_cb, q);
is_ver1 = AE_IS_VER1(ring_pair_cb->rcb_common->dsaf_dev->dsaf_ver);
if (ring_type == RX_RING) {
ring = &q->rx_ring;
ring->io_base = ring_pair_cb->q.io_base;
irq_idx = HNS_RCB_IRQ_IDX_RX;
mdnum_ppkt = HNS_RCB_RING_MAX_BD_PER_PKT;
} else {
ring = &q->tx_ring;
ring->io_base = (u8 __iomem *)ring_pair_cb->q.io_base +
HNS_RCB_TX_REG_OFFSET;
irq_idx = HNS_RCB_IRQ_IDX_TX;
mdnum_ppkt = is_ver1 ? HNS_RCB_RING_MAX_TXBD_PER_PKT :
HNS_RCBV2_RING_MAX_TXBD_PER_PKT;
}
rcb_common = ring_pair_cb->rcb_common;
desc_num = rcb_common->dsaf_dev->desc_num;
ring->desc = NULL;
ring->desc_cb = NULL;
ring->irq = ring_pair_cb->virq[irq_idx];
ring->desc_dma_addr = 0;
ring->buf_size = RCB_DEFAULT_BUFFER_SIZE;
ring->desc_num = desc_num;
ring->max_desc_num_per_pkt = mdnum_ppkt;
ring->max_raw_data_sz_per_desc = HNS_RCB_MAX_PKT_SIZE;
ring->max_pkt_size = HNS_RCB_MAX_PKT_SIZE;
ring->next_to_use = 0;
ring->next_to_clean = 0;
}
static void hns_rcb_ring_pair_get_cfg(struct ring_pair_cb *ring_pair_cb)
{
ring_pair_cb->q.handle = NULL;
hns_rcb_ring_get_cfg(&ring_pair_cb->q, RX_RING);
hns_rcb_ring_get_cfg(&ring_pair_cb->q, TX_RING);
}
static int hns_rcb_get_port_in_comm(
struct rcb_common_cb *rcb_common, int ring_idx)
{
return ring_idx / (rcb_common->max_q_per_vf * rcb_common->max_vfn);
}
#define SERVICE_RING_IRQ_IDX(v1) \
((v1) ? HNS_SERVICE_RING_IRQ_IDX : HNSV2_SERVICE_RING_IRQ_IDX)
static int hns_rcb_get_base_irq_idx(struct rcb_common_cb *rcb_common)
{
bool is_ver1 = AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver);
if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev))
return SERVICE_RING_IRQ_IDX(is_ver1);
else
return HNS_DEBUG_RING_IRQ_IDX;
}
#define RCB_COMM_BASE_TO_RING_BASE(base, ringid)\
((base) + 0x10000 + HNS_RCB_REG_OFFSET * (ringid))
/**
*hns_rcb_get_cfg - get rcb config
*@rcb_common: rcb common device
*/
int hns_rcb_get_cfg(struct rcb_common_cb *rcb_common)
{
struct ring_pair_cb *ring_pair_cb;
u32 i;
u32 ring_num = rcb_common->ring_num;
int base_irq_idx = hns_rcb_get_base_irq_idx(rcb_common);
struct platform_device *pdev =
to_platform_device(rcb_common->dsaf_dev->dev);
bool is_ver1 = AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver);
for (i = 0; i < ring_num; i++) {
ring_pair_cb = &rcb_common->ring_pair_cb[i];
ring_pair_cb->rcb_common = rcb_common;
ring_pair_cb->dev = rcb_common->dsaf_dev->dev;
ring_pair_cb->index = i;
ring_pair_cb->q.io_base =
RCB_COMM_BASE_TO_RING_BASE(rcb_common->io_base, i);
ring_pair_cb->port_id_in_comm =
hns_rcb_get_port_in_comm(rcb_common, i);
ring_pair_cb->virq[HNS_RCB_IRQ_IDX_TX] =
is_ver1 ? platform_get_irq(pdev, base_irq_idx + i * 2) :
platform_get_irq(pdev, base_irq_idx + i * 3 + 1);
ring_pair_cb->virq[HNS_RCB_IRQ_IDX_RX] =
is_ver1 ? platform_get_irq(pdev, base_irq_idx + i * 2 + 1) :
platform_get_irq(pdev, base_irq_idx + i * 3);
if ((ring_pair_cb->virq[HNS_RCB_IRQ_IDX_TX] == -EPROBE_DEFER) ||
(ring_pair_cb->virq[HNS_RCB_IRQ_IDX_RX] == -EPROBE_DEFER))
return -EPROBE_DEFER;
ring_pair_cb->q.phy_base =
RCB_COMM_BASE_TO_RING_BASE(rcb_common->phy_base, i);
hns_rcb_ring_pair_get_cfg(ring_pair_cb);
}
return 0;
}
/**
*hns_rcb_get_rx_coalesced_frames - get rcb port rx coalesced frames
*@rcb_common: rcb_common device
*@port_idx:port id in comm
*
*Returns: coalesced_frames
*/
u32 hns_rcb_get_rx_coalesced_frames(
struct rcb_common_cb *rcb_common, u32 port_idx)
{
return dsaf_read_dev(rcb_common, RCB_CFG_PKTLINE_REG + port_idx * 4);
}
/**
*hns_rcb_get_tx_coalesced_frames - get rcb port tx coalesced frames
*@rcb_common: rcb_common device
*@port_idx:port id in comm
*
*Returns: coalesced_frames
*/
u32 hns_rcb_get_tx_coalesced_frames(
struct rcb_common_cb *rcb_common, u32 port_idx)
{
u64 reg;
reg = RCB_CFG_PKTLINE_REG + (port_idx + HNS_RCB_TX_PKTLINE_OFFSET) * 4;
return dsaf_read_dev(rcb_common, reg);
}
/**
*hns_rcb_get_coalesce_usecs - get rcb port coalesced time_out
*@rcb_common: rcb_common device
*@port_idx:port id in comm
*
*Returns: time_out
*/
u32 hns_rcb_get_coalesce_usecs(
struct rcb_common_cb *rcb_common, u32 port_idx)
{
if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver))
return dsaf_read_dev(rcb_common, RCB_CFG_OVERTIME_REG) /
HNS_RCB_CLK_FREQ_MHZ;
else
return dsaf_read_dev(rcb_common,
RCB_PORT_CFG_OVERTIME_REG + port_idx * 4);
}
/**
*hns_rcb_set_coalesce_usecs - set rcb port coalesced time_out
*@rcb_common: rcb_common device
*@port_idx:port id in comm
*@timeout:tx/rx time for coalesced time_out
*
* Returns:
* Zero for success, or an error code in case of failure
*/
int hns_rcb_set_coalesce_usecs(
struct rcb_common_cb *rcb_common, u32 port_idx, u32 timeout)
{
u32 old_timeout = hns_rcb_get_coalesce_usecs(rcb_common, port_idx);
if (timeout == old_timeout)
return 0;
if (AE_IS_VER1(rcb_common->dsaf_dev->dsaf_ver)) {
if (!HNS_DSAF_IS_DEBUG(rcb_common->dsaf_dev)) {
dev_err(rcb_common->dsaf_dev->dev,
"error: not support coalesce_usecs setting!\n");
return -EINVAL;
}
}
if (timeout > HNS_RCB_MAX_COALESCED_USECS || timeout == 0) {
dev_err(rcb_common->dsaf_dev->dev,
"error: coalesce_usecs setting supports 1~1023us\n");
return -EINVAL;
}
hns_rcb_set_port_timeout(rcb_common, port_idx, timeout);
return 0;
}
/**
*hns_rcb_set_tx_coalesced_frames - set rcb coalesced frames
*@rcb_common: rcb_common device
*@port_idx:port id in comm
*@coalesced_frames:tx/rx BD num for coalesced frames
*
* Returns:
* Zero for success, or an error code in case of failure
*/
int hns_rcb_set_tx_coalesced_frames(
struct rcb_common_cb *rcb_common, u32 port_idx, u32 coalesced_frames)
{
u32 old_waterline =
hns_rcb_get_tx_coalesced_frames(rcb_common, port_idx);
u64 reg;
if (coalesced_frames == old_waterline)
return 0;
if (coalesced_frames != 1) {
dev_err(rcb_common->dsaf_dev->dev,
"error: not support tx coalesce_frames setting!\n");
return -EINVAL;
}
reg = RCB_CFG_PKTLINE_REG + (port_idx + HNS_RCB_TX_PKTLINE_OFFSET) * 4;
dsaf_write_dev(rcb_common, reg, coalesced_frames);
return 0;
}
/**
*hns_rcb_set_rx_coalesced_frames - set rcb rx coalesced frames
*@rcb_common: rcb_common device
*@port_idx:port id in comm
*@coalesced_frames:tx/rx BD num for coalesced frames
*
* Returns:
* Zero for success, or an error code in case of failure
*/
int hns_rcb_set_rx_coalesced_frames(
struct rcb_common_cb *rcb_common, u32 port_idx, u32 coalesced_frames)
{
u32 old_waterline =
hns_rcb_get_rx_coalesced_frames(rcb_common, port_idx);
if (coalesced_frames == old_waterline)
return 0;
if (coalesced_frames >= rcb_common->desc_num ||
coalesced_frames > HNS_RCB_MAX_COALESCED_FRAMES ||
coalesced_frames < HNS_RCB_MIN_COALESCED_FRAMES) {
dev_err(rcb_common->dsaf_dev->dev,
"error: not support coalesce_frames setting!\n");
return -EINVAL;
}
dsaf_write_dev(rcb_common, RCB_CFG_PKTLINE_REG + port_idx * 4,
coalesced_frames);
return 0;
}
/**
*hns_rcb_get_queue_mode - get max VM number and max ring number per VM
* accordding to dsaf mode
*@dsaf_mode: dsaf mode
*@max_vfn : max vfn number
*@max_q_per_vf:max ring number per vm
*/
void hns_rcb_get_queue_mode(enum dsaf_mode dsaf_mode, u16 *max_vfn,
u16 *max_q_per_vf)
{
switch (dsaf_mode) {
case DSAF_MODE_DISABLE_6PORT_0VM:
*max_vfn = 1;
*max_q_per_vf = 16;
break;
case DSAF_MODE_DISABLE_FIX:
case DSAF_MODE_DISABLE_SP:
*max_vfn = 1;
*max_q_per_vf = 1;
break;
case DSAF_MODE_DISABLE_2PORT_64VM:
*max_vfn = 64;
*max_q_per_vf = 1;
break;
case DSAF_MODE_DISABLE_6PORT_16VM:
*max_vfn = 16;
*max_q_per_vf = 1;
break;
default:
*max_vfn = 1;
*max_q_per_vf = 16;
break;
}
}
int hns_rcb_get_ring_num(struct dsaf_device *dsaf_dev)
{
switch (dsaf_dev->dsaf_mode) {
case DSAF_MODE_ENABLE_FIX:
case DSAF_MODE_DISABLE_SP:
return 1;
case DSAF_MODE_DISABLE_FIX:
return 6;
case DSAF_MODE_ENABLE_0VM:
return 32;
case DSAF_MODE_DISABLE_6PORT_0VM:
case DSAF_MODE_ENABLE_16VM:
case DSAF_MODE_DISABLE_6PORT_2VM:
case DSAF_MODE_DISABLE_6PORT_16VM:
case DSAF_MODE_DISABLE_6PORT_4VM:
case DSAF_MODE_ENABLE_8VM:
return 96;
case DSAF_MODE_DISABLE_2PORT_16VM:
case DSAF_MODE_DISABLE_2PORT_8VM:
case DSAF_MODE_ENABLE_32VM:
case DSAF_MODE_DISABLE_2PORT_64VM:
case DSAF_MODE_ENABLE_128VM:
return 128;
default:
dev_warn(dsaf_dev->dev,
"get ring num fail,use default!dsaf_mode=%d\n",
dsaf_dev->dsaf_mode);
return 128;
}
}
void __iomem *hns_rcb_common_get_vaddr(struct rcb_common_cb *rcb_common)
{
struct dsaf_device *dsaf_dev = rcb_common->dsaf_dev;
return dsaf_dev->ppe_base + RCB_COMMON_REG_OFFSET;
}
static phys_addr_t hns_rcb_common_get_paddr(struct rcb_common_cb *rcb_common)
{
struct dsaf_device *dsaf_dev = rcb_common->dsaf_dev;
return dsaf_dev->ppe_paddr + RCB_COMMON_REG_OFFSET;
}
int hns_rcb_common_get_cfg(struct dsaf_device *dsaf_dev,
int comm_index)
{
struct rcb_common_cb *rcb_common;
enum dsaf_mode dsaf_mode = dsaf_dev->dsaf_mode;
u16 max_vfn;
u16 max_q_per_vf;
int ring_num = hns_rcb_get_ring_num(dsaf_dev);
rcb_common =
devm_kzalloc(dsaf_dev->dev, sizeof(*rcb_common) +
ring_num * sizeof(struct ring_pair_cb), GFP_KERNEL);
if (!rcb_common) {
dev_err(dsaf_dev->dev, "rcb common devm_kzalloc fail!\n");
return -ENOMEM;
}
rcb_common->comm_index = comm_index;
rcb_common->ring_num = ring_num;
rcb_common->dsaf_dev = dsaf_dev;
rcb_common->desc_num = dsaf_dev->desc_num;
hns_rcb_get_queue_mode(dsaf_mode, &max_vfn, &max_q_per_vf);
rcb_common->max_vfn = max_vfn;
rcb_common->max_q_per_vf = max_q_per_vf;
rcb_common->io_base = hns_rcb_common_get_vaddr(rcb_common);
rcb_common->phy_base = hns_rcb_common_get_paddr(rcb_common);
dsaf_dev->rcb_common[comm_index] = rcb_common;
return 0;
}
void hns_rcb_common_free_cfg(struct dsaf_device *dsaf_dev,
u32 comm_index)
{
dsaf_dev->rcb_common[comm_index] = NULL;
}
void hns_rcb_update_stats(struct hnae_queue *queue)
{
struct ring_pair_cb *ring =
container_of(queue, struct ring_pair_cb, q);
struct dsaf_device *dsaf_dev = ring->rcb_common->dsaf_dev;
struct ppe_common_cb *ppe_common
= dsaf_dev->ppe_common[ring->rcb_common->comm_index];
struct hns_ring_hw_stats *hw_stats = &ring->hw_stats;
hw_stats->rx_pkts += dsaf_read_dev(queue,
RCB_RING_RX_RING_PKTNUM_RECORD_REG);
dsaf_write_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG, 0x1);
hw_stats->ppe_rx_ok_pkts += dsaf_read_dev(ppe_common,
PPE_COM_HIS_RX_PKT_QID_OK_CNT_REG + 4 * ring->index);
hw_stats->ppe_rx_drop_pkts += dsaf_read_dev(ppe_common,
PPE_COM_HIS_RX_PKT_QID_DROP_CNT_REG + 4 * ring->index);
hw_stats->tx_pkts += dsaf_read_dev(queue,
RCB_RING_TX_RING_PKTNUM_RECORD_REG);
dsaf_write_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG, 0x1);
hw_stats->ppe_tx_ok_pkts += dsaf_read_dev(ppe_common,
PPE_COM_HIS_TX_PKT_QID_OK_CNT_REG + 4 * ring->index);
hw_stats->ppe_tx_drop_pkts += dsaf_read_dev(ppe_common,
PPE_COM_HIS_TX_PKT_QID_ERR_CNT_REG + 4 * ring->index);
}
/**
*hns_rcb_get_stats - get rcb statistic
*@ring: rcb ring
*@data:statistic value
*/
void hns_rcb_get_stats(struct hnae_queue *queue, u64 *data)
{
u64 *regs_buff = data;
struct ring_pair_cb *ring =
container_of(queue, struct ring_pair_cb, q);
struct hns_ring_hw_stats *hw_stats = &ring->hw_stats;
regs_buff[0] = hw_stats->tx_pkts;
regs_buff[1] = hw_stats->ppe_tx_ok_pkts;
regs_buff[2] = hw_stats->ppe_tx_drop_pkts;
regs_buff[3] =
dsaf_read_dev(queue, RCB_RING_TX_RING_FBDNUM_REG);
regs_buff[4] = queue->tx_ring.stats.tx_pkts;
regs_buff[5] = queue->tx_ring.stats.tx_bytes;
regs_buff[6] = queue->tx_ring.stats.tx_err_cnt;
regs_buff[7] = queue->tx_ring.stats.io_err_cnt;
regs_buff[8] = queue->tx_ring.stats.sw_err_cnt;
regs_buff[9] = queue->tx_ring.stats.seg_pkt_cnt;
regs_buff[10] = queue->tx_ring.stats.restart_queue;
regs_buff[11] = queue->tx_ring.stats.tx_busy;
regs_buff[12] = hw_stats->rx_pkts;
regs_buff[13] = hw_stats->ppe_rx_ok_pkts;
regs_buff[14] = hw_stats->ppe_rx_drop_pkts;
regs_buff[15] =
dsaf_read_dev(queue, RCB_RING_RX_RING_FBDNUM_REG);
regs_buff[16] = queue->rx_ring.stats.rx_pkts;
regs_buff[17] = queue->rx_ring.stats.rx_bytes;
regs_buff[18] = queue->rx_ring.stats.rx_err_cnt;
regs_buff[19] = queue->rx_ring.stats.io_err_cnt;
regs_buff[20] = queue->rx_ring.stats.sw_err_cnt;
regs_buff[21] = queue->rx_ring.stats.seg_pkt_cnt;
regs_buff[22] = queue->rx_ring.stats.reuse_pg_cnt;
regs_buff[23] = queue->rx_ring.stats.err_pkt_len;
regs_buff[24] = queue->rx_ring.stats.non_vld_descs;
regs_buff[25] = queue->rx_ring.stats.err_bd_num;
regs_buff[26] = queue->rx_ring.stats.l2_err;
regs_buff[27] = queue->rx_ring.stats.l3l4_csum_err;
}
/**
*hns_rcb_get_ring_sset_count - rcb string set count
*@stringset:ethtool cmd
*return rcb ring string set count
*/
int hns_rcb_get_ring_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS)
return HNS_RING_STATIC_REG_NUM;
return 0;
}
/**
*hns_rcb_get_common_regs_count - rcb common regs count
*return regs count
*/
int hns_rcb_get_common_regs_count(void)
{
return HNS_RCB_COMMON_DUMP_REG_NUM;
}
/**
*rcb_get_sset_count - rcb ring regs count
*return regs count
*/
int hns_rcb_get_ring_regs_count(void)
{
return HNS_RCB_RING_DUMP_REG_NUM;
}
/**
*hns_rcb_get_strings - get rcb string set
*@stringset:string set index
*@data:strings name value
*@index:queue index
*/
void hns_rcb_get_strings(int stringset, u8 *data, int index)
{
char *buff = (char *)data;
if (stringset != ETH_SS_STATS)
return;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_rcb_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_ppe_tx_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_ppe_drop_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_fbd_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_bytes", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_err_cnt", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_io_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_sw_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_seg_pkt", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_restart_queue", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "tx_ring%d_tx_busy", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_rcb_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_ppe_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_ppe_drop_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_fbd_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_pkt_num", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_bytes", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_err_cnt", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_io_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_sw_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_seg_pkt", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_reuse_pg", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_len_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_non_vld_desc_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_bd_num_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_l2_err", index);
buff = buff + ETH_GSTRING_LEN;
snprintf(buff, ETH_GSTRING_LEN, "rx_ring%d_l3l4csum_err", index);
}
void hns_rcb_get_common_regs(struct rcb_common_cb *rcb_com, void *data)
{
u32 *regs = data;
bool is_ver1 = AE_IS_VER1(rcb_com->dsaf_dev->dsaf_ver);
bool is_dbg = HNS_DSAF_IS_DEBUG(rcb_com->dsaf_dev);
u32 reg_tmp;
u32 reg_num_tmp;
u32 i = 0;
/*rcb common registers */
regs[0] = dsaf_read_dev(rcb_com, RCB_COM_CFG_ENDIAN_REG);
regs[1] = dsaf_read_dev(rcb_com, RCB_COM_CFG_SYS_FSH_REG);
regs[2] = dsaf_read_dev(rcb_com, RCB_COM_CFG_INIT_FLAG_REG);
regs[3] = dsaf_read_dev(rcb_com, RCB_COM_CFG_PKT_REG);
regs[4] = dsaf_read_dev(rcb_com, RCB_COM_CFG_RINVLD_REG);
regs[5] = dsaf_read_dev(rcb_com, RCB_COM_CFG_FNA_REG);
regs[6] = dsaf_read_dev(rcb_com, RCB_COM_CFG_FA_REG);
regs[7] = dsaf_read_dev(rcb_com, RCB_COM_CFG_PKT_TC_BP_REG);
regs[8] = dsaf_read_dev(rcb_com, RCB_COM_CFG_PPE_TNL_CLKEN_REG);
regs[9] = dsaf_read_dev(rcb_com, RCB_COM_INTMSK_TX_PKT_REG);
regs[10] = dsaf_read_dev(rcb_com, RCB_COM_RINT_TX_PKT_REG);
regs[11] = dsaf_read_dev(rcb_com, RCB_COM_INTMASK_ECC_ERR_REG);
regs[12] = dsaf_read_dev(rcb_com, RCB_COM_INTSTS_ECC_ERR_REG);
regs[13] = dsaf_read_dev(rcb_com, RCB_COM_EBD_SRAM_ERR_REG);
regs[14] = dsaf_read_dev(rcb_com, RCB_COM_RXRING_ERR_REG);
regs[15] = dsaf_read_dev(rcb_com, RCB_COM_TXRING_ERR_REG);
regs[16] = dsaf_read_dev(rcb_com, RCB_COM_TX_FBD_ERR_REG);
regs[17] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK_EN_REG);
regs[18] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK0_REG);
regs[19] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK1_REG);
regs[20] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK2_REG);
regs[21] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK3_REG);
regs[22] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK4_REG);
regs[23] = dsaf_read_dev(rcb_com, RCB_SRAM_ECC_CHK5_REG);
regs[24] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR0_REG);
regs[25] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR3_REG);
regs[26] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR4_REG);
regs[27] = dsaf_read_dev(rcb_com, RCB_ECC_ERR_ADDR5_REG);
regs[28] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_INTMASK_RING);
regs[29] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_RING_STS);
regs[30] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_RING);
regs[31] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_INTMASK_BD);
regs[32] = dsaf_read_dev(rcb_com, RCB_COM_SF_CFG_BD_RINT_STS);
regs[33] = dsaf_read_dev(rcb_com, RCB_COM_RCB_RD_BD_BUSY);
regs[34] = dsaf_read_dev(rcb_com, RCB_COM_RCB_FBD_CRT_EN);
regs[35] = dsaf_read_dev(rcb_com, RCB_COM_AXI_WR_ERR_INTMASK);
regs[36] = dsaf_read_dev(rcb_com, RCB_COM_AXI_ERR_STS);
regs[37] = dsaf_read_dev(rcb_com, RCB_COM_CHK_TX_FBD_NUM_REG);
/* rcb common entry registers */
for (i = 0; i < 16; i++) { /* total 16 model registers */
regs[38 + i]
= dsaf_read_dev(rcb_com, RCB_CFG_BD_NUM_REG + 4 * i);
regs[54 + i]
= dsaf_read_dev(rcb_com, RCB_CFG_PKTLINE_REG + 4 * i);
}
reg_tmp = is_ver1 ? RCB_CFG_OVERTIME_REG : RCB_PORT_CFG_OVERTIME_REG;
reg_num_tmp = (is_ver1 || is_dbg) ? 1 : 6;
for (i = 0; i < reg_num_tmp; i++)
regs[70 + i] = dsaf_read_dev(rcb_com, reg_tmp);
regs[76] = dsaf_read_dev(rcb_com, RCB_CFG_PKTLINE_INT_NUM_REG);
regs[77] = dsaf_read_dev(rcb_com, RCB_CFG_OVERTIME_INT_NUM_REG);
/* mark end of rcb common regs */
for (i = 78; i < 80; i++)
regs[i] = 0xcccccccc;
}
void hns_rcb_get_ring_regs(struct hnae_queue *queue, void *data)
{
u32 *regs = data;
struct ring_pair_cb *ring_pair
= container_of(queue, struct ring_pair_cb, q);
u32 i = 0;
/*rcb ring registers */
regs[0] = dsaf_read_dev(queue, RCB_RING_RX_RING_BASEADDR_L_REG);
regs[1] = dsaf_read_dev(queue, RCB_RING_RX_RING_BASEADDR_H_REG);
regs[2] = dsaf_read_dev(queue, RCB_RING_RX_RING_BD_NUM_REG);
regs[3] = dsaf_read_dev(queue, RCB_RING_RX_RING_BD_LEN_REG);
regs[4] = dsaf_read_dev(queue, RCB_RING_RX_RING_PKTLINE_REG);
regs[5] = dsaf_read_dev(queue, RCB_RING_RX_RING_TAIL_REG);
regs[6] = dsaf_read_dev(queue, RCB_RING_RX_RING_HEAD_REG);
regs[7] = dsaf_read_dev(queue, RCB_RING_RX_RING_FBDNUM_REG);
regs[8] = dsaf_read_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG);
regs[9] = dsaf_read_dev(queue, RCB_RING_TX_RING_BASEADDR_L_REG);
regs[10] = dsaf_read_dev(queue, RCB_RING_TX_RING_BASEADDR_H_REG);
regs[11] = dsaf_read_dev(queue, RCB_RING_TX_RING_BD_NUM_REG);
regs[12] = dsaf_read_dev(queue, RCB_RING_TX_RING_BD_LEN_REG);
regs[13] = dsaf_read_dev(queue, RCB_RING_TX_RING_PKTLINE_REG);
regs[15] = dsaf_read_dev(queue, RCB_RING_TX_RING_TAIL_REG);
regs[16] = dsaf_read_dev(queue, RCB_RING_TX_RING_HEAD_REG);
regs[17] = dsaf_read_dev(queue, RCB_RING_TX_RING_FBDNUM_REG);
regs[18] = dsaf_read_dev(queue, RCB_RING_TX_RING_OFFSET_REG);
regs[19] = dsaf_read_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG);
regs[20] = dsaf_read_dev(queue, RCB_RING_PREFETCH_EN_REG);
regs[21] = dsaf_read_dev(queue, RCB_RING_CFG_VF_NUM_REG);
regs[22] = dsaf_read_dev(queue, RCB_RING_ASID_REG);
regs[23] = dsaf_read_dev(queue, RCB_RING_RX_VM_REG);
regs[24] = dsaf_read_dev(queue, RCB_RING_T0_BE_RST);
regs[25] = dsaf_read_dev(queue, RCB_RING_COULD_BE_RST);
regs[26] = dsaf_read_dev(queue, RCB_RING_WRR_WEIGHT_REG);
regs[27] = dsaf_read_dev(queue, RCB_RING_INTMSK_RXWL_REG);
regs[28] = dsaf_read_dev(queue, RCB_RING_INTSTS_RX_RING_REG);
regs[29] = dsaf_read_dev(queue, RCB_RING_INTMSK_TXWL_REG);
regs[30] = dsaf_read_dev(queue, RCB_RING_INTSTS_TX_RING_REG);
regs[31] = dsaf_read_dev(queue, RCB_RING_INTMSK_RX_OVERTIME_REG);
regs[32] = dsaf_read_dev(queue, RCB_RING_INTSTS_RX_OVERTIME_REG);
regs[33] = dsaf_read_dev(queue, RCB_RING_INTMSK_TX_OVERTIME_REG);
regs[34] = dsaf_read_dev(queue, RCB_RING_INTSTS_TX_OVERTIME_REG);
/* mark end of ring regs */
for (i = 35; i < 40; i++)
regs[i] = 0xcccccc00 + ring_pair->index;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3020_2 |
crossvul-cpp_data_good_3716_0 | /*
* Copyright (C) 2005-2012 Gilles Darold
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Some part of the code of squidclamav are learn or simply copy/paste
* from the srv_clamav c-icap service written by Christos Tsantilas.
*
* Copyright (C) 2004 Christos Tsantilas
*
* Thanks to him for his great work.
*/
#include "c-icap.h"
#include "service.h"
#include "header.h"
#include "body.h"
#include "simple_api.h"
#include "debug.h"
#include "cfg_param.h"
#include "squidclamav.h"
#include "filetype.h"
#include "ci_threads.h"
#include "mem.h"
#include "commands.h"
#include <errno.h>
#include <signal.h>
/* Structure used to store information passed throught the module methods */
typedef struct av_req_data{
ci_simple_file_t *body;
ci_request_t *req;
ci_membuf_t *error_page;
int blocked;
int no_more_scan;
int virus;
char *url;
char *user;
char *clientip;
} av_req_data_t;
static int SEND_PERCENT_BYTES = 0;
static ci_off_t START_SEND_AFTER = 1;
/*squidclamav service extra data ... */
ci_service_xdata_t *squidclamav_xdata = NULL;
int AVREQDATA_POOL = -1;
int squidclamav_init_service(ci_service_xdata_t * srv_xdata, struct ci_server_conf *server_conf);
int squidclamav_post_init_service(ci_service_xdata_t * srv_xdata, struct ci_server_conf *server_conf);
void squidclamav_close_service();
int squidclamav_check_preview_handler(char *preview_data, int preview_data_len, ci_request_t *);
int squidclamav_end_of_data_handler(ci_request_t *);
void *squidclamav_init_request_data(ci_request_t * req);
void squidclamav_release_request_data(void *data);
int squidclamav_io(char *wbuf, int *wlen, char *rbuf, int *rlen, int iseof, ci_request_t * req);
/* General functions */
void set_istag(ci_service_xdata_t * srv_xdata);
/* Declare SquidClamav C-ICAP service */
CI_DECLARE_MOD_DATA ci_service_module_t service = {
"squidclamav", /*Module name */
"SquidClamav/Antivirus service", /* Module short description */
ICAP_RESPMOD | ICAP_REQMOD, /* Service type modification */
squidclamav_init_service, /* init_service. */
squidclamav_post_init_service, /* post_init_service. */
squidclamav_close_service, /* close_service */
squidclamav_init_request_data, /* init_request_data. */
squidclamav_release_request_data, /* release request data */
squidclamav_check_preview_handler, /* Preview data */
squidclamav_end_of_data_handler, /* when all data has been received */
squidclamav_io,
NULL,
NULL
};
int debug = 0;
int statit = 0;
int timeout = 1;
char *redirect_url = NULL;
char *squidguard = NULL;
char *clamd_local = NULL;
char *clamd_ip = NULL;
char *clamd_port = NULL;
char *clamd_curr_ip = NULL;
SCPattern *patterns = NULL;
int pattc = 0;
int current_pattern_size = 0;
ci_off_t maxsize = 0;
int logredir = 0;
int dnslookup = 1;
/* Used by pipe to squidGuard */
int usepipe = 0;
pid_t pid;
FILE *sgfpw = NULL;
FILE *sgfpr = NULL;
/* --------------- URL CHECK --------------------------- */
#define MAX_URL_SIZE 8192
#define MAX_METHOD_SIZE 16
#define SMALL_BUFF 1024
struct http_info {
char method[MAX_METHOD_SIZE];
char url[MAX_URL_SIZE];
};
int extract_http_info(ci_request_t *, ci_headers_list_t *, struct http_info *);
char *http_content_type(ci_request_t *);
void free_global ();
void free_pipe ();
void generate_redirect_page(char *, ci_request_t *, av_req_data_t *);
void cfgreload_command(char *, int, char **);
int create_pipe(char *command);
int dconnect (void);
int connectINET(char *serverHost, uint16_t serverPort);
char * replace(const char *s, const char *old, const char *new);
/* ----------------------------------------------------- */
int squidclamav_init_service(ci_service_xdata_t * srv_xdata,
struct ci_server_conf *server_conf)
{
unsigned int xops;
ci_debug_printf(1, "DEBUG squidclamav_init_service: Going to initialize squidclamav\n");
squidclamav_xdata = srv_xdata;
set_istag(squidclamav_xdata);
ci_service_set_preview(srv_xdata, 1024);
ci_service_enable_204(srv_xdata);
ci_service_set_transfer_preview(srv_xdata, "*");
xops = CI_XCLIENTIP | CI_XSERVERIP;
xops |= CI_XAUTHENTICATEDUSER | CI_XAUTHENTICATEDGROUPS;
ci_service_set_xopts(srv_xdata, xops);
/*Initialize object pools*/
AVREQDATA_POOL = ci_object_pool_register("av_req_data_t", sizeof(av_req_data_t));
if(AVREQDATA_POOL < 0) {
ci_debug_printf(0, "FATAL squidclamav_init_service: error registering object_pool av_req_data_t\n");
return 0;
}
/* Reload configuration command */
register_command("squidclamav:cfgreload", MONITOR_PROC_CMD | CHILDS_PROC_CMD, cfgreload_command);
/*********************
read config files
********************/
clamd_curr_ip = (char *) malloc (sizeof (char) * 128);
memset(clamd_curr_ip, 0, sizeof(clamd_curr_ip));
if (load_patterns() == 0) {
return 0;
}
return 1;
}
void cfgreload_command(char *name, int type, char **argv)
{
ci_debug_printf(1, "DEBUG cfgreload_command: reload configuration command received\n");
free_global();
free_pipe();
debug = 0;
statit = 0;
pattc = 0;
current_pattern_size = 0;
maxsize = 0;
logredir = 0;
dnslookup = 1;
clamd_curr_ip = (char *) malloc (sizeof (char) * 128);
memset(clamd_curr_ip, 0, sizeof(clamd_curr_ip));
if (load_patterns() == 0)
ci_debug_printf(0, "FATAL cfgreload_command: reload configuration command failed!\n");
if (squidclamav_xdata)
set_istag(squidclamav_xdata);
if (squidguard != NULL) {
ci_debug_printf(1, "DEBUG cfgreload_command: reopening pipe to %s\n", squidguard);
create_pipe(squidguard);
}
}
int squidclamav_post_init_service(ci_service_xdata_t * srv_xdata, struct ci_server_conf *server_conf)
{
if (squidguard == NULL) return 0;
ci_debug_printf(1, "DEBUG squidclamav_post_init_service: opening pipe to %s\n", squidguard);
if (create_pipe(squidguard) == 1) {
return 0;
}
return 1;
}
void squidclamav_close_service()
{
ci_debug_printf(1, "DEBUG squidclamav_close_service: clean all memory!\n");
free_global();
free_pipe();
ci_object_pool_unregister(AVREQDATA_POOL);
}
void *squidclamav_init_request_data(ci_request_t * req)
{
int preview_size;
av_req_data_t *data;
preview_size = ci_req_preview_size(req);
ci_debug_printf(1, "DEBUG squidclamav_init_request_data: initializing request data handler.\n");
if (!(data = ci_object_pool_alloc(AVREQDATA_POOL))) {
ci_debug_printf(0, "FATAL squidclamav_init_request_data: Error allocation memory for service data!!!");
return NULL;
}
data->body = NULL;
data->error_page = NULL;
data->req = req;
data->blocked = 0;
data->no_more_scan = 0;
data->virus = 0;
return data;
}
void squidclamav_release_request_data(void *data)
{
if (data) {
ci_debug_printf(1, "DEBUG squidclamav_release_request_data: Releasing request data.\n");
if (((av_req_data_t *) data)->body) {
ci_simple_file_destroy(((av_req_data_t *) data)->body);
if (((av_req_data_t *) data)->url)
ci_buffer_free(((av_req_data_t *) data)->url);
if (((av_req_data_t *) data)->user)
ci_buffer_free(((av_req_data_t *) data)->user);
if (((av_req_data_t *) data)->clientip)
ci_buffer_free(((av_req_data_t *) data)->clientip);
}
if (((av_req_data_t *) data)->error_page)
ci_membuf_free(((av_req_data_t *) data)->error_page);
ci_object_pool_free(data);
}
}
int squidclamav_check_preview_handler(char *preview_data, int preview_data_len, ci_request_t * req)
{
ci_headers_list_t *req_header;
struct http_info httpinf;
av_req_data_t *data = ci_service_data(req);
char *clientip;
struct hostent *clientname;
unsigned long ip;
char *username;
char *content_type;
ci_off_t content_length;
char *chain_ret = NULL;
char *ret = NULL;
int chkipdone = 0;
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: processing preview header.\n");
if (preview_data_len)
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: preview data size is %d\n", preview_data_len);
/* Extract the HTTP header from the request */
if ((req_header = ci_http_request_headers(req)) == NULL) {
ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: bad http header, aborting.\n");
return CI_ERROR;
}
/* Get the Authenticated user */
if ((username = ci_headers_value(req->request_header, "X-Authenticated-User")) != NULL) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Authenticated-User: %s\n", username);
/* if a TRUSTUSER match => no squidguard and no virus scan */
if (simple_pattern_compare(username, TRUSTUSER) == 1) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTUSER match) for user: %s\n", username);
return CI_MOD_ALLOW204;
}
} else {
/* set null client to - */
username = (char *)malloc(sizeof(char)*2);
strcpy(username, "-");
}
/* Check client Ip against SquidClamav trustclient */
if ((clientip = ci_headers_value(req->request_header, "X-Client-IP")) != NULL) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: X-Client-IP: %s\n", clientip);
ip = inet_addr(clientip);
chkipdone = 0;
if (dnslookup == 1) {
if ( (clientname = gethostbyaddr((char *)&ip, sizeof(ip), AF_INET)) != NULL) {
if (clientname->h_name != NULL) {
/* if a TRUSTCLIENT match => no squidguard and no virus scan */
if (client_pattern_compare(clientip, clientname->h_name) > 0) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s(%s)\n", clientname->h_name, clientip);
return CI_MOD_ALLOW204;
}
chkipdone = 1;
}
}
}
if (chkipdone == 0) {
/* if a TRUSTCLIENT match => no squidguard and no virus scan */
if (client_pattern_compare(clientip, NULL) > 0) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (TRUSTCLIENT match) for client: %s\n", clientip);
return CI_MOD_ALLOW204;
}
}
} else {
/* set null client to - */
clientip = (char *)malloc(sizeof(char)*2);
strcpy(clientip, "-");
}
/* Get the requested URL */
if (!extract_http_info(req, req_header, &httpinf)) {
/* Something wrong in the header or unknow method */
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: bad http header, aborting.\n");
return CI_MOD_ALLOW204;
}
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: URL requested: %s\n", httpinf.url);
/* Check the URL against SquidClamav Whitelist */
if (simple_pattern_compare(httpinf.url, WHITELIST) == 1) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No squidguard and antivir check (WHITELIST match) for url: %s\n", httpinf.url);
return CI_MOD_ALLOW204;
}
/* Check URL header against squidGuard */
if (usepipe == 1) {
char *rbuff = NULL;
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Sending request to chained program: %s\n", squidguard);
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Request: %s %s %s %s\n", httpinf.url,clientip,username,httpinf.method);
/* escaping escaped character to prevent unescaping by squidguard */
rbuff = replace(httpinf.url, "%", "%25");
fprintf(sgfpw,"%s %s %s %s\n",rbuff,clientip,username,httpinf.method);
fflush(sgfpw);
xfree(rbuff);
/* the chained redirector must return empty line if ok or the redirection url */
chain_ret = (char *)malloc(sizeof(char)*MAX_URL_SIZE);
if (chain_ret != NULL) {
ret = fgets(chain_ret,MAX_URL_SIZE,sgfpr);
if ((ret != NULL) && (strlen(chain_ret) > 1)) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: Chained program redirection received: %s\n", chain_ret);
if (logredir)
ci_debug_printf(0, "INFO Chained program redirection received: %s\n", chain_ret);
/* Create the redirection url to squid */
data->blocked = 1;
generate_redirect_page(strtok(chain_ret, " "), req, data);
xfree(chain_ret);
chain_ret = NULL;
return CI_MOD_CONTINUE;
}
xfree(chain_ret);
chain_ret = NULL;
}
}
/* CONNECT method (https) can not be scanned so abort */
if (strcmp(httpinf.method, "CONNECT") == 0) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: method %s can't be scanned.\n", httpinf.method);
return CI_MOD_ALLOW204;
}
/* Check the URL against SquidClamav abort */
if (simple_pattern_compare(httpinf.url, ABORT) == 1) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORT match) for url: %s\n", httpinf.url);
return CI_MOD_ALLOW204;
}
/* Get the content length header */
content_length = ci_http_content_length(req);
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Length: %d\n", (int)content_length);
if ((content_length > 0) && (maxsize > 0) && (content_length >= maxsize)) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: No antivir check, content-length upper than maxsize (%d > %d)\n", content_length, (int)maxsize);
return CI_MOD_ALLOW204;
}
/* Get the content type header */
if ((content_type = http_content_type(req)) != NULL) {
ci_debug_printf(2, "DEBUG squidclamav_check_preview_handler: Content-Type: %s\n", content_type);
/* Check the Content-Type against SquidClamav abortcontent */
if (simple_pattern_compare(content_type, ABORTCONTENT)) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No antivir check (ABORTCONTENT match) for content-type: %s\n", content_type);
return CI_MOD_ALLOW204;
}
}
/* No data, so nothing to scan */
if (!data || !ci_req_hasbody(req)) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: No body data, allow 204\n");
return CI_MOD_ALLOW204;
}
if (preview_data_len == 0) {
ci_debug_printf(1, "DEBUG squidclamav_check_preview_handler: can not begin to scan url: No preview data.\n");
return CI_MOD_ALLOW204;
}
data->url = ci_buffer_alloc(strlen(httpinf.url)+1);
strcpy(data->url, httpinf.url);
if (username != NULL) {
data->user = ci_buffer_alloc(strlen(username)+1);
strcpy(data->user, username);
} else {
data->user = NULL;
}
if (clientip != NULL) {
data->clientip = ci_buffer_alloc(strlen(clientip)+1);
strcpy(data->clientip, clientip);
} else {
ci_debug_printf(0, "ERROR squidclamav_check_preview_handler: clientip is null, you must set 'icap_send_client_ip on' into squid.conf\n");
data->clientip = NULL;
}
data->body = ci_simple_file_new(0);
if ((SEND_PERCENT_BYTES >= 0) && (START_SEND_AFTER == 0)) {
ci_req_unlock_data(req);
ci_simple_file_lock_all(data->body);
}
if (!data->body)
return CI_ERROR;
if (preview_data_len) {
if (ci_simple_file_write(data->body, preview_data, preview_data_len, ci_req_hasalldata(req)) == CI_ERROR)
return CI_ERROR;
}
return CI_MOD_CONTINUE;
}
int squidclamav_read_from_net(char *buf, int len, int iseof, ci_request_t * req)
{
av_req_data_t *data = ci_service_data(req);
int allow_transfer;
if (!data)
return CI_ERROR;
if (!data->body)
return len;
if (data->no_more_scan == 1) {
return ci_simple_file_write(data->body, buf, len, iseof);
}
if ((maxsize > 0) && (data->body->bytes_in >= maxsize)) {
data->no_more_scan = 1;
ci_req_unlock_data(req);
ci_simple_file_unlock_all(data->body);
ci_debug_printf(1, "DEBUG squidclamav_read_from_net: No more antivir check, downloaded stream is upper than maxsize (%d>%d)\n", data->body->bytes_in, (int)maxsize);
} else if (SEND_PERCENT_BYTES && (START_SEND_AFTER < data->body->bytes_in)) {
ci_req_unlock_data(req);
allow_transfer = (SEND_PERCENT_BYTES * (data->body->endpos + len)) / 100;
ci_simple_file_unlock(data->body, allow_transfer);
}
return ci_simple_file_write(data->body, buf, len, iseof);
}
int squidclamav_write_to_net(char *buf, int len, ci_request_t * req)
{
int bytes;
av_req_data_t *data = ci_service_data(req);
if (!data)
return CI_ERROR;
if (data->blocked == 1 && data->error_page == 0) {
ci_debug_printf(2, "DEBUG squidclamav_write_to_net: ending here, content was blocked\n");
return CI_EOF;
}
if (data->virus == 1 && data->error_page == 0) {
ci_debug_printf(2, "DEBUG squidclamav_write_to_net: ending here, virus was found\n");
return CI_EOF;
}
/* if a virus was found or the page has been blocked, a warning page
has already been generated */
if (data->error_page)
return ci_membuf_read(data->error_page, buf, len);
if (data->body)
bytes = ci_simple_file_read(data->body, buf, len);
else
bytes =0;
return bytes;
}
int squidclamav_io(char *wbuf, int *wlen, char *rbuf, int *rlen, int iseof, ci_request_t * req)
{
int ret = CI_OK;
if (rbuf && rlen) {
*rlen = squidclamav_read_from_net(rbuf, *rlen, iseof, req);
if (*rlen == CI_ERROR)
return CI_ERROR;
else if (*rlen < 0)
ret = CI_OK;
} else if (iseof) {
if (squidclamav_read_from_net(NULL, 0, iseof, req) == CI_ERROR)
return CI_ERROR;
}
if (wbuf && wlen) {
*wlen = squidclamav_write_to_net(wbuf, *wlen, req);
}
return CI_OK;
}
int squidclamav_end_of_data_handler(ci_request_t * req)
{
av_req_data_t *data = ci_service_data(req);
ci_simple_file_t *body;
char cbuff[MAX_URL_SIZE];
char clbuf[SMALL_BUFF];
ssize_t ret;
int nbread = 0;
int loopw = 60;
uint16_t port;
struct sockaddr_in server;
struct sockaddr_in peer;
size_t peer_size;
char *pt = NULL;
int sockd;
int wsockd;
unsigned long total_read;
ci_debug_printf(2, "DEBUG squidclamav_end_of_data_handler: ending request data handler.\n");
/* Nothing more to scan */
if (!data || !data->body)
return CI_MOD_DONE;
if (data->blocked == 1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: blocked content, sending redirection header + error page.\n");
return CI_MOD_DONE;
}
body = data->body;
if (data->no_more_scan == 1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: no more data to scan, sending content.\n");
ci_simple_file_unlock_all(body);
return CI_MOD_DONE;
}
/* SCAN DATA HERE */
if ((sockd = dconnect ()) < 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't connect to Clamd daemon.\n");
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Sending STREAM command to clamd.\n");
if (write(sockd, "STREAM", 6) <= 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't write to Clamd socket.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
while (loopw > 0) {
memset (cbuff, 0, sizeof(cbuff));
ret = read (sockd, cbuff, MAX_URL_SIZE);
if ((ret > -1) && (pt = strstr (cbuff, "PORT"))) {
pt += 5;
sscanf(pt, "%d", (int *) &port);
break;
}
loopw--;
}
if (loopw == 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Clamd daemon not ready for stream scanning.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Received port %d from clamd.\n", port);
/* connect to clamd given port */
if ((wsockd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't create the Clamd socket.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
server.sin_family = AF_INET;
server.sin_port = htons (port);
peer_size = sizeof (peer);
if (getpeername(sockd, (struct sockaddr *) &peer, (socklen_t *) &peer_size) < 0) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't get socket peer name.\n");
close(sockd);
return CI_MOD_ALLOW204;
}
switch (peer.sin_family) {
case AF_UNIX:
server.sin_addr.s_addr = inet_addr ("127.0.0.1");
break;
case AF_INET:
server.sin_addr.s_addr = peer.sin_addr.s_addr;
break;
default:
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Unexpected socket type: %d.\n", peer.sin_family);
close(sockd);
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Trying to connect to clamd [port: %d].\n", port);
if (connect (wsockd, (struct sockaddr *) &server, sizeof (struct sockaddr_in)) < 0) {
close(wsockd);
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't connect to clamd [port: %d].\n", port);
return CI_MOD_ALLOW204;
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Ok connected to clamd on port: %d.\n", port);
/*-----------------------------------------------------*/
ci_debug_printf(1, "DEBUG: squidclamav_end_of_data_handler: Scanning data now\n");
lseek(body->fd, 0, SEEK_SET);
memset(cbuff, 0, sizeof(cbuff));
total_read = 0;
while (data->virus == 0 && (nbread = read(body->fd, cbuff, MAX_URL_SIZE)) > 0) {
total_read += nbread;
ret = write(wsockd, cbuff, nbread);
if ( (ret <= 0) && (total_read > 0) ) {
ci_debug_printf(3, "ERROR squidclamav_end_of_data_handler: Can't write to clamd socket (maybe we reach clamd StreamMaxLength, total read: %ld).\n", total_read);
break;
} else if ( ret <= 0 ) {
ci_debug_printf(0, "ERROR squidclamav_end_of_data_handler: Can't write to clamd socket.\n");
break;
} else {
ci_debug_printf(3, "DEBUG squidclamav_end_of_data_handler: Write %d bytes on %d to socket\n", (int)ret, nbread);
}
memset(cbuff, 0, sizeof(cbuff));
}
/* close socket to clamd */
if (wsockd > -1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: End Clamd connection, attempting to read result.\n");
close(wsockd);
}
memset (clbuf, 0, sizeof(clbuf));
while ((nbread = read(sockd, clbuf, SMALL_BUFF)) > 0) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: received from Clamd: %s", clbuf);
if (strstr (clbuf, "FOUND\n")) {
data->virus = 1;
if (!ci_req_sent_data(req)) {
chomp(clbuf);
char *urlredir = (char *) malloc( sizeof(char)*MAX_URL_SIZE );
snprintf(urlredir, MAX_URL_SIZE, "%s?url=%s&source=%s&user=%s&virus=%s", redirect_url, data->url, data->clientip, data->user, clbuf);
if (logredir == 0)
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Virus redirection: %s.\n", urlredir);
if (logredir)
ci_debug_printf(0, "INFO squidclamav_end_of_data_handler: Virus redirection: %s.\n", urlredir);
generate_redirect_page(urlredir, req, data);
xfree(urlredir);
}
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Virus found, ending download.\n");
break;
}
memset(clbuf, 0, sizeof(clbuf));
}
/* close second socket to clamd */
if (sockd > -1) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Closing Clamd connection.\n");
close(sockd);
}
if (data->virus) {
ci_debug_printf(1, "DEBUG squidclamav_end_of_data_handler: Virus found, sending redirection header + error page.\n");
return CI_MOD_DONE;
}
if (!ci_req_sent_data(req)) {
ci_debug_printf(2, "DEBUG squidclamav_end_of_data_handler: Responding with allow 204\n");
return CI_MOD_ALLOW204;
}
ci_debug_printf(3, "DEBUG squidclamav_end_of_data_handler: unlocking data to be sent.\n");
ci_simple_file_unlock_all(body);
return CI_MOD_DONE;
}
void set_istag(ci_service_xdata_t * srv_xdata)
{
char istag[SERVICE_ISTAG_SIZE + 1];
snprintf(istag, SERVICE_ISTAG_SIZE, "-%d-%s-%d%d",1, "squidclamav", 1, 0);
istag[SERVICE_ISTAG_SIZE] = '\0';
ci_service_set_istag(srv_xdata, istag);
ci_debug_printf(2, "DEBUG set_istag: setting istag to %s\n", istag);
}
/* util.c */
/* NUL-terminated version of strncpy() */
void
xstrncpy (char *dest, const char *src, size_t n) {
if ( (src == NULL) || (strcmp(src, "") == 0))
return;
strncpy(dest, src, n-1);
dest[n-1] = 0;
}
/* Emulate the Perl chomp() method: remove \r and \n from end of string */
void
chomp (char *str)
{
size_t len = 0;
if (str == NULL) return;
len = strlen(str);
if ((len > 0) && str[len - 1] == 10) {
str[len - 1] = 0;
len--;
}
if ((len > 0) && str[len - 1] == 13)
str[len - 1] = 0;
return;
}
/* return 0 if path exists, -1 otherwise */
int
isPathExists(const char *path)
{
struct stat sb;
if ( (path == NULL) || (strcmp(path, "") == 0) ) return -1;
if (lstat(path, &sb) != 0) {
return -1;
}
return 0;
}
/* return 0 if path is secure, -1 otherwise */
int
isPathSecure(const char *path)
{
struct stat sb;
/* no path => unreal, that's possible ! */
if (path == NULL) return -1;
/* file doesn't exist or access denied = secure */
/* fopen will fail */
if (lstat(path, &sb) != 0) return 0;
/* File is not a regular file => unsecure */
if ( S_ISLNK(sb.st_mode ) ) return -1;
if ( S_ISDIR(sb.st_mode ) ) return -1;
if ( S_ISCHR(sb.st_mode ) ) return -1;
if ( S_ISBLK(sb.st_mode ) ) return -1;
if ( S_ISFIFO(sb.st_mode ) ) return -1;
if ( S_ISSOCK(sb.st_mode ) ) return -1;
return 0;
}
/*
* xfree() - same as free(3). Will not call free(3) if s == NULL.
*/
void
xfree(void *s)
{
if (s != NULL)
free(s);
s = NULL;
}
/* Remove spaces and tabs from beginning and end of a string */
void
trim(char *str)
{
int i = 0;
int j = 0;
/* Remove spaces and tabs from beginning */
while ( (str[i] == ' ') || (str[i] == '\t') ) {
i++;
}
if (i > 0) {
for (j = i; j < strlen(str); j++) {
str[j-i] = str[j];
}
str[j-i] = '\0';
}
/* Now remove spaces and tabs from end */
i = strlen(str) - 1;
while ( (str[i] == ' ') || (str[i] == '\t')) {
i--;
}
if ( i < (strlen(str) - 1) ) {
str[i+1] = '\0';
}
}
/* Try to emulate the Perl split() method: str is splitted on the
all occurence of delim. Take care that empty fields are not returned */
char**
split( char* str, const char* delim)
{
int size = 0;
char** splitted = NULL;
char *tmp = NULL;
tmp = strtok(str, delim);
while (tmp != NULL) {
splitted = (char**) realloc(splitted, sizeof(char**) * (size+1));
if (splitted != NULL) {
splitted[size] = tmp;
} else {
return(NULL);
}
tmp = strtok(NULL, delim);
size++;
}
free(tmp);
tmp = NULL;
/* add null at end of array to help ptrarray_length */
splitted = (char**) realloc(splitted, sizeof(char**) * (size+1));
if (splitted != NULL) {
splitted[size] = NULL;
} else {
return(NULL);
}
return splitted;
}
/* Return the length of a pointer array. Must be ended by NULL */
int
ptrarray_length(char** arr)
{
int i = 0;
while(arr[i] != NULL) i++;
return i;
}
void *
xmallox (size_t len)
{
void *memres = malloc (len);
if (memres == NULL) {
fprintf(stderr, "Running Out of Memory!!!\n");
exit(EXIT_FAILURE);
}
return memres;
}
size_t
xstrnlen(const char *s, size_t n)
{
const char *p = (const char *)memchr(s, 0, n);
return(p ? p-s : n);
}
/* pattern.c */
int
isIpAddress(char *src_addr)
{
char *ptr;
int address;
int i;
char *s = (char *) malloc (sizeof (char) * LOW_CHAR);
xstrncpy(s, src_addr, LOW_CHAR);
/* make sure we have numbers and dots only! */
if(strspn(s, "0123456789.") != strlen(s)) {
xfree(s);
return 1;
}
/* split up each number from string */
ptr = strtok(s, ".");
if(ptr == NULL) {
xfree(s);
return 1;
}
address = atoi(ptr);
if(address < 0 || address > 255) {
xfree(s);
xfree(ptr);
return 1;
}
for(i = 2; i < 4; i++) {
ptr = strtok(NULL, ".");
if (ptr == NULL) {
xfree(s);
return 1;
}
address = atoi(ptr);
if (address < 0 || address > 255) {
xfree(ptr);
xfree(s);
return 1;
}
}
xfree(s);
return 0;
}
int
simple_pattern_compare(char *str, const int type)
{
int i = 0;
/* pass througth all regex pattern */
for (i = 0; i < pattc; i++) {
if ( (patterns[i].type == type) && (regexec(&patterns[i].regexv, str, 0, 0, 0) == 0) ) {
switch(type) {
/* return 1 if string matches whitelist pattern */
case WHITELIST:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: whitelist (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
/* return 1 if string matches abort pattern */
case ABORT:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: abort (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
/* return 1 if string matches trustuser pattern */
case TRUSTUSER:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: trustuser (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
/* return 1 if string matches abortcontent pattern */
case ABORTCONTENT:
if (debug > 0)
ci_debug_printf(2, "DEBUG simple_pattern_compare: abortcontent (%s) matched: %s\n", patterns[i].pattern, str);
return 1;
default:
ci_debug_printf(0, "ERROR simple_pattern_compare: unknown pattern match type: %s\n", str);
return -1;
}
}
}
/* return 0 otherwise */
return 0;
}
int
client_pattern_compare(char *ip, char *name)
{
int i = 0;
/* pass througth all regex pattern */
for (i = 0; i < pattc; i++) {
if (patterns[i].type == TRUSTCLIENT) {
/* Look at client ip pattern matching */
/* return 1 if string matches ip TRUSTCLIENT pattern */
if (regexec(&patterns[i].regexv, ip, 0, 0, 0) == 0) {
if (debug != 0)
ci_debug_printf(2, "DEBUG client_pattern_compare: trustclient (%s) matched: %s\n", patterns[i].pattern, ip);
return 1;
/* Look at client name pattern matching */
/* return 2 if string matches fqdn TRUSTCLIENT pattern */
} else if ((name != NULL) && (regexec(&patterns[i].regexv, name, 0, 0, 0) == 0)) {
if (debug != 0)
ci_debug_printf(2, "DEBUG client_pattern_compare: trustclient (%s) matched: %s\n", patterns[i].pattern, name);
return 2;
}
}
}
/* return 0 otherwise */
return 0;
}
/* scconfig.c */
/* load the squidclamav.conf */
int
load_patterns()
{
char *buf = NULL;
FILE *fp = NULL;
if (isPathExists(CONFIG_FILE) == 0) {
fp = fopen(CONFIG_FILE, "rt");
if (debug > 0)
ci_debug_printf(0, "LOG load_patterns: Reading configuration from %s\n", CONFIG_FILE);
}
if (fp == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to open configuration file: %s\n", CONFIG_FILE);
return 0;
}
buf = (char *)malloc(sizeof(char)*LOW_BUFF*2);
if (buf == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to allocate memory in load_patterns()\n");
fclose(fp);
return 0;
}
while ((fgets(buf, LOW_BUFF, fp) != NULL)) {
/* chop newline */
chomp(buf);
/* add to regex patterns array */
if (add_pattern(buf) == 0) {
xfree(buf);
fclose(fp);
return 0;
}
}
xfree(buf);
if (redirect_url == NULL) {
ci_debug_printf(0, "FATAL load_patterns: No redirection URL set, going to BRIDGE mode\n");
return 0;
}
if (squidguard != NULL) {
ci_debug_printf(0, "LOG load_patterns: Chaining with %s\n", squidguard);
}
if (fclose(fp) != 0)
ci_debug_printf(0, "ERROR load_patterns: Can't close configuration file\n");
/* Set default values */
if (clamd_local == NULL) {
if (clamd_ip == NULL) {
clamd_ip = (char *) malloc (sizeof (char) * SMALL_CHAR);
if(clamd_ip == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to allocate memory in load_patterns()\n");
return 0;
}
xstrncpy(clamd_ip, CLAMD_SERVER, SMALL_CHAR);
}
if (clamd_port == NULL) {
clamd_port = (char *) malloc (sizeof (char) * LOW_CHAR);
if(clamd_port == NULL) {
ci_debug_printf(0, "FATAL load_patterns: unable to allocate memory in load_patterns()\n");
return 0;
}
xstrncpy(clamd_port, CLAMD_PORT, LOW_CHAR);
}
}
return 1;
}
int
growPatternArray (SCPattern item)
{
void *_tmp = NULL;
if (pattc == current_pattern_size) {
if (current_pattern_size == 0)
current_pattern_size = PATTERN_ARR_SIZE;
else
current_pattern_size += PATTERN_ARR_SIZE;
_tmp = realloc(patterns, (current_pattern_size * sizeof(SCPattern)));
if (!_tmp) {
return(-1);
}
patterns = (SCPattern*)_tmp;
}
patterns[pattc] = item;
pattc++;
return(pattc);
}
/* Add regexp expression to patterns array */
int
add_pattern(char *s)
{
char *first = NULL;
char *type = NULL;
int stored = 0;
int regex_flags = REG_NOSUB;
SCPattern currItem;
char *end = NULL;
/* skip empty and commented lines */
if ( (xstrnlen(s, LOW_BUFF) == 0) || (strncmp(s, "#", 1) == 0)) return 1;
/* Config file directives are construct as follow: name value */
type = (char *)malloc(sizeof(char)*LOW_CHAR);
first = (char *)malloc(sizeof(char)*LOW_BUFF);
stored = sscanf(s, "%31s %255[^#]", type, first);
if (stored < 2) {
ci_debug_printf(0, "FATAL add_patterns: Bad configuration line for [%s]\n", s);
xfree(type);
xfree(first);
return 0;
}
/* remove extra space or tabulation */
trim(first);
/* URl to redirect Squid on virus found */
if(strcmp(type, "redirect") == 0) {
redirect_url = (char *) malloc (sizeof (char) * LOW_BUFF);
if(redirect_url == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(redirect_url, first, LOW_BUFF);
}
xfree(type);
xfree(first);
return 1;
}
/* Path to chained other Squid redirector, mostly SquidGuard */
if(strcmp(type, "squidguard") == 0) {
squidguard = (char *) malloc (sizeof (char) * LOW_BUFF);
if(squidguard == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
if (isPathExists(first) == 0) {
xstrncpy(squidguard, first, LOW_BUFF);
} else {
ci_debug_printf(0, "LOG add_patterns: Wrong path to SquidGuard, disabling.\n");
squidguard = NULL;
}
}
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "debug") == 0) {
if (debug == 0)
debug = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "logredir") == 0) {
if (logredir == 0)
logredir = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "dnslookup") == 0) {
if (dnslookup == 1)
dnslookup = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "timeout") == 0) {
timeout = atoi(first);
if (timeout > 10)
timeout = 10;
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "stat") == 0) {
statit = atoi(first);
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "clamd_ip") == 0) {
clamd_ip = (char *) malloc (sizeof (char) * SMALL_CHAR);
if (clamd_ip == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(clamd_ip, first, SMALL_CHAR);
}
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "clamd_port") == 0) {
clamd_port = (char *) malloc (sizeof (char) * LOW_CHAR);
if(clamd_port == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(clamd_port, first, LOW_CHAR);
}
xfree(type);
xfree(first);
return 1;
}
if(strcmp(type, "clamd_local") == 0) {
clamd_local = (char *) malloc (sizeof (char) * LOW_BUFF);
if(clamd_local == NULL) {
fprintf(stderr, "unable to allocate memory in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
} else {
xstrncpy(clamd_local, first, LOW_BUFF);
}
xfree(type);
xfree(first);
return 1;
}
if (strcmp(type, "maxsize") == 0) {
maxsize = ci_strto_off_t(first, &end, 10);
if ((maxsize == 0 && errno != 0) || maxsize < 0)
maxsize = 0;
if (*end == 'k' || *end == 'K')
maxsize = maxsize * 1024;
else if (*end == 'm' || *end == 'M')
maxsize = maxsize * 1024 * 1024;
else if (*end == 'g' || *end == 'G')
maxsize = maxsize * 1024 * 1024 * 1024;
xfree(type);
xfree(first);
return 1;
}
/* force case insensitive pattern matching */
/* so aborti, contenti, regexi are now obsolete */
regex_flags |= REG_ICASE;
/* Add extended regex search */
regex_flags |= REG_EXTENDED;
/* Fill the pattern type */
if (strcmp(type, "abort") == 0) {
currItem.type = ABORT;
} else if (strcmp(type, "abortcontent") == 0) {
currItem.type = ABORTCONTENT;
} else if(strcmp(type, "whitelist") == 0) {
currItem.type = WHITELIST;
} else if(strcmp(type, "trustuser") == 0) {
currItem.type = TRUSTUSER;
} else if(strcmp(type, "trustclient") == 0) {
currItem.type = TRUSTCLIENT;
} else if ( (strcmp(type, "squid_ip") != 0) && (strcmp(type, "squid_port") != 0) && (strcmp(type, "maxredir") != 0) && (strcmp(type, "useragent") != 0) && (strcmp(type, "trust_cache") != 0) ) {
fprintf(stderr, "WARNING: Bad configuration keyword: %s\n", s);
xfree(type);
xfree(first);
return 1;
}
/* Fill the pattern flag */
currItem.flag = regex_flags;
/* Fill pattern array */
currItem.pattern = malloc(sizeof(char)*(strlen(first)+1));
if (currItem.pattern == NULL) {
fprintf(stderr, "unable to allocate new pattern in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
}
strncpy(currItem.pattern, first, strlen(first) + 1);
if ((stored = regcomp(&currItem.regexv, currItem.pattern, currItem.flag)) != 0) {
ci_debug_printf(0, "ERROR add_pattern: Invalid regex pattern: %s\n", currItem.pattern);
} else {
if (growPatternArray(currItem) < 0) {
fprintf(stderr, "unable to allocate new pattern in add_to_patterns()\n");
xfree(type);
xfree(first);
return 0;
}
}
xfree(type);
xfree(first);
return 1;
}
int extract_http_info(ci_request_t * req, ci_headers_list_t * req_header,
struct http_info *httpinf)
{
char *str;
int i = 0;
/* Format of the HTTP header we want to parse:
GET http://www.squid-cache.org/Doc/config/icap_service HTTP/1.1
*/
httpinf->url[0]='\0';
httpinf->method[0] = '\0';
str = req_header->headers[0];
/* if we can't find a space character, there's somethings wrong */
if (strchr(str, ' ') == NULL) {
return 0;
}
/* extract the HTTP method */
while (*str != ' ' && i < MAX_METHOD_SIZE) {
httpinf->method[i] = *str;
str++;
i++;
}
httpinf->method[i] = '\0';
ci_debug_printf(3, "DEBUG extract_http_info: method %s\n", httpinf->method);
/* Extract the URL part of the header */
while (*str == ' ') str++;
i = 0;
while (*str != ' ' && i < MAX_URL_SIZE) {
httpinf->url[i] = *str;
i++;
str++;
}
httpinf->url[i] = '\0';
ci_debug_printf(3, "DEBUG extract_http_info: url %s\n", httpinf->url);
if (*str != ' ') {
return 0;
}
/* we must find the HTTP version after all */
while (*str == ' ')
str++;
if (*str != 'H' || *(str + 4) != '/') {
return 0;
}
return 1;
}
char *http_content_type(ci_request_t * req)
{
ci_headers_list_t *heads;
char *val;
if (!(heads = ci_http_response_headers(req))) {
/* Then maybe is a reqmod request, try to get request headers */
if (!(heads = ci_http_request_headers(req)))
return NULL;
}
if (!(val = ci_headers_value(heads, "Content-Type")))
return NULL;
return val;
}
void
free_global ()
{
xfree(clamd_local);
xfree(clamd_ip);
xfree(clamd_port);
xfree(clamd_curr_ip);
xfree(redirect_url);
if (patterns != NULL) {
while (pattc > 0) {
pattc--;
regfree(&patterns[pattc].regexv);
xfree(patterns[pattc].pattern);
}
free(patterns);
patterns = NULL;
}
}
void
free_pipe ()
{
xfree(squidguard);
if (sgfpw) fclose(sgfpw);
if (sgfpr) fclose(sgfpr);
}
static const char *blocked_header_message =
"<html>\n"
"<body>\n"
"<p>\n"
"You will be redirected in few seconds, if not use this <a href=\"";
static const char *blocked_footer_message =
"\">direct link</a>.\n"
"</p>\n"
"</body>\n"
"</html>\n";
void generate_redirect_page(char * redirect, ci_request_t * req, av_req_data_t * data)
{
int new_size = 0;
char buf[MAX_URL_SIZE];
ci_membuf_t *error_page;
new_size = strlen(blocked_header_message) + strlen(redirect) + strlen(blocked_footer_message) + 10;
if ( ci_http_response_headers(req))
ci_http_response_reset_headers(req);
else
ci_http_response_create(req, 1, 1);
ci_debug_printf(2, "DEBUG generate_redirect_page: creating redirection page\n");
snprintf(buf, MAX_URL_SIZE, "Location: %s", redirect);
/*strcat(buf, ";");*/
ci_debug_printf(3, "DEBUG generate_redirect_page: %s\n", buf);
ci_http_response_add_header(req, "HTTP/1.0 301 Moved Permanently");
ci_http_response_add_header(req, buf);
ci_http_response_add_header(req, "Server: C-ICAP");
ci_http_response_add_header(req, "Connection: close");
/*ci_http_response_add_header(req, "Content-Type: text/html;");*/
ci_http_response_add_header(req, "Content-Type: text/html");
ci_http_response_add_header(req, "Content-Language: en");
if (data->blocked == 1) {
error_page = ci_membuf_new_sized(new_size);
((av_req_data_t *) data)->error_page = error_page;
ci_membuf_write(error_page, (char *) blocked_header_message, strlen(blocked_header_message), 0);
ci_membuf_write(error_page, (char *) redirect, strlen(redirect), 0);
ci_membuf_write(error_page, (char *) blocked_footer_message, strlen(blocked_footer_message), 1);
}
ci_debug_printf(3, "DEBUG generate_redirect_page: done\n");
}
int create_pipe(char *command)
{
int pipe1[2];
int pipe2[2];
ci_debug_printf(1, "DEBUG create_pipe: Open pipe to squidGuard %s!\n", command);
if (command != NULL) {
if ( pipe(pipe1) < 0 || pipe(pipe2) < 0 ) {
ci_debug_printf(0, "ERROR create_pipe: unable to open pipe, disabling call to %s.\n", command);
perror("pipe");
usepipe = 0;
} else {
if ( (pid = fork()) == -1) {
ci_debug_printf(0, "ERROR create_pipe: unable to fork, disabling call to %s.\n", command);
usepipe = 0;
} else {
if(pid == 0) {
close(pipe1[1]);
dup2(pipe1[0],0);
close(pipe2[0]);
dup2(pipe2[1],1);
setsid();
/* Running chained program */
execlp(command,(char *)basename(command),(char *)0);
exit(EXIT_SUCCESS);
return(0);
} else {
close(pipe1[0]);
sgfpw = fdopen(pipe1[1], "w");
if (!sgfpw) {
ci_debug_printf(0, "ERROR create_pipe: unable to fopen command's child stdin, disabling it.\n");
usepipe = 0;
} else {
/* make pipe line buffered */
if (setvbuf (sgfpw, (char *)NULL, _IOLBF, 0) != 0)
ci_debug_printf(1, "DEBUG create_pipe: unable to line buffering pipe.\n");
sgfpr = fdopen(pipe2[0], "r");
if(!sgfpr) {
ci_debug_printf(0, "ERROR create_pipe: unable to fopen command's child stdout, disabling it.\n");
usepipe = 0;
} else {
ci_debug_printf(1, "DEBUG create_pipe: bidirectional pipe to %s childs ready...\n", command);
usepipe = 1;
}
}
}
}
}
}
return 1;
}
int
dconnect ()
{
struct sockaddr_un userver;
int asockd;
memset ((char *) &userver, 0, sizeof (userver));
ci_debug_printf(1, "dconnect: entering.\n");
if (clamd_local != NULL) {
userver.sun_family = AF_UNIX;
xstrncpy (userver.sun_path, clamd_local, sizeof(userver.sun_path));
if ((asockd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) {
ci_debug_printf(0, "ERROR dconnect: Can't bind local socket on %s.\n", clamd_local);
return -1;
}
if (connect (asockd, (struct sockaddr *) &userver, sizeof (struct sockaddr_un)) < 0) {
close (asockd);
ci_debug_printf(0, "ERROR dconnect: Can't connect to clamd on local socket %s.\n", clamd_local);
return -1;
}
return asockd;
} else {
if (clamd_curr_ip[0] != 0) {
asockd = connectINET(clamd_curr_ip, atoi(clamd_port));
if ( asockd != -1 ) {
ci_debug_printf(1, "DEBUG dconnect: Connected to Clamd (%s:%s)\n", clamd_curr_ip,clamd_port);
return asockd;
}
}
char *ptr;
char *s = (char *) malloc (sizeof (char) * SMALL_CHAR);
xstrncpy(s, clamd_ip, SMALL_CHAR);
ptr = strtok(s, ",");
while (ptr != NULL) {
asockd = connectINET(ptr, atoi(clamd_port));
if ( asockd != -1 ) {
ci_debug_printf(1, "DEBUG dconnect: Connected to Clamd (%s:%s)\n", ptr,clamd_port);
/* Store last working clamd */
xstrncpy(clamd_curr_ip, ptr, LOW_CHAR);
xfree(s);
break;
}
ptr = strtok(NULL, ",");
}
return asockd;
xfree(s);
}
return 0;
}
void connect_timeout() {
// doesn't actually need to do anything
}
int
connectINET(char *serverHost, uint16_t serverPort)
{
struct sockaddr_in server;
struct hostent *he;
int asockd;
struct sigaction action;
action.sa_handler = connect_timeout;
memset ((char *) &server, 0, sizeof (server));
server.sin_addr.s_addr = inet_addr(serverHost);
if ((asockd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
ci_debug_printf(0, "ERROR connectINET: Can't create a socket.\n");
return -1;
}
server.sin_family = AF_INET;
server.sin_port = htons(serverPort);
if ((he = gethostbyname(serverHost)) == 0)
{
close(asockd);
ci_debug_printf(0, "ERROR connectINET: Can't lookup hostname of %s\n", serverHost);
return -1;
}
server.sin_addr = *(struct in_addr *) he->h_addr_list[0];
sigaction(SIGALRM, &action, NULL);
alarm(timeout);
if (connect (asockd, (struct sockaddr *) &server, sizeof (struct sockaddr_in)) < 0) {
close (asockd);
ci_debug_printf(0, "ERROR connectINET: Can't connect on %s:%d.\n", serverHost,serverPort);
return -1;
}
int err = errno;
alarm(0);
if (err == EINTR) {
close(asockd);
ci_debug_printf(0, "ERROR connectINET: Timeout connecting to clamd on %s:%d.\n", serverHost,serverPort);
}
return asockd;
}
/**
* Searches all occurrences of old into s
* and replaces with new
*/
char *
replace(const char *s, const char *old, const char *new)
{
char *ret;
int i, count = 0;
size_t newlen = strlen(new);
size_t oldlen = strlen(old);
for (i = 0; s[i] != '\0'; i++) {
if (strstr(&s[i], old) == &s[i]) {
count++;
i += oldlen - 1;
}
}
ret = malloc(i + 1 + count * (newlen - oldlen));
if (ret != NULL) {
i = 0;
while (*s) {
if (strstr(s, old) == s) {
strcpy(&ret[i], new);
i += newlen;
s += oldlen;
} else {
ret[i++] = *s++;
}
}
ret[i] = '\0';
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3716_0 |
crossvul-cpp_data_bad_2183_1 | /* $Id: miniwget.c,v 1.60 2013/10/07 10:03:16 nanard Exp $ */
/* Project : miniupnp
* Website : http://miniupnp.free.fr/
* Author : Thomas Bernard
* Copyright (c) 2005-2013 Thomas Bernard
* This software is subject to the conditions detailed in the
* LICENCE file provided in this distribution. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <io.h>
#define MAXHOSTNAMELEN 64
#define MIN(x,y) (((x)<(y))?(x):(y))
#define snprintf _snprintf
#define socklen_t int
#ifndef strncasecmp
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#define strncasecmp _memicmp
#else /* defined(_MSC_VER) && (_MSC_VER >= 1400) */
#define strncasecmp memicmp
#endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */
#endif /* #ifndef strncasecmp */
#else /* #ifdef _WIN32 */
#include <unistd.h>
#include <sys/param.h>
#if defined(__amigaos__) && !defined(__amigaos4__)
#define socklen_t int
#else /* #if defined(__amigaos__) && !defined(__amigaos4__) */
#include <sys/select.h>
#endif /* #else defined(__amigaos__) && !defined(__amigaos4__) */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#define closesocket close
/* defining MINIUPNPC_IGNORE_EINTR enable the ignore of interruptions
* during the connect() call */
#define MINIUPNPC_IGNORE_EINTR
#endif /* #else _WIN32 */
#if defined(__sun) || defined(sun)
#define MIN(x,y) (((x)<(y))?(x):(y))
#endif
#include "miniupnpcstrings.h"
#include "miniwget.h"
#include "connecthostport.h"
#include "receivedata.h"
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif
/*
* Read a HTTP response from a socket.
* Process Content-Length and Transfer-encoding headers.
* return a pointer to the content buffer, which length is saved
* to the length parameter.
*/
void *
getHTTPResponse(int s, int * size)
{
char buf[2048];
int n;
int endofheaders = 0;
int chunked = 0;
int content_length = -1;
unsigned int chunksize = 0;
unsigned int bytestocopy = 0;
/* buffers : */
char * header_buf;
unsigned int header_buf_len = 2048;
unsigned int header_buf_used = 0;
char * content_buf;
unsigned int content_buf_len = 2048;
unsigned int content_buf_used = 0;
char chunksize_buf[32];
unsigned int chunksize_buf_index;
header_buf = malloc(header_buf_len);
content_buf = malloc(content_buf_len);
chunksize_buf[0] = '\0';
chunksize_buf_index = 0;
while((n = receivedata(s, buf, 2048, 5000, NULL)) > 0)
{
if(endofheaders == 0)
{
int i;
int linestart=0;
int colon=0;
int valuestart=0;
if(header_buf_used + n > header_buf_len) {
header_buf = realloc(header_buf, header_buf_used + n);
header_buf_len = header_buf_used + n;
}
memcpy(header_buf + header_buf_used, buf, n);
header_buf_used += n;
/* search for CR LF CR LF (end of headers)
* recognize also LF LF */
i = 0;
while(i < ((int)header_buf_used-1) && (endofheaders == 0)) {
if(header_buf[i] == '\r') {
i++;
if(header_buf[i] == '\n') {
i++;
if(i < (int)header_buf_used && header_buf[i] == '\r') {
i++;
if(i < (int)header_buf_used && header_buf[i] == '\n') {
endofheaders = i+1;
}
}
}
} else if(header_buf[i] == '\n') {
i++;
if(header_buf[i] == '\n') {
endofheaders = i+1;
}
}
i++;
}
if(endofheaders == 0)
continue;
/* parse header lines */
for(i = 0; i < endofheaders - 1; i++) {
if(colon <= linestart && header_buf[i]==':')
{
colon = i;
while(i < (endofheaders-1)
&& (header_buf[i+1] == ' ' || header_buf[i+1] == '\t'))
i++;
valuestart = i + 1;
}
/* detecting end of line */
else if(header_buf[i]=='\r' || header_buf[i]=='\n')
{
if(colon > linestart && valuestart > colon)
{
#ifdef DEBUG
printf("header='%.*s', value='%.*s'\n",
colon-linestart, header_buf+linestart,
i-valuestart, header_buf+valuestart);
#endif
if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart))
{
content_length = atoi(header_buf+valuestart);
#ifdef DEBUG
printf("Content-Length: %d\n", content_length);
#endif
}
else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart)
&& 0==strncasecmp(header_buf+valuestart, "chunked", 7))
{
#ifdef DEBUG
printf("chunked transfer-encoding!\n");
#endif
chunked = 1;
}
}
while(header_buf[i]=='\r' || header_buf[i] == '\n')
i++;
linestart = i;
colon = linestart;
valuestart = 0;
}
}
/* copy the remaining of the received data back to buf */
n = header_buf_used - endofheaders;
memcpy(buf, header_buf + endofheaders, n);
/* if(headers) */
}
if(endofheaders)
{
/* content */
if(chunked)
{
int i = 0;
while(i < n)
{
if(chunksize == 0)
{
/* reading chunk size */
if(chunksize_buf_index == 0) {
/* skipping any leading CR LF */
if(i<n && buf[i] == '\r') i++;
if(i<n && buf[i] == '\n') i++;
}
while(i<n && isxdigit(buf[i])
&& chunksize_buf_index < (sizeof(chunksize_buf)-1))
{
chunksize_buf[chunksize_buf_index++] = buf[i];
chunksize_buf[chunksize_buf_index] = '\0';
i++;
}
while(i<n && buf[i] != '\r' && buf[i] != '\n')
i++; /* discarding chunk-extension */
if(i<n && buf[i] == '\r') i++;
if(i<n && buf[i] == '\n') {
unsigned int j;
for(j = 0; j < chunksize_buf_index; j++) {
if(chunksize_buf[j] >= '0'
&& chunksize_buf[j] <= '9')
chunksize = (chunksize << 4) + (chunksize_buf[j] - '0');
else
chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);
}
chunksize_buf[0] = '\0';
chunksize_buf_index = 0;
i++;
} else {
/* not finished to get chunksize */
continue;
}
#ifdef DEBUG
printf("chunksize = %u (%x)\n", chunksize, chunksize);
#endif
if(chunksize == 0)
{
#ifdef DEBUG
printf("end of HTTP content - %d %d\n", i, n);
/*printf("'%.*s'\n", n-i, buf+i);*/
#endif
goto end_of_stream;
}
}
bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);
if((content_buf_used + bytestocopy) > content_buf_len)
{
if(content_length >= (int)(content_buf_used + bytestocopy)) {
content_buf_len = content_length;
} else {
content_buf_len = content_buf_used + bytestocopy;
}
content_buf = (char *)realloc((void *)content_buf,
content_buf_len);
}
memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
content_buf_used += bytestocopy;
i += bytestocopy;
chunksize -= bytestocopy;
}
}
else
{
/* not chunked */
if(content_length > 0
&& (int)(content_buf_used + n) > content_length) {
/* skipping additional bytes */
n = content_length - content_buf_used;
}
if(content_buf_used + n > content_buf_len)
{
if(content_length >= (int)(content_buf_used + n)) {
content_buf_len = content_length;
} else {
content_buf_len = content_buf_used + n;
}
content_buf = (char *)realloc((void *)content_buf,
content_buf_len);
}
memcpy(content_buf + content_buf_used, buf, n);
content_buf_used += n;
}
}
/* use the Content-Length header value if available */
if(content_length > 0 && (int)content_buf_used >= content_length)
{
#ifdef DEBUG
printf("End of HTTP content\n");
#endif
break;
}
}
end_of_stream:
free(header_buf); header_buf = NULL;
*size = content_buf_used;
if(content_buf_used == 0)
{
free(content_buf);
content_buf = NULL;
}
return content_buf;
}
/* miniwget3() :
* do all the work.
* Return NULL if something failed. */
static void *
miniwget3(const char * host,
unsigned short port, const char * path,
int * size, char * addr_str, int addr_str_len,
const char * httpversion, unsigned int scope_id)
{
char buf[2048];
int s;
int n;
int len;
int sent;
void * content;
*size = 0;
s = connecthostport(host, port, scope_id);
if(s < 0)
return NULL;
/* get address for caller ! */
if(addr_str)
{
struct sockaddr_storage saddr;
socklen_t saddrlen;
saddrlen = sizeof(saddr);
if(getsockname(s, (struct sockaddr *)&saddr, &saddrlen) < 0)
{
perror("getsockname");
}
else
{
#if defined(__amigaos__) && !defined(__amigaos4__)
/* using INT WINAPI WSAAddressToStringA(LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFOA, LPSTR, LPDWORD);
* But his function make a string with the port : nn.nn.nn.nn:port */
/* if(WSAAddressToStringA((SOCKADDR *)&saddr, sizeof(saddr),
NULL, addr_str, (DWORD *)&addr_str_len))
{
printf("WSAAddressToStringA() failed : %d\n", WSAGetLastError());
}*/
/* the following code is only compatible with ip v4 addresses */
strncpy(addr_str, inet_ntoa(((struct sockaddr_in *)&saddr)->sin_addr), addr_str_len);
#else
#if 0
if(saddr.sa_family == AF_INET6) {
inet_ntop(AF_INET6,
&(((struct sockaddr_in6 *)&saddr)->sin6_addr),
addr_str, addr_str_len);
} else {
inet_ntop(AF_INET,
&(((struct sockaddr_in *)&saddr)->sin_addr),
addr_str, addr_str_len);
}
#endif
/* getnameinfo return ip v6 address with the scope identifier
* such as : 2a01:e35:8b2b:7330::%4281128194 */
n = getnameinfo((const struct sockaddr *)&saddr, saddrlen,
addr_str, addr_str_len,
NULL, 0,
NI_NUMERICHOST | NI_NUMERICSERV);
if(n != 0) {
#ifdef _WIN32
fprintf(stderr, "getnameinfo() failed : %d\n", n);
#else
fprintf(stderr, "getnameinfo() failed : %s\n", gai_strerror(n));
#endif
}
#endif
}
#ifdef DEBUG
printf("address miniwget : %s\n", addr_str);
#endif
}
len = snprintf(buf, sizeof(buf),
"GET %s HTTP/%s\r\n"
"Host: %s:%d\r\n"
"Connection: Close\r\n"
"User-Agent: " OS_STRING ", UPnP/1.0, MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n"
"\r\n",
path, httpversion, host, port);
sent = 0;
/* sending the HTTP request */
while(sent < len)
{
n = send(s, buf+sent, len-sent, 0);
if(n < 0)
{
perror("send");
closesocket(s);
return NULL;
}
else
{
sent += n;
}
}
content = getHTTPResponse(s, size);
closesocket(s);
return content;
}
/* miniwget2() :
* Call miniwget3(); retry with HTTP/1.1 if 1.0 fails. */
static void *
miniwget2(const char * host,
unsigned short port, const char * path,
int * size, char * addr_str, int addr_str_len,
unsigned int scope_id)
{
char * respbuffer;
#if 1
respbuffer = miniwget3(host, port, path, size,
addr_str, addr_str_len, "1.1", scope_id);
#else
respbuffer = miniwget3(host, port, path, size,
addr_str, addr_str_len, "1.0", scope_id);
if (*size == 0)
{
#ifdef DEBUG
printf("Retrying with HTTP/1.1\n");
#endif
free(respbuffer);
respbuffer = miniwget3(host, port, path, size,
addr_str, addr_str_len, "1.1", scope_id);
}
#endif
return respbuffer;
}
/* parseURL()
* arguments :
* url : source string not modified
* hostname : hostname destination string (size of MAXHOSTNAMELEN+1)
* port : port (destination)
* path : pointer to the path part of the URL
*
* Return values :
* 0 - Failure
* 1 - Success */
int
parseURL(const char * url,
char * hostname, unsigned short * port,
char * * path, unsigned int * scope_id)
{
char * p1, *p2, *p3;
if(!url)
return 0;
p1 = strstr(url, "://");
if(!p1)
return 0;
p1 += 3;
if( (url[0]!='h') || (url[1]!='t')
||(url[2]!='t') || (url[3]!='p'))
return 0;
memset(hostname, 0, MAXHOSTNAMELEN + 1);
if(*p1 == '[')
{
/* IP v6 : http://[2a00:1450:8002::6a]/path/abc */
char * scope;
scope = strchr(p1, '%');
p2 = strchr(p1, ']');
if(p2 && scope && scope < p2 && scope_id) {
/* parse scope */
#ifdef IF_NAMESIZE
char tmp[IF_NAMESIZE];
int l;
scope++;
/* "%25" is just '%' in URL encoding */
if(scope[0] == '2' && scope[1] == '5')
scope += 2; /* skip "25" */
l = p2 - scope;
if(l >= IF_NAMESIZE)
l = IF_NAMESIZE - 1;
memcpy(tmp, scope, l);
tmp[l] = '\0';
*scope_id = if_nametoindex(tmp);
if(*scope_id == 0) {
*scope_id = (unsigned int)strtoul(tmp, NULL, 10);
}
#else
/* under windows, scope is numerical */
char tmp[8];
int l;
scope++;
/* "%25" is just '%' in URL encoding */
if(scope[0] == '2' && scope[1] == '5')
scope += 2; /* skip "25" */
l = p2 - scope;
if(l >= sizeof(tmp))
l = sizeof(tmp) - 1;
memcpy(tmp, scope, l);
tmp[l] = '\0';
*scope_id = (unsigned int)strtoul(tmp, NULL, 10);
#endif
}
p3 = strchr(p1, '/');
if(p2 && p3)
{
p2++;
strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1)));
if(*p2 == ':')
{
*port = 0;
p2++;
while( (*p2 >= '0') && (*p2 <= '9'))
{
*port *= 10;
*port += (unsigned short)(*p2 - '0');
p2++;
}
}
else
{
*port = 80;
}
*path = p3;
return 1;
}
}
p2 = strchr(p1, ':');
p3 = strchr(p1, '/');
if(!p3)
return 0;
if(!p2 || (p2>p3))
{
strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p3-p1)));
*port = 80;
}
else
{
strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1)));
*port = 0;
p2++;
while( (*p2 >= '0') && (*p2 <= '9'))
{
*port *= 10;
*port += (unsigned short)(*p2 - '0');
p2++;
}
}
*path = p3;
return 1;
}
void *
miniwget(const char * url, int * size, unsigned int scope_id)
{
unsigned short port;
char * path;
/* protocol://host:port/chemin */
char hostname[MAXHOSTNAMELEN+1];
*size = 0;
if(!parseURL(url, hostname, &port, &path, &scope_id))
return NULL;
#ifdef DEBUG
printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
hostname, port, path, scope_id);
#endif
return miniwget2(hostname, port, path, size, 0, 0, scope_id);
}
void *
miniwget_getaddr(const char * url, int * size,
char * addr, int addrlen, unsigned int scope_id)
{
unsigned short port;
char * path;
/* protocol://host:port/path */
char hostname[MAXHOSTNAMELEN+1];
*size = 0;
if(addr)
addr[0] = '\0';
if(!parseURL(url, hostname, &port, &path, &scope_id))
return NULL;
#ifdef DEBUG
printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
hostname, port, path, scope_id);
#endif
return miniwget2(hostname, port, path, size, addr, addrlen, scope_id);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2183_1 |
crossvul-cpp_data_good_1050_2 | /* -*- coding: utf-8 -*- */
/* Copyright (C) 2000-2012 by George Williams */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <fontforge-config.h>
#include "autotrace.h"
#include "charset.h"
#include "encoding.h"
#include "ffglib.h"
#include "fontforgeui.h"
#include "gfile.h"
#include "gkeysym.h"
#include "gresedit.h"
#include "gresource.h"
#include "groups.h"
#include "macenc.h"
#include "namelist.h"
#include "othersubrs.h"
#include "prefs.h"
#include "sfd.h"
#include "splineutil.h"
#include "ttf.h"
#include "ustring.h"
#include <dirent.h>
#include <locale.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#if HAVE_LANGINFO_H
# include <langinfo.h>
#endif
#define RAD2DEG (180/3.1415926535897932)
static void change_res_filename(const char *newname);
extern int splash;
extern int adjustwidth;
extern int adjustlbearing;
extern Encoding *default_encoding;
extern int autohint_before_generate;
extern int use_freetype_to_rasterize_fv;
extern int use_freetype_with_aa_fill_cv;
extern int OpenCharsInNewWindow;
extern int ItalicConstrained;
extern int accent_offset;
extern int GraveAcuteCenterBottom;
extern int PreferSpacingAccents;
extern int CharCenterHighest;
extern int ask_user_for_resolution;
#ifndef _NO_LIBPNG
extern int WritePNGInSFD;
#endif
extern int stop_at_join;
extern int recognizePUA;
extern float arrowAmount;
extern float arrowAccelFactor;
extern float snapdistance;
extern float snapdistancemeasuretool;
extern int measuretoolshowhorizontolvertical;
extern int snaptoint;
extern float joinsnap;
extern char *BDFFoundry;
extern char *TTFFoundry;
extern char *xuid;
extern char *SaveTablesPref;
/*struct cvshows CVShows = { 1, 1, 1, 1, 1, 0, 1 };*/ /* in charview */
/* int default_fv_font_size = 24; */ /* in fontview */
/* int default_fv_antialias = false */ /* in fontview */
/* int default_fv_bbsized = false */ /* in fontview */
extern int default_fv_row_count; /* in fontview */
extern int default_fv_col_count; /* in fontview */
extern int default_fv_showhmetrics; /* in fontview */
extern int default_fv_showvmetrics; /* in fontview */
extern int default_fv_glyphlabel; /* in fontview */
extern int save_to_dir; /* in fontview, use sfdir rather than sfd */
extern int palettes_docked; /* in cvpalettes */
extern int cvvisible[2], bvvisible[3]; /* in cvpalettes.c */
extern int maxundoes; /* in cvundoes */
extern int pref_mv_shift_and_arrow_skip; /* in metricsview.c */
extern int pref_mv_control_shift_and_arrow_skip; /* in metricsview.c */
extern int mv_type; /* in metricsview.c */
extern int prefer_cjk_encodings; /* in parsettf */
extern int onlycopydisplayed, copymetadata, copyttfinstr;
extern struct cvshows CVShows;
extern int infowindowdistance; /* in cvruler.c */
extern int oldformatstate; /* in savefontdlg.c */
extern int oldbitmapstate; /* in savefontdlg.c */
static int old_ttf_flags=0, old_otf_flags=0;
extern int old_sfnt_flags; /* in savefont.c */
extern int old_ps_flags; /* in savefont.c */
extern int old_validate; /* in savefontdlg.c */
extern int old_fontlog; /* in savefontdlg.c */
extern int oldsystem; /* in bitmapdlg.c */
extern int preferpotrace; /* in autotrace.c */
extern int autotrace_ask; /* in autotrace.c */
extern int mf_ask; /* in autotrace.c */
extern int mf_clearbackgrounds; /* in autotrace.c */
extern int mf_showerrors; /* in autotrace.c */
extern char *mf_args; /* in autotrace.c */
static int glyph_2_name_map=0; /* was in tottf.c, now a flag in savefont options dlg */
extern int coverageformatsallowed; /* in tottfgpos.c */
extern int debug_wins; /* in cvdebug.c */
extern int gridfit_dpi, gridfit_depth; /* in cvgridfit.c */
extern float gridfit_pointsizey; /* in cvgridfit.c */
extern float gridfit_pointsizex; /* in cvgridfit.c */
extern int gridfit_x_sameas_y; /* in cvgridfit.c */
extern int hint_diagonal_ends; /* in stemdb.c */
extern int hint_diagonal_intersections; /* in stemdb.c */
extern int hint_bounding_boxes; /* in stemdb.c */
extern int detect_diagonal_stems; /* in stemdb.c */
extern float stem_slope_error; /* in stemdb.c */
extern float stub_slope_error; /* in stemdb.c */
extern int instruct_diagonal_stems; /* in nowakowskittfinstr.c */
extern int instruct_serif_stems; /* in nowakowskittfinstr.c */
extern int instruct_ball_terminals; /* in nowakowskittfinstr.c */
extern int interpolate_strong; /* in nowakowskittfinstr.c */
extern int control_counters; /* in nowakowskittfinstr.c */
extern unichar_t *script_menu_names[SCRIPT_MENU_MAX];
extern char *script_filenames[SCRIPT_MENU_MAX];
static char *xdefs_filename;
extern int new_em_size; /* in splineutil2.c */
extern int new_fonts_are_order2; /* in splineutil2.c */
extern int loaded_fonts_same_as_new; /* in splineutil2.c */
extern int use_second_indic_scripts; /* in tottfgpos.c */
static char *othersubrsfile = NULL;
extern MacFeat *default_mac_feature_map, /* from macenc.c */
*user_mac_feature_map;
extern int updateflex; /* in charview.c */
extern int default_autokern_dlg; /* in lookupui.c */
extern int allow_utf8_glyphnames; /* in lookupui.c */
extern int add_char_to_name_list; /* in charinfo.c */
extern int clear_tt_instructions_when_needed; /* in cvundoes.c */
extern int export_clipboard; /* in cvundoes.c */
extern int cv_width; /* in charview.c */
extern int cv_height; /* in charview.c */
extern int cv_show_fill_with_space; /* in charview.c */
extern int interpCPsOnMotion; /* in charview.c */
extern int DrawOpenPathsWithHighlight; /* in charview.c */
extern float prefs_cvEditHandleSize; /* in charview.c */
extern int prefs_cvInactiveHandleAlpha; /* in charview.c */
extern int mv_width; /* in metricsview.c */
extern int mv_height; /* in metricsview.c */
extern int bv_width; /* in bitmapview.c */
extern int bv_height; /* in bitmapview.c */
extern int ask_user_for_cmap; /* in parsettf.c */
extern int mvshowgrid; /* in metricsview.c */
extern int rectelipse, polystar, regular_star; /* from cvpalettes.c */
extern int center_out[2]; /* from cvpalettes.c */
extern float rr_radius; /* from cvpalettes.c */
extern int ps_pointcnt; /* from cvpalettes.c */
extern float star_percent; /* from cvpalettes.c */
extern int home_char; /* from fontview.c */
extern int compact_font_on_open; /* from fontview.c */
extern int aa_pixelsize; /* from anchorsaway.c */
extern enum cvtools cv_b1_tool, cv_cb1_tool, cv_b2_tool, cv_cb2_tool; /* cvpalettes.c */
extern int show_kerning_pane_in_class; /* kernclass.c */
extern int AutoSaveFrequency; /* autosave.c */
extern int UndoRedoLimitToSave; /* sfd.c */
extern int UndoRedoLimitToLoad; /* sfd.c */
extern int prefRevisionsToRetain; /* sfd.c */
extern int prefs_cv_show_control_points_always_initially; /* from charview.c */
extern int prefs_create_dragging_comparison_outline; /* from charview.c */
extern int prefs_cv_outline_thickness; /* from charview.c */
extern float OpenTypeLoadHintEqualityTolerance; /* autohint.c */
extern float GenerateHintWidthEqualityTolerance; /* splinesave.c */
extern bool warn_script_unsaved; /* fontview.c */
extern NameList *force_names_when_opening;
extern NameList *force_names_when_saving;
extern NameList *namelist_for_new_fonts;
extern int default_font_filter_index;
extern struct openfilefilters *user_font_filters;
static int alwaysgenapple=false, alwaysgenopentype=false;
static int gfc_showhidden, gfc_dirplace;
static char *gfc_bookmarks=NULL;
static int prefs_usecairo = true;
static int pointless;
/* These first three must match the values in macenc.c */
#define CID_Features 101
#define CID_FeatureDel 103
#define CID_FeatureEdit 105
#define CID_Mapping 102
#define CID_MappingDel 104
#define CID_MappingEdit 106
#define CID_ScriptMNameBase 200
#define CID_ScriptMFileBase (200+SCRIPT_MENU_MAX)
#define CID_ScriptMBrowseBase (200+2*SCRIPT_MENU_MAX)
#define CID_PrefsBase 1000
#define CID_PrefsOffset 100
#define CID_PrefsBrowseOffset (CID_PrefsOffset/2)
//////////////////////////////////
// The _oldval_ are used to cache the setting when the prefs window
// is created so that a redraw can be performed only when the
// value has changed.
float prefs_oldval_cvEditHandleSize = 0;
int prefs_oldval_cvInactiveHandleAlpha = 0;
/* ************************************************************************** */
/* ***************************** mac data ***************************** */
/* ************************************************************************** */
extern struct macsettingname macfeat_otftag[], *user_macfeat_otftag;
static void UserSettingsFree(void) {
free( user_macfeat_otftag );
user_macfeat_otftag = NULL;
}
static int UserSettingsDiffer(void) {
int i,j;
if ( user_macfeat_otftag==NULL )
return( false );
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i );
for ( j=0; macfeat_otftag[j].otf_tag!=0; ++j );
if ( i!=j )
return( true );
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i ) {
for ( j=0; macfeat_otftag[j].otf_tag!=0; ++j ) {
if ( macfeat_otftag[j].mac_feature_type ==
user_macfeat_otftag[i].mac_feature_type &&
macfeat_otftag[j].mac_feature_setting ==
user_macfeat_otftag[i].mac_feature_setting &&
macfeat_otftag[j].otf_tag ==
user_macfeat_otftag[i].otf_tag )
break;
}
if ( macfeat_otftag[j].otf_tag==0 )
return( true );
}
return( false );
}
/**************************************************************************** */
/* don't use mnemonics 'C' or 'O' (Cancel & OK) */
enum pref_types { pr_int, pr_real, pr_bool, pr_enum, pr_encoding, pr_string,
pr_file, pr_namelist, pr_unicode, pr_angle };
struct enums { char *name; int value; };
struct enums fvsize_enums[] = { {NULL, 0} };
#define PREFS_LIST_EMPTY { NULL, 0, NULL, NULL, NULL, '\0', NULL, 0, NULL }
static struct prefs_list {
char *name;
/* In the prefs file the untranslated name will always be used, but */
/* in the UI that name may be translated. */
enum pref_types type;
void *val;
void *(*get)(void);
void (*set)(void *);
char mn;
struct enums *enums;
unsigned int dontdisplay: 1;
char *popup;
} general_list[] = {
/* GT: The following strings have no spaces and an odd capitalization */
/* GT: this is because these strings are used in two different ways, one */
/* GT: translated (which the user sees, and should probably have added spaces,*/
/* GT: and one untranslated which needs the current odd format */
{ N_("ResourceFile"), pr_file, &xdefs_filename, NULL, NULL, 'R', NULL, 0, N_("When FontForge starts up, it loads the user interface theme from\nthis file. Any changes will only take effect the next time you start FontForge.") },
{ N_("OtherSubrsFile"), pr_file, &othersubrsfile, NULL, NULL, 'O', NULL, 0, N_("If you wish to replace Adobe's OtherSubrs array (for Type1 fonts)\nwith an array of your own, set this to point to a file containing\na list of up to 14 PostScript subroutines. Each subroutine must\nbe preceded by a line starting with '%%%%' (any text before the\nfirst '%%%%' line will be treated as an initial copyright notice).\nThe first three subroutines are for flex hints, the next for hint\nsubstitution (this MUST be present), the 14th (or 13 as the\nnumbering actually starts with 0) is for counter hints.\nThe subroutines should not be enclosed in a [ ] pair.") },
{ N_("FreeTypeInFontView"), pr_bool, &use_freetype_to_rasterize_fv, NULL, NULL, 'O', NULL, 0, N_("Use the FreeType rasterizer (when available)\nto rasterize glyphs in the font view.\nThis generally results in better quality.") },
{ N_("FreeTypeAAFillInOutlineView"), pr_bool, &use_freetype_with_aa_fill_cv, NULL, NULL, 'O', NULL, 0, N_("When filling using freetype in the outline view,\nhave freetype render the glyph antialiased.") },
{ N_("SplashScreen"), pr_bool, &splash, NULL, NULL, 'S', NULL, 0, N_("Show splash screen on start-up") },
#ifndef _NO_LIBCAIRO
{ N_("UseCairoDrawing"), pr_bool, &prefs_usecairo, NULL, NULL, '\0', NULL, 0, N_("Use the cairo library for drawing (if available)\nThis makes for prettier (anti-aliased) but slower drawing\nThis applies to any windows created AFTER this is set.\nAlready existing windows will continue as they are.") },
#endif
{ N_("ExportClipboard"), pr_bool, &export_clipboard, NULL, NULL, '\0', NULL, 0, N_( "If you are running an X11 clipboard manager you might want\nto turn this off. FF can put things into its internal clipboard\nwhich it cannot export to X11 (things like copying more than\none glyph in the fontview). If you have a clipboard manager\nrunning it will force these to be exported with consequent\nloss of data.") },
{ N_("AutoSaveFrequency"), pr_int, &AutoSaveFrequency, NULL, NULL, '\0', NULL, 0, N_( "The number of seconds between autosaves. If you set this to 0 there will be no autosaves.") },
{ N_("RevisionsToRetain"), pr_int, &prefRevisionsToRetain, NULL, NULL, '\0', NULL, 0, N_( "When Saving, keep this number of previous versions of the file. file.sfd-01 will be the last saved file, file.sfd-02 will be the file saved before that, and so on. If you set this to 0 then no revisions will be retained.") },
{ N_("UndoRedoLimitToSave"), pr_int, &UndoRedoLimitToSave, NULL, NULL, '\0', NULL, 0, N_( "The number of undo and redo operations which will be saved in sfd files.\nIf you set this to 0 undo/redo information is not saved to sfd files.\nIf set to -1 then all available undo/redo information is saved without limit.") },
{ N_("WarnScriptUnsaved"), pr_bool, &warn_script_unsaved, NULL, NULL, '\0', NULL, 0, N_( "Whether or not to warn you if you have an unsaved script in the «Execute Script» dialog.") },
PREFS_LIST_EMPTY
},
new_list[] = {
{ N_("NewCharset"), pr_encoding, &default_encoding, NULL, NULL, 'N', NULL, 0, N_("Default encoding for\nnew fonts") },
{ N_("NewEmSize"), pr_int, &new_em_size, NULL, NULL, 'S', NULL, 0, N_("The default size of the Em-Square in a newly created font.") },
{ N_("NewFontsQuadratic"), pr_bool, &new_fonts_are_order2, NULL, NULL, 'Q', NULL, 0, N_("Whether new fonts should contain splines of quadratic (truetype)\nor cubic (postscript & opentype).") },
{ N_("LoadedFontsAsNew"), pr_bool, &loaded_fonts_same_as_new, NULL, NULL, 'L', NULL, 0, N_("Whether fonts loaded from the disk should retain their splines\nwith the original order (quadratic or cubic), or whether the\nsplines should be converted to the default order for new fonts\n(see NewFontsQuadratic).") },
PREFS_LIST_EMPTY
},
open_list[] = {
{ N_("PreferCJKEncodings"), pr_bool, &prefer_cjk_encodings, NULL, NULL, 'C', NULL, 0, N_("When loading a truetype or opentype font which has both a unicode\nand a CJK encoding table, use this flag to specify which\nshould be loaded for the font.") },
{ N_("AskUserForCMap"), pr_bool, &ask_user_for_cmap, NULL, NULL, 'O', NULL, 0, N_("When loading a font in sfnt format (TrueType, OpenType, etc.),\nask the user to specify which cmap to use initially.") },
{ N_("PreserveTables"), pr_string, &SaveTablesPref, NULL, NULL, 'P', NULL, 0, N_("Enter a list of 4 letter table tags, separated by commas.\nFontForge will make a binary copy of these tables when it\nloads a True/OpenType font, and will output them (unchanged)\nwhen it generates the font. Do not include table tags which\nFontForge thinks it understands.") },
{ N_("SeekCharacter"), pr_unicode, &home_char, NULL, NULL, '\0', NULL, 0, N_("When fontforge opens a (non-sfd) font it will try to display this unicode character in the fontview.")},
{ N_("CompactOnOpen"), pr_bool, &compact_font_on_open, NULL, NULL, 'O', NULL, 0, N_("When a font is opened, should it be made compact?")},
{ N_("UndoRedoLimitToLoad"), pr_int, &UndoRedoLimitToLoad, NULL, NULL, '\0', NULL, 0, N_( "The number of undo and redo operations to load from sfd files.\nWith this option you can disregard undo information while loading SFD files.\nIf set to 0 then no undo/redo information is loaded.\nIf set to -1 then all available undo/redo information is loaded without limit.") },
{ N_("OpenTypeLoadHintEqualityTolerance"), pr_real, &OpenTypeLoadHintEqualityTolerance, NULL, NULL, '\0', NULL, 0, N_( "When importing an OpenType font, for the purposes of hinting spline points might not exactly match boundaries. For example, a point might be -0.0002 instead of exactly 0\nThis setting gives the user some control over this allowing a small tolerance value to be fed into the OpenType loading code.\nComparisons are then not performed for raw equality but for equality within tolerance (e.g., values within the range -0.0002 to 0.0002 will be considered equal to 0 when figuring out hints).") },
PREFS_LIST_EMPTY
},
navigation_list[] = {
{ N_("GlyphAutoGoto"), pr_bool, &cv_auto_goto, NULL, NULL, '\0', NULL, 0, N_("Typing a normal character in the glyph view window changes the window to look at that character.\nEnabling GlyphAutoGoto will disable the shortcut where holding just the ` key will enable Preview mode as long as the key is held.") },
{ N_("OpenCharsInNewWindow"), pr_bool, &OpenCharsInNewWindow, NULL, NULL, '\0', NULL, 0, N_("When double clicking on a character in the font view\nopen that character in a new window, otherwise\nreuse an existing one.") },
PREFS_LIST_EMPTY
},
editing_list[] = {
{ N_("ItalicConstrained"), pr_bool, &ItalicConstrained, NULL, NULL, '\0', NULL, 0, N_("In the Outline View, the Shift key constrains motion to be parallel to the ItalicAngle rather than constraining it to be vertical.") },
{ N_("InterpolateCPsOnMotion"), pr_bool, &interpCPsOnMotion, NULL, NULL, '\0', NULL, 0, N_("When moving one end point of a spline but not the other\ninterpolate the control points between the two.") },
{ N_("SnapDistance"), pr_real, &snapdistance, NULL, NULL, '\0', NULL, 0, N_("When the mouse pointer is within this many pixels\nof one of the various interesting features (baseline,\nwidth, grid splines, etc.) the pointer will snap\nto that feature.") },
{ N_("SnapDistanceMeasureTool"), pr_real, &snapdistancemeasuretool, NULL, NULL, '\0', NULL, 0, N_("When the measure tool is active and when the mouse pointer is within this many pixels\nof one of the various interesting features (baseline,\nwidth, grid splines, etc.) the pointer will snap\nto that feature.") },
{ N_("SnapToInt"), pr_bool, &snaptoint, NULL, NULL, '\0', NULL, 0, N_("When the user clicks in the editing window, round the location to the nearest integers.") },
{ N_("StopAtJoin"), pr_bool, &stop_at_join, NULL, NULL, '\0', NULL, 0, N_("When dragging points in the outline view a join may occur\n(two open contours may connect at their endpoints). When\nthis is On a join will cause FontForge to stop moving the\nselection (as if the user had released the mouse button).\nThis is handy if your fingers are inclined to wiggle a bit.") },
{ N_("JoinSnap"), pr_real, &joinsnap, NULL, NULL, '\0', NULL, 0, N_("The Edit->Join command will join points which are this close together\nA value of 0 means they must be coincident") },
{ N_("CopyMetaData"), pr_bool, ©metadata, NULL, NULL, '\0', NULL, 0, N_("When copying glyphs from the font view, also copy the\nglyphs' metadata (name, encoding, comment, etc).") },
{ N_("UndoDepth"), pr_int, &maxundoes, NULL, NULL, '\0', NULL, 0, N_("The maximum number of Undoes/Redoes stored in a glyph. Use -1 for infinite Undoes\n(but watch RAM consumption and use the Edit menu's Remove Undoes as needed)") },
{ N_("UpdateFlex"), pr_bool, &updateflex, NULL, NULL, '\0', NULL, 0, N_("Figure out flex hints after every change") },
{ N_("AutoKernDialog"), pr_bool, &default_autokern_dlg, NULL, NULL, '\0', NULL, 0, N_("Open AutoKern dialog for new kerning subtables") },
{ N_("MetricsShiftSkip"), pr_int, &pref_mv_shift_and_arrow_skip, NULL, NULL, '\0', NULL, 0, N_("Number of units to increment/decrement a table value by in the metrics window when shift is held") },
{ N_("MetricsControlShiftSkip"), pr_int, &pref_mv_control_shift_and_arrow_skip, NULL, NULL, '\0', NULL, 0, N_("Number of units to increment/decrement a table value by in the metrics window when both control and shift is held") },
PREFS_LIST_EMPTY
},
editing_interface_list[] = {
{ N_("ArrowMoveSize"), pr_real, &arrowAmount, NULL, NULL, '\0', NULL, 0, N_("The number of em-units by which an arrow key will move a selected point") },
{ N_("ArrowAccelFactor"), pr_real, &arrowAccelFactor, NULL, NULL, '\0', NULL, 0, N_("Holding down the Shift key will speed up arrow key motion by this factor") },
{ N_("DrawOpenPathsWithHighlight"), pr_bool, &DrawOpenPathsWithHighlight, NULL, NULL, '\0', NULL, 0, N_("Open paths should be drawn in a special highlight color to make them more apparent.") },
{ N_("MeasureToolShowHorizontalVertical"), pr_bool, &measuretoolshowhorizontolvertical, NULL, NULL, '\0', NULL, 0, N_("Have the measure tool show horizontal and vertical distances on the canvas.") },
{ N_("EditHandleSize"), pr_real, &prefs_cvEditHandleSize, NULL, NULL, '\0', NULL, 0, N_("The size of the handles showing control points and other interesting points in the glyph editor (default is 5).") },
{ N_("InactiveHandleAlpha"), pr_int, &prefs_cvInactiveHandleAlpha, NULL, NULL, '\0', NULL, 0, N_("Inactive handles in the glyph editor will be drawn with this alpha value (range: 0-255 default is 255).") },
{ N_("ShowControlPointsAlways"), pr_bool, &prefs_cv_show_control_points_always_initially, NULL, NULL, '\0', NULL, 0, N_("Always show the control points when editing a glyph.\nThis can be turned off in the menu View/Show, this setting will effect if control points are shown initially.\nChange requires a restart of fontforge.") },
{ N_("ShowFillWithSpace"), pr_bool, &cv_show_fill_with_space, NULL, NULL, '\0', NULL, 0, N_("Also enable preview mode when the space bar is pressed.") },
{ N_("OutlineThickness"), pr_int, &prefs_cv_outline_thickness, NULL, NULL, '\0', NULL, 0, N_("Setting above 1 will cause a thick outline to be drawn for glyph paths\n which is only extended inwards from the edge of the glyph.\n See also the ForegroundThickOutlineColor Resource for the color of this outline.") },
PREFS_LIST_EMPTY
},
sync_list[] = {
{ N_("AutoWidthSync"), pr_bool, &adjustwidth, NULL, NULL, '\0', NULL, 0, N_("Changing the width of a glyph\nchanges the widths of all accented\nglyphs based on it.") },
{ N_("AutoLBearingSync"), pr_bool, &adjustlbearing, NULL, NULL, '\0', NULL, 0, N_("Changing the left side bearing\nof a glyph adjusts the lbearing\nof other references in all accented\nglyphs based on it.") },
PREFS_LIST_EMPTY
},
tt_list[] = {
{ N_("ClearInstrsBigChanges"), pr_bool, &clear_tt_instructions_when_needed, NULL, NULL, 'C', NULL, 0, N_("Instructions in a TrueType font refer to\npoints by number, so if you edit a glyph\nin such a way that some points have different\nnumbers (add points, remove them, etc.) then\nthe instructions will be applied to the wrong\npoints with disasterous results.\n Normally FontForge will remove the instructions\nif it detects that the points have been renumbered\nin order to avoid the above problem. You may turn\nthis behavior off -- but be careful!") },
{ N_("CopyTTFInstrs"), pr_bool, ©ttfinstr, NULL, NULL, '\0', NULL, 0, N_("When copying glyphs from the font view, also copy the\nglyphs' truetype instructions.") },
PREFS_LIST_EMPTY
},
accent_list[] = {
{ N_("AccentOffsetPercent"), pr_int, &accent_offset, NULL, NULL, '\0', NULL, 0, N_("The percentage of an em by which an accent is offset from its base glyph in Build Accent") },
{ N_("AccentCenterLowest"), pr_bool, &GraveAcuteCenterBottom, NULL, NULL, '\0', NULL, 0, N_("When placing grave and acute accents above letters, should\nFontForge center them based on their full width, or\nshould it just center based on the lowest point\nof the accent.") },
{ N_("CharCenterHighest"), pr_bool, &CharCenterHighest, NULL, NULL, '\0', NULL, 0, N_("When centering an accent over a glyph, should the accent\nbe centered on the highest point(s) of the glyph,\nor the middle of the glyph?") },
{ N_("PreferSpacingAccents"), pr_bool, &PreferSpacingAccents, NULL, NULL, '\0', NULL, 0, N_("Use spacing accents (Unicode: 02C0-02FF) rather than\ncombining accents (Unicode: 0300-036F) when\nbuilding accented glyphs.") },
PREFS_LIST_EMPTY
},
args_list[] = {
{ N_("PreferPotrace"), pr_bool, &preferpotrace, NULL, NULL, '\0', NULL, 0, N_("FontForge supports two different helper applications to do autotracing\n autotrace and potrace\nIf your system only has one it will use that one, if you have both\nuse this option to tell FontForge which to pick.") },
{ N_("AutotraceArgs"), pr_string, NULL, GetAutoTraceArgs, SetAutoTraceArgs, '\0', NULL, 0, N_("Extra arguments for configuring the autotrace program\n(either autotrace or potrace)") },
{ N_("AutotraceAsk"), pr_bool, &autotrace_ask, NULL, NULL, '\0', NULL, 0, N_("Ask the user for autotrace arguments each time autotrace is invoked") },
{ N_("MfArgs"), pr_string, &mf_args, NULL, NULL, '\0', NULL, 0, N_("Commands to pass to mf (metafont) program, the filename will follow these") },
{ N_("MfAsk"), pr_bool, &mf_ask, NULL, NULL, '\0', NULL, 0, N_("Ask the user for mf commands each time mf is invoked") },
{ N_("MfClearBg"), pr_bool, &mf_clearbackgrounds, NULL, NULL, '\0', NULL, 0, N_("FontForge loads large images into the background of each glyph\nprior to autotracing them. You may retain those\nimages to look at after mf processing is complete, or\nremove them to save space") },
{ N_("MfShowErr"), pr_bool, &mf_showerrors, NULL, NULL, '\0', NULL, 0, N_("MetaFont (mf) generates lots of verbiage to stdout.\nMost of the time I find it an annoyance but it is\nimportant to see if something goes wrong.") },
PREFS_LIST_EMPTY
},
fontinfo_list[] = {
{ N_("FoundryName"), pr_string, &BDFFoundry, NULL, NULL, 'F', NULL, 0, N_("Name used for foundry field in bdf\nfont generation") },
{ N_("TTFFoundry"), pr_string, &TTFFoundry, NULL, NULL, 'T', NULL, 0, N_("Name used for Vendor ID field in\nttf (OS/2 table) font generation.\nMust be no more than 4 characters") },
{ N_("NewFontNameList"), pr_namelist, &namelist_for_new_fonts, NULL, NULL, '\0', NULL, 0, N_("FontForge will use this namelist when assigning\nglyph names to code points in a new font.") },
{ N_("RecognizePUANames"), pr_bool, &recognizePUA, NULL, NULL, 'U', NULL, 0, N_("Once upon a time, Adobe assigned PUA (public use area) encodings\nfor many stylistic variants of characters (small caps, old style\nnumerals, etc.). Adobe no longer believes this to be a good idea,\nand recommends that these encodings be ignored.\n\n The assignments were originally made because most applications\ncould not handle OpenType features for accessing variants. Adobe\nnow believes that all apps that matter can now do so. Applications\nlike Word and OpenOffice still can't handle these features, so\n fontforge's default behavior is to ignore Adobe's current\nrecommendations.\n\nNote: This does not affect figuring out unicode from the font's encoding,\nit just controls determining unicode from a name.") },
{ N_("UnicodeGlyphNames"), pr_bool, &allow_utf8_glyphnames, NULL, NULL, 'O', NULL, 0, N_("Allow the full unicode character set in glyph names.\nThis does not conform to adobe's glyph name standard.\nSuch names should be for internal use only and\nshould NOT end up in production fonts." ) },
{ N_("AddCharToNameList"), pr_bool, &add_char_to_name_list, NULL, NULL, 'O', NULL, 0, N_( "When displaying a list of glyph names\n(or sometimes just a single glyph name)\nFontForge will add the unicode character\nthe name refers to in parenthesis after\nthe name. It does this because some names\nare obscure.\nSome people would prefer not to see this,\nso this preference item lets you turn off\n this behavior" ) },
PREFS_LIST_EMPTY
},
generate_list[] = {
{ N_("AskBDFResolution"), pr_bool, &ask_user_for_resolution, NULL, NULL, 'B', NULL, 0, N_("When generating a set of BDF fonts ask the user\nto specify the screen resolution of the fonts\notherwise FontForge will guess depending on the pixel size.") },
{ N_("AutoHint"), pr_bool, &autohint_before_generate, NULL, NULL, 'H', NULL, 0, N_("AutoHint changed glyphs before generating a font") },
#ifndef _NO_LIBPNG
{ N_("WritePNGInSFD"), pr_bool, &WritePNGInSFD, NULL, NULL, 'B', NULL, 0, N_("If your SFD contains images, write them as PNG; this results in smaller SFDs; but was not supported in FontForge versions compiled before July 2019, so older FontForge versions cannot read them.") },
#endif
{ N_("GenerateHintWidthEqualityTolerance"), pr_real, &GenerateHintWidthEqualityTolerance, NULL, NULL, '\0', NULL, 0, N_( "When generating a font, ignore slight rounding errors for hints that should be at the top or bottom of the glyph. For example, you might like to set this to 0.02 so that 19.999 will be considered 20. But only for the hint width value.") },
PREFS_LIST_EMPTY
},
hints_list[] = {
{ N_("StandardSlopeError"), pr_angle, &stem_slope_error, NULL, NULL, '\0', NULL, 0, N_("The maximum slope difference which still allows to consider two points \"parallel\".\nEnlarge this to make the autohinter more tolerable to small deviations from straight lines when detecting stem edges.") },
{ N_("SerifSlopeError"), pr_angle, &stub_slope_error, NULL, NULL, '\0', NULL, 0, N_("Same as above, but for terminals of small features (e. g. serifs), which can deviate more significantly from the horizontal or vertical direction.") },
{ N_("HintBoundingBoxes"), pr_bool, &hint_bounding_boxes, NULL, NULL, '\0', NULL, 0, N_("FontForge will place vertical or horizontal hints to describe the bounding boxes of suitable glyphs.") },
{ N_("HintDiagonalEnds"), pr_bool, &hint_diagonal_ends, NULL, NULL, '\0', NULL, 0, N_("FontForge will place vertical or horizontal hints at the ends of diagonal stems.") },
{ N_("HintDiagonalInter"), pr_bool, &hint_diagonal_intersections, NULL, NULL, '\0', NULL, 0, N_("FontForge will place vertical or horizontal hints at the intersections of diagonal stems.") },
{ N_("DetectDiagonalStems"), pr_bool, &detect_diagonal_stems, NULL, NULL, '\0', NULL, 0, N_("FontForge will generate diagonal stem hints, which then can be used by the AutoInstr command.") },
PREFS_LIST_EMPTY
},
instrs_list[] = {
{ N_("InstructDiagonalStems"), pr_bool, &instruct_diagonal_stems, NULL, NULL, '\0', NULL, 0, N_("Generate instructions for diagonal stem hints.") },
{ N_("InstructSerifs"), pr_bool, &instruct_serif_stems, NULL, NULL, '\0', NULL, 0, N_("Try to detect serifs and other elements protruding from base stems and generate instructions for them.") },
{ N_("InstructBallTerminals"), pr_bool, &instruct_ball_terminals, NULL, NULL, '\0', NULL, 0, N_("Generate instructions for ball terminals.") },
{ N_("InterpolateStrongPoints"), pr_bool, &interpolate_strong, NULL, NULL, '\0', NULL, 0, N_("Interpolate between stem edges some important points, not affected by other instructions.") },
{ N_("CounterControl"), pr_bool, &control_counters, NULL, NULL, '\0', NULL, 0, N_("Make sure similar or equal counters remain the same in gridfitted outlines.\nEnabling this option may result in glyph advance widths being\ninconsistently scaled at some PPEMs.") },
PREFS_LIST_EMPTY
},
opentype_list[] = {
{ N_("UseNewIndicScripts"), pr_bool, &use_second_indic_scripts, NULL, NULL, 'C', NULL, 0, N_("MS has changed (in August 2006) the inner workings of their Indic shaping\nengine, and to disambiguate this change has created a parallel set of script\ntags (generally ending in '2') for Indic writing systems. If you are working\nwith the new system set this flag, if you are working with the old unset it.\n(if you aren't doing Indic work, this flag is irrelevant).") },
PREFS_LIST_EMPTY
},
/* These are hidden, so will never appear in preference ui, hence, no "N_(" */
/* They are controled elsewhere AntiAlias is a menu item in the font window's View menu */
/* etc. */
hidden_list[] = {
{ "AntiAlias", pr_bool, &default_fv_antialias, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFVShowHmetrics", pr_int, &default_fv_showhmetrics, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFVShowVmetrics", pr_int, &default_fv_showvmetrics, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFVSize", pr_int, &default_fv_font_size, NULL, NULL, 'S', NULL, 1, NULL },
{ "DefaultFVRowCount", pr_int, &default_fv_row_count, NULL, NULL, 'S', NULL, 1, NULL },
{ "DefaultFVColCount", pr_int, &default_fv_col_count, NULL, NULL, 'S', NULL, 1, NULL },
{ "DefaultFVGlyphLabel", pr_int, &default_fv_glyphlabel, NULL, NULL, 'S', NULL, 1, NULL },
{ "SaveToDir", pr_int, &save_to_dir, NULL, NULL, 'S', NULL, 1, NULL },
{ "OnlyCopyDisplayed", pr_bool, &onlycopydisplayed, NULL, NULL, '\0', NULL, 1, NULL },
{ "PalettesDocked", pr_bool, &palettes_docked, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultCVWidth", pr_int, &cv_width, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultCVHeight", pr_int, &cv_height, NULL, NULL, '\0', NULL, 1, NULL },
{ "CVVisible0", pr_bool, &cvvisible[0], NULL, NULL, '\0', NULL, 1, NULL },
{ "CVVisible1", pr_bool, &cvvisible[1], NULL, NULL, '\0', NULL, 1, NULL },
{ "BVVisible0", pr_bool, &bvvisible[0], NULL, NULL, '\0', NULL, 1, NULL },
{ "BVVisible1", pr_bool, &bvvisible[1], NULL, NULL, '\0', NULL, 1, NULL },
{ "BVVisible2", pr_bool, &bvvisible[2], NULL, NULL, '\0', NULL, 1, NULL },
{ "MarkExtrema", pr_int, &CVShows.markextrema, NULL, NULL, '\0', NULL, 1, NULL },
{ "MarkPointsOfInflect", pr_int, &CVShows.markpoi, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowRulers", pr_bool, &CVShows.showrulers, NULL, NULL, '\0', NULL, 1, N_("Display rulers in the Outline Glyph View") },
{ "ShowCPInfo", pr_int, &CVShows.showcpinfo, NULL, NULL, '\0', NULL, 1, NULL },
{ "CreateDraggingComparisonOutline", pr_int, &prefs_create_dragging_comparison_outline, NULL, NULL, '\0', NULL, 1, NULL },
{ "InfoWindowDistance", pr_int, &infowindowdistance, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowSideBearings", pr_int, &CVShows.showsidebearings, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowRefNames", pr_int, &CVShows.showrefnames, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowPoints", pr_bool, &CVShows.showpoints, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowFilled", pr_int, &CVShows.showfilled, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowTabs", pr_int, &CVShows.showtabs, NULL, NULL, '\0', NULL, 1, NULL },
{ "SnapOutlines", pr_int, &CVShows.snapoutlines, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowAlmostHVLines", pr_bool, &CVShows.showalmosthvlines, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowAlmostHVCurves", pr_bool, &CVShows.showalmosthvcurves, NULL, NULL, '\0', NULL, 1, NULL },
{ "AlmostHVBound", pr_int, &CVShows.hvoffset, NULL, NULL, '\0', NULL, 1, NULL },
{ "CheckSelfIntersects", pr_bool, &CVShows.checkselfintersects, NULL, NULL, '\0', NULL, 1, NULL },
{ "ShowDebugChanges", pr_bool, &CVShows.showdebugchanges, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultScreenDpiSystem", pr_int, &oldsystem, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultOutputFormat", pr_int, &oldformatstate, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultBitmapFormat", pr_int, &oldbitmapstate, NULL, NULL, '\0', NULL, 1, NULL },
{ "SaveValidate", pr_int, &old_validate, NULL, NULL, '\0', NULL, 1, NULL },
{ "SaveFontLogAsk", pr_int, &old_fontlog, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultSFNTflags", pr_int, &old_sfnt_flags, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultPSflags", pr_int, &old_ps_flags, NULL, NULL, '\0', NULL, 1, NULL },
{ "PageWidth", pr_int, &pagewidth, NULL, NULL, '\0', NULL, 1, NULL },
{ "PageHeight", pr_int, &pageheight, NULL, NULL, '\0', NULL, 1, NULL },
{ "PrintType", pr_int, &printtype, NULL, NULL, '\0', NULL, 1, NULL },
{ "PrintCommand", pr_string, &printcommand, NULL, NULL, '\0', NULL, 1, NULL },
{ "PageLazyPrinter", pr_string, &printlazyprinter, NULL, NULL, '\0', NULL, 1, NULL },
{ "RegularStar", pr_bool, ®ular_star, NULL, NULL, '\0', NULL, 1, NULL },
{ "PolyStar", pr_bool, &polystar, NULL, NULL, '\0', NULL, 1, NULL },
{ "RectEllipse", pr_bool, &rectelipse, NULL, NULL, '\0', NULL, 1, NULL },
{ "RectCenterOut", pr_bool, ¢er_out[0], NULL, NULL, '\0', NULL, 1, NULL },
{ "EllipseCenterOut", pr_bool, ¢er_out[1], NULL, NULL, '\0', NULL, 1, NULL },
{ "PolyStartPointCnt", pr_int, &ps_pointcnt, NULL, NULL, '\0', NULL, 1, NULL },
{ "RoundRectRadius", pr_real, &rr_radius, NULL, NULL, '\0', NULL, 1, NULL },
{ "StarPercent", pr_real, &star_percent, NULL, NULL, '\0', NULL, 1, NULL },
{ "CoverageFormatsAllowed", pr_int, &coverageformatsallowed, NULL, NULL, '\0', NULL, 1, NULL },
{ "DebugWins", pr_int, &debug_wins, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitDpi", pr_int, &gridfit_dpi, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitDepth", pr_int, &gridfit_depth, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitPointSize", pr_real, &gridfit_pointsizey, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitPointSizeX", pr_real, &gridfit_pointsizex, NULL, NULL, '\0', NULL, 1, NULL },
{ "GridFitSameAs", pr_int, &gridfit_x_sameas_y, NULL, NULL, '\0', NULL, 1, NULL },
{ "MVShowGrid", pr_int, &mvshowgrid, NULL, NULL, '\0', NULL, 1, NULL },
{ "ForceNamesWhenOpening", pr_namelist, &force_names_when_opening, NULL, NULL, '\0', NULL, 1, NULL },
{ "ForceNamesWhenSaving", pr_namelist, &force_names_when_saving, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultFontFilterIndex", pr_int, &default_font_filter_index, NULL, NULL, '\0', NULL, 1, NULL },
{ "FCShowHidden", pr_bool, &gfc_showhidden, NULL, NULL, '\0', NULL, 1, NULL },
{ "FCDirPlacement", pr_int, &gfc_dirplace, NULL, NULL, '\0', NULL, 1, NULL },
{ "FCBookmarks", pr_string, &gfc_bookmarks, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultMVType", pr_int, &mv_type, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultMVWidth", pr_int, &mv_width, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultMVHeight", pr_int, &mv_height, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultBVWidth", pr_int, &bv_width, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultBVHeight", pr_int, &bv_height, NULL, NULL, '\0', NULL, 1, NULL },
{ "AnchorControlPixelSize", pr_int, &aa_pixelsize, NULL, NULL, '\0', NULL, 1, NULL },
#ifdef _NO_LIBCAIRO
{ "UseCairoDrawing", pr_bool, &prefs_usecairo, NULL, NULL, '\0', NULL, 0, N_("Use the cairo library for drawing (if available)\nThis makes for prettier (anti-aliased) but slower drawing\nThis applies to any windows created AFTER this is set.\nAlready existing windows will continue as they are.") },
#endif
{ "CV_B1Tool", pr_int, (int *) &cv_b1_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "CV_CB1Tool", pr_int, (int *) &cv_cb1_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "CV_B2Tool", pr_int, (int *) &cv_b2_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "CV_CB2Tool", pr_int, (int *) &cv_cb2_tool, NULL, NULL, '\0', NULL, 1, NULL },
{ "XUID-Base", pr_string, &xuid, NULL, NULL, 'X', NULL, 0, N_("If specified this should be a space separated list of integers each\nless than 16777216 which uniquely identify your organization\nFontForge will generate a random number for the final component.") }, /* Obsolete */
{ "ShowKerningPane", pr_int, (int *) &show_kerning_pane_in_class, NULL, NULL, '\0', NULL, 1, NULL },
PREFS_LIST_EMPTY
},
oldnames[] = {
{ "DumpGlyphMap", pr_bool, &glyph_2_name_map, NULL, NULL, '\0', NULL, 0, N_("When generating a truetype or opentype font it is occasionally\nuseful to know the mapping between truetype glyph ids and\nglyph names. Setting this option will cause FontForge to\nproduce a file (with extension .g2n) containing those data.") },
{ "DefaultTTFApple", pr_int, &pointless, NULL, NULL, '\0', NULL, 1, NULL },
{ "AcuteCenterBottom", pr_bool, &GraveAcuteCenterBottom, NULL, NULL, '\0', NULL, 1, N_("When placing grave and acute accents above letters, should\nFontForge center them based on their full width, or\nshould it just center based on the lowest point\nof the accent.") },
{ "AlwaysGenApple", pr_bool, &alwaysgenapple, NULL, NULL, 'A', NULL, 0, N_("Apple and MS/Adobe differ about the format of truetype and opentype files.\nThis controls the default setting of the Apple checkbox in the\nFile->Generate Font dialog.\nThe main differences are:\n Bitmap data are stored in different tables\n Scaled composite glyphs are treated differently\n Use of GSUB rather than morx(t)/feat\n Use of GPOS rather than kern/opbd\n Use of GDEF rather than lcar/prop\nIf both this and OpenType are set, both formats are generated") },
{ "AlwaysGenOpenType", pr_bool, &alwaysgenopentype, NULL, NULL, 'O', NULL, 0, N_("Apple and MS/Adobe differ about the format of truetype and opentype files.\nThis controls the default setting of the OpenType checkbox in the\nFile->Generate Font dialog.\nThe main differences are:\n Bitmap data are stored in different tables\n Scaled composite glyphs are treated differently\n Use of GSUB rather than morx(t)/feat\n Use of GPOS rather than kern/opbd\n Use of GDEF rather than lcar/prop\nIf both this and Apple are set, both formats are generated") },
{ "DefaultTTFflags", pr_int, &old_ttf_flags, NULL, NULL, '\0', NULL, 1, NULL },
{ "DefaultOTFflags", pr_int, &old_otf_flags, NULL, NULL, '\0', NULL, 1, NULL },
PREFS_LIST_EMPTY
},
*prefs_list[] = { general_list, new_list, open_list, navigation_list, sync_list, editing_list, editing_interface_list, accent_list, args_list, fontinfo_list, generate_list, tt_list, opentype_list, hints_list, instrs_list,
hidden_list, NULL },
*load_prefs_list[] = { general_list, new_list, open_list, navigation_list, sync_list, editing_list, editing_interface_list, accent_list, args_list, fontinfo_list, generate_list, tt_list, opentype_list, hints_list, instrs_list,
hidden_list, oldnames, NULL };
struct visible_prefs_list { char *tab_name; int nest; struct prefs_list *pl; } visible_prefs_list[] = {
{ N_("Generic"), 0, general_list},
{ N_("New Font"), 0, new_list},
{ N_("Open Font"), 0, open_list},
{ N_("Navigation"), 0, navigation_list},
{ N_("Editing"), 0, editing_list},
{ N_("Interface"), 1, editing_interface_list},
{ N_("Synchronize"), 1, sync_list},
{ N_("TT"), 1, tt_list},
{ N_("Accents"), 1, accent_list},
{ N_("Apps"), 1, args_list},
{ N_("Font Info"), 0, fontinfo_list},
{ N_("Generate"), 0, generate_list},
{ N_("PS Hints"), 1, hints_list},
{ N_("TT Instrs"), 1, instrs_list},
{ N_("OpenType"), 1, opentype_list},
{ NULL, 0, NULL }
};
static void FileChooserPrefsChanged(void *pointless) {
SavePrefs(true);
}
static void ProcessFileChooserPrefs(void) {
unichar_t **b;
int i;
GFileChooserSetShowHidden(gfc_showhidden);
GFileChooserSetDirectoryPlacement(gfc_dirplace);
if ( gfc_bookmarks==NULL ) {
b = malloc(8*sizeof(unichar_t *));
i = 0;
#ifdef __Mac
b[i++] = uc_copy("~/Library/Fonts/");
#endif
b[i++] = uc_copy("~/fonts");
#ifdef __Mac
b[i++] = uc_copy("/Library/Fonts/");
b[i++] = uc_copy("/System/Library/Fonts/");
#endif
#if __CygWin
b[i++] = uc_copy("/cygdrive/c/Windows/Fonts/");
#endif
b[i++] = uc_copy("/usr/X11R6/lib/X11/fonts/");
b[i++] = NULL;
GFileChooserSetBookmarks(b);
} else {
char *pt, *start;
start = gfc_bookmarks;
for ( i=0; ; ++i ) {
pt = strchr(start,';');
if ( pt==NULL )
break;
start = pt+1;
}
start = gfc_bookmarks;
b = malloc((i+2)*sizeof(unichar_t *));
for ( i=0; ; ++i ) {
pt = strchr(start,';');
if ( pt!=NULL )
*pt = '\0';
b[i] = utf82u_copy(start);
if ( pt==NULL )
break;
*pt = ';';
start = pt+1;
}
b[i+1] = NULL;
GFileChooserSetBookmarks(b);
}
GFileChooserSetPrefsChangedCallback(NULL,FileChooserPrefsChanged);
}
static void GetFileChooserPrefs(void) {
unichar_t **foo;
gfc_showhidden = GFileChooserGetShowHidden();
gfc_dirplace = GFileChooserGetDirectoryPlacement();
foo = GFileChooserGetBookmarks();
free(gfc_bookmarks);
if ( foo==NULL || foo[0]==NULL )
gfc_bookmarks = NULL;
else {
int i,len=0;
for ( i=0; foo[i]!=NULL; ++i )
len += 4*u_strlen(foo[i])+1;
gfc_bookmarks = malloc(len+10);
len = 0;
for ( i=0; foo[i]!=NULL; ++i ) {
u2utf8_strcpy(gfc_bookmarks+len,foo[i]);
len += strlen(gfc_bookmarks+len);
gfc_bookmarks[len++] = ';';
}
if ( len>0 )
gfc_bookmarks[len-1] = '\0';
else {
free(gfc_bookmarks);
gfc_bookmarks = NULL;
}
}
}
#define TOPICS (sizeof(visible_prefs_list)/sizeof(visible_prefs_list[0])-1)
static int PrefsUI_GetPrefs(char *name,Val *val) {
int i,j;
/* Support for obsolete preferences */
alwaysgenapple=(old_sfnt_flags&ttf_flag_applemode)?1:0;
alwaysgenopentype=(old_sfnt_flags&ttf_flag_otmode)?1:0;
for ( i=0; prefs_list[i]!=NULL; ++i ) for ( j=0; prefs_list[i][j].name!=NULL; ++j ) {
if ( strcmp(prefs_list[i][j].name,name)==0 ) {
struct prefs_list *pf = &prefs_list[i][j];
if ( pf->type == pr_bool || pf->type == pr_int || pf->type == pr_unicode ) {
val->type = v_int;
val->u.ival = *((int *) (pf->val));
} else if ( pf->type == pr_string || pf->type == pr_file ) {
val->type = v_str;
char *tmpstr = pf->val ? *((char **) (pf->val)) : (char *) (pf->get)();
val->u.sval = copy( tmpstr ? tmpstr : "" );
if( ! pf->val )
free( tmpstr );
} else if ( pf->type == pr_encoding ) {
val->type = v_str;
if ( *((NameList **) (pf->val))==NULL )
val->u.sval = copy( "NULL" );
else
val->u.sval = copy( (*((Encoding **) (pf->val)))->enc_name );
} else if ( pf->type == pr_namelist ) {
val->type = v_str;
val->u.sval = copy( (*((NameList **) (pf->val)))->title );
} else if ( pf->type == pr_real || pf->type == pr_angle ) {
val->type = v_real;
val->u.fval = *((float *) (pf->val));
if ( pf->type == pr_angle )
val->u.fval *= RAD2DEG;
} else
return( false );
return( true );
}
}
return( false );
}
static void CheckObsoletePrefs(void) {
if ( alwaysgenapple==false ) {
old_sfnt_flags &= ~ttf_flag_applemode;
} else if ( alwaysgenapple==true ) {
old_sfnt_flags |= ttf_flag_applemode;
}
if ( alwaysgenopentype==false ) {
old_sfnt_flags &= ~ttf_flag_otmode;
} else if ( alwaysgenopentype==true ) {
old_sfnt_flags |= ttf_flag_otmode;
}
if ( old_ttf_flags!=0 )
old_sfnt_flags = old_ttf_flags | old_otf_flags;
}
static int PrefsUI_SetPrefs(char *name,Val *val1, Val *val2) {
int i,j;
/* Support for obsolete preferences */
alwaysgenapple=-1; alwaysgenopentype=-1;
for ( i=0; prefs_list[i]!=NULL; ++i ) for ( j=0; prefs_list[i][j].name!=NULL; ++j ) {
if ( strcmp(prefs_list[i][j].name,name)==0 ) {
struct prefs_list *pf = &prefs_list[i][j];
if ( pf->type == pr_bool || pf->type == pr_int || pf->type == pr_unicode ) {
if ( (val1->type!=v_int && val1->type!=v_unicode) || val2!=NULL )
return( -1 );
*((int *) (pf->val)) = val1->u.ival;
} else if ( pf->type == pr_real || pf->type == pr_angle ) {
if ( val1->type==v_real && val2==NULL )
*((float *) (pf->val)) = val1->u.fval;
else if ( val1->type!=v_int || (val2!=NULL && val2->type!=v_int ))
return( -1 );
else
*((float *) (pf->val)) = (val2==NULL ? val1->u.ival : val1->u.ival / (double) val2->u.ival);
if ( pf->type == pr_angle )
*((float *) (pf->val)) /= RAD2DEG;
} else if ( pf->type == pr_string || pf->type == pr_file ) {
if ( val1->type!=v_str || val2!=NULL )
return( -1 );
if ( pf->set ) {
pf->set( val1->u.sval );
} else {
free( *((char **) (pf->val)));
*((char **) (pf->val)) = copy( val1->u.sval );
}
} else if ( pf->type == pr_encoding ) {
if ( val2!=NULL )
return( -1 );
else if ( val1->type==v_str && pf->val == &default_encoding) {
Encoding *enc = FindOrMakeEncoding(val1->u.sval);
if ( enc==NULL )
return( -1 );
*((Encoding **) (pf->val)) = enc;
} else
return( -1 );
} else if ( pf->type == pr_namelist ) {
if ( val2!=NULL )
return( -1 );
else if ( val1->type==v_str ) {
NameList *nl = NameListByName(val1->u.sval);
if ( strcmp(val1->u.sval,"NULL")==0 && pf->val != &namelist_for_new_fonts )
nl = NULL;
else if ( nl==NULL )
return( -1 );
*((NameList **) (pf->val)) = nl;
} else
return( -1 );
} else
return( false );
CheckObsoletePrefs();
SavePrefs(true);
return( true );
}
}
return( false );
}
static char *getPfaEditPrefs(void) {
static char *prefs=NULL;
char buffer[1025];
char *ffdir;
if ( prefs!=NULL )
return prefs;
ffdir = getFontForgeUserDir(Config);
if ( ffdir==NULL )
return NULL;
sprintf(buffer,"%s/prefs", ffdir);
free(ffdir);
prefs = copy(buffer);
return prefs;
}
static char *PrefsUI_getFontForgeShareDir(void) {
return getShareDir();
}
static int encmatch(const char *enc,int subok) {
static struct { char *name; int enc; } encs[] = {
{ "US-ASCII", e_usascii },
{ "ASCII", e_usascii },
{ "ISO646-NO", e_iso646_no },
{ "ISO646-SE", e_iso646_se },
{ "LATIN10", e_iso8859_16 },
{ "LATIN1", e_iso8859_1 },
{ "ISO-8859-1", e_iso8859_1 },
{ "ISO-8859-2", e_iso8859_2 },
{ "ISO-8859-3", e_iso8859_3 },
{ "ISO-8859-4", e_iso8859_4 },
{ "ISO-8859-5", e_iso8859_4 },
{ "ISO-8859-6", e_iso8859_4 },
{ "ISO-8859-7", e_iso8859_4 },
{ "ISO-8859-8", e_iso8859_4 },
{ "ISO-8859-9", e_iso8859_4 },
{ "ISO-8859-10", e_iso8859_10 },
{ "ISO-8859-11", e_iso8859_11 },
{ "ISO-8859-13", e_iso8859_13 },
{ "ISO-8859-14", e_iso8859_14 },
{ "ISO-8859-15", e_iso8859_15 },
{ "ISO-8859-16", e_iso8859_16 },
{ "ISO_8859-1", e_iso8859_1 },
{ "ISO_8859-2", e_iso8859_2 },
{ "ISO_8859-3", e_iso8859_3 },
{ "ISO_8859-4", e_iso8859_4 },
{ "ISO_8859-5", e_iso8859_4 },
{ "ISO_8859-6", e_iso8859_4 },
{ "ISO_8859-7", e_iso8859_4 },
{ "ISO_8859-8", e_iso8859_4 },
{ "ISO_8859-9", e_iso8859_4 },
{ "ISO_8859-10", e_iso8859_10 },
{ "ISO_8859-11", e_iso8859_11 },
{ "ISO_8859-13", e_iso8859_13 },
{ "ISO_8859-14", e_iso8859_14 },
{ "ISO_8859-15", e_iso8859_15 },
{ "ISO_8859-16", e_iso8859_16 },
{ "ISO8859-1", e_iso8859_1 },
{ "ISO8859-2", e_iso8859_2 },
{ "ISO8859-3", e_iso8859_3 },
{ "ISO8859-4", e_iso8859_4 },
{ "ISO8859-5", e_iso8859_4 },
{ "ISO8859-6", e_iso8859_4 },
{ "ISO8859-7", e_iso8859_4 },
{ "ISO8859-8", e_iso8859_4 },
{ "ISO8859-9", e_iso8859_4 },
{ "ISO8859-10", e_iso8859_10 },
{ "ISO8859-11", e_iso8859_11 },
{ "ISO8859-13", e_iso8859_13 },
{ "ISO8859-14", e_iso8859_14 },
{ "ISO8859-15", e_iso8859_15 },
{ "ISO8859-16", e_iso8859_16 },
{ "ISO88591", e_iso8859_1 },
{ "ISO88592", e_iso8859_2 },
{ "ISO88593", e_iso8859_3 },
{ "ISO88594", e_iso8859_4 },
{ "ISO88595", e_iso8859_4 },
{ "ISO88596", e_iso8859_4 },
{ "ISO88597", e_iso8859_4 },
{ "ISO88598", e_iso8859_4 },
{ "ISO88599", e_iso8859_4 },
{ "ISO885910", e_iso8859_10 },
{ "ISO885911", e_iso8859_11 },
{ "ISO885913", e_iso8859_13 },
{ "ISO885914", e_iso8859_14 },
{ "ISO885915", e_iso8859_15 },
{ "ISO885916", e_iso8859_16 },
{ "8859_1", e_iso8859_1 },
{ "8859_2", e_iso8859_2 },
{ "8859_3", e_iso8859_3 },
{ "8859_4", e_iso8859_4 },
{ "8859_5", e_iso8859_4 },
{ "8859_6", e_iso8859_4 },
{ "8859_7", e_iso8859_4 },
{ "8859_8", e_iso8859_4 },
{ "8859_9", e_iso8859_4 },
{ "8859_10", e_iso8859_10 },
{ "8859_11", e_iso8859_11 },
{ "8859_13", e_iso8859_13 },
{ "8859_14", e_iso8859_14 },
{ "8859_15", e_iso8859_15 },
{ "8859_16", e_iso8859_16 },
{ "KOI8-R", e_koi8_r },
{ "KOI8R", e_koi8_r },
{ "WINDOWS-1252", e_win },
{ "CP1252", e_win },
{ "Big5", e_big5 },
{ "Big-5", e_big5 },
{ "BigFive", e_big5 },
{ "Big-Five", e_big5 },
{ "Big5HKSCS", e_big5hkscs },
{ "Big5-HKSCS", e_big5hkscs },
{ "UTF-8", e_utf8 },
{ "ISO-10646/UTF-8", e_utf8 },
{ "ISO_10646/UTF-8", e_utf8 },
{ "UCS2", e_unicode },
{ "UCS-2", e_unicode },
{ "UCS-2-INTERNAL", e_unicode },
{ "ISO-10646", e_unicode },
{ "ISO_10646", e_unicode },
/* { "eucJP", e_euc }, */
/* { "EUC-JP", e_euc }, */
/* { "ujis", ??? }, */
/* { "EUC-KR", e_euckorean }, */
{ NULL, 0 }
};
int i;
char buffer[80];
#if HAVE_ICONV_H
static char *last_complaint;
iconv_t test;
free(iconv_local_encoding_name);
iconv_local_encoding_name= NULL;
#endif
if ( strchr(enc,'@')!=NULL && strlen(enc)<sizeof(buffer)-1 ) {
strcpy(buffer,enc);
*strchr(buffer,'@') = '\0';
enc = buffer;
}
for ( i=0; encs[i].name!=NULL; ++i )
if ( strmatch(enc,encs[i].name)==0 )
return( encs[i].enc );
if ( subok ) {
for ( i=0; encs[i].name!=NULL; ++i )
if ( strstrmatch(enc,encs[i].name)!=NULL )
return( encs[i].enc );
#if HAVE_ICONV_H
/* I only try to use iconv if the encoding doesn't match one I support*/
/* loading iconv unicode data takes a while */
test = iconv_open(enc,FindUnicharName());
if ( test==(iconv_t) (-1) || test==NULL ) {
if ( last_complaint==NULL || strcmp(last_complaint,enc)!=0 ) {
fprintf( stderr, "Neither FontForge nor iconv() supports your encoding (%s) we will pretend\n you asked for latin1 instead.\n", enc );
free( last_complaint );
last_complaint = copy(enc);
}
} else {
if ( last_complaint==NULL || strcmp(last_complaint,enc)!=0 ) {
fprintf( stderr, "FontForge does not support your encoding (%s), it will try to use iconv()\n or it will pretend the local encoding is latin1\n", enc );
free( last_complaint );
last_complaint = copy(enc);
}
iconv_local_encoding_name= copy(enc);
iconv_close(test);
}
#else
fprintf( stderr, "FontForge does not support your encoding (%s), it will pretend the local encoding is latin1\n", enc );
#endif
return( e_iso8859_1 );
}
return( e_unknown );
}
static int DefaultEncoding(void) {
const char *loc;
int enc;
#if HAVE_LANGINFO_H
loc = nl_langinfo(CODESET);
enc = encmatch(loc,false);
if ( enc!=e_unknown )
return( enc );
#endif
loc = getenv("LC_ALL");
if ( loc==NULL ) loc = getenv("LC_CTYPE");
/*if ( loc==NULL ) loc = getenv("LC_MESSAGES");*/
if ( loc==NULL ) loc = getenv("LANG");
if ( loc==NULL )
return( e_iso8859_1 );
enc = encmatch(loc,false);
if ( enc==e_unknown ) {
loc = strrchr(loc,'.');
if ( loc==NULL )
return( e_iso8859_1 );
enc = encmatch(loc+1,true);
}
if ( enc==e_unknown )
return( e_iso8859_1 );
return( enc );
}
static void DefaultXUID(void) {
/* Adobe has assigned PfaEdit a base XUID of 1021. Each new user is going */
/* to get a couple of random numbers appended to that, hoping that will */
/* make for a fairly safe system. */
/* FontForge will use the same scheme */
int r1, r2;
char buffer[50];
struct timeval tv;
gettimeofday(&tv,NULL);
srand(tv.tv_usec);
do {
r1 = rand()&0x3ff;
} while ( r1==0 ); /* I reserve "0" for me! */
gettimeofday(&tv,NULL);
g_random_set_seed(tv.tv_usec+1);
r2 = g_random_int();
sprintf( buffer, "1021 %d %d", r1, r2 );
if (xuid != NULL) free(xuid);
xuid = copy(buffer);
}
static void PrefsUI_SetDefaults(void) {
DefaultXUID();
local_encoding = DefaultEncoding();
}
static void ParseMacMapping(char *pt,struct macsettingname *ms) {
char *end;
ms->mac_feature_type = strtol(pt,&end,10);
if ( *end==',' ) ++end;
ms->mac_feature_setting = strtol(end,&end,10);
if ( *end==' ' ) ++end;
ms->otf_tag =
((end[0]&0xff)<<24) |
((end[1]&0xff)<<16) |
((end[2]&0xff)<<8) |
(end[3]&0xff);
}
static void ParseNewMacFeature(FILE *p,char *line) {
fseek(p,-(strlen(line)-strlen("MacFeat:")),SEEK_CUR);
line[strlen("MacFeat:")] ='\0';
default_mac_feature_map = SFDParseMacFeatures(p,line);
fseek(p,-strlen(line),SEEK_CUR);
if ( user_mac_feature_map!=NULL )
MacFeatListFree(user_mac_feature_map);
user_mac_feature_map = default_mac_feature_map;
}
static void PrefsUI_LoadPrefs_FromFile( char* filename )
{
FILE *p;
char line[1100];
int i, j, ri=0, mn=0, ms=0, fn=0, ff=0, filt_max=0;
int msp=0, msc=0;
char *pt;
struct prefs_list *pl;
if ( filename!=NULL && (p=fopen(filename,"r"))!=NULL ) {
while ( fgets(line,sizeof(line),p)!=NULL ) {
if ( *line=='#' )
continue;
pt = strchr(line,':');
if ( pt==NULL )
continue;
for ( j=0; load_prefs_list[j]!=NULL; ++j ) {
for ( i=0; load_prefs_list[j][i].name!=NULL; ++i )
if ( strncmp(line,load_prefs_list[j][i].name,pt-line)==0 )
break;
if ( load_prefs_list[j][i].name!=NULL )
break;
}
pl = NULL;
if ( load_prefs_list[j]!=NULL )
pl = &load_prefs_list[j][i];
for ( ++pt; *pt=='\t'; ++pt );
if ( line[strlen(line)-1]=='\n' )
line[strlen(line)-1] = '\0';
if ( line[strlen(line)-1]=='\r' )
line[strlen(line)-1] = '\0';
if ( pl==NULL ) {
if ( strncmp(line,"Recent:",strlen("Recent:"))==0 && ri<RECENT_MAX )
RecentFiles[ri++] = copy(pt);
else if ( strncmp(line,"MenuScript:",strlen("MenuScript:"))==0 && ms<SCRIPT_MENU_MAX )
script_filenames[ms++] = copy(pt);
else if ( strncmp(line,"MenuName:",strlen("MenuName:"))==0 && mn<SCRIPT_MENU_MAX )
script_menu_names[mn++] = utf82u_copy(pt);
else if ( strncmp(line,"FontFilterName:",strlen("FontFilterName:"))==0 ) {
if ( fn>=filt_max )
user_font_filters = realloc(user_font_filters,((filt_max+=10)+1)*sizeof( struct openfilefilters));
user_font_filters[fn].filter = NULL;
user_font_filters[fn++].name = copy(pt);
user_font_filters[fn].name = NULL;
} else if ( strncmp(line,"FontFilter:",strlen("FontFilter:"))==0 ) {
if ( ff<filt_max )
user_font_filters[ff++].filter = copy(pt);
} else if ( strncmp(line,"MacMapCnt:",strlen("MacSetCnt:"))==0 ) {
sscanf( pt, "%d", &msc );
msp = 0;
user_macfeat_otftag = calloc(msc+1,sizeof(struct macsettingname));
} else if ( strncmp(line,"MacMapping:",strlen("MacMapping:"))==0 && msp<msc ) {
ParseMacMapping(pt,&user_macfeat_otftag[msp++]);
} else if ( strncmp(line,"MacFeat:",strlen("MacFeat:"))==0 ) {
ParseNewMacFeature(p,line);
}
continue;
}
switch ( pl->type ) {
case pr_encoding:
{ Encoding *enc = FindOrMakeEncoding(pt);
if ( enc==NULL )
enc = FindOrMakeEncoding("ISO8859-1");
if ( enc==NULL )
enc = &custom;
*((Encoding **) (pl->val)) = enc;
}
break;
case pr_namelist:
{ NameList *nl = NameListByName(pt);
if ( strcmp(pt,"NULL")==0 && pl->val != &namelist_for_new_fonts )
*((NameList **) (pl->val)) = NULL;
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
break;
case pr_bool: case pr_int:
sscanf( pt, "%d", (int *) pl->val );
break;
case pr_unicode:
if ( sscanf( pt, "U+%x", (int *) pl->val )!=1 )
if ( sscanf( pt, "u+%x", (int *) pl->val )!=1 )
sscanf( pt, "%x", (int *) pl->val );
break;
case pr_real: case pr_angle:
{ char *end;
*((float *) pl->val) = strtod(pt,&end);
if (( *end==',' || *end=='.' ) ) {
*end = (*end=='.')?',':'.';
*((float *) pl->val) = strtod(pt,NULL);
}
}
if ( pl->type == pr_angle )
*(float *) pl->val /= RAD2DEG;
break;
case pr_string: case pr_file:
if ( *pt=='\0' ) pt=NULL;
if ( pl->val!=NULL )
*((char **) (pl->val)) = copy(pt);
else
(pl->set)(copy(pt));
break;
}
}
fclose(p);
}
}
void Prefs_LoadDefaultPreferences( void )
{
char filename[PATH_MAX+1];
char* sharedir = getShareDir();
snprintf(filename,PATH_MAX,"%s/prefs", sharedir );
PrefsUI_LoadPrefs_FromFile( filename );
}
static void PrefsUI_LoadPrefs(void)
{
char *prefs = getPfaEditPrefs();
FILE *p;
char line[1100], path[PATH_MAX];
int i, j, ri=0, mn=0, ms=0, fn=0, ff=0, filt_max=0;
int msp=0, msc=0;
char *pt, *real_xdefs_filename = NULL;
struct prefs_list *pl;
LoadPfaEditEncodings();
LoadGroupList();
if ( prefs!=NULL && (p=fopen(prefs,"r"))!=NULL ) {
while ( fgets(line,sizeof(line),p)!=NULL ) {
if ( *line=='#' )
continue;
pt = strchr(line,':');
if ( pt==NULL )
continue;
for ( j=0; load_prefs_list[j]!=NULL; ++j ) {
for ( i=0; load_prefs_list[j][i].name!=NULL; ++i )
if ( strncmp(line,load_prefs_list[j][i].name,pt-line)==0 )
break;
if ( load_prefs_list[j][i].name!=NULL )
break;
}
pl = NULL;
if ( load_prefs_list[j]!=NULL )
pl = &load_prefs_list[j][i];
for ( ++pt; *pt=='\t'; ++pt );
if ( line[strlen(line)-1]=='\n' )
line[strlen(line)-1] = '\0';
if ( line[strlen(line)-1]=='\r' )
line[strlen(line)-1] = '\0';
if ( pl==NULL ) {
if ( strncmp(line,"Recent:",strlen("Recent:"))==0 && ri<RECENT_MAX )
RecentFiles[ri++] = copy(pt);
else if ( strncmp(line,"MenuScript:",strlen("MenuScript:"))==0 && ms<SCRIPT_MENU_MAX )
script_filenames[ms++] = copy(pt);
else if ( strncmp(line,"MenuName:",strlen("MenuName:"))==0 && mn<SCRIPT_MENU_MAX )
script_menu_names[mn++] = utf82u_copy(pt);
else if ( strncmp(line,"FontFilterName:",strlen("FontFilterName:"))==0 ) {
if ( fn>=filt_max )
user_font_filters = realloc(user_font_filters,((filt_max+=10)+1)*sizeof( struct openfilefilters));
user_font_filters[fn].filter = NULL;
user_font_filters[fn++].name = copy(pt);
user_font_filters[fn].name = NULL;
} else if ( strncmp(line,"FontFilter:",strlen("FontFilter:"))==0 ) {
if ( ff<filt_max )
user_font_filters[ff++].filter = copy(pt);
} else if ( strncmp(line,"MacMapCnt:",strlen("MacSetCnt:"))==0 ) {
sscanf( pt, "%d", &msc );
msp = 0;
user_macfeat_otftag = calloc(msc+1,sizeof(struct macsettingname));
} else if ( strncmp(line,"MacMapping:",strlen("MacMapping:"))==0 && msp<msc ) {
ParseMacMapping(pt,&user_macfeat_otftag[msp++]);
} else if ( strncmp(line,"MacFeat:",strlen("MacFeat:"))==0 ) {
ParseNewMacFeature(p,line);
}
continue;
}
switch ( pl->type ) {
case pr_encoding:
{ Encoding *enc = FindOrMakeEncoding(pt);
if ( enc==NULL )
enc = FindOrMakeEncoding("ISO8859-1");
if ( enc==NULL )
enc = &custom;
*((Encoding **) (pl->val)) = enc;
}
break;
case pr_namelist:
{ NameList *nl = NameListByName(pt);
if ( strcmp(pt,"NULL")==0 && pl->val != &namelist_for_new_fonts )
*((NameList **) (pl->val)) = NULL;
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
break;
case pr_bool: case pr_int:
sscanf( pt, "%d", (int *) pl->val );
break;
case pr_unicode:
if ( sscanf( pt, "U+%x", (int *) pl->val )!=1 )
if ( sscanf( pt, "u+%x", (int *) pl->val )!=1 )
sscanf( pt, "%x", (int *) pl->val );
break;
case pr_real: case pr_angle:
{ char *end;
*((float *) pl->val) = strtod(pt,&end);
if (( *end==',' || *end=='.' ) ) {
*end = (*end=='.')?',':'.';
*((float *) pl->val) = strtod(pt,NULL);
}
}
if ( pl->type == pr_angle )
*(float *) pl->val /= RAD2DEG;
break;
case pr_string: case pr_file:
if ( *pt=='\0' ) pt=NULL;
if ( pl->val!=NULL )
*((char **) (pl->val)) = copy(pt);
else
(pl->set)(copy(pt));
break;
}
}
fclose(p);
}
//
// If the user has no theme set, then use the default
//
real_xdefs_filename = xdefs_filename;
if ( !real_xdefs_filename )
{
// fprintf(stderr,"no xdefs_filename!\n");
// if (!quiet) {
// fprintf(stderr,"TESTING: getPixmapDir:%s\n", getPixmapDir() );
// fprintf(stderr,"TESTING: getShareDir:%s\n", getShareDir() );
// fprintf(stderr,"TESTING: GResourceProgramDir:%s\n", GResourceProgramDir );
// }
snprintf(path, PATH_MAX, "%s/%s", getPixmapDir(), "resources" );
// if (!quiet)
// fprintf(stderr,"trying default theme:%s\n", path );
real_xdefs_filename = path;
}
GResourceAddResourceFile(real_xdefs_filename,GResourceProgramName,true);
if ( othersubrsfile!=NULL && ReadOtherSubrsFile(othersubrsfile)<=0 )
fprintf( stderr, "Failed to read OtherSubrs from %s\n", othersubrsfile );
if ( glyph_2_name_map )
old_sfnt_flags |= ttf_flag_glyphmap;
LoadNamelistDir(NULL);
ProcessFileChooserPrefs();
GDrawEnableCairo( prefs_usecairo );
}
static void PrefsUI_SavePrefs(int not_if_script) {
char *prefs = getPfaEditPrefs();
FILE *p;
int i, j;
char *temp;
struct prefs_list *pl;
extern int running_script;
if ( prefs==NULL )
return;
if ( not_if_script && running_script )
return;
if ( (p=fopen(prefs,"w"))==NULL )
return;
GetFileChooserPrefs();
for ( j=0; prefs_list[j]!=NULL; ++j ) for ( i=0; prefs_list[j][i].name!=NULL; ++i ) {
pl = &prefs_list[j][i];
switch ( pl->type ) {
case pr_encoding:
fprintf( p, "%s:\t%s\n", pl->name, (*((Encoding **) (pl->val)))->enc_name );
break;
case pr_namelist:
fprintf( p, "%s:\t%s\n", pl->name, *((NameList **) (pl->val))==NULL ? "NULL" :
(*((NameList **) (pl->val)))->title );
break;
case pr_bool: case pr_int:
fprintf( p, "%s:\t%d\n", pl->name, *(int *) (pl->val) );
break;
case pr_unicode:
fprintf( p, "%s:\tU+%04x\n", pl->name, *(int *) (pl->val) );
break;
case pr_real:
fprintf( p, "%s:\t%g\n", pl->name, (double) *(float *) (pl->val) );
break;
case pr_string: case pr_file:
if ( (pl->val)!=NULL )
temp = *(char **) (pl->val);
else
temp = (char *) (pl->get());
if ( temp!=NULL )
fprintf( p, "%s:\t%s\n", pl->name, temp );
if ( (pl->val)==NULL )
free(temp);
break;
case pr_angle:
fprintf( p, "%s:\t%g\n", pl->name, ((double) *(float *) pl->val) * RAD2DEG );
break;
}
}
for ( i=0; i<RECENT_MAX && RecentFiles[i]!=NULL; ++i )
fprintf( p, "Recent:\t%s\n", RecentFiles[i]);
for ( i=0; i<SCRIPT_MENU_MAX && script_filenames[i]!=NULL; ++i ) {
fprintf( p, "MenuScript:\t%s\n", script_filenames[i]);
fprintf( p, "MenuName:\t%s\n", temp = u2utf8_copy(script_menu_names[i]));
free(temp);
}
if ( user_font_filters!=NULL ) {
for ( i=0; user_font_filters[i].name!=NULL; ++i ) {
fprintf( p, "FontFilterName:\t%s\n", user_font_filters[i].name);
fprintf( p, "FontFilter:\t%s\n", user_font_filters[i].filter);
}
}
if ( user_macfeat_otftag!=NULL && UserSettingsDiffer()) {
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i );
fprintf( p, "MacMapCnt: %d\n", i );
for ( i=0; user_macfeat_otftag[i].otf_tag!=0; ++i ) {
fprintf( p, "MacMapping: %d,%d %c%c%c%c\n",
user_macfeat_otftag[i].mac_feature_type,
user_macfeat_otftag[i].mac_feature_setting,
(int) (user_macfeat_otftag[i].otf_tag>>24),
(int) ((user_macfeat_otftag[i].otf_tag>>16)&0xff),
(int) ((user_macfeat_otftag[i].otf_tag>>8)&0xff),
(int) (user_macfeat_otftag[i].otf_tag&0xff) );
}
}
if ( UserFeaturesDiffer())
SFDDumpMacFeat(p,default_mac_feature_map);
fclose(p);
}
struct pref_data {
int done;
struct prefs_list* plist;
};
static int Prefs_ScriptBrowse(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GGadget *tf = GWidgetGetControl(gw,GGadgetGetCid(g)-SCRIPT_MENU_MAX);
char *cur = GGadgetGetTitle8(tf); char *ret;
if ( *cur=='\0' ) cur=NULL;
ret = gwwv_open_filename(_("Call Script"), cur, "*.pe", NULL);
free(cur);
if ( ret==NULL )
return(true);
GGadgetSetTitle8(tf,ret);
free(ret);
}
return( true );
}
static int Prefs_BrowseFile(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GGadget *tf = GWidgetGetControl(gw,GGadgetGetCid(g)-CID_PrefsBrowseOffset);
char *cur = GGadgetGetTitle8(tf); char *ret;
struct prefs_list *pl = GGadgetGetUserData(tf);
ret = gwwv_open_filename(pl->name, *cur=='\0'? NULL : cur, NULL, NULL);
free(cur);
if ( ret==NULL )
return(true);
GGadgetSetTitle8(tf,ret);
free(ret);
}
return( true );
}
static GTextInfo *Pref_MappingList(int use_user) {
struct macsettingname *msn = use_user && user_macfeat_otftag!=NULL ?
user_macfeat_otftag :
macfeat_otftag;
GTextInfo *ti;
int i;
char buf[60];
for ( i=0; msn[i].otf_tag!=0; ++i );
ti = calloc(i+1,sizeof( GTextInfo ));
for ( i=0; msn[i].otf_tag!=0; ++i ) {
sprintf(buf,"%3d,%2d %c%c%c%c",
msn[i].mac_feature_type, msn[i].mac_feature_setting,
(int) (msn[i].otf_tag>>24), (int) ((msn[i].otf_tag>>16)&0xff), (int) ((msn[i].otf_tag>>8)&0xff), (int) (msn[i].otf_tag&0xff) );
ti[i].text = uc_copy(buf);
}
return( ti );
}
void GListAddStr(GGadget *list,unichar_t *str, void *ud) {
int32 i,len;
GTextInfo **ti = GGadgetGetList(list,&len);
GTextInfo **replace = malloc((len+2)*sizeof(GTextInfo *));
replace[len+1] = calloc(1,sizeof(GTextInfo));
for ( i=0; i<len; ++i ) {
replace[i] = malloc(sizeof(GTextInfo));
*replace[i] = *ti[i];
replace[i]->text = u_copy(ti[i]->text);
}
replace[i] = calloc(1,sizeof(GTextInfo));
replace[i]->fg = replace[i]->bg = COLOR_DEFAULT;
replace[i]->text = str;
replace[i]->userdata = ud;
GGadgetSetList(list,replace,false);
}
void GListReplaceStr(GGadget *list,int index, unichar_t *str, void *ud) {
int32 i,len;
GTextInfo **ti = GGadgetGetList(list,&len);
GTextInfo **replace = malloc((len+2)*sizeof(GTextInfo *));
for ( i=0; i<len; ++i ) {
replace[i] = malloc(sizeof(GTextInfo));
*replace[i] = *ti[i];
if ( i!=index )
replace[i]->text = u_copy(ti[i]->text);
}
replace[i] = calloc(1,sizeof(GTextInfo));
replace[index]->text = str;
replace[index]->userdata = ud;
GGadgetSetList(list,replace,false);
}
struct setdata {
GWindow gw;
GGadget *list;
GGadget *flist;
GGadget *feature;
GGadget *set_code;
GGadget *otf;
GGadget *ok;
GGadget *cancel;
int index;
int done;
unichar_t *ret;
};
static int set_e_h(GWindow gw, GEvent *event) {
struct setdata *sd = GDrawGetUserData(gw);
int i;
int32 len;
GTextInfo **ti;
const unichar_t *ret1; unichar_t *end;
int on, feat, val1, val2;
unichar_t ubuf[4];
char buf[40];
if ( event->type==et_close ) {
sd->done = true;
} else if ( event->type==et_char ) {
if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) {
help("prefs.html#Features");
return( true );
}
return( false );
} else if ( event->type==et_controlevent && event->u.control.subtype == et_buttonactivate ) {
if ( event->u.control.g == sd->cancel ) {
sd->done = true;
} else if ( event->u.control.g == sd->ok ) {
ret1 = _GGadgetGetTitle(sd->set_code);
on = u_strtol(ret1,&end,10);
if ( *end!='\0' ) {
ff_post_error(_("Bad Number"),_("Bad Number"));
return( true );
}
ret1 = _GGadgetGetTitle(sd->feature);
feat = u_strtol(ret1,&end,10);
if ( *end!='\0' && *end!=' ' ) {
ff_post_error(_("Bad Number"),_("Bad Number"));
return( true );
}
ti = GGadgetGetList(sd->list,&len);
for ( i=0; i<len; ++i ) if ( i!=sd->index ) {
val1 = u_strtol(ti[i]->text,&end,10);
val2 = u_strtol(end+1,NULL,10);
if ( val1==feat && val2==on ) {
static char *buts[3];
buts[0] = _("_Yes");
buts[1] = _("_No");
buts[2] = NULL;
if ( gwwv_ask(_("This feature, setting combination is already used"),(const char **) buts,0,1,
_("This feature, setting combination is already used\nDo you really wish to reuse it?"))==1 )
return( true );
}
}
ret1 = _GGadgetGetTitle(sd->otf);
if ( (ubuf[0] = ret1[0])==0 )
ubuf[0] = ubuf[1] = ubuf[2] = ubuf[3] = ' ';
else if ( (ubuf[1] = ret1[1])==0 )
ubuf[1] = ubuf[2] = ubuf[3] = ' ';
else if ( (ubuf[2] = ret1[2])==0 )
ubuf[2] = ubuf[3] = ' ';
else if ( (ubuf[3] = ret1[3])==0 )
ubuf[3] = ' ';
len = u_strlen(ret1);
if ( len<2 || len>4 || ubuf[0]>=0x7f || ubuf[1]>=0x7f || ubuf[2]>=0x7f || ubuf[3]>=0x7f ) {
ff_post_error(_("Tag too long"),_("Feature tags must be exactly 4 ASCII characters"));
return( true );
}
sprintf(buf,"%3d,%2d %c%c%c%c",
feat, on,
ubuf[0], ubuf[1], ubuf[2], ubuf[3]);
sd->done = true;
sd->ret = uc_copy(buf);
}
}
return( true );
}
static unichar_t *AskSetting(struct macsettingname *temp,GGadget *list, int index,GGadget *flist) {
GRect pos;
GWindow gw;
GWindowAttrs wattrs;
GGadgetCreateData gcd[17];
GTextInfo label[17];
struct setdata sd;
char buf[20];
unichar_t ubuf3[6];
int32 len, i;
GTextInfo **ti;
memset(&sd,0,sizeof(sd));
sd.list = list;
sd.flist = flist;
sd.index = index;
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg;
wattrs.event_masks = ~(1<<et_charup);
wattrs.restrict_input_to_me = 1;
wattrs.is_dlg = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Mapping");
pos.x = pos.y = 0;
pos.width = GGadgetScale(GDrawPointsToPixels(NULL,240));
pos.height = GDrawPointsToPixels(NULL,120);
gw = GDrawCreateTopWindow(NULL,&pos,set_e_h,&sd,&wattrs);
sd.gw = gw;
memset(gcd,0,sizeof(gcd));
memset(label,0,sizeof(label));
label[0].text = (unichar_t *) _("_Feature:");
label[0].text_is_1byte = true;
label[0].text_in_resource = true;
gcd[0].gd.label = &label[0];
gcd[0].gd.pos.x = 5; gcd[0].gd.pos.y = 5+4;
gcd[0].gd.flags = gg_enabled|gg_visible;
gcd[0].creator = GLabelCreate;
gcd[1].gd.pos.x = 50; gcd[1].gd.pos.y = 5; gcd[1].gd.pos.width = 170;
gcd[1].gd.flags = gg_enabled|gg_visible;
gcd[1].creator = GListButtonCreate;
label[2].text = (unichar_t *) _("Setting");
label[2].text_is_1byte = true;
gcd[2].gd.label = &label[2];
gcd[2].gd.pos.x = 5; gcd[2].gd.pos.y = gcd[0].gd.pos.y+26;
gcd[2].gd.flags = gg_enabled|gg_visible;
gcd[2].creator = GLabelCreate;
sprintf( buf, "%d", temp->mac_feature_setting );
label[3].text = (unichar_t *) buf;
label[3].text_is_1byte = true;
gcd[3].gd.label = &label[3];
gcd[3].gd.pos.x = gcd[1].gd.pos.x; gcd[3].gd.pos.y = gcd[2].gd.pos.y-4; gcd[3].gd.pos.width = 50;
gcd[3].gd.flags = gg_enabled|gg_visible;
gcd[3].creator = GTextFieldCreate;
label[4].text = (unichar_t *) _("_Tag:");
label[4].text_is_1byte = true;
label[4].text_in_resource = true;
gcd[4].gd.label = &label[4];
gcd[4].gd.pos.x = 5; gcd[4].gd.pos.y = gcd[3].gd.pos.y+26;
gcd[4].gd.flags = gg_enabled|gg_visible;
gcd[4].creator = GLabelCreate;
ubuf3[0] = temp->otf_tag>>24; ubuf3[1] = (temp->otf_tag>>16)&0xff; ubuf3[2] = (temp->otf_tag>>8)&0xff; ubuf3[3] = temp->otf_tag&0xff; ubuf3[4] = 0;
label[5].text = ubuf3;
gcd[5].gd.label = &label[5];
gcd[5].gd.pos.x = gcd[3].gd.pos.x; gcd[5].gd.pos.y = gcd[4].gd.pos.y-4; gcd[5].gd.pos.width = 50;
gcd[5].gd.flags = gg_enabled|gg_visible;
/*gcd[5].gd.u.list = tags;*/
gcd[5].creator = GTextFieldCreate;
gcd[6].gd.pos.x = 13-3; gcd[6].gd.pos.y = gcd[5].gd.pos.y+30;
gcd[6].gd.pos.width = -1; gcd[6].gd.pos.height = 0;
gcd[6].gd.flags = gg_visible | gg_enabled | gg_but_default;
label[6].text = (unichar_t *) _("_OK");
label[6].text_is_1byte = true;
label[6].text_in_resource = true;
gcd[6].gd.label = &label[6];
/*gcd[6].gd.handle_controlevent = Prefs_Ok;*/
gcd[6].creator = GButtonCreate;
gcd[7].gd.pos.x = -13; gcd[7].gd.pos.y = gcd[7-1].gd.pos.y+3;
gcd[7].gd.pos.width = -1; gcd[7].gd.pos.height = 0;
gcd[7].gd.flags = gg_visible | gg_enabled | gg_but_cancel;
label[7].text = (unichar_t *) _("_Cancel");
label[7].text_is_1byte = true;
label[7].text_in_resource = true;
gcd[7].gd.label = &label[7];
gcd[7].creator = GButtonCreate;
GGadgetsCreate(gw,gcd);
sd.feature = gcd[1].ret;
sd.set_code = gcd[3].ret;
sd.otf = gcd[5].ret;
sd.ok = gcd[6].ret;
sd.cancel = gcd[7].ret;
ti = GGadgetGetList(flist,&len);
GGadgetSetList(sd.feature,ti,true);
for ( i=0; i<len; ++i ) {
int val = u_strtol(ti[i]->text,NULL,10);
if ( val==temp->mac_feature_type ) {
GGadgetSetTitle(sd.feature,ti[i]->text);
break;
}
}
GDrawSetVisible(gw,true);
GWidgetIndicateFocusGadget(gcd[1].ret);
while ( !sd.done )
GDrawProcessOneEvent(NULL);
GDrawDestroyWindow(gw);
return( sd.ret );
}
static void ChangeSetting(GGadget *list,int index,GGadget *flist) {
struct macsettingname temp;
int32 len;
GTextInfo **ti = GGadgetGetList(list,&len);
char *str;
unichar_t *ustr;
str = cu_copy(ti[index]->text);
ParseMacMapping(str,&temp);
free(str);
if ( (ustr=AskSetting(&temp,list,index,flist))==NULL )
return;
GListReplaceStr(list,index,ustr,NULL);
}
static int Pref_NewMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GGadget *list = GWidgetGetControl(gw,CID_Mapping);
GGadget *flist = GWidgetGetControl(GDrawGetParentWindow(gw),CID_Features);
struct macsettingname temp;
unichar_t *str;
memset(&temp,0,sizeof(temp));
temp.mac_feature_type = -1;
if ( (str=AskSetting(&temp,list,-1,flist))==NULL )
return( true );
GListAddStr(list,str,NULL);
/*free(str);*/
}
return( true );
}
static int Pref_DelMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GGadgetGetWindow(g);
GListDelSelected(GWidgetGetControl(gw,CID_Mapping));
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingDel),false);
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingEdit),false);
}
return( true );
}
static int Pref_EditMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GWindow gw = GDrawGetParentWindow(GGadgetGetWindow(g));
GGadget *list = GWidgetGetControl(gw,CID_Mapping);
GGadget *flist = GWidgetGetControl(gw,CID_Features);
ChangeSetting(list,GGadgetGetFirstListSelectedItem(list),flist);
}
return( true );
}
static int Pref_MappingSel(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
int32 len;
GTextInfo **ti = GGadgetGetList(g,&len);
GWindow gw = GGadgetGetWindow(g);
int i, sel_cnt=0;
for ( i=0; i<len; ++i )
if ( ti[i]->selected ) ++sel_cnt;
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingDel),sel_cnt!=0);
GGadgetSetEnabled(GWidgetGetControl(gw,CID_MappingEdit),sel_cnt==1);
} else if ( e->type==et_controlevent && e->u.control.subtype == et_listdoubleclick ) {
GGadget *flist = GWidgetGetControl( GDrawGetParentWindow(GGadgetGetWindow(g)),CID_Features);
ChangeSetting(g,e->u.control.u.list.changed_index!=-1?e->u.control.u.list.changed_index:
GGadgetGetFirstListSelectedItem(g),flist);
}
return( true );
}
static int Pref_DefaultMapping(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
GGadget *list = GWidgetGetControl(GGadgetGetWindow(g),CID_Mapping);
GTextInfo *ti, **arr;
uint16 cnt;
ti = Pref_MappingList(false);
arr = GTextInfoArrayFromList(ti,&cnt);
GGadgetSetList(list,arr,false);
GTextInfoListFree(ti);
}
return( true );
}
static int Prefs_Ok(GGadget *g, GEvent *e) {
int i, j, mi;
int err=0, enc;
struct pref_data *p;
GWindow gw;
const unichar_t *ret;
const unichar_t *names[SCRIPT_MENU_MAX], *scripts[SCRIPT_MENU_MAX];
struct prefs_list *pl;
GTextInfo **list;
int32 len;
int maxl, t;
char *str;
real dangle;
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
gw = GGadgetGetWindow(g);
p = GDrawGetUserData(gw);
for ( i=0; i<SCRIPT_MENU_MAX; ++i ) {
names[i] = _GGadgetGetTitle(GWidgetGetControl(gw,CID_ScriptMNameBase+i));
scripts[i] = _GGadgetGetTitle(GWidgetGetControl(gw,CID_ScriptMFileBase+i));
if ( *names[i]=='\0' ) names[i] = NULL;
if ( *scripts[i]=='\0' ) scripts[i] = NULL;
if ( scripts[i]==NULL && names[i]!=NULL ) {
ff_post_error(_("Menu name with no associated script"),_("Menu name with no associated script"));
return( true );
} else if ( scripts[i]!=NULL && names[i]==NULL ) {
ff_post_error(_("Script with no associated menu name"),_("Script with no associated menu name"));
return( true );
}
}
for ( i=mi=0; i<SCRIPT_MENU_MAX; ++i ) {
if ( names[i]!=NULL ) {
names[mi] = names[i];
scripts[mi] = scripts[i];
++mi;
}
}
for ( j=0; visible_prefs_list[j].tab_name!=0; ++j ) for ( i=0; visible_prefs_list[j].pl[i].name!=NULL; ++i ) {
pl = &visible_prefs_list[j].pl[i];
/* before assigning values, check for any errors */
/* if any errors, then NO values should be assigned, in case they cancel */
if ( pl->dontdisplay )
continue;
if ( pl->type==pr_int ) {
GetInt8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
} else if ( pl->type==pr_real ) {
GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
} else if ( pl->type==pr_angle ) {
dangle = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
if ( dangle > 90 || dangle < 0 ) {
GGadgetProtest8(pl->name);
err = true;
}
} else if ( pl->type==pr_unicode ) {
GetUnicodeChar8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
}
}
if ( err )
return( true );
for ( j=0; visible_prefs_list[j].tab_name!=0; ++j ) for ( i=0; visible_prefs_list[j].pl[i].name!=NULL; ++i ) {
pl = &visible_prefs_list[j].pl[i];
if ( pl->dontdisplay )
continue;
switch( pl->type ) {
case pr_int:
*((int *) (pl->val)) = GetInt8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_unicode:
*((int *) (pl->val)) = GetUnicodeChar8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_bool:
*((int *) (pl->val)) = GGadgetIsChecked(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
break;
case pr_real:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_encoding:
{ Encoding *e;
e = ParseEncodingNameFromList(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( e!=NULL )
*((Encoding **) (pl->val)) = e;
enc = 1; /* So gcc doesn't complain about unused. It is unused, but why add the ifdef and make the code even messier? Sigh. icc complains anyway */
}
break;
case pr_namelist:
{ NameList *nl;
GTextInfo *ti = GGadgetGetListItemSelected(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( ti!=NULL ) {
char *name = u2utf8_copy(ti->text);
nl = NameListByName(name);
free(name);
if ( nl!=NULL && nl->uses_unicode && !allow_utf8_glyphnames)
ff_post_error(_("Namelist contains non-ASCII names"),_("Glyph names should be limited to characters in the ASCII character set, but there are names in this namelist which use characters outside that range."));
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
}
break;
case pr_string: case pr_file:
ret = _GGadgetGetTitle(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( pl->val!=NULL ) {
free( *((char **) (pl->val)) );
*((char **) (pl->val)) = NULL;
if ( ret!=NULL && *ret!='\0' )
*((char **) (pl->val)) = /* u2def_*/ cu_copy(ret);
} else {
char *cret = cu_copy(ret);
(pl->set)(cret);
free(cret);
}
break;
case pr_angle:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err)/RAD2DEG;
break;
}
}
for ( i=0; i<SCRIPT_MENU_MAX; ++i ) {
free(script_menu_names[i]); script_menu_names[i] = NULL;
free(script_filenames[i]); script_filenames[i] = NULL;
}
for ( i=0; i<mi; ++i ) {
script_menu_names[i] = u_copy(names[i]);
script_filenames[i] = u2def_copy(scripts[i]);
}
list = GGadgetGetList(GWidgetGetControl(gw,CID_Mapping),&len);
UserSettingsFree();
user_macfeat_otftag = malloc((len+1)*sizeof(struct macsettingname));
user_macfeat_otftag[len].otf_tag = 0;
maxl = 0;
for ( i=0; i<len; ++i ) {
t = u_strlen(list[i]->text);
if ( t>maxl ) maxl = t;
}
str = malloc(maxl+3);
for ( i=0; i<len; ++i ) {
u2encoding_strncpy(str,list[i]->text,maxl+1,e_mac);
ParseMacMapping(str,&user_macfeat_otftag[i]);
}
free(str);
Prefs_ReplaceMacFeatures(GWidgetGetControl(gw,CID_Features));
if ( xuid!=NULL ) {
char *pt;
for ( pt=xuid; *pt==' ' ; ++pt );
if ( *pt=='[' ) { /* People who know PS well, might want to put brackets arround the xuid base array, but I don't want them */
pt = copy(pt+1);
if (xuid != NULL) free( xuid );
xuid = pt;
}
for ( pt=xuid+strlen(xuid)-1; pt>xuid && *pt==' '; --pt );
if ( pt >= xuid && *pt==']' ) *pt = '\0';
}
p->done = true;
PrefsUI_SavePrefs(true);
if ( maxundoes==0 ) { FontView *fv;
for ( fv=fv_list ; fv!=NULL; fv=(FontView *) (fv->b.next) )
SFRemoveUndoes(fv->b.sf,NULL,NULL);
}
if ( othersubrsfile!=NULL && ReadOtherSubrsFile(othersubrsfile)<=0 )
fprintf( stderr, "Failed to read OtherSubrs from %s\n", othersubrsfile );
GDrawEnableCairo(prefs_usecairo);
int force_redraw_charviews = 0;
if( prefs_oldval_cvEditHandleSize != prefs_cvEditHandleSize )
force_redraw_charviews = 1;
if( prefs_oldval_cvInactiveHandleAlpha != prefs_cvInactiveHandleAlpha )
force_redraw_charviews = 1;
if( force_redraw_charviews )
{
FontView *fv;
for ( fv=fv_list ; fv!=NULL; fv=(FontView *) (fv->b.next) )
{
FVRedrawAllCharViews( fv );
}
}
}
return( true );
}
static int Prefs_Cancel(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct pref_data *p = GDrawGetUserData(GGadgetGetWindow(g));
MacFeatListFree(GGadgetGetUserData((GWidgetGetControl(
GGadgetGetWindow(g),CID_Features))));
p->done = true;
}
return( true );
}
static int e_h(GWindow gw, GEvent *event) {
if ( event->type==et_close ) {
struct pref_data *p = GDrawGetUserData(gw);
p->done = true;
if(GWidgetGetControl(gw,CID_Features)) {
MacFeatListFree(GGadgetGetUserData((GWidgetGetControl(gw,CID_Features))));
}
} else if ( event->type==et_char ) {
if ( event->u.chr.keysym == GK_F1 || event->u.chr.keysym == GK_Help ) {
help("prefs.html");
return( true );
}
return( false );
}
return( true );
}
static void PrefsInit(void) {
static int done = false;
int i;
if ( done )
return;
done = true;
for ( i=0; visible_prefs_list[i].tab_name!=NULL; ++i )
visible_prefs_list[i].tab_name = _(visible_prefs_list[i].tab_name);
}
void DoPrefs(void) {
GRect pos;
GWindow gw;
GWindowAttrs wattrs;
GGadgetCreateData *pgcd, gcd[5], sgcd[45], mgcd[3], mfgcd[9], msgcd[9];
GGadgetCreateData mfboxes[3], *mfarray[14];
GGadgetCreateData mpboxes[3], *mparray[14];
GGadgetCreateData sboxes[2], *sarray[50];
GGadgetCreateData mboxes[3], *varray[5], *harray[8];
GTextInfo *plabel, **list, label[5], slabel[45], *plabels[TOPICS+5], mflabels[9], mslabels[9];
GTabInfo aspects[TOPICS+5], subaspects[3];
GGadgetCreateData **hvarray, boxes[2*TOPICS];
struct pref_data p;
int i, gc, sgc, j, k, line, line_max, y, y2, ii, si;
int32 llen;
char buf[20];
int gcnt[20];
static unichar_t nullstr[] = { 0 };
struct prefs_list *pl;
char *tempstr;
FontRequest rq;
GFont *font;
PrefsInit();
MfArgsInit();
for ( k=line_max=0; visible_prefs_list[k].tab_name!=0; ++k ) {
for ( i=line=gcnt[k]=0; visible_prefs_list[k].pl[i].name!=NULL; ++i ) {
if ( visible_prefs_list[k].pl[i].dontdisplay )
continue;
gcnt[k] += 2;
if ( visible_prefs_list[k].pl[i].type==pr_bool ) ++gcnt[k];
else if ( visible_prefs_list[k].pl[i].type==pr_file ) ++gcnt[k];
else if ( visible_prefs_list[k].pl[i].type==pr_angle ) ++gcnt[k];
++line;
}
if ( visible_prefs_list[k].pl == args_list ) {
gcnt[k] += 6;
line += 6;
}
if ( line>line_max ) line_max = line;
}
prefs_oldval_cvEditHandleSize = prefs_cvEditHandleSize;
prefs_oldval_cvInactiveHandleAlpha = prefs_cvInactiveHandleAlpha;
memset(&p,'\0',sizeof(p));
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg;
wattrs.event_masks = ~(1<<et_charup);
wattrs.restrict_input_to_me = 1;
wattrs.is_dlg = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Preferences");
pos.x = pos.y = 0;
pos.width = GGadgetScale(GDrawPointsToPixels(NULL,350));
pos.height = GDrawPointsToPixels(NULL,line_max*26+69);
gw = GDrawCreateTopWindow(NULL,&pos,e_h,&p,&wattrs);
memset(sgcd,0,sizeof(sgcd));
memset(slabel,0,sizeof(slabel));
memset(&mfgcd,0,sizeof(mfgcd));
memset(&msgcd,0,sizeof(msgcd));
memset(&mflabels,0,sizeof(mflabels));
memset(&mslabels,0,sizeof(mslabels));
memset(&mfboxes,0,sizeof(mfboxes));
memset(&mpboxes,0,sizeof(mpboxes));
memset(&sboxes,0,sizeof(sboxes));
memset(&boxes,0,sizeof(boxes));
GCDFillMacFeat(mfgcd,mflabels,250,default_mac_feature_map, true, mfboxes, mfarray);
sgc = 0;
msgcd[sgc].gd.pos.x = 6; msgcd[sgc].gd.pos.y = 6;
msgcd[sgc].gd.pos.width = 250; msgcd[sgc].gd.pos.height = 16*12+10;
msgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_list_alphabetic | gg_list_multiplesel;
msgcd[sgc].gd.cid = CID_Mapping;
msgcd[sgc].gd.u.list = Pref_MappingList(true);
msgcd[sgc].gd.handle_controlevent = Pref_MappingSel;
msgcd[sgc++].creator = GListCreate;
mparray[0] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = 6; msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y+msgcd[sgc-1].gd.pos.height+10;
msgcd[sgc].gd.flags = gg_visible | gg_enabled;
mslabels[sgc].text = (unichar_t *) S_("MacMap|_New...");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.handle_controlevent = Pref_NewMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[4] = GCD_Glue; mparray[5] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = msgcd[sgc-1].gd.pos.x+10+GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor);
msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y;
msgcd[sgc].gd.flags = gg_visible ;
mslabels[sgc].text = (unichar_t *) _("_Delete");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.cid = CID_MappingDel;
msgcd[sgc].gd.handle_controlevent = Pref_DelMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[5] = GCD_Glue; mparray[6] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = msgcd[sgc-1].gd.pos.x+10+GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor);
msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y;
msgcd[sgc].gd.flags = gg_visible ;
mslabels[sgc].text = (unichar_t *) _("_Edit...");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.cid = CID_MappingEdit;
msgcd[sgc].gd.handle_controlevent = Pref_EditMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[7] = GCD_Glue; mparray[8] = &msgcd[sgc-1];
msgcd[sgc].gd.pos.x = msgcd[sgc-1].gd.pos.x+10+GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor);
msgcd[sgc].gd.pos.y = msgcd[sgc-1].gd.pos.y;
msgcd[sgc].gd.flags = gg_visible | gg_enabled;
mslabels[sgc].text = (unichar_t *) S_("MacMapping|Default");
mslabels[sgc].text_is_1byte = true;
mslabels[sgc].text_in_resource = true;
msgcd[sgc].gd.label = &mslabels[sgc];
msgcd[sgc].gd.handle_controlevent = Pref_DefaultMapping;
msgcd[sgc++].creator = GButtonCreate;
mparray[9] = GCD_Glue; mparray[10] = &msgcd[sgc-1];
mparray[11] = GCD_Glue; mparray[12] = NULL;
mpboxes[2].gd.flags = gg_enabled|gg_visible;
mpboxes[2].gd.u.boxelements = mparray+4;
mpboxes[2].creator = GHBoxCreate;
mparray[1] = GCD_Glue;
mparray[2] = &mpboxes[2];
mparray[3] = NULL;
mpboxes[0].gd.flags = gg_enabled|gg_visible;
mpboxes[0].gd.u.boxelements = mparray;
mpboxes[0].creator = GVBoxCreate;
sgc = 0;
y2=5;
si = 0;
slabel[sgc].text = (unichar_t *) _("Menu Name");
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.popup_msg = (unichar_t *) _("You may create a script menu containing up to 10 frequently used scripts.\nEach entry in the menu needs both a name to display in the menu and\na script file to execute. The menu name may contain any unicode characters.\nThe button labeled \"...\" will allow you to browse for a script file.");
sgcd[sgc].gd.pos.x = 8;
sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
sgcd[sgc++].creator = GLabelCreate;
sarray[si++] = &sgcd[sgc-1];
slabel[sgc].text = (unichar_t *) _("Script File");
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.popup_msg = (unichar_t *) _("You may create a script menu containing up to 10 frequently used scripts\nEach entry in the menu needs both a name to display in the menu and\na script file to execute. The menu name may contain any unicode characters.\nThe button labeled \"...\" will allow you to browse for a script file.");
sgcd[sgc].gd.pos.x = 110;
sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
sgcd[sgc++].creator = GLabelCreate;
sarray[si++] = &sgcd[sgc-1];
sarray[si++] = GCD_Glue;
sarray[si++] = NULL;
y2 += 14;
for ( i=0; i<SCRIPT_MENU_MAX; ++i ) {
sgcd[sgc].gd.pos.x = 8; sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled | gg_text_xim;
slabel[sgc].text = script_menu_names[i]==NULL?nullstr:script_menu_names[i];
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.cid = i+CID_ScriptMNameBase;
sgcd[sgc++].creator = GTextFieldCreate;
sarray[si++] = &sgcd[sgc-1];
sgcd[sgc].gd.pos.x = 110; sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled;
slabel[sgc].text = (unichar_t *) (script_filenames[i]==NULL?"":script_filenames[i]);
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.cid = i+CID_ScriptMFileBase;
sgcd[sgc++].creator = GTextFieldCreate;
sarray[si++] = &sgcd[sgc-1];
sgcd[sgc].gd.pos.x = 210; sgcd[sgc].gd.pos.y = y2;
sgcd[sgc].gd.flags = gg_visible | gg_enabled;
slabel[sgc].text = (unichar_t *) _("...");
slabel[sgc].text_is_1byte = true;
sgcd[sgc].gd.label = &slabel[sgc];
sgcd[sgc].gd.cid = i+CID_ScriptMBrowseBase;
sgcd[sgc].gd.handle_controlevent = Prefs_ScriptBrowse;
sgcd[sgc++].creator = GButtonCreate;
sarray[si++] = &sgcd[sgc-1];
sarray[si++] = NULL;
y2 += 26;
}
sarray[si++] = GCD_Glue; sarray[si++] = GCD_Glue; sarray[si++] = GCD_Glue;
sarray[si++] = NULL;
sarray[si++] = NULL;
sboxes[0].gd.flags = gg_enabled|gg_visible;
sboxes[0].gd.u.boxelements = sarray;
sboxes[0].creator = GHVBoxCreate;
memset(&mgcd,0,sizeof(mgcd));
memset(&mgcd,0,sizeof(mgcd));
memset(&subaspects,'\0',sizeof(subaspects));
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
memset(&aspects,'\0',sizeof(aspects));
aspects[0].selected = true;
for ( k=0; visible_prefs_list[k].tab_name!=0; ++k ) {
pgcd = calloc(gcnt[k]+4,sizeof(GGadgetCreateData));
plabel = calloc(gcnt[k]+4,sizeof(GTextInfo));
hvarray = calloc((gcnt[k]+6)*5+2,sizeof(GGadgetCreateData *));
aspects[k].text = (unichar_t *) visible_prefs_list[k].tab_name;
aspects[k].text_is_1byte = true;
aspects[k].gcd = &boxes[2*k];
aspects[k].nesting = visible_prefs_list[k].nest;
plabels[k] = plabel;
gc = si = 0;
for ( i=line=0, y=5; visible_prefs_list[k].pl[i].name!=NULL; ++i ) {
pl = &visible_prefs_list[k].pl[i];
if ( pl->dontdisplay )
continue;
plabel[gc].text = (unichar_t *) _(pl->name);
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) _(pl->popup);
pgcd[gc].gd.pos.x = 8;
pgcd[gc].gd.pos.y = y + 6;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) _(pl->popup);
pgcd[gc].gd.pos.x = 110;
pgcd[gc].gd.pos.y = y;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc].data = pl;
pgcd[gc].gd.cid = k*CID_PrefsOffset+CID_PrefsBase+i;
switch ( pl->type ) {
case pr_bool:
plabel[gc].text = (unichar_t *) _("On");
pgcd[gc].gd.pos.y += 3;
pgcd[gc++].creator = GRadioCreate;
hvarray[si++] = &pgcd[gc-1];
pgcd[gc] = pgcd[gc-1];
pgcd[gc].gd.pos.x += 50;
pgcd[gc].gd.cid = 0;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) _("Off");
plabel[gc].text_is_1byte = true;
hvarray[si++] = &pgcd[gc];
hvarray[si++] = GCD_Glue;
if ( *((int *) pl->val))
pgcd[gc-1].gd.flags |= gg_cb_on;
else
pgcd[gc].gd.flags |= gg_cb_on;
++gc;
y += 22;
break;
case pr_int:
sprintf(buf,"%d", *((int *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_unicode:
/*sprintf(buf,"U+%04x", *((int *) pl->val));*/
{ char *pt; pt=buf; pt=utf8_idpb(pt,*((int *)pl->val),UTF8IDPB_NOZERO); *pt='\0'; }
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_real:
sprintf(buf,"%g", *((float *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_encoding:
pgcd[gc].gd.u.list = GetEncodingTypes();
pgcd[gc].gd.label = EncodingTypesFindEnc(pgcd[gc].gd.u.list,
*(Encoding **) pl->val);
for ( ii=0; pgcd[gc].gd.u.list[ii].text!=NULL ||pgcd[gc].gd.u.list[ii].line; ++ii )
if ( pgcd[gc].gd.u.list[ii].userdata!=NULL &&
(strcmp(pgcd[gc].gd.u.list[ii].userdata,"Compacted")==0 ||
strcmp(pgcd[gc].gd.u.list[ii].userdata,"Original")==0 ))
pgcd[gc].gd.u.list[ii].disabled = true;
pgcd[gc].creator = GListFieldCreate;
pgcd[gc].gd.pos.width = 160;
if ( pgcd[gc].gd.label==NULL ) pgcd[gc].gd.label = &encodingtypes[0];
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
break;
case pr_namelist:
{ char **nlnames = AllNamelistNames();
int cnt;
GTextInfo *namelistnames;
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt);
namelistnames = calloc(cnt+1,sizeof(GTextInfo));
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt) {
namelistnames[cnt].text = (unichar_t *) nlnames[cnt];
namelistnames[cnt].text_is_1byte = true;
if ( strcmp(_((*(NameList **) (pl->val))->title),nlnames[cnt])==0 ) {
namelistnames[cnt].selected = true;
pgcd[gc].gd.label = &namelistnames[cnt];
}
}
pgcd[gc].gd.u.list = namelistnames;
pgcd[gc].creator = GListButtonCreate;
pgcd[gc].gd.pos.width = 160;
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
} break;
case pr_string: case pr_file:
if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args )
pgcd[gc].gd.pos.width = 160;
if ( pl->val!=NULL )
tempstr = *((char **) (pl->val));
else
tempstr = (char *) ((pl->get)());
if ( tempstr!=NULL )
plabel[gc].text = /* def2u_*/ uc_copy( tempstr );
else if ( ((char **) pl->val)==&BDFFoundry )
plabel[gc].text = /* def2u_*/ uc_copy( "FontForge" );
else
plabel[gc].text = /* def2u_*/ uc_copy( "" );
plabel[gc].text_is_1byte = false;
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
if ( pl->type==pr_file ) {
pgcd[gc] = pgcd[gc-1];
pgcd[gc-1].gd.pos.width = 140;
hvarray[si++] = GCD_ColSpan;
pgcd[gc].gd.pos.x += 145;
pgcd[gc].gd.cid += CID_PrefsBrowseOffset;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) "...";
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.handle_controlevent = Prefs_BrowseFile;
pgcd[gc++].creator = GButtonCreate;
hvarray[si++] = &pgcd[gc-1];
} else if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args ) {
hvarray[si++] = GCD_ColSpan;
hvarray[si++] = GCD_Glue;
} else {
hvarray[si++] = GCD_Glue;
hvarray[si++] = GCD_Glue;
}
y += 26;
if ( pl->val==NULL )
free(tempstr);
break;
case pr_angle:
sprintf(buf,"%g", *((float *) pl->val) * RAD2DEG);
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text = (unichar_t *) U_("°");
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.pos.x = pgcd[gc-1].gd.pos.x+gcd[gc-1].gd.pos.width+2; pgcd[gc].gd.pos.y = pgcd[gc-1].gd.pos.y;
pgcd[gc].gd.flags = gg_enabled|gg_visible;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue;
y += 26;
break;
}
++line;
hvarray[si++] = NULL;
}
if ( visible_prefs_list[k].pl == args_list ) {
static char *text[] = {
/* GT: See the long comment at "Property|New" */
/* GT: This and the next few strings show a limitation of my widget set which */
/* GT: cannot handle multi-line text labels. These strings should be concatenated */
/* GT: (after striping off "Prefs_App|") together, translated, and then broken up */
/* GT: to fit the dialog. There is an extra blank line, not used in English, */
/* GT: into which your text may extend if needed. */
N_("Prefs_App|Normally FontForge will find applications by searching for"),
N_("Prefs_App|them in your PATH environment variable, if you want"),
N_("Prefs_App|to alter that behavior you may set an environment"),
N_("Prefs_App|variable giving the full path spec of the application."),
N_("Prefs_App|FontForge recognizes BROWSER, MF and AUTOTRACE."),
N_("Prefs_App| "), /* A blank line */
NULL };
y += 8;
for ( i=0; text[i]!=0; ++i ) {
plabel[gc].text = (unichar_t *) S_(text[i]);
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.pos.x = 8;
pgcd[gc].gd.pos.y = y;
pgcd[gc].gd.flags = gg_visible | gg_enabled;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
hvarray[si++] = NULL;
y += 12;
}
}
if ( y>y2 ) y2 = y;
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
hvarray[si++] = NULL;
hvarray[si++] = NULL;
boxes[2*k].gd.flags = gg_enabled|gg_visible;
boxes[2*k].gd.u.boxelements = hvarray;
boxes[2*k].creator = GHVBoxCreate;
}
aspects[k].text = (unichar_t *) _("Script Menu");
aspects[k].text_is_1byte = true;
aspects[k++].gcd = sboxes;
subaspects[0].text = (unichar_t *) _("Features");
subaspects[0].text_is_1byte = true;
subaspects[0].gcd = mfboxes;
subaspects[1].text = (unichar_t *) _("Mapping");
subaspects[1].text_is_1byte = true;
subaspects[1].gcd = mpboxes;
mgcd[0].gd.pos.x = 4; gcd[0].gd.pos.y = 6;
mgcd[0].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
mgcd[0].gd.pos.height = y2;
mgcd[0].gd.u.tabs = subaspects;
mgcd[0].gd.flags = gg_visible | gg_enabled;
mgcd[0].creator = GTabSetCreate;
aspects[k].text = (unichar_t *) _("Mac");
aspects[k].text_is_1byte = true;
aspects[k++].gcd = mgcd;
gc = 0;
gcd[gc].gd.pos.x = gcd[gc].gd.pos.y = 2;
gcd[gc].gd.pos.width = pos.width-4; gcd[gc].gd.pos.height = pos.height-2;
gcd[gc].gd.flags = gg_enabled | gg_visible | gg_pos_in_pixels;
gcd[gc++].creator = GGroupCreate;
gcd[gc].gd.pos.x = 4; gcd[gc].gd.pos.y = 6;
gcd[gc].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-8;
gcd[gc].gd.pos.height = y2+20+18+4;
gcd[gc].gd.u.tabs = aspects;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_tabset_vert;
gcd[gc++].creator = GTabSetCreate;
varray[0] = &gcd[gc-1]; varray[1] = NULL;
y = gcd[gc-1].gd.pos.y+gcd[gc-1].gd.pos.height;
gcd[gc].gd.pos.x = 30-3; gcd[gc].gd.pos.y = y+5-3;
gcd[gc].gd.pos.width = -1; gcd[gc].gd.pos.height = 0;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_but_default;
label[gc].text = (unichar_t *) _("_OK");
label[gc].text_is_1byte = true;
label[gc].text_in_resource = true;
gcd[gc].gd.mnemonic = 'O';
gcd[gc].gd.label = &label[gc];
gcd[gc].gd.handle_controlevent = Prefs_Ok;
gcd[gc++].creator = GButtonCreate;
harray[0] = GCD_Glue; harray[1] = &gcd[gc-1]; harray[2] = GCD_Glue; harray[3] = GCD_Glue;
gcd[gc].gd.pos.x = -30; gcd[gc].gd.pos.y = gcd[gc-1].gd.pos.y+3;
gcd[gc].gd.pos.width = -1; gcd[gc].gd.pos.height = 0;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_but_cancel;
label[gc].text = (unichar_t *) _("_Cancel");
label[gc].text_is_1byte = true;
label[gc].text_in_resource = true;
gcd[gc].gd.label = &label[gc];
gcd[gc].gd.mnemonic = 'C';
gcd[gc].gd.handle_controlevent = Prefs_Cancel;
gcd[gc++].creator = GButtonCreate;
harray[4] = GCD_Glue; harray[5] = &gcd[gc-1]; harray[6] = GCD_Glue; harray[7] = NULL;
memset(mboxes,0,sizeof(mboxes));
mboxes[2].gd.flags = gg_enabled|gg_visible;
mboxes[2].gd.u.boxelements = harray;
mboxes[2].creator = GHBoxCreate;
varray[2] = &mboxes[2];
varray[3] = NULL;
varray[4] = NULL;
mboxes[0].gd.pos.x = mboxes[0].gd.pos.y = 2;
mboxes[0].gd.flags = gg_enabled|gg_visible;
mboxes[0].gd.u.boxelements = varray;
mboxes[0].creator = GHVGroupCreate;
y = GDrawPointsToPixels(NULL,y+37);
gcd[0].gd.pos.height = y-4;
GGadgetsCreate(gw,mboxes);
GTextInfoListFree(mfgcd[0].gd.u.list);
GTextInfoListFree(msgcd[0].gd.u.list);
GHVBoxSetExpandableRow(mboxes[0].ret,0);
GHVBoxSetExpandableCol(mboxes[2].ret,gb_expandgluesame);
GHVBoxSetExpandableRow(mfboxes[0].ret,0);
GHVBoxSetExpandableCol(mfboxes[2].ret,gb_expandgluesame);
GHVBoxSetExpandableRow(mpboxes[0].ret,0);
GHVBoxSetExpandableCol(mpboxes[2].ret,gb_expandgluesame);
GHVBoxSetExpandableRow(sboxes[0].ret,gb_expandglue);
for ( k=0; k<TOPICS; ++k )
GHVBoxSetExpandableRow(boxes[2*k].ret,gb_expandglue);
memset(&rq,0,sizeof(rq));
rq.utf8_family_name = MONO_UI_FAMILIES;
rq.point_size = 12;
rq.weight = 400;
font = GDrawInstanciateFont(gw,&rq);
GGadgetSetFont(mfgcd[0].ret,font);
GGadgetSetFont(msgcd[0].ret,font);
GHVBoxFitWindow(mboxes[0].ret);
for ( k=0; visible_prefs_list[k].tab_name!=0; ++k ) for ( gc=0,i=0; visible_prefs_list[k].pl[i].name!=NULL; ++i ) {
GGadgetCreateData *gcd = aspects[k].gcd[0].gd.u.boxelements[0];
pl = &visible_prefs_list[k].pl[i];
if ( pl->dontdisplay )
continue;
switch ( pl->type ) {
case pr_bool:
++gc;
break;
case pr_encoding: {
GGadget *g = gcd[gc+1].ret;
list = GGadgetGetList(g,&llen);
for ( j=0; j<llen ; ++j ) {
if ( list[j]->text!=NULL &&
(void *) (intpt) ( *((int *) pl->val)) == list[j]->userdata )
list[j]->selected = true;
else
list[j]->selected = false;
}
if ( gcd[gc+1].gd.u.list!=encodingtypes )
GTextInfoListFree(gcd[gc+1].gd.u.list);
} break;
case pr_namelist:
free(gcd[gc+1].gd.u.list);
break;
case pr_string: case pr_file: case pr_int: case pr_real: case pr_unicode: case pr_angle:
free(plabels[k][gc+1].text);
if ( pl->type==pr_file || pl->type==pr_angle )
++gc;
break;
}
gc += 2;
}
for ( k=0; visible_prefs_list[k].tab_name!=0; ++k ) {
free(aspects[k].gcd->gd.u.boxelements[0]);
free(aspects[k].gcd->gd.u.boxelements);
free(plabels[k]);
}
GWidgetHidePalettes();
GDrawSetVisible(gw,true);
while ( !p.done )
GDrawProcessOneEvent(NULL);
GDrawDestroyWindow(gw);
}
void RecentFilesRemember(char *filename) {
int i,j;
for ( i=0; i<RECENT_MAX && RecentFiles[i]!=NULL; ++i )
if ( strcmp(RecentFiles[i],filename)==0 )
break;
if ( i<RECENT_MAX && RecentFiles[i]!=NULL ) {
if ( i!=0 ) {
filename = RecentFiles[i];
for ( j=i; j>0; --j )
RecentFiles[j] = RecentFiles[j-1];
RecentFiles[0] = filename;
}
} else {
if ( RecentFiles[RECENT_MAX-1]!=NULL )
free( RecentFiles[RECENT_MAX-1]);
for ( i=RECENT_MAX-1; i>0; --i )
RecentFiles[i] = RecentFiles[i-1];
RecentFiles[0] = copy(filename);
}
PrefsUI_SavePrefs(true);
}
void LastFonts_Save(void) {
FontView *fv, *next;
char buffer[1024];
char *ffdir = getFontForgeUserDir(Config);
FILE *preserve = NULL;
if ( ffdir ) {
sprintf(buffer, "%s/FontsOpenAtLastQuit", ffdir);
preserve = fopen(buffer,"w");
free(ffdir);
}
for ( fv = fv_list; fv!=NULL; fv = next ) {
next = (FontView *) (fv->b.next);
if ( preserve ) {
SplineFont *sf = fv->b.cidmaster?fv->b.cidmaster:fv->b.sf;
fprintf(preserve, "%s\n", sf->filename?sf->filename:sf->origname);
}
}
if ( preserve )
fclose(preserve);
}
struct prefs_interface gdraw_prefs_interface = {
PrefsUI_SavePrefs,
PrefsUI_LoadPrefs,
PrefsUI_GetPrefs,
PrefsUI_SetPrefs,
PrefsUI_getFontForgeShareDir,
PrefsUI_SetDefaults
};
static void change_res_filename(const char *newname) {
free(xdefs_filename);
xdefs_filename = copy( newname );
SavePrefs(true);
}
void DoXRes(void) {
extern GResInfo fontview_ri;
MVColInit();
CVColInit();
GResEdit(&fontview_ri,xdefs_filename,change_res_filename);
}
struct prefs_list pointer_dialog_list[] = {
{ N_("ArrowMoveSize"), pr_real, &arrowAmount, NULL, NULL, '\0', NULL, 0, N_("The number of em-units by which an arrow key will move a selected point") },
{ N_("ArrowAccelFactor"), pr_real, &arrowAccelFactor, NULL, NULL, '\0', NULL, 0, N_("Holding down the Shift key will speed up arrow key motion by this factor") },
{ N_("InterpolateCPsOnMotion"), pr_bool, &interpCPsOnMotion, NULL, NULL, '\0', NULL, 0, N_("When moving one end point of a spline but not the other\ninterpolate the control points between the two.") },
PREFS_LIST_EMPTY
};
struct prefs_list ruler_dialog_list[] = {
{ N_("SnapDistanceMeasureTool"), pr_real, &snapdistancemeasuretool, NULL, NULL, '\0', NULL, 0, N_("When the measure tool is active and when the mouse pointer is within this many pixels\nof one of the various interesting features (baseline,\nwidth, grid splines, etc.) the pointer will snap\nto that feature.") },
{ N_("MeasureToolShowHorizontalVertical"), pr_bool, &measuretoolshowhorizontolvertical, NULL, NULL, '\0', NULL, 0, N_("Have the measure tool show horizontal and vertical distances on the canvas.") },
PREFS_LIST_EMPTY
};
static int PrefsSubSet_Ok(GGadget *g, GEvent *e) {
GWindow gw = GGadgetGetWindow(g);
struct pref_data *p = GDrawGetUserData(GGadgetGetWindow(g));
struct prefs_list* plist = p->plist;
struct prefs_list* pl = plist;
int i=0,j=0;
int err=0, enc;
const unichar_t *ret;
p->done = true;
for ( i=0, pl=plist; pl->name; ++i, ++pl ) {
switch( pl->type ) {
case pr_int:
*((int *) (pl->val)) = GetInt8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_unicode:
*((int *) (pl->val)) = GetUnicodeChar8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_bool:
*((int *) (pl->val)) = GGadgetIsChecked(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
break;
case pr_real:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err);
break;
case pr_encoding:
{ Encoding *e;
e = ParseEncodingNameFromList(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( e!=NULL )
*((Encoding **) (pl->val)) = e;
enc = 1; /* So gcc doesn't complain about unused. It is unused, but why add the ifdef and make the code even messier? Sigh. icc complains anyway */
}
break;
case pr_namelist:
{ NameList *nl;
GTextInfo *ti = GGadgetGetListItemSelected(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( ti!=NULL ) {
char *name = u2utf8_copy(ti->text);
nl = NameListByName(name);
free(name);
if ( nl!=NULL && nl->uses_unicode && !allow_utf8_glyphnames)
ff_post_error(_("Namelist contains non-ASCII names"),_("Glyph names should be limited to characters in the ASCII character set, but there are names in this namelist which use characters outside that range."));
else if ( nl!=NULL )
*((NameList **) (pl->val)) = nl;
}
}
break;
case pr_string: case pr_file:
ret = _GGadgetGetTitle(GWidgetGetControl(gw,j*CID_PrefsOffset+CID_PrefsBase+i));
if ( pl->val!=NULL ) {
free( *((char **) (pl->val)) );
*((char **) (pl->val)) = NULL;
if ( ret!=NULL && *ret!='\0' )
*((char **) (pl->val)) = /* u2def_*/ cu_copy(ret);
} else {
char *cret = cu_copy(ret);
(pl->set)(cret);
free(cret);
}
break;
case pr_angle:
*((float *) (pl->val)) = GetReal8(gw,j*CID_PrefsOffset+CID_PrefsBase+i,pl->name,&err)/RAD2DEG;
break;
}
}
return( true );
}
static void PrefsSubSetDlg(CharView *cv,char* windowTitle,struct prefs_list* plist) {
struct prefs_list* pl = plist;
GRect pos;
GWindow gw;
GWindowAttrs wattrs;
GGadgetCreateData *pgcd, gcd[20], sgcd[45], mgcd[3], mfgcd[9], msgcd[9];
GGadgetCreateData mfboxes[3], *mfarray[14];
GGadgetCreateData mpboxes[3];
GGadgetCreateData sboxes[2];
GGadgetCreateData mboxes[3], mboxes2[5], *varray[5], *harray[8];
GTextInfo *plabel, label[20], slabel[45], mflabels[9], mslabels[9];
GTabInfo aspects[TOPICS+5], subaspects[3];
GGadgetCreateData **hvarray, boxes[2*TOPICS];
struct pref_data p;
int line = 0,line_max = 3;
int i = 0, gc = 0, ii, y=0, si=0, k=0;
char buf[20];
char *tempstr;
PrefsInit();
MfArgsInit();
line_max=0;
for ( i=0, pl=plist; pl->name; ++i, ++pl ) {
++line_max;
}
int itemCount = 100;
pgcd = calloc(itemCount,sizeof(GGadgetCreateData));
plabel = calloc(itemCount,sizeof(GTextInfo));
hvarray = calloc((itemCount)*5,sizeof(GGadgetCreateData *));
memset(&p,'\0',sizeof(p));
memset(&wattrs,0,sizeof(wattrs));
memset(sgcd,0,sizeof(sgcd));
memset(slabel,0,sizeof(slabel));
memset(&mfgcd,0,sizeof(mfgcd));
memset(&msgcd,0,sizeof(msgcd));
memset(&mflabels,0,sizeof(mflabels));
memset(&mslabels,0,sizeof(mslabels));
memset(&mfboxes,0,sizeof(mfboxes));
memset(&mpboxes,0,sizeof(mpboxes));
memset(&sboxes,0,sizeof(sboxes));
memset(&boxes,0,sizeof(boxes));
memset(&mgcd,0,sizeof(mgcd));
memset(&mgcd,0,sizeof(mgcd));
memset(&subaspects,'\0',sizeof(subaspects));
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
memset(&aspects,'\0',sizeof(aspects));
GCDFillMacFeat(mfgcd,mflabels,250,default_mac_feature_map, true, mfboxes, mfarray);
p.plist = plist;
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_restrict|wam_isdlg;
wattrs.event_masks = ~(1<<et_charup);
wattrs.restrict_input_to_me = 1;
wattrs.is_dlg = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = windowTitle;
pos.x = pos.y = 0;
pos.width = GGadgetScale(GDrawPointsToPixels(NULL,340));
pos.height = GDrawPointsToPixels(NULL,line_max*26+25);
gw = GDrawCreateTopWindow(NULL,&pos,e_h,&p,&wattrs);
for ( i=0, pl=plist; pl->name; ++i, ++pl ) {
plabel[gc].text = (unichar_t *) _(pl->name);
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) 0;//_(pl->popup);
pgcd[gc].gd.pos.x = 8;
pgcd[gc].gd.pos.y = y + 6;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.mnemonic = '\0';
pgcd[gc].gd.popup_msg = (unichar_t *) 0;//_(pl->popup);
pgcd[gc].gd.pos.x = 110;
pgcd[gc].gd.pos.y = y;
pgcd[gc].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
pgcd[gc].data = pl;
pgcd[gc].gd.cid = k*CID_PrefsOffset+CID_PrefsBase+i;
switch ( pl->type ) {
case pr_bool:
plabel[gc].text = (unichar_t *) _("On");
pgcd[gc].gd.pos.y += 3;
pgcd[gc++].creator = GRadioCreate;
hvarray[si++] = &pgcd[gc-1];
pgcd[gc] = pgcd[gc-1];
pgcd[gc].gd.pos.x += 50;
pgcd[gc].gd.cid = 0;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) _("Off");
plabel[gc].text_is_1byte = true;
hvarray[si++] = &pgcd[gc];
hvarray[si++] = GCD_Glue;
if ( *((int *) pl->val))
pgcd[gc-1].gd.flags |= gg_cb_on;
else
pgcd[gc].gd.flags |= gg_cb_on;
++gc;
y += 22;
break;
case pr_int:
sprintf(buf,"%d", *((int *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_unicode:
/*sprintf(buf,"U+%04x", *((int *) pl->val));*/
{ char *pt; pt=buf; pt=utf8_idpb(pt,*((int *)pl->val),UTF8IDPB_NOZERO); *pt='\0'; }
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_real:
sprintf(buf,"%g", *((float *) pl->val));
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue; hvarray[si++] = GCD_Glue;
y += 26;
break;
case pr_encoding:
pgcd[gc].gd.u.list = GetEncodingTypes();
pgcd[gc].gd.label = EncodingTypesFindEnc(pgcd[gc].gd.u.list,
*(Encoding **) pl->val);
for ( ii=0; pgcd[gc].gd.u.list[ii].text!=NULL ||pgcd[gc].gd.u.list[ii].line; ++ii )
if ( pgcd[gc].gd.u.list[ii].userdata!=NULL &&
(strcmp(pgcd[gc].gd.u.list[ii].userdata,"Compacted")==0 ||
strcmp(pgcd[gc].gd.u.list[ii].userdata,"Original")==0 ))
pgcd[gc].gd.u.list[ii].disabled = true;
pgcd[gc].creator = GListFieldCreate;
pgcd[gc].gd.pos.width = 160;
if ( pgcd[gc].gd.label==NULL ) pgcd[gc].gd.label = &encodingtypes[0];
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
break;
case pr_namelist:
{ char **nlnames = AllNamelistNames();
int cnt;
GTextInfo *namelistnames;
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt);
namelistnames = calloc(cnt+1,sizeof(GTextInfo));
for ( cnt=0; nlnames[cnt]!=NULL; ++cnt) {
namelistnames[cnt].text = (unichar_t *) nlnames[cnt];
namelistnames[cnt].text_is_1byte = true;
if ( strcmp(_((*(NameList **) (pl->val))->title),nlnames[cnt])==0 ) {
namelistnames[cnt].selected = true;
pgcd[gc].gd.label = &namelistnames[cnt];
}
}
pgcd[gc].gd.u.list = namelistnames;
pgcd[gc].creator = GListButtonCreate;
pgcd[gc].gd.pos.width = 160;
++gc;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_ColSpan; hvarray[si++] = GCD_ColSpan;
y += 28;
} break;
case pr_string: case pr_file:
if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args )
pgcd[gc].gd.pos.width = 160;
if ( pl->val!=NULL )
tempstr = *((char **) (pl->val));
else
tempstr = (char *) ((pl->get)());
if ( tempstr!=NULL )
plabel[gc].text = /* def2u_*/ uc_copy( tempstr );
else if ( ((char **) pl->val)==&BDFFoundry )
plabel[gc].text = /* def2u_*/ uc_copy( "FontForge" );
else
plabel[gc].text = /* def2u_*/ uc_copy( "" );
plabel[gc].text_is_1byte = false;
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
if ( pl->type==pr_file ) {
pgcd[gc] = pgcd[gc-1];
pgcd[gc-1].gd.pos.width = 140;
hvarray[si++] = GCD_ColSpan;
pgcd[gc].gd.pos.x += 145;
pgcd[gc].gd.cid += CID_PrefsBrowseOffset;
pgcd[gc].gd.label = &plabel[gc];
plabel[gc].text = (unichar_t *) "...";
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.handle_controlevent = Prefs_BrowseFile;
pgcd[gc++].creator = GButtonCreate;
hvarray[si++] = &pgcd[gc-1];
} else if ( pl->set==SetAutoTraceArgs || ((char **) pl->val)==&mf_args ) {
hvarray[si++] = GCD_ColSpan;
hvarray[si++] = GCD_Glue;
} else {
hvarray[si++] = GCD_Glue;
hvarray[si++] = GCD_Glue;
}
y += 26;
if ( pl->val==NULL )
free(tempstr);
break;
case pr_angle:
sprintf(buf,"%g", *((float *) pl->val) * RAD2DEG);
plabel[gc].text = (unichar_t *) copy( buf );
pgcd[gc++].creator = GTextFieldCreate;
hvarray[si++] = &pgcd[gc-1];
plabel[gc].text = (unichar_t *) U_("°");
plabel[gc].text_is_1byte = true;
pgcd[gc].gd.label = &plabel[gc];
pgcd[gc].gd.pos.x = pgcd[gc-1].gd.pos.x+gcd[gc-1].gd.pos.width+2; pgcd[gc].gd.pos.y = pgcd[gc-1].gd.pos.y;
pgcd[gc].gd.flags = gg_enabled|gg_visible;
pgcd[gc++].creator = GLabelCreate;
hvarray[si++] = &pgcd[gc-1];
hvarray[si++] = GCD_Glue;
y += 26;
break;
}
++line;
hvarray[si++] = NULL;
}
harray[4] = 0;
harray[5] = 0;
harray[6] = 0;
harray[7] = 0;
gcd[gc].gd.pos.x = 30-3;
gcd[gc].gd.pos.y = y+5-3;
gcd[gc].gd.pos.width = -1;
gcd[gc].gd.pos.height = 0;
gcd[gc].gd.flags = gg_visible | gg_enabled | gg_but_default;
label[gc].text = (unichar_t *) _("_OK");
label[gc].text_is_1byte = true;
label[gc].text_in_resource = true;
gcd[gc].gd.mnemonic = 'O';
gcd[gc].gd.label = &label[gc];
gcd[gc].gd.handle_controlevent = PrefsSubSet_Ok;
gcd[gc++].creator = GButtonCreate;
harray[0] = GCD_Glue; harray[1] = &gcd[gc-1]; harray[2] = GCD_Glue; harray[3] = GCD_Glue;
memset(mboxes,0,sizeof(mboxes));
memset(mboxes2,0,sizeof(mboxes2));
mboxes[2].gd.pos.x = 2;
mboxes[2].gd.pos.y = 20;
mboxes[2].gd.flags = gg_enabled|gg_visible;
mboxes[2].gd.u.boxelements = harray;
mboxes[2].creator = GHBoxCreate;
mboxes[0].gd.pos.x = mboxes[0].gd.pos.y = 2;
mboxes[0].gd.flags = gg_enabled|gg_visible;
mboxes[0].gd.u.boxelements = hvarray;
mboxes[0].creator = GHVGroupCreate;
varray[0] = &mboxes[0];
varray[1] = &mboxes[2];
varray[2] = 0;
varray[3] = 0;
varray[4] = 0;
/* varray[0] = &mboxes[2]; */
/* varray[1] = 0;//&mboxes[2]; */
/* varray[2] = 0; */
/* varray[3] = 0; */
/* varray[4] = 0; */
mboxes2[0].gd.pos.x = 4;
mboxes2[0].gd.pos.y = 4;
mboxes2[0].gd.flags = gg_enabled|gg_visible;
mboxes2[0].gd.u.boxelements = varray;
mboxes2[0].creator = GVBoxCreate;
GGadgetsCreate(gw,mboxes2);
GDrawSetVisible(gw,true);
while ( !p.done )
GDrawProcessOneEvent(NULL);
GDrawDestroyWindow(gw);
}
void PointerDlg(CharView *cv) {
PrefsSubSetDlg( cv, _("Arrow Options"), pointer_dialog_list );
}
void RulerDlg(CharView *cv) {
PrefsSubSetDlg( cv, _("Ruler Options"), ruler_dialog_list );
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1050_2 |
crossvul-cpp_data_good_340_7 | /*
* sc.c: General functions
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef ENABLE_OPENSSL
#include <openssl/crypto.h> /* for OPENSSL_cleanse */
#endif
#include "internal.h"
#ifdef PACKAGE_VERSION
static const char *sc_version = PACKAGE_VERSION;
#else
static const char *sc_version = "(undef)";
#endif
const char *sc_get_version(void)
{
return sc_version;
}
int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen)
{
int err = SC_SUCCESS;
size_t left, count = 0, in_len;
if (in == NULL || out == NULL || outlen == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
left = *outlen;
in_len = strlen(in);
while (*in != '\0') {
int byte = 0, nybbles = 2;
while (nybbles-- && *in && *in != ':' && *in != ' ') {
char c;
byte <<= 4;
c = *in++;
if ('0' <= c && c <= '9')
c -= '0';
else
if ('a' <= c && c <= 'f')
c = c - 'a' + 10;
else
if ('A' <= c && c <= 'F')
c = c - 'A' + 10;
else {
err = SC_ERROR_INVALID_ARGUMENTS;
goto out;
}
byte |= c;
}
/* Detect premature end of string before byte is complete */
if (in_len > 1 && *in == '\0' && nybbles >= 0) {
err = SC_ERROR_INVALID_ARGUMENTS;
break;
}
if (*in == ':' || *in == ' ')
in++;
if (left <= 0) {
err = SC_ERROR_BUFFER_TOO_SMALL;
break;
}
out[count++] = (u8) byte;
left--;
}
out:
*outlen = count;
return err;
}
int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len,
int in_sep)
{
unsigned int n, sep_len;
char *pos, *end, sep;
sep = (char)in_sep;
sep_len = sep > 0 ? 1 : 0;
pos = out;
end = out + out_len;
for (n = 0; n < in_len; n++) {
if (pos + 3 + sep_len >= end)
return SC_ERROR_BUFFER_TOO_SMALL;
if (n && sep_len)
*pos++ = sep;
sprintf(pos, "%02x", in[n]);
pos += 2;
}
*pos = '\0';
return SC_SUCCESS;
}
/*
* Right trim all non-printable characters
*/
size_t sc_right_trim(u8 *buf, size_t len) {
size_t i;
if (!buf)
return 0;
if (len > 0) {
for(i = len-1; i > 0; i--) {
if(!isprint(buf[i])) {
buf[i] = '\0';
len--;
continue;
}
break;
}
}
return len;
}
u8 *ulong2bebytes(u8 *buf, unsigned long x)
{
if (buf != NULL) {
buf[3] = (u8) (x & 0xff);
buf[2] = (u8) ((x >> 8) & 0xff);
buf[1] = (u8) ((x >> 16) & 0xff);
buf[0] = (u8) ((x >> 24) & 0xff);
}
return buf;
}
u8 *ushort2bebytes(u8 *buf, unsigned short x)
{
if (buf != NULL) {
buf[1] = (u8) (x & 0xff);
buf[0] = (u8) ((x >> 8) & 0xff);
}
return buf;
}
unsigned long bebytes2ulong(const u8 *buf)
{
if (buf == NULL)
return 0UL;
return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]);
}
unsigned short bebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short) (buf[0] << 8 | buf[1]);
}
unsigned short lebytes2ushort(const u8 *buf)
{
if (buf == NULL)
return 0U;
return (unsigned short)buf[1] << 8 | (unsigned short)buf[0];
}
void sc_init_oid(struct sc_object_id *oid)
{
int ii;
if (!oid)
return;
for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++)
oid->value[ii] = -1;
}
int sc_format_oid(struct sc_object_id *oid, const char *in)
{
int ii, ret = SC_ERROR_INVALID_ARGUMENTS;
const char *p;
char *q;
if (oid == NULL || in == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
sc_init_oid(oid);
p = in;
for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) {
oid->value[ii] = strtol(p, &q, 10);
if (!*q)
break;
if (!(q[0] == '.' && isdigit(q[1])))
goto out;
p = q + 1;
}
if (!sc_valid_oid(oid))
goto out;
ret = SC_SUCCESS;
out:
if (ret)
sc_init_oid(oid);
return ret;
}
int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2)
{
int i;
if (oid1 == NULL || oid2 == NULL) {
return SC_ERROR_INVALID_ARGUMENTS;
}
for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) {
if (oid1->value[i] != oid2->value[i])
return 0;
if (oid1->value[i] == -1)
break;
}
return 1;
}
int sc_valid_oid(const struct sc_object_id *oid)
{
int ii;
if (!oid)
return 0;
if (oid->value[0] == -1 || oid->value[1] == -1)
return 0;
if (oid->value[0] > 2 || oid->value[1] > 39)
return 0;
for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++)
if (oid->value[ii])
break;
if (ii==SC_MAX_OBJECT_ID_OCTETS)
return 0;
return 1;
}
int sc_detect_card_presence(sc_reader_t *reader)
{
int r;
LOG_FUNC_CALLED(reader->ctx);
if (reader->ops->detect_card_presence == NULL)
LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED);
r = reader->ops->detect_card_presence(reader);
LOG_FUNC_RETURN(reader->ctx, r);
}
int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len,
int idx, int count)
{
if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(path, 0, sizeof(*path));
memcpy(path->value, id, id_len);
path->len = id_len;
path->type = type;
path->index = idx;
path->count = count;
return SC_SUCCESS;
}
void sc_format_path(const char *str, sc_path_t *path)
{
int type = SC_PATH_TYPE_PATH;
if (path) {
memset(path, 0, sizeof(*path));
if (*str == 'i' || *str == 'I') {
type = SC_PATH_TYPE_FILE_ID;
str++;
}
path->len = sizeof(path->value);
if (sc_hex_to_bin(str, path->value, &path->len) >= 0) {
path->type = type;
}
path->count = -1;
}
}
int sc_append_path(sc_path_t *dest, const sc_path_t *src)
{
return sc_concatenate_path(dest, dest, src);
}
int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen)
{
if (dest->len + idlen > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(dest->value + dest->len, id, idlen);
dest->len += idlen;
return SC_SUCCESS;
}
int sc_append_file_id(sc_path_t *dest, unsigned int fid)
{
u8 id[2] = { fid >> 8, fid & 0xff };
return sc_append_path_id(dest, id, 2);
}
int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2)
{
sc_path_t tpath;
if (d == NULL || p1 == NULL || p2 == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME)
/* we do not support concatenation of AIDs at the moment */
return SC_ERROR_NOT_SUPPORTED;
if (p1->len + p2->len > SC_MAX_PATH_SIZE)
return SC_ERROR_INVALID_ARGUMENTS;
memset(&tpath, 0, sizeof(sc_path_t));
memcpy(tpath.value, p1->value, p1->len);
memcpy(tpath.value + p1->len, p2->value, p2->len);
tpath.len = p1->len + p2->len;
tpath.type = SC_PATH_TYPE_PATH;
/* use 'index' and 'count' entry of the second path object */
tpath.index = p2->index;
tpath.count = p2->count;
/* the result is currently always as path */
tpath.type = SC_PATH_TYPE_PATH;
*d = tpath;
return SC_SUCCESS;
}
const char *sc_print_path(const sc_path_t *path)
{
static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE];
if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS)
buffer[0] = '\0';
return buffer;
}
int sc_path_print(char *buf, size_t buflen, const sc_path_t *path)
{
size_t i;
if (buf == NULL || path == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (buflen < path->len * 2 + path->aid.len * 2 + 1)
return SC_ERROR_BUFFER_TOO_SMALL;
buf[0] = '\0';
if (path->aid.len) {
for (i = 0; i < path->aid.len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]);
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
}
for (i = 0; i < path->len; i++)
snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]);
if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME)
snprintf(buf + strlen(buf), buflen - strlen(buf), "::");
return SC_SUCCESS;
}
int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2)
{
return path1->len == path2->len
&& !memcmp(path1->value, path2->value, path1->len);
}
int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path)
{
sc_path_t tpath;
if (prefix->len > path->len)
return 0;
tpath = *path;
tpath.len = prefix->len;
return sc_compare_path(&tpath, prefix);
}
const sc_path_t *sc_get_mf_path(void)
{
static const sc_path_t mf_path = {
{0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2,
0,
0,
SC_PATH_TYPE_PATH,
{{0},0}
};
return &mf_path;
}
int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation,
unsigned int method, unsigned long key_ref)
{
sc_acl_entry_t *p, *_new;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return SC_ERROR_INVALID_ARGUMENTS;
}
switch (method) {
case SC_AC_NEVER:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 1;
return SC_SUCCESS;
case SC_AC_NONE:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 2;
return SC_SUCCESS;
case SC_AC_UNKNOWN:
sc_file_clear_acl_entries(file, operation);
file->acl[operation] = (sc_acl_entry_t *) 3;
return SC_SUCCESS;
default:
/* NONE and UNKNOWN get zapped when a new AC is added.
* If the ACL is NEVER, additional entries will be
* dropped silently. */
if (file->acl[operation] == (sc_acl_entry_t *) 1)
return SC_SUCCESS;
if (file->acl[operation] == (sc_acl_entry_t *) 2
|| file->acl[operation] == (sc_acl_entry_t *) 3)
file->acl[operation] = NULL;
}
/* If the entry is already present (e.g. due to the mapping)
* of the card's AC with OpenSC's), don't add it again. */
for (p = file->acl[operation]; p != NULL; p = p->next) {
if ((p->method == method) && (p->key_ref == key_ref))
return SC_SUCCESS;
}
_new = malloc(sizeof(sc_acl_entry_t));
if (_new == NULL)
return SC_ERROR_OUT_OF_MEMORY;
_new->method = method;
_new->key_ref = key_ref;
_new->next = NULL;
p = file->acl[operation];
if (p == NULL) {
file->acl[operation] = _new;
return SC_SUCCESS;
}
while (p->next != NULL)
p = p->next;
p->next = _new;
return SC_SUCCESS;
}
const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file,
unsigned int operation)
{
sc_acl_entry_t *p;
static const sc_acl_entry_t e_never = {
SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_none = {
SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
static const sc_acl_entry_t e_unknown = {
SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL
};
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return NULL;
}
p = file->acl[operation];
if (p == (sc_acl_entry_t *) 1)
return &e_never;
if (p == (sc_acl_entry_t *) 2)
return &e_none;
if (p == (sc_acl_entry_t *) 3)
return &e_unknown;
return file->acl[operation];
}
void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation)
{
sc_acl_entry_t *e;
if (file == NULL || operation >= SC_MAX_AC_OPS) {
return;
}
e = file->acl[operation];
if (e == (sc_acl_entry_t *) 1 ||
e == (sc_acl_entry_t *) 2 ||
e == (sc_acl_entry_t *) 3) {
file->acl[operation] = NULL;
return;
}
while (e != NULL) {
sc_acl_entry_t *tmp = e->next;
free(e);
e = tmp;
}
file->acl[operation] = NULL;
}
sc_file_t * sc_file_new(void)
{
sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t));
if (file == NULL)
return NULL;
file->magic = SC_FILE_MAGIC;
return file;
}
void sc_file_free(sc_file_t *file)
{
unsigned int i;
if (file == NULL || !sc_file_valid(file))
return;
file->magic = 0;
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_clear_acl_entries(file, i);
if (file->sec_attr)
free(file->sec_attr);
if (file->prop_attr)
free(file->prop_attr);
if (file->type_attr)
free(file->type_attr);
if (file->encoded_content)
free(file->encoded_content);
free(file);
}
void sc_file_dup(sc_file_t **dest, const sc_file_t *src)
{
sc_file_t *newf;
const sc_acl_entry_t *e;
unsigned int op;
*dest = NULL;
if (!sc_file_valid(src))
return;
newf = sc_file_new();
if (newf == NULL)
return;
*dest = newf;
memcpy(&newf->path, &src->path, sizeof(struct sc_path));
memcpy(&newf->name, &src->name, sizeof(src->name));
newf->namelen = src->namelen;
newf->type = src->type;
newf->shareable = src->shareable;
newf->ef_structure = src->ef_structure;
newf->size = src->size;
newf->id = src->id;
newf->status = src->status;
for (op = 0; op < SC_MAX_AC_OPS; op++) {
newf->acl[op] = NULL;
e = sc_file_get_acl_entry(src, op);
if (e != NULL) {
if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0)
goto err;
}
}
newf->record_length = src->record_length;
newf->record_count = src->record_count;
if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0)
goto err;
if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0)
goto err;
if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0)
goto err;
if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0)
goto err;
return;
err:
sc_file_free(newf);
*dest = NULL;
}
int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL || sec_attr_len) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr,
size_t prop_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (prop_attr == NULL) {
if (file->prop_attr != NULL)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->prop_attr, prop_attr_len);
if (!tmp) {
if (file->prop_attr)
free(file->prop_attr);
file->prop_attr = NULL;
file->prop_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->prop_attr = tmp;
memcpy(file->prop_attr, prop_attr, prop_attr_len);
file->prop_attr_len = prop_attr_len;
return SC_SUCCESS;
}
int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr,
size_t type_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (type_attr == NULL) {
if (file->type_attr != NULL)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->type_attr, type_attr_len);
if (!tmp) {
if (file->type_attr)
free(file->type_attr);
file->type_attr = NULL;
file->type_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->type_attr = tmp;
memcpy(file->type_attr, type_attr, type_attr_len);
file->type_attr_len = type_attr_len;
return SC_SUCCESS;
}
int sc_file_set_content(sc_file_t *file, const u8 *content,
size_t content_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (content == NULL) {
if (file->encoded_content != NULL)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_SUCCESS;
}
tmp = (u8 *) realloc(file->encoded_content, content_len);
if (!tmp) {
if (file->encoded_content)
free(file->encoded_content);
file->encoded_content = NULL;
file->encoded_content_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->encoded_content = tmp;
memcpy(file->encoded_content, content, content_len);
file->encoded_content_len = content_len;
return SC_SUCCESS;
}
int sc_file_valid(const sc_file_t *file) {
if (file == NULL)
return 0;
return file->magic == SC_FILE_MAGIC;
}
int _sc_parse_atr(sc_reader_t *reader)
{
u8 *p = reader->atr.value;
int atr_len = (int) reader->atr.len;
int n_hist, x;
int tx[4] = {-1, -1, -1, -1};
int i, FI, DI;
const int Fi_table[] = {
372, 372, 558, 744, 1116, 1488, 1860, -1,
-1, 512, 768, 1024, 1536, 2048, -1, -1 };
const int f_table[] = {
40, 50, 60, 80, 120, 160, 200, -1,
-1, 50, 75, 100, 150, 200, -1, -1 };
const int Di_table[] = {
-1, 1, 2, 4, 8, 16, 32, -1,
12, 20, -1, -1, -1, -1, -1, -1 };
reader->atr_info.hist_bytes_len = 0;
reader->atr_info.hist_bytes = NULL;
if (atr_len == 0) {
sc_log(reader->ctx, "empty ATR - card not present?\n");
return SC_ERROR_INTERNAL;
}
if (p[0] != 0x3B && p[0] != 0x3F) {
sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]);
return SC_ERROR_INTERNAL;
}
n_hist = p[1] & 0x0F;
x = p[1] >> 4;
p += 2;
atr_len -= 2;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
if (tx[0] >= 0) {
reader->atr_info.FI = FI = tx[0] >> 4;
reader->atr_info.DI = DI = tx[0] & 0x0F;
reader->atr_info.Fi = Fi_table[FI];
reader->atr_info.f = f_table[FI];
reader->atr_info.Di = Di_table[DI];
} else {
reader->atr_info.Fi = -1;
reader->atr_info.f = -1;
reader->atr_info.Di = -1;
}
if (tx[2] >= 0)
reader->atr_info.N = tx[3];
else
reader->atr_info.N = -1;
while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) {
x = tx[3] >> 4;
for (i = 0; i < 4 && atr_len > 0; i++) {
if (x & (1 << i)) {
tx[i] = *p;
p++;
atr_len--;
} else
tx[i] = -1;
}
}
if (atr_len <= 0)
return SC_SUCCESS;
if (n_hist > atr_len)
n_hist = atr_len;
reader->atr_info.hist_bytes_len = n_hist;
reader->atr_info.hist_bytes = p;
return SC_SUCCESS;
}
void sc_mem_clear(void *ptr, size_t len)
{
if (len > 0) {
#ifdef ENABLE_OPENSSL
OPENSSL_cleanse(ptr, len);
#else
memset(ptr, 0, len);
#endif
}
}
int sc_mem_reverse(unsigned char *buf, size_t len)
{
unsigned char ch;
size_t ii;
if (!buf || !len)
return SC_ERROR_INVALID_ARGUMENTS;
for (ii = 0; ii < len / 2; ii++) {
ch = *(buf + ii);
*(buf + ii) = *(buf + len - 1 - ii);
*(buf + len - 1 - ii) = ch;
}
return SC_SUCCESS;
}
static int
sc_remote_apdu_allocate(struct sc_remote_data *rdata,
struct sc_remote_apdu **new_rapdu)
{
struct sc_remote_apdu *rapdu = NULL, *rr;
if (!rdata)
return SC_ERROR_INVALID_ARGUMENTS;
rapdu = calloc(1, sizeof(struct sc_remote_apdu));
if (rapdu == NULL)
return SC_ERROR_OUT_OF_MEMORY;
rapdu->apdu.data = &rapdu->sbuf[0];
rapdu->apdu.resp = &rapdu->rbuf[0];
rapdu->apdu.resplen = sizeof(rapdu->rbuf);
if (new_rapdu)
*new_rapdu = rapdu;
if (rdata->data == NULL) {
rdata->data = rapdu;
rdata->length = 1;
return SC_SUCCESS;
}
for (rr = rdata->data; rr->next; rr = rr->next)
;
rr->next = rapdu;
rdata->length++;
return SC_SUCCESS;
}
static void
sc_remote_apdu_free (struct sc_remote_data *rdata)
{
struct sc_remote_apdu *rapdu = NULL;
if (!rdata)
return;
rapdu = rdata->data;
while(rapdu) {
struct sc_remote_apdu *rr = rapdu->next;
free(rapdu);
rapdu = rr;
}
}
void sc_remote_data_init(struct sc_remote_data *rdata)
{
if (!rdata)
return;
memset(rdata, 0, sizeof(struct sc_remote_data));
rdata->alloc = sc_remote_apdu_allocate;
rdata->free = sc_remote_apdu_free;
}
static unsigned long sc_CRC_tab32[256];
static int sc_CRC_tab32_initialized = 0;
unsigned sc_crc32(const unsigned char *value, size_t len)
{
size_t ii, jj;
unsigned long crc;
unsigned long index, long_c;
if (!sc_CRC_tab32_initialized) {
for (ii=0; ii<256; ii++) {
crc = (unsigned long) ii;
for (jj=0; jj<8; jj++) {
if ( crc & 0x00000001L )
crc = ( crc >> 1 ) ^ 0xEDB88320l;
else
crc = crc >> 1;
}
sc_CRC_tab32[ii] = crc;
}
sc_CRC_tab32_initialized = 1;
}
crc = 0xffffffffL;
for (ii=0; ii<len; ii++) {
long_c = 0x000000ffL & (unsigned long) (*(value + ii));
index = crc ^ long_c;
crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ];
}
crc ^= 0xffffffff;
return crc%0xffff;
}
const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen)
{
if (buf != NULL) {
size_t idx;
u8 plain_tag = tag & 0xF0;
size_t expected_len = tag & 0x0F;
for (idx = 0; idx < len; idx++) {
if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len &&
(expected_len == 0 || expected_len == (buf[idx] & 0x0F))) {
if (outlen != NULL)
*outlen = buf[idx] & 0x0F;
return buf + (idx + 1);
}
idx += (buf[idx] & 0x0F);
}
}
return NULL;
}
/**************************** mutex functions ************************/
int sc_mutex_create(const sc_context_t *ctx, void **mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL)
return ctx->thread_ctx->create_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_lock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL)
return ctx->thread_ctx->lock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_unlock(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL)
return ctx->thread_ctx->unlock_mutex(mutex);
else
return SC_SUCCESS;
}
int sc_mutex_destroy(const sc_context_t *ctx, void *mutex)
{
if (ctx == NULL)
return SC_ERROR_INVALID_ARGUMENTS;
if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL)
return ctx->thread_ctx->destroy_mutex(mutex);
else
return SC_SUCCESS;
}
unsigned long sc_thread_id(const sc_context_t *ctx)
{
if (ctx == NULL || ctx->thread_ctx == NULL ||
ctx->thread_ctx->thread_id == NULL)
return 0UL;
else
return ctx->thread_ctx->thread_id();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_340_7 |
crossvul-cpp_data_good_639_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <rasmus@php.net> |
| Jim Winstead <jimw@php.net> |
| Hartmut Holzgraefe <hholzgra@php.net> |
| Wez Furlong <wez@thebrainroom.com> |
| Sara Golemon <pollita@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "php_globals.h"
#include "php_streams.h"
#include "php_network.h"
#include "php_ini.h"
#include "ext/standard/basic_functions.h"
#include "ext/standard/php_smart_str.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef PHP_WIN32
#define O_RDONLY _O_RDONLY
#include "win32/param.h"
#else
#include <sys/param.h>
#endif
#include "php_standard.h"
#include <sys/types.h>
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef PHP_WIN32
#include <winsock2.h>
#elif defined(NETWARE) && defined(USE_WINSOCK)
#include <novsock2.h>
#else
#include <netinet/in.h>
#include <netdb.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#endif
#if defined(PHP_WIN32) || defined(__riscos__) || defined(NETWARE)
#undef AF_UNIX
#endif
#if defined(AF_UNIX)
#include <sys/un.h>
#endif
#include "php_fopen_wrappers.h"
#define HTTP_HEADER_BLOCK_SIZE 1024
#define PHP_URL_REDIRECT_MAX 20
#define HTTP_HEADER_USER_AGENT 1
#define HTTP_HEADER_HOST 2
#define HTTP_HEADER_AUTH 4
#define HTTP_HEADER_FROM 8
#define HTTP_HEADER_CONTENT_LENGTH 16
#define HTTP_HEADER_TYPE 32
#define HTTP_HEADER_CONNECTION 64
#define HTTP_WRAPPER_HEADER_INIT 1
#define HTTP_WRAPPER_REDIRECTED 2
static inline void strip_header(char *header_bag, char *lc_header_bag,
const char *lc_header_name)
{
char *lc_header_start = strstr(lc_header_bag, lc_header_name);
char *header_start = header_bag + (lc_header_start - lc_header_bag);
if (lc_header_start
&& (lc_header_start == lc_header_bag || *(lc_header_start-1) == '\n')
) {
char *lc_eol = strchr(lc_header_start, '\n');
char *eol = header_start + (lc_eol - lc_header_start);
if (lc_eol) {
size_t eollen = strlen(lc_eol);
memmove(lc_header_start, lc_eol+1, eollen);
memmove(header_start, eol+1, eollen);
} else {
*lc_header_start = '\0';
*header_start = '\0';
}
}
}
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
const char *path, const char *mode, int options, char **opened_path,
php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */
{
php_stream *stream = NULL;
php_url *resource = NULL;
int use_ssl;
int use_proxy = 0;
char *scratch = NULL;
char *tmp = NULL;
char *ua_str = NULL;
zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL;
int scratch_len = 0;
int body = 0;
char location[HTTP_HEADER_BLOCK_SIZE];
zval *response_header = NULL;
int reqok = 0;
char *http_header_line = NULL;
char tmp_line[128];
size_t chunk_size = 0, file_size = 0;
int eol_detect = 0;
char *transport_string, *errstr = NULL;
int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0;
char *protocol_version = NULL;
int protocol_version_len = 3; /* Default: "1.0" */
struct timeval timeout;
char *user_headers = NULL;
int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);
int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);
int follow_location = 1;
php_stream_filter *transfer_encoding = NULL;
int response_code;
tmp_line[0] = '\0';
if (redirect_max < 1) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting");
return NULL;
}
resource = php_url_parse(path);
if (resource == NULL) {
return NULL;
}
if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) {
if (!context ||
php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE ||
Z_TYPE_PP(tmpzval) != IS_STRING ||
Z_STRLEN_PP(tmpzval) <= 0) {
php_url_free(resource);
return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context);
}
/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */
request_fulluri = 1;
use_ssl = 0;
use_proxy = 1;
transport_len = Z_STRLEN_PP(tmpzval);
transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
/* Normal http request (possibly with proxy) */
if (strpbrk(mode, "awx+")) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections");
php_url_free(resource);
return NULL;
}
use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';
/* choose default ports */
if (use_ssl && resource->port == 0)
resource->port = 443;
else if (resource->port == 0)
resource->port = 80;
if (context &&
php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING &&
Z_STRLEN_PP(tmpzval) > 0) {
use_proxy = 1;
transport_len = Z_STRLEN_PP(tmpzval);
transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port);
}
}
if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_double_ex(tmpzval);
timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval);
timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000);
} else {
timeout.tv_sec = FG(default_socket_timeout);
timeout.tv_usec = 0;
}
stream = php_stream_xport_create(transport_string, transport_len, options,
STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
NULL, &timeout, context, &errstr, NULL);
if (stream) {
php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);
}
if (errstr) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr);
efree(errstr);
errstr = NULL;
}
efree(transport_string);
if (stream && use_proxy && use_ssl) {
smart_str header = {0};
/* Set peer_name or name verification will try to use the proxy server name */
if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) {
MAKE_STD_ZVAL(ssl_proxy_peer_name);
ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1);
php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name);
}
smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1);
smart_str_appends(&header, resource->host);
smart_str_appendc(&header, ':');
smart_str_append_unsigned(&header, resource->port);
smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1);
/* check if we have Proxy-Authorization header */
if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
char *s, *p;
if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
HashPosition pos;
zval **tmpheader = NULL;
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) {
if (Z_TYPE_PP(tmpheader) == IS_STRING) {
s = Z_STRVAL_PP(tmpheader);
do {
while (*s == ' ' || *s == '\t') s++;
p = s;
while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
if (*p == ':') {
p++;
if (p - s == sizeof("Proxy-Authorization:") - 1 &&
zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
"Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
smart_str_appendl(&header, s, p - s);
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
goto finish;
} else {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
}
}
s = p;
while (*s == '\r' || *s == '\n') s++;
} while (*s != 0);
}
}
} else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
s = Z_STRVAL_PP(tmpzval);
do {
while (*s == ' ' || *s == '\t') s++;
p = s;
while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
if (*p == ':') {
p++;
if (p - s == sizeof("Proxy-Authorization:") - 1 &&
zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
"Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
smart_str_appendl(&header, s, p - s);
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
goto finish;
} else {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
}
}
s = p;
while (*s == '\r' || *s == '\n') s++;
} while (*s != 0);
}
}
finish:
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
if (php_stream_write(stream, header.c, header.len) != header.len) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
php_stream_close(stream);
stream = NULL;
}
smart_str_free(&header);
if (stream) {
char header_line[HTTP_HEADER_BLOCK_SIZE];
/* get response header */
while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) {
if (header_line[0] == '\n' ||
header_line[0] == '\r' ||
header_line[0] == '\0') {
break;
}
}
}
/* enable SSL transport layer */
if (stream) {
if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 ||
php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
php_stream_close(stream);
stream = NULL;
}
}
}
if (stream == NULL)
goto out;
/* avoid buffering issues while reading header */
if (options & STREAM_WILL_CAST)
chunk_size = php_stream_set_chunk_size(stream, 1);
/* avoid problems with auto-detecting when reading the headers -> the headers
* are always in canonical \r\n format */
eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
php_stream_context_set(stream, context);
php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);
if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_long_ex(tmpzval);
redirect_max = Z_LVAL_PP(tmpzval);
}
if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
/* As per the RFC, automatically redirected requests MUST NOT use other methods than
* GET and HEAD unless it can be confirmed by the user */
if (!redirected
|| (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0)
|| (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0)
) {
scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);
scratch = emalloc(scratch_len);
strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
strncat(scratch, " ", 1);
}
}
}
if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_double_ex(tmpzval);
protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval));
}
if (!scratch) {
scratch_len = strlen(path) + 29 + protocol_version_len;
scratch = emalloc(scratch_len);
strncpy(scratch, "GET ", scratch_len);
}
/* Should we send the entire path in the request line, default to no. */
if (!request_fulluri &&
context &&
php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) {
zval ztmp = **tmpzval;
zval_copy_ctor(&ztmp);
convert_to_boolean(&ztmp);
request_fulluri = Z_BVAL(ztmp) ? 1 : 0;
zval_dtor(&ztmp);
}
if (request_fulluri) {
/* Ask for everything */
strcat(scratch, path);
} else {
/* Send the traditional /path/to/file?query_string */
/* file */
if (resource->path && *resource->path) {
strlcat(scratch, resource->path, scratch_len);
} else {
strlcat(scratch, "/", scratch_len);
}
/* query string */
if (resource->query) {
strlcat(scratch, "?", scratch_len);
strlcat(scratch, resource->query, scratch_len);
}
}
/* protocol version we are speaking */
if (protocol_version) {
strlcat(scratch, " HTTP/", scratch_len);
strlcat(scratch, protocol_version, scratch_len);
strlcat(scratch, "\r\n", scratch_len);
} else {
strlcat(scratch, " HTTP/1.0\r\n", scratch_len);
}
/* send it */
php_stream_write(stream, scratch, strlen(scratch));
if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
tmp = NULL;
if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
HashPosition pos;
zval **tmpheader = NULL;
smart_str tmpstr = {0};
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)
) {
if (Z_TYPE_PP(tmpheader) == IS_STRING) {
smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader));
smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1);
}
}
smart_str_0(&tmpstr);
/* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */
if (tmpstr.c) {
tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC);
smart_str_free(&tmpstr);
}
}
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
/* Remove newlines and spaces from start and end php_trim will estrndup() */
tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);
}
if (tmp && strlen(tmp) > 0) {
char *s;
user_headers = estrdup(tmp);
/* Make lowercase for easy comparison against 'standard' headers */
php_strtolower(tmp, strlen(tmp));
if (!header_init) {
/* strip POST headers on redirect */
strip_header(user_headers, tmp, "content-length:");
strip_header(user_headers, tmp, "content-type:");
}
if ((s = strstr(tmp, "user-agent:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_USER_AGENT;
}
if ((s = strstr(tmp, "host:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_HOST;
}
if ((s = strstr(tmp, "from:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_FROM;
}
if ((s = strstr(tmp, "authorization:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_AUTH;
}
if ((s = strstr(tmp, "content-length:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
if ((s = strstr(tmp, "content-type:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_TYPE;
}
if ((s = strstr(tmp, "connection:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_CONNECTION;
}
/* remove Proxy-Authorization header */
if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
char *p = s + sizeof("proxy-authorization:") - 1;
while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--;
while (*p != 0 && *p != '\r' && *p != '\n') p++;
while (*p == '\r' || *p == '\n') p++;
if (*p == 0) {
if (s == tmp) {
efree(user_headers);
user_headers = NULL;
} else {
while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--;
user_headers[s - tmp] = 0;
}
} else {
memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1);
}
}
}
if (tmp) {
efree(tmp);
}
}
/* auth header if it was specified */
if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) {
/* decode the strings first */
php_url_decode(resource->user, strlen(resource->user));
/* scratch is large enough, since it was made large enough for the whole URL */
strcpy(scratch, resource->user);
strcat(scratch, ":");
/* Note: password is optional! */
if (resource->pass) {
php_url_decode(resource->pass, strlen(resource->pass));
strcat(scratch, resource->pass);
}
tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);
if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) {
php_stream_write(stream, scratch, strlen(scratch));
php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
}
efree(tmp);
tmp = NULL;
}
/* if the user has configured who they are, send a From: line */
if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) {
if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0)
php_stream_write(stream, scratch, strlen(scratch));
}
/* Send Host: header so name-based virtual hosts work */
if ((have_header & HTTP_HEADER_HOST) == 0) {
if ((use_ssl && resource->port != 443 && resource->port != 0) ||
(!use_ssl && resource->port != 80 && resource->port != 0)) {
if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0)
php_stream_write(stream, scratch, strlen(scratch));
} else {
if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) {
php_stream_write(stream, scratch, strlen(scratch));
}
}
}
/* Send a Connection: close header to avoid hanging when the server
* interprets the RFC literally and establishes a keep-alive connection,
* unless the user specifically requests something else by specifying a
* Connection header in the context options. Send that header even for
* HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1
* keep-alive response, which is the preferred response type. */
if ((have_header & HTTP_HEADER_CONNECTION) == 0) {
php_stream_write_string(stream, "Connection: close\r\n");
}
if (context &&
php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS &&
Z_TYPE_PP(ua_zval) == IS_STRING) {
ua_str = Z_STRVAL_PP(ua_zval);
} else if (FG(user_agent)) {
ua_str = FG(user_agent);
}
if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {
#define _UA_HEADER "User-Agent: %s\r\n"
char *ua;
size_t ua_len;
ua_len = sizeof(_UA_HEADER) + strlen(ua_str);
/* ensure the header is only sent if user_agent is not blank */
if (ua_len > sizeof(_UA_HEADER)) {
ua = emalloc(ua_len + 1);
if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
ua[ua_len] = 0;
php_stream_write(stream, ua, ua_len);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header");
}
if (ua) {
efree(ua);
}
}
}
if (user_headers) {
/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST
* see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
*/
if (
header_init &&
context &&
!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0
) {
scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
php_stream_write(stream, scratch, scratch_len);
have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
php_stream_write(stream, user_headers, strlen(user_headers));
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
efree(user_headers);
}
/* Request content, such as for POST requests */
if (header_init && context &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
php_stream_write(stream, scratch, scratch_len);
}
if (!(have_header & HTTP_HEADER_TYPE)) {
php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n",
sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1);
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded");
}
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
}
location[0] = '\0';
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (header_init) {
zval *ztmp;
MAKE_STD_ZVAL(ztmp);
array_init(ztmp);
ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp);
}
{
zval **rh;
if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten");
goto out;
}
response_header = *rh;
Z_ADDREF_P(response_header);
}
if (!php_stream_eof(stream)) {
size_t tmp_line_len;
/* get response header */
if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {
zval *http_response;
if (tmp_line_len > 9) {
response_code = atoi(tmp_line + 9);
} else {
response_code = 0;
}
if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) {
ignore_errors = zend_is_true(*tmpzval);
}
/* when we request only the header, don't fail even on error codes */
if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) {
reqok = 1;
}
/* status codes of 1xx are "informational", and will be followed by a real response
* e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed,
* and MAY be ignored. As such, we need to skip ahead to the "real" status*/
if (response_code >= 100 && response_code < 200) {
/* consume lines until we find a line starting 'HTTP/1' */
while (
!php_stream_eof(stream)
&& php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL
&& ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) )
);
if (tmp_line_len > 9) {
response_code = atoi(tmp_line + 9);
} else {
response_code = 0;
}
}
/* all status codes in the 2xx range are defined by the specification as successful;
* all status codes in the 3xx range are for redirection, and so also should never
* fail */
if (response_code >= 200 && response_code < 400) {
reqok = 1;
} else {
switch(response_code) {
case 403:
php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
tmp_line, response_code);
break;
default:
/* safety net in the event tmp_line == NULL */
if (!tmp_line_len) {
tmp_line[0] = '\0';
}
php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
tmp_line, response_code);
}
}
if (tmp_line_len >= 1 && tmp_line[tmp_line_len - 1] == '\n') {
--tmp_line_len;
if (tmp_line_len >= 1 &&tmp_line[tmp_line_len - 1] == '\r') {
--tmp_line_len;
}
}
MAKE_STD_ZVAL(http_response);
ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);
}
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!");
goto out;
}
/* read past HTTP headers */
http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);
while (!body && !php_stream_eof(stream)) {
size_t http_header_line_length;
if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') {
char *e = http_header_line + http_header_line_length - 1;
if (*e != '\n') {
do { /* partial header */
if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers");
goto out;
}
e = http_header_line + http_header_line_length - 1;
} while (*e != '\n');
continue;
}
while (*e == '\n' || *e == '\r') {
e--;
}
http_header_line_length = e - http_header_line + 1;
http_header_line[http_header_line_length] = '\0';
if (!strncasecmp(http_header_line, "Location: ", 10)) {
if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_long_ex(tmpzval);
follow_location = Z_LVAL_PP(tmpzval);
} else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) {
/* we shouldn't redirect automatically
if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307)
see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1
RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */
follow_location = 0;
}
strlcpy(location, http_header_line + 10, sizeof(location));
} else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
} else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
file_size = atoi(http_header_line + 16);
php_stream_notify_file_size(context, file_size, http_header_line, 0);
} else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) {
/* create filter to decode response body */
if (!(options & STREAM_ONLY_GET_HEADERS)) {
long decode = 1;
if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_boolean(*tmpzval);
decode = Z_LVAL_PP(tmpzval);
}
if (decode) {
transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC);
if (transfer_encoding) {
/* don't store transfer-encodeing header */
continue;
}
}
}
}
if (http_header_line[0] == '\0') {
body = 1;
} else {
zval *http_header;
MAKE_STD_ZVAL(http_header);
ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
}
} else {
break;
}
}
if (!reqok || (location[0] != '\0' && follow_location)) {
if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
goto out;
}
if (location[0] != '\0')
php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);
php_stream_close(stream);
stream = NULL;
if (location[0] != '\0') {
char new_path[HTTP_HEADER_BLOCK_SIZE];
char loc_path[HTTP_HEADER_BLOCK_SIZE];
*new_path='\0';
if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
strncasecmp(location, "https://", sizeof("https://")-1) &&
strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
{
if (*location != '/') {
if (*(location+1) != '\0' && resource->path) {
char *s = strrchr(resource->path, '/');
if (!s) {
s = resource->path;
if (!s[0]) {
efree(s);
s = resource->path = estrdup("/");
} else {
*s = '/';
}
}
s[1] = '\0';
if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
} else {
snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
}
} else {
snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
}
} else {
strlcpy(loc_path, location, sizeof(loc_path));
}
if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
} else {
snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
}
} else {
strlcpy(new_path, location, sizeof(new_path));
}
php_url_free(resource);
/* check for invalid redirection URLs */
if ((resource = php_url_parse(new_path)) == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);
goto out;
}
#define CHECK_FOR_CNTRL_CHARS(val) { \
if (val) { \
unsigned char *s, *e; \
int l; \
l = php_url_decode(val, strlen(val)); \
s = (unsigned char*)val; e = s + l; \
while (s < e) { \
if (iscntrl(*s)) { \
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \
goto out; \
} \
s++; \
} \
} \
}
/* check for control characters in login, password & path */
if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
CHECK_FOR_CNTRL_CHARS(resource->user)
CHECK_FOR_CNTRL_CHARS(resource->pass)
CHECK_FOR_CNTRL_CHARS(resource->path)
}
stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC);
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line);
}
}
out:
if (protocol_version) {
efree(protocol_version);
}
if (http_header_line) {
efree(http_header_line);
}
if (scratch) {
efree(scratch);
}
if (resource) {
php_url_free(resource);
}
if (stream) {
if (header_init) {
stream->wrapperdata = response_header;
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
}
php_stream_notify_progress_init(context, 0, file_size);
/* Restore original chunk size now that we're done with headers */
if (options & STREAM_WILL_CAST)
php_stream_set_chunk_size(stream, chunk_size);
/* restore the users auto-detect-line-endings setting */
stream->flags |= eol_detect;
/* as far as streams are concerned, we are now at the start of
* the stream */
stream->position = 0;
/* restore mode */
strlcpy(stream->mode, mode, sizeof(stream->mode));
if (transfer_encoding) {
php_stream_filter_append(&stream->readfilters, transfer_encoding);
}
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
if (transfer_encoding) {
php_stream_filter_free(transfer_encoding TSRMLS_CC);
}
}
return stream;
}
/* }}} */
php_stream *php_stream_url_wrap_http(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) /* {{{ */
{
return php_stream_url_wrap_http_ex(wrapper, path, mode, options, opened_path, context, PHP_URL_REDIRECT_MAX, HTTP_WRAPPER_HEADER_INIT STREAMS_CC TSRMLS_CC);
}
/* }}} */
static int php_stream_http_stream_stat(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
{
/* one day, we could fill in the details based on Date: and Content-Length:
* headers. For now, we return with a failure code to prevent the underlying
* file's details from being used instead. */
return -1;
}
/* }}} */
static php_stream_wrapper_ops http_stream_wops = {
php_stream_url_wrap_http,
NULL, /* stream_close */
php_stream_http_stream_stat,
NULL, /* stat_url */
NULL, /* opendir */
"http",
NULL, /* unlink */
NULL, /* rename */
NULL, /* mkdir */
NULL /* rmdir */
};
PHPAPI php_stream_wrapper php_stream_http_wrapper = {
&http_stream_wops,
NULL,
1 /* is_url */
};
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_639_0 |
crossvul-cpp_data_good_4865_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
* Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR
* Copyright (c) 2012, CS Systemes d'Information, France
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
#include "opj_common.h"
/* ----------------------------------------------------------------------- */
/* TODO MSD: */
#ifdef TODO_MSD
void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img)
{
int tileno, compno, resno, bandno, precno;/*, cblkno;*/
fprintf(fd, "image {\n");
fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n",
img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0,
tcd->image->y1);
for (tileno = 0; tileno < img->th * img->tw; tileno++) {
opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno];
fprintf(fd, " tile {\n");
fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n",
tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps);
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
fprintf(fd, " tilec {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n",
tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions);
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
fprintf(fd, "\n res {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n",
res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands);
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
fprintf(fd, " band {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n",
band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps);
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
fprintf(fd, " prec {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n",
prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch);
/*
for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) {
opj_tcd_cblk_t *cblk = &prec->cblks[cblkno];
fprintf(fd, " cblk {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d\n",
cblk->x0, cblk->y0, cblk->x1, cblk->y1);
fprintf(fd, " }\n");
}
*/
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, "}\n");
}
#endif
/**
* Initializes tile coding/decoding
*/
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
opj_event_mgr_t* manager);
/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
p_code_block);
/**
* Deallocates the decoding data of the given precinct.
*/
static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct);
/**
* Allocates memory for an encoding code block (but not data).
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
p_code_block);
/**
* Allocates data for an encoding code block
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block);
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct);
/**
Free the memory allocated for encoding
@param tcd TCD handle
*/
static void opj_tcd_free_tile(opj_tcd_t *tcd);
static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_src_size,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info);
static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info);
/* ----------------------------------------------------------------------- */
/**
Create a new TCD handle
*/
opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder)
{
opj_tcd_t *l_tcd = 00;
/* create the tcd structure */
l_tcd = (opj_tcd_t*) opj_calloc(1, sizeof(opj_tcd_t));
if (!l_tcd) {
return 00;
}
l_tcd->m_is_decoder = p_is_decoder ? 1 : 0;
l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1, sizeof(opj_tcd_image_t));
if (!l_tcd->tcd_image) {
opj_free(l_tcd);
return 00;
}
return l_tcd;
}
/* ----------------------------------------------------------------------- */
void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd)
{
OPJ_UINT32 layno;
for (layno = 0; layno < tcd->tcp->numlayers; layno++) {
opj_tcd_makelayer_fixed(tcd, layno, 1);
}
}
void opj_tcd_makelayer(opj_tcd_t *tcd,
OPJ_UINT32 layno,
OPJ_FLOAT64 thresh,
OPJ_UINT32 final)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
OPJ_UINT32 passno;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
tcd_tile->distolayer[layno] = 0; /* fixed_quality */
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 n;
if (layno == 0) {
cblk->numpassesinlayers = 0;
}
n = cblk->numpassesinlayers;
for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) {
OPJ_UINT32 dr;
OPJ_FLOAT64 dd;
opj_tcd_pass_t *pass = &cblk->passes[passno];
if (n == 0) {
dr = pass->rate;
dd = pass->distortiondec;
} else {
dr = pass->rate - cblk->passes[n - 1].rate;
dd = pass->distortiondec - cblk->passes[n - 1].distortiondec;
}
if (!dr) {
if (dd != 0) {
n = passno + 1;
}
continue;
}
if (thresh - (dd / dr) <
DBL_EPSILON) { /* do not rely on float equality, check with DBL_EPSILON margin */
n = passno + 1;
}
}
layer->numpasses = n - cblk->numpassesinlayers;
if (!layer->numpasses) {
layer->disto = 0;
continue;
}
if (cblk->numpassesinlayers == 0) {
layer->len = cblk->passes[n - 1].rate;
layer->data = cblk->data;
layer->disto = cblk->passes[n - 1].distortiondec;
} else {
layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers -
1].rate;
layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
layer->disto = cblk->passes[n - 1].distortiondec -
cblk->passes[cblk->numpassesinlayers - 1].distortiondec;
}
tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */
if (final) {
cblk->numpassesinlayers = n;
}
}
}
}
}
}
}
void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno,
OPJ_UINT32 final)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */
OPJ_INT32 matrice[10][10][3];
OPJ_UINT32 i, j, k;
opj_cp_t *cp = tcd->cp;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
opj_tcp_t *tcd_tcp = tcd->tcp;
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
for (i = 0; i < tcd_tcp->numlayers; i++) {
for (j = 0; j < tilec->numresolutions; j++) {
for (k = 0; k < 3; k++) {
matrice[i][j][k] =
(OPJ_INT32)((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i *
tilec->numresolutions * 3 + j * 3 + k]
* (OPJ_FLOAT32)(tcd->image->comps[compno].prec / 16.0));
}
}
}
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 n;
OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec -
cblk->numbps); /* number of bit-plan equal to zero */
/* Correction of the matrix of coefficient to include the IMSB information */
if (layno == 0) {
value = matrice[layno][resno][bandno];
if (imsb >= value) {
value = 0;
} else {
value -= imsb;
}
} else {
value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno];
if (imsb >= matrice[layno - 1][resno][bandno]) {
value -= (imsb - matrice[layno - 1][resno][bandno]);
if (value < 0) {
value = 0;
}
}
}
if (layno == 0) {
cblk->numpassesinlayers = 0;
}
n = cblk->numpassesinlayers;
if (cblk->numpassesinlayers == 0) {
if (value != 0) {
n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers;
} else {
n = cblk->numpassesinlayers;
}
} else {
n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers;
}
layer->numpasses = n - cblk->numpassesinlayers;
if (!layer->numpasses) {
continue;
}
if (cblk->numpassesinlayers == 0) {
layer->len = cblk->passes[n - 1].rate;
layer->data = cblk->data;
} else {
layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers -
1].rate;
layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
}
if (final) {
cblk->numpassesinlayers = n;
}
}
}
}
}
}
}
OPJ_BOOL opj_tcd_rateallocate(opj_tcd_t *tcd,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 len,
opj_codestream_info_t *cstr_info)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno;
OPJ_UINT32 passno;
OPJ_FLOAT64 min, max;
OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */
const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */
OPJ_FLOAT64 maxSE = 0;
opj_cp_t *cp = tcd->cp;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
opj_tcp_t *tcd_tcp = tcd->tcp;
min = DBL_MAX;
max = 0;
tcd_tile->numpix = 0; /* fixed_quality */
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
tilec->numpix = 0;
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
for (passno = 0; passno < cblk->totalpasses; passno++) {
opj_tcd_pass_t *pass = &cblk->passes[passno];
OPJ_INT32 dr;
OPJ_FLOAT64 dd, rdslope;
if (passno == 0) {
dr = (OPJ_INT32)pass->rate;
dd = pass->distortiondec;
} else {
dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate);
dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec;
}
if (dr == 0) {
continue;
}
rdslope = dd / dr;
if (rdslope < min) {
min = rdslope;
}
if (rdslope > max) {
max = rdslope;
}
} /* passno */
/* fixed_quality */
tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
} /* cbklno */
} /* precno */
} /* bandno */
} /* resno */
maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0)
* ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0))
* ((OPJ_FLOAT64)(tilec->numpix));
} /* compno */
/* index file */
if (cstr_info) {
opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno];
tile_info->numpix = tcd_tile->numpix;
tile_info->distotile = tcd_tile->distotile;
tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(
OPJ_FLOAT64));
if (!tile_info->thresh) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
}
for (layno = 0; layno < tcd_tcp->numlayers; layno++) {
OPJ_FLOAT64 lo = min;
OPJ_FLOAT64 hi = max;
OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min(((
OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len;
OPJ_FLOAT64 goodthresh = 0;
OPJ_FLOAT64 stable_thresh = 0;
OPJ_UINT32 i;
OPJ_FLOAT64 distotarget; /* fixed_quality */
/* fixed_quality */
distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10,
tcd_tcp->distoratio[layno] / 10));
/* Don't try to find an optimal threshold but rather take everything not included yet, if
-r xx,yy,zz,0 (disto_alloc == 1 and rates == 0)
-q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0)
==> possible to have some lossy layers and the last layer for sure lossless */
if (((cp->m_specific_param.m_enc.m_disto_alloc == 1) &&
(tcd_tcp->rates[layno] > 0.0f)) ||
((cp->m_specific_param.m_enc.m_fixed_quality == 1) &&
(tcd_tcp->distoratio[layno] > 0.0))) {
opj_t2_t*t2 = opj_t2_create(tcd->image, cp);
OPJ_FLOAT64 thresh = 0;
if (t2 == 00) {
return OPJ_FALSE;
}
for (i = 0; i < 128; ++i) {
OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */
thresh = (lo + hi) / 2;
opj_tcd_makelayer(tcd, layno, thresh, 0);
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */
if (OPJ_IS_CINEMA(cp->rsiz)) {
if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,
THRESH_CALC)) {
lo = thresh;
continue;
} else {
distoachieved = layno == 0 ?
tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];
if (distoachieved < distotarget) {
hi = thresh;
stable_thresh = thresh;
continue;
} else {
lo = thresh;
}
}
} else {
distoachieved = (layno == 0) ?
tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
if (distoachieved < distotarget) {
hi = thresh;
stable_thresh = thresh;
continue;
}
lo = thresh;
}
} else {
if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,
THRESH_CALC)) {
/* TODO: what to do with l ??? seek / tell ??? */
/* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */
lo = thresh;
continue;
}
hi = thresh;
stable_thresh = thresh;
}
}
goodthresh = stable_thresh == 0 ? thresh : stable_thresh;
opj_t2_destroy(t2);
} else {
goodthresh = min;
}
if (cstr_info) { /* Threshold for Marcela Index */
cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh;
}
opj_tcd_makelayer(tcd, layno, goodthresh, 1);
/* fixed_quality */
cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] :
(cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_init(opj_tcd_t *p_tcd,
opj_image_t * p_image,
opj_cp_t * p_cp,
opj_thread_pool_t* p_tp)
{
p_tcd->image = p_image;
p_tcd->cp = p_cp;
p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,
sizeof(opj_tcd_tile_t));
if (! p_tcd->tcd_image->tiles) {
return OPJ_FALSE;
}
p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(
p_image->numcomps, sizeof(opj_tcd_tilecomp_t));
if (! p_tcd->tcd_image->tiles->comps) {
return OPJ_FALSE;
}
p_tcd->tcd_image->tiles->numcomps = p_image->numcomps;
p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos;
p_tcd->thread_pool = p_tp;
return OPJ_TRUE;
}
/**
Destroy a previously created TCD handle
*/
void opj_tcd_destroy(opj_tcd_t *tcd)
{
if (tcd) {
opj_tcd_free_tile(tcd);
if (tcd->tcd_image) {
opj_free(tcd->tcd_image);
tcd->tcd_image = 00;
}
opj_free(tcd);
}
}
OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec)
{
if ((l_tilec->data == 00) ||
((l_tilec->data_size_needed > l_tilec->data_size) &&
(l_tilec->ownsData == OPJ_FALSE))) {
l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed);
if (! l_tilec->data) {
return OPJ_FALSE;
}
/*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/
l_tilec->data_size = l_tilec->data_size_needed;
l_tilec->ownsData = OPJ_TRUE;
} else if (l_tilec->data_size_needed > l_tilec->data_size) {
/* We don't need to keep old data */
opj_aligned_free(l_tilec->data);
l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed);
if (! l_tilec->data) {
l_tilec->data_size = 0;
l_tilec->data_size_needed = 0;
l_tilec->ownsData = OPJ_FALSE;
return OPJ_FALSE;
}
/*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/
l_tilec->data_size = l_tilec->data_size_needed;
l_tilec->ownsData = OPJ_TRUE;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
opj_event_mgr_t* manager)
{
OPJ_UINT32(*l_gain_ptr)(OPJ_UINT32) = 00;
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
opj_tcp_t * l_tcp = 00;
opj_cp_t * l_cp = 00;
opj_tcd_tile_t * l_tile = 00;
opj_tccp_t *l_tccp = 00;
opj_tcd_tilecomp_t *l_tilec = 00;
opj_image_comp_t * l_image_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_stepsize_t * l_step_size = 00;
opj_tcd_precinct_t *l_current_precinct = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 p, q;
OPJ_UINT32 l_level_no;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_gain;
OPJ_INT32 l_x0b, l_y0b;
OPJ_UINT32 l_tx0, l_ty0;
/* extent of precincts , top left, bottom right**/
OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
/* number of precinct for a resolution */
OPJ_UINT32 l_nb_precincts;
/* room needed to store l_nb_precinct precinct for a resolution */
OPJ_UINT32 l_nb_precinct_size;
/* number of code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks;
/* room needed to store l_nb_code_blocks code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks_size;
/* size of data for a tile */
OPJ_UINT32 l_data_size;
l_cp = p_tcd->cp;
l_tcp = &(l_cp->tcps[p_tile_no]);
l_tile = p_tcd->tcd_image->tiles;
l_tccp = l_tcp->tccps;
l_tilec = l_tile->comps;
l_image = p_tcd->image;
l_image_comp = p_tcd->image->comps;
p = p_tile_no % l_cp->tw; /* tile coordinates */
q = p_tile_no / l_cp->tw;
/*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/
/* 4 borders of the tile rescale on the image if necessary */
l_tx0 = l_cp->tx0 + p *
l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */
l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0);
l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx),
l_image->x1);
/* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */
if ((l_tile->x0 < 0) || (l_tile->x1 <= l_tile->x0)) {
opj_event_msg(manager, EVT_ERROR, "Tile X coordinates are not supported\n");
return OPJ_FALSE;
}
l_ty0 = l_cp->ty0 + q *
l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */
l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0);
l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy),
l_image->y1);
/* all those OPJ_UINT32 are casted to OPJ_INT32, let's do some sanity check */
if ((l_tile->y0 < 0) || (l_tile->y1 <= l_tile->y0)) {
opj_event_msg(manager, EVT_ERROR, "Tile Y coordinates are not supported\n");
return OPJ_FALSE;
}
/* testcase 1888.pdf.asan.35.988 */
if (l_tccp->numresolutions == 0) {
opj_event_msg(manager, EVT_ERROR, "tiles require at least one resolution\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/
/*tile->numcomps = image->numcomps; */
for (compno = 0; compno < l_tile->numcomps; ++compno) {
/*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/
l_image_comp->resno_decoded = 0;
/* border of each l_tile component (global) */
l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx);
l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy);
l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);
l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);
/*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/
/* compute l_data_size with overflow check */
l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
/* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
if ((l_data_size > 0U) &&
((((OPJ_UINT32) - 1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 -
l_tilec->y0))) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_tilec->numresolutions = l_tccp->numresolutions;
if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) {
l_tilec->minimum_num_resolutions = 1;
} else {
l_tilec->minimum_num_resolutions = l_tccp->numresolutions -
l_cp->m_specific_param.m_dec.m_reduce;
}
l_tilec->data_size_needed = l_data_size;
if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(
opj_tcd_resolution_t);
if (l_tilec->resolutions == 00) {
l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
if (! l_tilec->resolutions) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
l_tilec->resolutions_size = l_data_size;
memset(l_tilec->resolutions, 0, l_data_size);
} else if (l_data_size > l_tilec->resolutions_size) {
opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(
l_tilec->resolutions, l_data_size);
if (! new_resolutions) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n");
opj_free(l_tilec->resolutions);
l_tilec->resolutions = NULL;
l_tilec->resolutions_size = 0;
return OPJ_FALSE;
}
l_tilec->resolutions = new_resolutions;
/*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
memset(((OPJ_BYTE*) l_tilec->resolutions) + l_tilec->resolutions_size, 0,
l_data_size - l_tilec->resolutions_size);
l_tilec->resolutions_size = l_data_size;
}
l_level_no = l_tilec->numresolutions;
l_res = l_tilec->resolutions;
l_step_size = l_tccp->stepsizes;
if (l_tccp->qmfbid == 0) {
l_gain_ptr = &opj_dwt_getgain_real;
} else {
l_gain_ptr = &opj_dwt_getgain;
}
/*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
/*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
--l_level_no;
/* border for each resolution level (global) */
l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
/*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/
/* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
/*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
/* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */
l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
/*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/
l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((
l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((
l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
/*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
if ((l_res->pw != 0U) && ((((OPJ_UINT32) - 1) / l_res->pw) < l_res->ph)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_nb_precincts = l_res->pw * l_res->ph;
if ((((OPJ_UINT32) - 1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) <
l_nb_precincts) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
if (resno == 0) {
tlcbgxstart = l_tl_prc_x_start;
tlcbgystart = l_tl_prc_y_start;
/*brcbgxend = l_br_prc_x_end;*/
/* brcbgyend = l_br_prc_y_end;*/
cbgwidthexpn = l_pdx;
cbgheightexpn = l_pdy;
l_res->numbands = 1;
} else {
tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
/*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
/*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
cbgwidthexpn = l_pdx - 1;
cbgheightexpn = l_pdy - 1;
l_res->numbands = 3;
}
cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) {
OPJ_INT32 numbps;
/*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
if (resno == 0) {
l_band->bandno = 0 ;
l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
} else {
l_band->bandno = bandno + 1;
/* x0b = 1 if bandno = 1 or 3 */
l_x0b = l_band->bandno & 1;
/* y0b = 1 if bandno = 2 or 3 */
l_y0b = (OPJ_INT32)((l_band->bandno) >> 1);
/* l_band border (global) */
l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b <<
l_level_no), (OPJ_INT32)(l_level_no + 1));
}
if (isEncoder) {
/* Skip empty bands */
if (opj_tcd_is_band_empty(l_band)) {
/* Do not zero l_band->precints to avoid leaks */
/* but make sure we don't use it later, since */
/* it will point to precincts of previous bands... */
continue;
}
}
/** avoid an if with storing function pointer */
l_gain = (*l_gain_ptr)(l_band->bandno);
numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0,
(OPJ_INT32)(numbps - l_step_size->expn)))) * fraction;
l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits -
1; /* WHY -1 ? */
if (!l_band->precincts && (l_nb_precincts > 0U)) {
l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */
l_nb_precinct_size);
if (! l_band->precincts) {
opj_event_msg(manager, EVT_ERROR,
"Not enough memory to handle band precints\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */
memset(l_band->precincts, 0, l_nb_precinct_size);
l_band->precincts_data_size = l_nb_precinct_size;
} else if (l_band->precincts_data_size < l_nb_precinct_size) {
opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(
l_band->precincts,/*3 * */ l_nb_precinct_size);
if (! new_precincts) {
opj_event_msg(manager, EVT_ERROR,
"Not enough memory to handle band precints\n");
opj_free(l_band->precincts);
l_band->precincts = NULL;
l_band->precincts_data_size = 0;
return OPJ_FALSE;
}
l_band->precincts = new_precincts;
/*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/
memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size, 0,
l_nb_precinct_size - l_band->precincts_data_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
l_current_precinct = l_band->precincts;
for (precno = 0; precno < l_nb_precincts; ++precno) {
OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) *
(1 << cbgwidthexpn);
OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) *
(1 << cbgheightexpn);
OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
/*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
/*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
/* precinct size (global) */
/*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
/*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/
tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0,
(OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0,
(OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1,
(OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1,
(OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >>
cblkwidthexpn);
l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >>
cblkheightexpn);
l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
/*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */
l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) {
l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
if (! l_current_precinct->cblks.blocks) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
memset(l_current_precinct->cblks.blocks, 0, l_nb_code_blocks_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
} else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks,
l_nb_code_blocks_size);
if (! new_blocks) {
opj_free(l_current_precinct->cblks.blocks);
l_current_precinct->cblks.blocks = NULL;
l_current_precinct->block_size = 0;
opj_event_msg(manager, EVT_ERROR,
"Not enough memory for current precinct codeblock element\n");
return OPJ_FALSE;
}
l_current_precinct->cblks.blocks = new_blocks;
/*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */
memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) +
l_current_precinct->block_size
, 0
, l_nb_code_blocks_size - l_current_precinct->block_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
if (! l_current_precinct->incltree) {
l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw,
l_current_precinct->ch, manager);
} else {
l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree,
l_current_precinct->cw, l_current_precinct->ch, manager);
}
if (! l_current_precinct->imsbtree) {
l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw,
l_current_precinct->ch, manager);
} else {
l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree,
l_current_precinct->cw, l_current_precinct->ch, manager);
}
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno %
l_current_precinct->cw) * (1 << cblkwidthexpn);
OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno /
l_current_precinct->cw) * (1 << cblkheightexpn);
OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
if (isEncoder) {
opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
return OPJ_FALSE;
}
} else {
opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
}
}
++l_current_precinct;
} /* precno */
} /* bandno */
++l_res;
} /* resno */
++l_tccp;
++l_tilec;
++l_image_comp;
} /* compno */
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
opj_event_mgr_t* p_manager)
{
return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F,
sizeof(opj_tcd_cblk_enc_t), p_manager);
}
OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
opj_event_mgr_t* p_manager)
{
return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F,
sizeof(opj_tcd_cblk_dec_t), p_manager);
}
/**
* Allocates memory for an encoding code block (but not data memory).
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
p_code_block)
{
if (! p_code_block->layers) {
/* no memset since data */
p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100,
sizeof(opj_tcd_layer_t));
if (! p_code_block->layers) {
return OPJ_FALSE;
}
}
if (! p_code_block->passes) {
p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100,
sizeof(opj_tcd_pass_t));
if (! p_code_block->passes) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
/**
* Allocates data memory for an encoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block)
{
OPJ_UINT32 l_data_size;
/* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
(p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
if (l_data_size > p_code_block->data_size) {
if (p_code_block->data) {
/* We refer to data - 1 since below we incremented it */
opj_free(p_code_block->data - 1);
}
p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
if (! p_code_block->data) {
p_code_block->data_size = 0U;
return OPJ_FALSE;
}
p_code_block->data_size = l_data_size;
/* We reserve the initial byte as a fake byte to a non-FF value */
/* and increment the data pointer, so that opj_mqc_init_enc() */
/* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
/* it. */
p_code_block->data[0] = 0;
p_code_block->data += 1; /*why +1 ?*/
}
return OPJ_TRUE;
}
/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
p_code_block)
{
if (! p_code_block->data) {
p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_COMMON_DEFAULT_CBLK_DATA_SIZE);
if (! p_code_block->data) {
return OPJ_FALSE;
}
p_code_block->data_max_size = OPJ_COMMON_DEFAULT_CBLK_DATA_SIZE;
/*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/
p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,
sizeof(opj_tcd_seg_t));
if (! p_code_block->segs) {
return OPJ_FALSE;
}
/*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/
p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS;
/*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/
} else {
/* sanitize */
OPJ_BYTE* l_data = p_code_block->data;
OPJ_UINT32 l_data_max_size = p_code_block->data_max_size;
opj_tcd_seg_t * l_segs = p_code_block->segs;
OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs;
memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t));
p_code_block->data = l_data;
p_code_block->data_max_size = l_data_max_size;
p_code_block->segs = l_segs;
p_code_block->m_current_max_segs = l_current_max_segs;
}
return OPJ_TRUE;
}
OPJ_UINT32 opj_tcd_get_decoded_tile_size(opj_tcd_t *p_tcd)
{
OPJ_UINT32 i;
OPJ_UINT32 l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tcd_resolution_t * l_res = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_temp;
l_tile_comp = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1;
l_temp = (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 -
l_res->y0)); /* x1*y1 can't overflow */
if (l_size_comp && UINT_MAX / l_size_comp < l_temp) {
return UINT_MAX;
}
l_temp *= l_size_comp;
if (l_temp > UINT_MAX - l_data_size) {
return UINT_MAX;
}
l_data_size += l_temp;
++l_img_comp;
++l_tile_comp;
}
return l_data_size;
}
OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
OPJ_UINT32 p_tile_no,
OPJ_BYTE *p_dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_length,
opj_codestream_info_t *p_cstr_info)
{
if (p_tcd->cur_tp_num == 0) {
p_tcd->tcd_tileno = p_tile_no;
p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];
/* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */
if (p_cstr_info) {
OPJ_UINT32 l_num_packs = 0;
OPJ_UINT32 i;
opj_tcd_tilecomp_t *l_tilec_idx =
&p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */
opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */
for (i = 0; i < l_tilec_idx->numresolutions; i++) {
opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i];
p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw;
p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph;
l_num_packs += l_res_idx->pw * l_res_idx->ph;
p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i];
p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i];
}
p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((
size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs,
sizeof(opj_packet_info_t));
if (!p_cstr_info->tile[p_tile_no].packet) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
}
/* << INDEX */
/* FIXME _ProfStart(PGROUP_DC_SHIFT); */
/*---------------TILE-------------------*/
if (! opj_tcd_dc_level_shift_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DC_SHIFT); */
/* FIXME _ProfStart(PGROUP_MCT); */
if (! opj_tcd_mct_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_MCT); */
/* FIXME _ProfStart(PGROUP_DWT); */
if (! opj_tcd_dwt_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DWT); */
/* FIXME _ProfStart(PGROUP_T1); */
if (! opj_tcd_t1_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T1); */
/* FIXME _ProfStart(PGROUP_RATE); */
if (! opj_tcd_rate_allocate_encode(p_tcd, p_dest, p_max_length, p_cstr_info)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_RATE); */
}
/*--------------TIER2------------------*/
/* INDEX */
if (p_cstr_info) {
p_cstr_info->index_write = 1;
}
/* FIXME _ProfStart(PGROUP_T2); */
if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length,
p_cstr_info)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T2); */
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_decode_tile(opj_tcd_t *p_tcd,
OPJ_BYTE *p_src,
OPJ_UINT32 p_max_length,
OPJ_UINT32 p_tile_no,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager
)
{
OPJ_UINT32 l_data_read;
p_tcd->tcd_tileno = p_tile_no;
p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]);
#ifdef TODO_MSD /* FIXME */
/* INDEX >> */
if (p_cstr_info) {
OPJ_UINT32 resno, compno, numprec = 0;
for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) {
opj_tcp_t *tcp = &p_tcd->cp->tcps[0];
opj_tccp_t *tccp = &tcp->tccps[compno];
opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno];
for (resno = 0; resno < tilec_idx->numresolutions; resno++) {
opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno];
p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw;
p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph;
numprec += res_idx->pw * res_idx->ph;
p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno];
p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno];
}
}
p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(
p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t));
p_cstr_info->packno = 0;
}
/* << INDEX */
#endif
/*--------------TIER2------------------*/
/* FIXME _ProfStart(PGROUP_T2); */
l_data_read = 0;
if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index,
p_manager)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T2); */
/*------------------TIER1-----------------*/
/* FIXME _ProfStart(PGROUP_T1); */
if (! opj_tcd_t1_decode(p_tcd, p_manager)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T1); */
/*----------------DWT---------------------*/
/* FIXME _ProfStart(PGROUP_DWT); */
if
(! opj_tcd_dwt_decode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DWT); */
/*----------------MCT-------------------*/
/* FIXME _ProfStart(PGROUP_MCT); */
if
(! opj_tcd_mct_decode(p_tcd, p_manager)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_MCT); */
/* FIXME _ProfStart(PGROUP_DC_SHIFT); */
if
(! opj_tcd_dc_level_shift_decode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DC_SHIFT); */
/*---------------TILE-------------------*/
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest,
OPJ_UINT32 p_dest_length
)
{
OPJ_UINT32 i, j, k, l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_tcd_resolution_t * l_res;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_stride, l_width, l_height;
l_data_size = opj_tcd_get_decoded_tile_size(p_tcd);
if (l_data_size == UINT_MAX || l_data_size > p_dest_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest;
const OPJ_INT32 * l_src_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
*(l_dest_ptr++) = (OPJ_CHAR)(*(l_src_ptr++));
}
l_src_ptr += l_stride;
}
} else {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
*(l_dest_ptr++) = (OPJ_CHAR)((*(l_src_ptr++)) & 0xff);
}
l_src_ptr += l_stride;
}
}
p_dest = (OPJ_BYTE *)l_dest_ptr;
}
break;
case 2: {
const OPJ_INT32 * l_src_ptr = l_tilec->data;
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest;
if (l_img_comp->sgnd) {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
OPJ_INT16 val = (OPJ_INT16)(*(l_src_ptr++));
memcpy(l_dest_ptr, &val, sizeof(val));
l_dest_ptr ++;
}
l_src_ptr += l_stride;
}
} else {
for (j = 0; j < l_height; ++j) {
for (k = 0; k < l_width; ++k) {
OPJ_INT16 val = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff);
memcpy(l_dest_ptr, &val, sizeof(val));
l_dest_ptr ++;
}
l_src_ptr += l_stride;
}
}
p_dest = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4: {
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest;
OPJ_INT32 * l_src_ptr = l_tilec->data;
for (j = 0; j < l_height; ++j) {
memcpy(l_dest_ptr, l_src_ptr, l_width * sizeof(OPJ_INT32));
l_dest_ptr += l_width;
l_src_ptr += l_width + l_stride;
}
p_dest = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
static void opj_tcd_free_tile(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno, resno, bandno, precno;
opj_tcd_tile_t *l_tile = 00;
opj_tcd_tilecomp_t *l_tile_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_tcd_precinct_t *l_precinct = 00;
OPJ_UINT32 l_nb_resolutions, l_nb_precincts;
void (* l_tcd_code_block_deallocate)(opj_tcd_precinct_t *) = 00;
if (! p_tcd) {
return;
}
if (! p_tcd->tcd_image) {
return;
}
if (p_tcd->m_is_decoder) {
l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate;
} else {
l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate;
}
l_tile = p_tcd->tcd_image->tiles;
if (! l_tile) {
return;
}
l_tile_comp = l_tile->comps;
for (compno = 0; compno < l_tile->numcomps; ++compno) {
l_res = l_tile_comp->resolutions;
if (l_res) {
l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t);
for (resno = 0; resno < l_nb_resolutions; ++resno) {
l_band = l_res->bands;
for (bandno = 0; bandno < 3; ++bandno) {
l_precinct = l_band->precincts;
if (l_precinct) {
l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t);
for (precno = 0; precno < l_nb_precincts; ++precno) {
opj_tgt_destroy(l_precinct->incltree);
l_precinct->incltree = 00;
opj_tgt_destroy(l_precinct->imsbtree);
l_precinct->imsbtree = 00;
(*l_tcd_code_block_deallocate)(l_precinct);
++l_precinct;
}
opj_free(l_band->precincts);
l_band->precincts = 00;
}
++l_band;
} /* for (resno */
++l_res;
}
opj_free(l_tile_comp->resolutions);
l_tile_comp->resolutions = 00;
}
if (l_tile_comp->ownsData && l_tile_comp->data) {
opj_aligned_free(l_tile_comp->data);
l_tile_comp->data = 00;
l_tile_comp->ownsData = 0;
l_tile_comp->data_size = 0;
l_tile_comp->data_size_needed = 0;
}
++l_tile_comp;
}
opj_free(l_tile->comps);
l_tile->comps = 00;
opj_free(p_tcd->tcd_image->tiles);
p_tcd->tcd_image->tiles = 00;
}
static OPJ_BOOL opj_tcd_t2_decode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_src_size,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager
)
{
opj_t2_t * l_t2;
l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
if (l_t2 == 00) {
return OPJ_FALSE;
}
if (! opj_t2_decode_packets(
l_t2,
p_tcd->tcd_tileno,
p_tcd->tcd_image->tiles,
p_src_data,
p_data_read,
p_max_src_size,
p_cstr_index,
p_manager)) {
opj_t2_destroy(l_t2);
return OPJ_FALSE;
}
opj_t2_destroy(l_t2);
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t1_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
OPJ_UINT32 compno;
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
volatile OPJ_BOOL ret = OPJ_TRUE;
OPJ_BOOL check_pterm = OPJ_FALSE;
opj_mutex_t* p_manager_mutex = NULL;
p_manager_mutex = opj_mutex_create();
/* Only enable PTERM check if we decode all layers */
if (p_tcd->tcp->num_layers_to_decode == p_tcd->tcp->numlayers &&
(l_tccp->cblksty & J2K_CCP_CBLKSTY_PTERM) != 0) {
check_pterm = OPJ_TRUE;
}
for (compno = 0; compno < l_tile->numcomps; ++compno) {
opj_t1_decode_cblks(p_tcd->thread_pool, &ret, l_tile_comp, l_tccp,
p_manager, p_manager_mutex, check_pterm);
if (!ret) {
break;
}
++l_tile_comp;
++l_tccp;
}
opj_thread_pool_wait_completion(p_tcd->thread_pool, 0);
if (p_manager_mutex) {
opj_mutex_destroy(p_manager_mutex);
}
return ret;
}
static OPJ_BOOL opj_tcd_dwt_decode(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno;
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
opj_image_comp_t * l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
/*
if (tcd->cp->reduce != 0) {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
if (tcd->image->comps[compno].resno_decoded < 0)
{
return false;
}
}
numres2decode = tcd->image->comps[compno].resno_decoded + 1;
if(numres2decode > 0){
*/
if (l_tccp->qmfbid == 1) {
if (! opj_dwt_decode(p_tcd->thread_pool, l_tile_comp,
l_img_comp->resno_decoded + 1)) {
return OPJ_FALSE;
}
} else {
if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded + 1)) {
return OPJ_FALSE;
}
}
++l_tile_comp;
++l_img_comp;
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcp_t * l_tcp = p_tcd->tcp;
opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
OPJ_UINT32 l_samples, i;
if (! l_tcp->mct) {
return OPJ_TRUE;
}
l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
(l_tile_comp->y1 - l_tile_comp->y0));
if (l_tile->numcomps >= 3) {
/* testcase 1336.pdf.asan.47.376 */
if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 -
l_tile->comps[0].y0) < (OPJ_INT32)l_samples ||
(l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 -
l_tile->comps[1].y0) < (OPJ_INT32)l_samples ||
(l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 -
l_tile->comps[2].y0) < (OPJ_INT32)l_samples) {
opj_event_msg(p_manager, EVT_ERROR,
"Tiles don't all have the same dimension. Skip the MCT step.\n");
return OPJ_FALSE;
} else if (l_tcp->mct == 2) {
OPJ_BYTE ** l_data;
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_TRUE;
}
l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
if (! l_data) {
return OPJ_FALSE;
}
for (i = 0; i < l_tile->numcomps; ++i) {
l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++l_tile_comp;
}
if (! opj_mct_decode_custom(/* MCT data */
(OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
/* size of components */
l_samples,
/* components */
l_data,
/* nb of components (i.e. size of pData) */
l_tile->numcomps,
/* tells if the data is signed */
p_tcd->image->comps->sgnd)) {
opj_free(l_data);
return OPJ_FALSE;
}
opj_free(l_data);
} else {
if (l_tcp->tccps->qmfbid == 1) {
opj_mct_decode(l_tile->comps[0].data,
l_tile->comps[1].data,
l_tile->comps[2].data,
l_samples);
} else {
opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
(OPJ_FLOAT32*)l_tile->comps[1].data,
(OPJ_FLOAT32*)l_tile->comps[2].data,
l_samples);
}
}
} else {
opj_event_msg(p_manager, EVT_ERROR,
"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",
l_tile->numcomps);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dc_level_shift_decode(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tccp_t * l_tccp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_resolution_t* l_res = 00;
opj_tcd_tile_t * l_tile;
OPJ_UINT32 l_width, l_height, i, j;
OPJ_INT32 * l_current_ptr;
OPJ_INT32 l_min, l_max;
OPJ_UINT32 l_stride;
l_tile = p_tcd->tcd_image->tiles;
l_tile_comp = l_tile->comps;
l_tccp = p_tcd->tcp->tccps;
l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded;
l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width;
assert(l_height == 0 ||
l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/
if (l_img_comp->sgnd) {
l_min = -(1 << (l_img_comp->prec - 1));
l_max = (1 << (l_img_comp->prec - 1)) - 1;
} else {
l_min = 0;
l_max = (1 << l_img_comp->prec) - 1;
}
l_current_ptr = l_tile_comp->data;
if (l_tccp->qmfbid == 1) {
for (j = 0; j < l_height; ++j) {
for (i = 0; i < l_width; ++i) {
*l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min,
l_max);
++l_current_ptr;
}
l_current_ptr += l_stride;
}
} else {
for (j = 0; j < l_height; ++j) {
for (i = 0; i < l_width; ++i) {
OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr);
OPJ_INT32 l_value_int = (OPJ_INT32)opj_lrintf(l_value);
if (l_value > INT_MAX ||
(l_value_int > 0 && l_tccp->m_dc_level_shift > 0 &&
l_value_int > INT_MAX - l_tccp->m_dc_level_shift)) {
*l_current_ptr = l_max;
} else {
*l_current_ptr = opj_int_clamp(
l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
}
++l_current_ptr;
}
l_current_ptr += l_stride;
}
}
++l_img_comp;
++l_tccp;
++l_tile_comp;
}
return OPJ_TRUE;
}
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct)
{
OPJ_UINT32 cblkno, l_nb_code_blocks;
opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec;
if (l_code_block) {
/*fprintf(stderr,"deallocate codeblock:{\n");*/
/*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/
/*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/
l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t);
/*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
if (l_code_block->data) {
opj_free(l_code_block->data);
l_code_block->data = 00;
}
if (l_code_block->segs) {
opj_free(l_code_block->segs);
l_code_block->segs = 00;
}
++l_code_block;
}
opj_free(p_precinct->cblks.dec);
p_precinct->cblks.dec = 00;
}
}
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_enc_deallocate(opj_tcd_precinct_t * p_precinct)
{
OPJ_UINT32 cblkno, l_nb_code_blocks;
opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc;
if (l_code_block) {
l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t);
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
if (l_code_block->data) {
/* We refer to data - 1 since below we incremented it */
/* in opj_tcd_code_block_enc_allocate_data() */
opj_free(l_code_block->data - 1);
l_code_block->data = 00;
}
if (l_code_block->layers) {
opj_free(l_code_block->layers);
l_code_block->layers = 00;
}
if (l_code_block->passes) {
opj_free(l_code_block->passes);
l_code_block->passes = 00;
}
++l_code_block;
}
opj_free(p_precinct->cblks.enc);
p_precinct->cblks.enc = 00;
}
}
OPJ_UINT32 opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd)
{
OPJ_UINT32 i, l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) *
(l_tilec->y1 - l_tilec->y0));
++l_img_comp;
++l_tilec;
}
return l_data_size;
}
static OPJ_BOOL opj_tcd_dc_level_shift_encode(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tccp_t * l_tccp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tile_t * l_tile;
OPJ_UINT32 l_nb_elem, i;
OPJ_INT32 * l_current_ptr;
l_tile = p_tcd->tcd_image->tiles;
l_tile_comp = l_tile->comps;
l_tccp = p_tcd->tcp->tccps;
l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
l_current_ptr = l_tile_comp->data;
l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
(l_tile_comp->y1 - l_tile_comp->y0));
if (l_tccp->qmfbid == 1) {
for (i = 0; i < l_nb_elem; ++i) {
*l_current_ptr -= l_tccp->m_dc_level_shift ;
++l_current_ptr;
}
} else {
for (i = 0; i < l_nb_elem; ++i) {
*l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
++l_current_ptr;
}
}
++l_img_comp;
++l_tccp;
++l_tile_comp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_mct_encode(opj_tcd_t *p_tcd)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *
(l_tile_comp->y1 - l_tile_comp->y0));
OPJ_UINT32 i;
OPJ_BYTE ** l_data = 00;
opj_tcp_t * l_tcp = p_tcd->tcp;
if (!p_tcd->tcp->mct) {
return OPJ_TRUE;
}
if (p_tcd->tcp->mct == 2) {
if (! p_tcd->tcp->m_mct_coding_matrix) {
return OPJ_TRUE;
}
l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));
if (! l_data) {
return OPJ_FALSE;
}
for (i = 0; i < l_tile->numcomps; ++i) {
l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++l_tile_comp;
}
if (! opj_mct_encode_custom(/* MCT data */
(OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix,
/* size of components */
samples,
/* components */
l_data,
/* nb of components (i.e. size of pData) */
l_tile->numcomps,
/* tells if the data is signed */
p_tcd->image->comps->sgnd)) {
opj_free(l_data);
return OPJ_FALSE;
}
opj_free(l_data);
} else if (l_tcp->tccps->qmfbid == 0) {
opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data,
l_tile->comps[2].data, samples);
} else {
opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
l_tile->comps[2].data, samples);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
OPJ_UINT32 compno;
for (compno = 0; compno < l_tile->numcomps; ++compno) {
if (l_tccp->qmfbid == 1) {
if (! opj_dwt_encode(l_tile_comp)) {
return OPJ_FALSE;
}
} else if (l_tccp->qmfbid == 0) {
if (! opj_dwt_encode_real(l_tile_comp)) {
return OPJ_FALSE;
}
}
++l_tile_comp;
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
{
opj_t1_t * l_t1;
const OPJ_FLOAT64 * l_mct_norms;
OPJ_UINT32 l_mct_numcomps = 0U;
opj_tcp_t * l_tcp = p_tcd->tcp;
l_t1 = opj_t1_create(OPJ_TRUE);
if (l_t1 == 00) {
return OPJ_FALSE;
}
if (l_tcp->mct == 1) {
l_mct_numcomps = 3U;
/* irreversible encoding */
if (l_tcp->tccps->qmfbid == 0) {
l_mct_norms = opj_mct_get_mct_norms_real();
} else {
l_mct_norms = opj_mct_get_mct_norms();
}
} else {
l_mct_numcomps = p_tcd->image->numcomps;
l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
}
if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
l_mct_numcomps)) {
opj_t1_destroy(l_t1);
return OPJ_FALSE;
}
opj_t1_destroy(l_t1);
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info)
{
opj_t2_t * l_t2;
l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
if (l_t2 == 00) {
return OPJ_FALSE;
}
if (! opj_t2_encode_packets(
l_t2,
p_tcd->tcd_tileno,
p_tcd->tcd_image->tiles,
p_tcd->tcp->numlayers,
p_dest_data,
p_data_written,
p_max_dest_size,
p_cstr_info,
p_tcd->tp_num,
p_tcd->tp_pos,
p_tcd->cur_pino,
FINAL_PASS)) {
opj_t2_destroy(l_t2);
return OPJ_FALSE;
}
opj_t2_destroy(l_t2);
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info)
{
opj_cp_t * l_cp = p_tcd->cp;
OPJ_UINT32 l_nb_written = 0;
if (p_cstr_info) {
p_cstr_info->index_write = 0;
}
if (l_cp->m_specific_param.m_enc.m_disto_alloc ||
l_cp->m_specific_param.m_enc.m_fixed_quality) {
/* fixed_quality */
/* Normal Rate/distortion allocation */
if (! opj_tcd_rateallocate(p_tcd, p_dest_data, &l_nb_written, p_max_dest_size,
p_cstr_info)) {
return OPJ_FALSE;
}
} else {
/* Fixed layer allocation */
opj_tcd_rateallocate_fixed(p_tcd);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
OPJ_BYTE * p_src,
OPJ_UINT32 p_src_length)
{
OPJ_UINT32 i, j, l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_nb_elem;
l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
if (l_data_size != p_src_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i = 0; i < p_tcd->image->numcomps; ++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 -
l_tilec->y0));
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp) {
case 1: {
OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
}
} else {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (*(l_src_ptr++)) & 0xff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 2: {
OPJ_INT32 * l_dest_ptr = l_tilec->data;
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
if (l_img_comp->sgnd) {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
}
} else {
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (*(l_src_ptr++)) & 0xffff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4: {
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
for (j = 0; j < l_nb_elem; ++j) {
*(l_dest_ptr++) = (OPJ_INT32)(*(l_src_ptr++));
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_is_band_empty(opj_tcd_band_t* band)
{
return (band->x1 - band->x0 == 0) || (band->y1 - band->y0 == 0);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4865_0 |
crossvul-cpp_data_good_160_4 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Variables
* ----------------------------------------------------------------------------
*/
#include "jsvar.h"
#include "jslex.h"
#include "jsparse.h"
#include "jswrap_json.h"
#include "jsinteractive.h"
#include "jswrapper.h"
#include "jswrap_math.h" // for jswrap_math_mod
#include "jswrap_object.h" // for jswrap_object_toString
#include "jswrap_arraybuffer.h" // for jsvNewTypedArray
#include "jswrap_dataview.h" // for jsvNewDataViewWithData
#ifdef DEBUG
/** When freeing, clear the references (nextChild/etc) in the JsVar.
* This means we can assert at the end of jsvFreePtr to make sure
* everything really is free. */
#define CLEAR_MEMORY_ON_FREE
#endif
/** Basically, JsVars are stored in one big array, so save the need for
* lots of memory allocation. On Linux, the arrays are in blocks, so that
* more blocks can be allocated. We can't use realloc on one big block as
* this may change the address of vars that are already locked!
*
*/
#ifdef RESIZABLE_JSVARS
JsVar **jsVarBlocks = 0;
unsigned int jsVarsSize = 0;
#define JSVAR_BLOCK_SIZE 4096
#define JSVAR_BLOCK_SHIFT 12
#else
JsVar jsVars[JSVAR_CACHE_SIZE];
unsigned int jsVarsSize = JSVAR_CACHE_SIZE;
#endif
typedef enum {
MEM_NOT_BUSY,
MEMBUSY_SYSTEM,
MEMBUSY_GC
} MemBusyType;
volatile bool touchedFreeList = false;
volatile JsVarRef jsVarFirstEmpty; ///< reference of first unused variable (variables are in a linked list)
volatile MemBusyType isMemoryBusy; ///< Are we doing garbage collection or similar, so can't access memory?
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
bool jsvIsRoot(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ROOT; }
bool jsvIsPin(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_PIN; }
bool jsvIsSimpleInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_INTEGER; } // is just a very basic integer value
bool jsvIsInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_INTEGER || (v->flags&JSV_VARTYPEMASK)==JSV_PIN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); }
bool jsvIsFloat(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLOAT; }
bool jsvIsBoolean(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_BOOLEAN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); }
bool jsvIsString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_STRING_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_STRING_END; } ///< String, or a NAME too
bool jsvIsBasicString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=JSV_STRING_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_STRING_MAX; } ///< Just a string (NOT a name)
bool jsvIsStringExt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=JSV_STRING_EXT_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_STRING_EXT_MAX; } ///< The extra bits dumped onto the end of a string to store more data
bool jsvIsFlatString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLAT_STRING; }
bool jsvIsNativeString(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NATIVE_STRING; }
bool jsvIsNumeric(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NUMERIC_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NUMERIC_END; }
bool jsvIsFunction(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION || (v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); }
bool jsvIsFunctionReturn(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_FUNCTION_RETURN); } ///< Is this a function with an implicit 'return' at the start?
bool jsvIsFunctionParameter(const JsVar *v) { return v && (v->flags&JSV_NATIVE) && jsvIsString(v); }
bool jsvIsObject(const JsVar *v) { return v && (((v->flags&JSV_VARTYPEMASK)==JSV_OBJECT) || ((v->flags&JSV_VARTYPEMASK)==JSV_ROOT)); }
bool jsvIsArray(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ARRAY; }
bool jsvIsArrayBuffer(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_ARRAYBUFFER; }
bool jsvIsArrayBufferName(const JsVar *v) { return v && (v->flags&(JSV_VARTYPEMASK))==JSV_ARRAYBUFFERNAME; }
bool jsvIsNative(const JsVar *v) { return v && (v->flags&JSV_NATIVE)!=0; }
bool jsvIsNativeFunction(const JsVar *v) { return v && (v->flags&(JSV_NATIVE|JSV_VARTYPEMASK))==(JSV_NATIVE|JSV_FUNCTION); }
bool jsvIsUndefined(const JsVar *v) { return v==0; }
bool jsvIsNull(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NULL; }
bool jsvIsBasic(const JsVar *v) { return jsvIsNumeric(v) || jsvIsString(v);} ///< Is this *not* an array/object/etc
bool jsvIsName(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NAME_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NAME_END; } ///< NAMEs are what's used to name a variable (it is not the data itself)
/// Names with values have firstChild set to a value - AND NOT A REFERENCE
bool jsvIsNameWithValue(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NAME_WITH_VALUE_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NAME_WITH_VALUE_END; }
bool jsvIsNameInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || ((v->flags&JSV_VARTYPEMASK)>=JSV_NAME_STRING_INT_0 && (v->flags&JSV_VARTYPEMASK)<=JSV_NAME_STRING_INT_MAX)); }
bool jsvIsNameIntInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT; }
bool jsvIsNameIntBool(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL; }
/// What happens when we access a variable that doesn't exist. We get a NAME where the next + previous siblings point to the object that may one day contain them
bool jsvIsNewChild(const JsVar *v) { return jsvIsName(v) && jsvGetNextSibling(v) && jsvGetNextSibling(v)==jsvGetPrevSibling(v); }
/// Are var.varData.ref.* (excl pad) used for data (so we expect them not to be empty)
bool jsvIsRefUsedForData(const JsVar *v) { return jsvIsStringExt(v) || (jsvIsString(v)&&!jsvIsName(v)) || jsvIsFloat(v) || jsvIsNativeFunction(v) || jsvIsArrayBuffer(v) || jsvIsArrayBufferName(v); }
/// Can the given variable be converted into an integer without loss of precision
bool jsvIsIntegerish(const JsVar *v) { return jsvIsInt(v) || jsvIsPin(v) || jsvIsBoolean(v) || jsvIsNull(v); }
bool jsvIsIterable(const JsVar *v) {
return jsvIsArray(v) || jsvIsObject(v) || jsvIsFunction(v) ||
jsvIsString(v) || jsvIsArrayBuffer(v);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/** Return a pointer - UNSAFE for null refs.
* This is effectively a Lock without locking! */
static ALWAYS_INLINE JsVar *jsvGetAddressOf(JsVarRef ref) {
assert(ref);
#ifdef RESIZABLE_JSVARS
JsVarRef t = ref-1;
return &jsVarBlocks[t>>JSVAR_BLOCK_SHIFT][t&(JSVAR_BLOCK_SIZE-1)];
#else
return &jsVars[ref-1];
#endif
}
JsVar *_jsvGetAddressOf(JsVarRef ref) {
return jsvGetAddressOf(ref);
}
#ifdef JSVARREF_PACKED_BITS
#define JSVARREF_PACKED_BIT_MASK ((1U<<JSVARREF_PACKED_BITS)-1)
JsVarRef jsvGetFirstChild(const JsVar *v) { return (JsVarRef)(v->varData.ref.firstChild | (((v->varData.ref.pack)&JSVARREF_PACKED_BIT_MASK))<<8); }
JsVarRefSigned jsvGetFirstChildSigned(const JsVar *v) {
JsVarRefSigned r = (JsVarRefSigned)jsvGetFirstChild(v);
if (r & (1<<(JSVARREF_PACKED_BITS+7)))
r -= 1<<(JSVARREF_PACKED_BITS+8);
return r;
}
JsVarRef jsvGetNextSibling(const JsVar *v) { return (JsVarRef)(v->varData.ref.nextSibling | (((v->varData.ref.pack >> (JSVARREF_PACKED_BITS*2))&JSVARREF_PACKED_BIT_MASK))<<8); }
JsVarRef jsvGetPrevSibling(const JsVar *v) { return (JsVarRef)(v->varData.ref.prevSibling | (((v->varData.ref.pack >> (JSVARREF_PACKED_BITS*3))&JSVARREF_PACKED_BIT_MASK))<<8); }
void jsvSetFirstChild(JsVar *v, JsVarRef r) {
v->varData.ref.firstChild = (unsigned char)(r & 0xFF);
v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~JSVARREF_PACKED_BIT_MASK) | ((r >> 8) & JSVARREF_PACKED_BIT_MASK));
}
void jsvSetNextSibling(JsVar *v, JsVarRef r) {
v->varData.ref.nextSibling = (unsigned char)(r & 0xFF);
v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~(JSVARREF_PACKED_BIT_MASK<<(JSVARREF_PACKED_BITS*2))) | (((r >> 8) & JSVARREF_PACKED_BIT_MASK) << (JSVARREF_PACKED_BITS*2)));
}
void jsvSetPrevSibling(JsVar *v, JsVarRef r) {
v->varData.ref.prevSibling = (unsigned char)(r & 0xFF);
v->varData.ref.pack = (unsigned char)((v->varData.ref.pack & ~(JSVARREF_PACKED_BIT_MASK<<(JSVARREF_PACKED_BITS*3))) | (((r >> 8) & JSVARREF_PACKED_BIT_MASK) << (JSVARREF_PACKED_BITS*3)));
}
/* lastchild stores the upper 2 bits in JsVarFlags because then STRING_EXT can use one more character! */
JsVarRef jsvGetLastChild(const JsVar *v) {
return (JsVarRef)(v->varData.ref.lastChild | (((v->flags >> JSV_LASTCHILD_BIT_SHIFT)&JSVARREF_PACKED_BIT_MASK))<<8);
}
void jsvSetLastChild(JsVar *v, JsVarRef r) {
v->varData.ref.lastChild = (unsigned char)(r & 0xFF);
v->flags = (v->flags & ~JSV_LASTCHILD_BIT_MASK) | ((r >> 8) << JSV_LASTCHILD_BIT_SHIFT);
}
#endif
// For debugging/testing ONLY - maximum # of vars we are allowed to use
void jsvSetMaxVarsUsed(unsigned int size) {
#ifdef RESIZABLE_JSVARS
assert(size < JSVAR_BLOCK_SIZE); // remember - this is only for DEBUGGING - as such it doesn't use multiple blocks
#else
assert(size < JSVAR_CACHE_SIZE);
#endif
jsVarsSize = size;
}
// maps the empty variables in...
void jsvCreateEmptyVarList() {
assert(!isMemoryBusy);
isMemoryBusy = MEMBUSY_SYSTEM;
jsVarFirstEmpty = 0;
JsVar firstVar; // temporary var to simplify code in the loop below
jsvSetNextSibling(&firstVar, 0);
JsVar *lastEmpty = &firstVar;
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) {
jsvSetNextSibling(lastEmpty, i);
lastEmpty = var;
} else if (jsvIsFlatString(var)) {
// skip over used blocks for flat strings
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
jsvSetNextSibling(lastEmpty, 0);
jsVarFirstEmpty = jsvGetNextSibling(&firstVar);
isMemoryBusy = MEM_NOT_BUSY;
}
/* Removes the empty variable counter, cleaving clear runs of 0s
where no data resides. This helps if compressing the variables
for storage. */
void jsvClearEmptyVarList() {
assert(!isMemoryBusy);
isMemoryBusy = MEMBUSY_SYSTEM;
jsVarFirstEmpty = 0;
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) == JSV_UNUSED) {
// completely zero it (JSV_UNUSED==0, so it still stays the same)
memset((void*)var,0,sizeof(JsVar));
} else if (jsvIsFlatString(var)) {
// skip over used blocks for flat strings
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
isMemoryBusy = MEM_NOT_BUSY;
}
void jsvSoftInit() {
jsvCreateEmptyVarList();
}
void jsvSoftKill() {
jsvClearEmptyVarList();
}
/** This links all JsVars together, so we can have our nice
* linked list of free JsVars. It returns the ref of the first
* item - that we should set jsVarFirstEmpty to (if it is 0) */
static JsVarRef jsvInitJsVars(JsVarRef start, unsigned int count) {
JsVarRef i;
for (i=start;i<start+count;i++) {
JsVar *v = jsvGetAddressOf(i);
v->flags = JSV_UNUSED;
// v->locks = 0; // locks is 0 anyway because it is stored in flags
jsvSetNextSibling(v, (JsVarRef)(i+1)); // link to next
}
jsvSetNextSibling(jsvGetAddressOf((JsVarRef)(start+count-1)), (JsVarRef)0); // set the final one to 0
return start;
}
void jsvInit() {
#ifdef RESIZABLE_JSVARS
jsVarsSize = JSVAR_BLOCK_SIZE;
jsVarBlocks = malloc(sizeof(JsVar*)); // just 1
jsVarBlocks[0] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE);
#endif
jsVarFirstEmpty = jsvInitJsVars(1/*first*/, jsVarsSize);
jsvSoftInit();
}
void jsvKill() {
#ifdef RESIZABLE_JSVARS
unsigned int i;
for (i=0;i<jsVarsSize>>JSVAR_BLOCK_SHIFT;i++)
free(jsVarBlocks[i]);
free(jsVarBlocks);
jsVarBlocks = 0;
jsVarsSize = 0;
#endif
}
/** Find or create the ROOT variable item - used mainly
* if recovering from a saved state. */
JsVar *jsvFindOrCreateRoot() {
JsVarRef i;
for (i=1;i<=jsVarsSize;i++)
if (jsvIsRoot(jsvGetAddressOf(i)))
return jsvLock(i);
return jsvRef(jsvNewWithFlags(JSV_ROOT));
}
/// Get number of memory records (JsVars) used
unsigned int jsvGetMemoryUsage() {
unsigned int usage = 0;
unsigned int i;
for (i=1;i<=jsVarsSize;i++) {
JsVar *v = jsvGetAddressOf((JsVarRef)i);
if ((v->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
usage++;
if (jsvIsFlatString(v)) {
unsigned int b = (unsigned int)jsvGetFlatStringBlocks(v);
i+=b;
usage+=b;
}
}
}
return usage;
}
/// Get total amount of memory records
unsigned int jsvGetMemoryTotal() {
return jsVarsSize;
}
/// Try and allocate more memory - only works if RESIZABLE_JSVARS is defined
void jsvSetMemoryTotal(unsigned int jsNewVarCount) {
#ifdef RESIZABLE_JSVARS
assert(!isMemoryBusy);
if (jsNewVarCount <= jsVarsSize) return; // never allow us to have less!
isMemoryBusy = MEMBUSY_SYSTEM;
// When resizing, we just allocate a bunch more
unsigned int oldSize = jsVarsSize;
unsigned int oldBlockCount = jsVarsSize >> JSVAR_BLOCK_SHIFT;
unsigned int newBlockCount = (jsNewVarCount+JSVAR_BLOCK_SIZE-1) >> JSVAR_BLOCK_SHIFT;
jsVarsSize = newBlockCount << JSVAR_BLOCK_SHIFT;
// resize block table
jsVarBlocks = realloc(jsVarBlocks, sizeof(JsVar*)*newBlockCount);
// allocate more blocks
unsigned int i;
for (i=oldBlockCount;i<newBlockCount;i++)
jsVarBlocks[i] = malloc(sizeof(JsVar) * JSVAR_BLOCK_SIZE);
/** and now reset all the newly allocated vars. We know jsVarFirstEmpty
* is 0 (because jsiFreeMoreMemory returned 0) so we can just assign it. */
assert(!jsVarFirstEmpty);
jsVarFirstEmpty = jsvInitJsVars(oldSize+1, jsVarsSize-oldSize);
// jsiConsolePrintf("Resized memory from %d blocks to %d\n", oldBlockCount, newBlockCount);
touchedFreeList = true;
isMemoryBusy = MEM_NOT_BUSY;
#else
NOT_USED(jsNewVarCount);
assert(0);
#endif
}
bool jsvMoreFreeVariablesThan(unsigned int vars) {
if (!vars) return false;
JsVarRef r = jsVarFirstEmpty;
while (r) {
if (!vars--) return true;
r = jsvGetNextSibling(jsvGetAddressOf(r));
}
return false;
}
/// Get whether memory is full or not
bool jsvIsMemoryFull() {
return !jsVarFirstEmpty;
}
// Show what is still allocated, for debugging memory problems
void jsvShowAllocated() {
JsVarRef i;
for (i=1;i<=jsVarsSize;i++) {
if ((jsvGetAddressOf(i)->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
jsiConsolePrintf("USED VAR #%d:",i);
jsvTrace(jsvGetAddressOf(i), 2);
}
}
}
bool jsvHasCharacterData(const JsVar *v) {
return jsvIsString(v) || jsvIsStringExt(v);
}
bool jsvHasStringExt(const JsVar *v) {
return jsvIsString(v) || jsvIsStringExt(v);
}
bool jsvHasChildren(const JsVar *v) {
return jsvIsFunction(v) || jsvIsObject(v) || jsvIsArray(v) || jsvIsRoot(v);
}
/// Is this variable a type that uses firstChild to point to a single Variable (ie. it doesn't have multiple children)
bool jsvHasSingleChild(const JsVar *v) {
return jsvIsArrayBuffer(v) ||
(jsvIsName(v) && !jsvIsNameWithValue(v));
}
/** Return the is the number of characters this one JsVar can contain, NOT string length (eg, a chain of JsVars)
* This will return an invalid length when applied to Flat Strings */
size_t jsvGetMaxCharactersInVar(const JsVar *v) {
// see jsvCopy - we need to know about this in there too
if (jsvIsStringExt(v)) return JSVAR_DATA_STRING_MAX_LEN;
assert(jsvHasCharacterData(v));
if (jsvIsName(v)) return JSVAR_DATA_STRING_NAME_LEN;
return JSVAR_DATA_STRING_LEN;
}
/// This is the number of characters a JsVar can contain, NOT string length
size_t jsvGetCharactersInVar(const JsVar *v) {
unsigned int f = v->flags&JSV_VARTYPEMASK;
if (f == JSV_FLAT_STRING)
return (size_t)v->varData.integer;
if (f == JSV_NATIVE_STRING)
return (size_t)v->varData.nativeStr.len;
assert(f >= JSV_NAME_STRING_INT_0);
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
if (f<=JSV_NAME_STRING_MAX) {
if (f<=JSV_NAME_STRING_INT_MAX)
return f-JSV_NAME_STRING_INT_0;
else
return f-JSV_NAME_STRING_0;
} else {
if (f<=JSV_STRING_MAX) return f-JSV_STRING_0;
assert(f <= JSV_STRING_EXT_MAX);
return f - JSV_STRING_EXT_0;
}
}
/// This is the number of characters a JsVar can contain, NOT string length
void jsvSetCharactersInVar(JsVar *v, size_t chars) {
unsigned int f = v->flags&JSV_VARTYPEMASK;
assert(!(jsvIsFlatString(v) || jsvIsNativeString(v)));
JsVarFlags m = (JsVarFlags)(v->flags&~JSV_VARTYPEMASK);
assert(f >= JSV_NAME_STRING_INT_0);
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
if (f<=JSV_NAME_STRING_MAX) {
assert(chars <= JSVAR_DATA_STRING_NAME_LEN);
if (f<=JSV_NAME_STRING_INT_MAX)
v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_INT_0+chars));
else
v->flags = (JsVarFlags)(m | (JSV_NAME_STRING_0+chars));
} else {
if (f<=JSV_STRING_MAX) {
assert(chars <= JSVAR_DATA_STRING_LEN);
v->flags = (JsVarFlags)(m | (JSV_STRING_0+chars));
} else {
assert(chars <= JSVAR_DATA_STRING_MAX_LEN);
assert(f <= JSV_STRING_EXT_MAX);
v->flags = (JsVarFlags)(m | (JSV_STRING_EXT_0+chars));
}
}
}
void jsvResetVariable(JsVar *v, JsVarFlags flags) {
assert((v->flags&JSV_VARTYPEMASK) == JSV_UNUSED);
// make sure we clear all data...
/* Force a proper zeroing of all data. We don't use
* memset because that'd create a function call. This
* should just generate a bunch of STR instructions */
unsigned int i;
assert((sizeof(JsVar)&3) == 0); // must be a multiple of 4 in size
for (i=0;i<sizeof(JsVar)/sizeof(uint32_t);i++)
((uint32_t*)v)[i] = 0;
// set flags
assert(!(flags & JSV_LOCK_MASK));
v->flags = flags | JSV_LOCK_ONE;
}
JsVar *jsvNewWithFlags(JsVarFlags flags) {
if (isMemoryBusy) {
jsErrorFlags |= JSERR_MEMORY_BUSY;
return 0;
}
JsVar *v = 0;
jshInterruptOff(); // to allow this to be used from an IRQ
if (jsVarFirstEmpty!=0) {
v = jsvGetAddressOf(jsVarFirstEmpty); // jsvResetVariable will lock
jsVarFirstEmpty = jsvGetNextSibling(v); // move our reference to the next in the fr
touchedFreeList = true;
}
jshInterruptOn();
if (v) {
assert(v->flags == JSV_UNUSED);
// Cope with IRQs/multi-threading when getting a new free variable
/* JsVarRef empty;
JsVarRef next;
JsVar *v;
do {
empty = jsVarFirstEmpty;
v = jsvGetAddressOf(empty); // jsvResetVariable will lock
next = jsvGetNextSibling(v); // move our reference to the next in the free list
touchedFreeList = true;
} while (!__sync_bool_compare_and_swap(&jsVarFirstEmpty, empty, next));
assert(v->flags == JSV_UNUSED);*/
jsvResetVariable(v, flags); // setup variable, and add one lock
// return pointer
return v;
}
jsErrorFlags |= JSERR_LOW_MEMORY;
/* If we're calling from an IRQ, do NOT try and do fancy
* stuff to free memory */
if (jshIsInInterrupt()) {
return 0;
}
/* we don't have memory - second last hope - run garbage collector */
if (jsvGarbageCollect()) {
return jsvNewWithFlags(flags); // if it freed something, continue
}
/* we don't have memory - last hope - ask jsInteractive to try and free some it
may have kicking around */
if (jsiFreeMoreMemory()) {
return jsvNewWithFlags(flags);
}
/* We couldn't claim any more memory by Garbage collecting... */
#ifdef RESIZABLE_JSVARS
jsvSetMemoryTotal(jsVarsSize*2);
return jsvNewWithFlags(flags);
#else
// On a micro, we're screwed.
jsErrorFlags |= JSERR_MEMORY;
jspSetInterrupted(true);
return 0;
#endif
}
static NO_INLINE void jsvFreePtrInternal(JsVar *var) {
assert(jsvGetLocks(var)==0);
var->flags = JSV_UNUSED;
// add this to our free list
jshInterruptOff(); // to allow this to be used from an IRQ
jsvSetNextSibling(var, jsVarFirstEmpty);
jsVarFirstEmpty = jsvGetRef(var);
touchedFreeList = true;
jshInterruptOn();
}
ALWAYS_INLINE void jsvFreePtr(JsVar *var) {
/* To be here, we're not supposed to be part of anything else. If
* we were, we'd have been freed by jsvGarbageCollect */
assert((!jsvGetNextSibling(var) && !jsvGetPrevSibling(var)) || // check that next/prevSibling are not set
jsvIsRefUsedForData(var) || // UNLESS we're part of a string and nextSibling/prevSibling are used for string data
(jsvIsName(var) && (jsvGetNextSibling(var)==jsvGetPrevSibling(var)))); // UNLESS we're signalling that we're jsvIsNewChild
// Names that Link to other things
if (jsvIsNameWithValue(var)) {
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // it just contained random data - zero it
#endif // CLEAR_MEMORY_ON_FREE
} else if (jsvHasSingleChild(var)) {
if (jsvGetFirstChild(var)) {
JsVar *child = jsvLock(jsvGetFirstChild(var));
jsvUnRef(child);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // unlink the child
#endif // CLEAR_MEMORY_ON_FREE
jsvUnLock(child); // unlock should trigger a free
}
}
/* No else, because a String Name may have a single child, but
* also StringExts */
/* Now, free children - see jsvar.h comments for how! */
if (jsvHasStringExt(var)) {
// Free the string without recursing
JsVarRef stringDataRef = jsvGetLastChild(var);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetLastChild(var, 0);
#endif // CLEAR_MEMORY_ON_FREE
while (stringDataRef) {
JsVar *child = jsvGetAddressOf(stringDataRef);
assert(jsvIsStringExt(child));
stringDataRef = jsvGetLastChild(child);
jsvFreePtrInternal(child);
}
// We might be a flat string
if (jsvIsFlatString(var)) {
// in which case we need to free all the blocks.
size_t count = jsvGetFlatStringBlocks(var);
JsVarRef i = (JsVarRef)(jsvGetRef(var)+count);
// do it in reverse, so the free list ends up in kind of the right order
while (count--) {
JsVar *p = jsvGetAddressOf(i--);
p->flags = JSV_UNUSED; // set locks to 0 so the assert in jsvFreePtrInternal doesn't get fed up
jsvFreePtrInternal(p);
}
} else if (jsvIsBasicString(var)) {
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0); // firstchild could have had string data in
#endif // CLEAR_MEMORY_ON_FREE
}
}
/* NO ELSE HERE - because jsvIsNewChild stuff can be for Names, which
can be ints or strings */
if (jsvHasChildren(var)) {
JsVarRef childref = jsvGetFirstChild(var);
#ifdef CLEAR_MEMORY_ON_FREE
jsvSetFirstChild(var, 0);
jsvSetLastChild(var, 0);
#endif // CLEAR_MEMORY_ON_FREE
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsName(child));
childref = jsvGetNextSibling(child);
jsvSetPrevSibling(child, 0);
jsvSetNextSibling(child, 0);
jsvUnRef(child);
jsvUnLock(child);
}
} else {
#ifdef CLEAR_MEMORY_ON_FREE
#if JSVARREF_SIZE==1
assert(jsvIsFloat(var) || !jsvGetFirstChild(var));
assert(jsvIsFloat(var) || !jsvGetLastChild(var));
#else
assert(!jsvGetFirstChild(var)); // strings use firstchild now as well
assert(!jsvGetLastChild(var));
#endif
#endif // CLEAR_MEMORY_ON_FREE
if (jsvIsName(var)) {
assert(jsvGetNextSibling(var)==jsvGetPrevSibling(var)); // the case for jsvIsNewChild
if (jsvGetNextSibling(var)) {
jsvUnRefRef(jsvGetNextSibling(var));
jsvUnRefRef(jsvGetPrevSibling(var));
}
}
}
// free!
jsvFreePtrInternal(var);
}
/// Get a reference from a var - SAFE for null vars
ALWAYS_INLINE JsVarRef jsvGetRef(JsVar *var) {
if (!var) return 0;
#ifdef RESIZABLE_JSVARS
unsigned int i, c = jsVarsSize>>JSVAR_BLOCK_SHIFT;
for (i=0;i<c;i++) {
if (var>=jsVarBlocks[i] && var<&jsVarBlocks[i][JSVAR_BLOCK_SIZE]) {
JsVarRef r = (JsVarRef)(1 + (i<<JSVAR_BLOCK_SHIFT) + (var - jsVarBlocks[i]));
return r;
}
}
return 0;
#else
return (JsVarRef)(1 + (var - jsVars));
#endif
}
/// Lock this reference and return a pointer - UNSAFE for null refs
ALWAYS_INLINE JsVar *jsvLock(JsVarRef ref) {
JsVar *var = jsvGetAddressOf(ref);
//var->locks++;
assert(jsvGetLocks(var) < JSV_LOCK_MAX);
var->flags += JSV_LOCK_ONE;
#ifdef DEBUG
if (jsvGetLocks(var)==0) {
jsError("Too many locks to Variable!");
//jsPrint("Var #");jsPrintInt(ref);jsPrint("\n");
}
#endif
return var;
}
/// Lock this pointer and return a pointer - UNSAFE for null pointer
ALWAYS_INLINE JsVar *jsvLockAgain(JsVar *var) {
assert(var);
assert(jsvGetLocks(var) < JSV_LOCK_MAX);
var->flags += JSV_LOCK_ONE;
return var;
}
/// Lock this pointer and return a pointer - UNSAFE for null pointer
ALWAYS_INLINE JsVar *jsvLockAgainSafe(JsVar *var) {
return var ? jsvLockAgain(var) : 0;
}
// CALL ONLY FROM jsvUnlock
// jsvGetLocks(var) must == 0
static NO_INLINE void jsvUnLockFreeIfNeeded(JsVar *var) {
assert(jsvGetLocks(var) == 0);
/* if we know we're free, then we can just free this variable right now.
* Loops of variables are handled by the Garbage Collector.
* Note: we checked locks already in jsvUnLock as it is fastest to check */
if (jsvGetRefs(var) == 0 &&
jsvHasRef(var) &&
(var->flags&JSV_VARTYPEMASK)!=JSV_UNUSED) { // we might be in an IRQ now, with GC in the main thread. If so, don't free!
jsvFreePtr(var);
}
}
/// Unlock this variable - this is SAFE for null variables
ALWAYS_INLINE void jsvUnLock(JsVar *var) {
if (!var) return;
assert(jsvGetLocks(var)>0);
var->flags -= JSV_LOCK_ONE;
// Now see if we can properly free the data
// Note: we check locks first as they are already in a register
if ((var->flags & JSV_LOCK_MASK) == 0) jsvUnLockFreeIfNeeded(var);
}
/// Unlock 2 variables in one go
void jsvUnLock2(JsVar *var1, JsVar *var2) {
jsvUnLock(var1);
jsvUnLock(var2);
}
/// Unlock 3 variables in one go
void jsvUnLock3(JsVar *var1, JsVar *var2, JsVar *var3) {
jsvUnLock(var1);
jsvUnLock(var2);
jsvUnLock(var3);
}
/// Unlock 4 variables in one go
void jsvUnLock4(JsVar *var1, JsVar *var2, JsVar *var3, JsVar *var4) {
jsvUnLock(var1);
jsvUnLock(var2);
jsvUnLock(var3);
jsvUnLock(var4);
}
/// Unlock an array of variables
NO_INLINE void jsvUnLockMany(unsigned int count, JsVar **vars) {
while (count) jsvUnLock(vars[--count]);
}
/// Reference - set this variable as used by something
JsVar *jsvRef(JsVar *var) {
assert(var && jsvHasRef(var));
jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)+1));
assert(jsvGetRefs(var));
return var;
}
/// Unreference - set this variable as not used by anything
void jsvUnRef(JsVar *var) {
assert(var && jsvGetRefs(var)>0 && jsvHasRef(var));
jsvSetRefs(var, (JsVarRefCounter)(jsvGetRefs(var)-1));
}
/// Helper fn, Reference - set this variable as used by something
JsVarRef jsvRefRef(JsVarRef ref) {
JsVar *v;
assert(ref);
v = jsvLock(ref);
assert(!jsvIsStringExt(v));
jsvRef(v);
jsvUnLock(v);
return ref;
}
/// Helper fn, Unreference - set this variable as not used by anything
JsVarRef jsvUnRefRef(JsVarRef ref) {
JsVar *v;
assert(ref);
v = jsvLock(ref);
assert(!jsvIsStringExt(v));
jsvUnRef(v);
jsvUnLock(v);
return 0;
}
JsVar *jsvNewFlatStringOfLength(unsigned int byteLength) {
if (isMemoryBusy) {
jsErrorFlags |= JSERR_MEMORY_BUSY;
return 0;
}
// Work out how many blocks we need. One for the header, plus some for the characters
size_t requiredBlocks = 1 + ((byteLength+sizeof(JsVar)-1) / sizeof(JsVar));
JsVar *flatString = 0;
/* Now try and find a contiguous set of 'requiredBlocks' blocks by
searching the free list. This can be done as long as nobody's
messed with the free list in the mean time (which we check for with
touchedFreeList). If someone has messed with it, we restart.*/
bool memoryTouched = true;
while (memoryTouched) {
memoryTouched = false;
touchedFreeList = false;
JsVarRef beforeStartBlock = 0;
JsVarRef curr = jsVarFirstEmpty;
JsVarRef startBlock = curr;
unsigned int blockCount = 1;
while (curr && !touchedFreeList) {
JsVar *currVar = jsvGetAddressOf(curr);
JsVarRef next = jsvGetNextSibling(currVar);
#ifdef RESIZABLE_JSVARS
if (next && jsvGetAddressOf(next)==currVar+1) {
#else
if (next == curr+1) {
#endif
blockCount++;
if (blockCount>=requiredBlocks) {
JsVar *nextVar = jsvGetAddressOf(next);
JsVarRef nextFree = jsvGetNextSibling(nextVar);
jshInterruptOff();
if (!touchedFreeList) {
// we're there! Quickly re-link free list
if (beforeStartBlock) {
jsvSetNextSibling(jsvGetAddressOf(beforeStartBlock),nextFree);
} else {
jsVarFirstEmpty = nextFree;
}
flatString = jsvGetAddressOf(startBlock);
// Set up the header block (including one lock)
jsvResetVariable(flatString, JSV_FLAT_STRING);
flatString->varData.integer = (JsVarInt)byteLength;
}
jshInterruptOn();
// if success, break out!
if (flatString) break;
}
} else {
// this block is not immediately after the last - restart run
blockCount = 1;
beforeStartBlock = curr;
startBlock = next;
}
// move to next!
curr = next;
}
// memory list has been touched - restart!
if (touchedFreeList) {
memoryTouched = true;
}
}
/* Nope... we couldn't find a free string. It could be because
* the free list is fragmented, so GCing might well fix it - which
* we'll try. */
if (!flatString) {
if (jsvGarbageCollect())
return jsvNewFlatStringOfLength(byteLength);
return 0;
}
/* We now have the string! All that's left is to clear it,
* which we can do outside of an IRQ */
// clear data
memset((char*)&flatString[1], 0, sizeof(JsVar)*(requiredBlocks-1));
/* We did mess with the free list - set it here in case we
are trying to create a flat string in an IRQ while trying to
make one outside the IRQ too */
touchedFreeList = true;
// and we're done
return flatString;
}
JsVar *jsvNewFromString(const char *str) {
// Create a var
JsVar *first = jsvNewWithFlags(JSV_STRING_0);
if (!first) return 0; // out of memory
// Now we copy the string, but keep creating new jsVars if we go
// over the end
JsVar *var = jsvLockAgain(first);
while (*str) {
// copy data in
size_t i, l = jsvGetMaxCharactersInVar(var);
for (i=0;i<l && *str;i++)
var->varData.str[i] = *(str++);
// we already set the variable data to 0, so no need for adding one
// we've stopped if the string was empty
jsvSetCharactersInVar(var, i);
// if there is still some left, it's because we filled up our var...
// make a new one, link it in, and unlock the old one.
if (*str) {
JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0);
if (!next) {
// Truncating string as not enough memory
jsvUnLock(var);
return first;
}
// we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner)
jsvSetLastChild(var, jsvGetRef(next));
jsvUnLock(var);
var = next;
}
}
jsvUnLock(var);
// return
return first;
}
JsVar *jsvNewStringOfLength(unsigned int byteLength, const char *initialData) {
// if string large enough, try and make a flat string instead
if (byteLength > JSV_FLAT_STRING_BREAK_EVEN) {
JsVar *v = jsvNewFlatStringOfLength(byteLength);
if (v) {
if (initialData) jsvSetString(v, initialData, byteLength);
return v;
}
}
// Create a var
JsVar *first = jsvNewWithFlags(JSV_STRING_0);
if (!first) return 0; // out of memory, will have already set flag
// Now keep creating enough new jsVars
JsVar *var = jsvLockAgain(first);
while (true) {
// copy data in
unsigned int l = (unsigned int)jsvGetMaxCharactersInVar(var);
if (l>=byteLength) {
if (initialData)
memcpy(var->varData.str, initialData, byteLength);
// we've got enough
jsvSetCharactersInVar(var, byteLength);
break;
} else {
if (initialData) {
memcpy(var->varData.str, initialData, l);
initialData+=l;
}
// We need more
jsvSetCharactersInVar(var, l);
byteLength -= l;
// Make a new one, link it in, and unlock the old one.
JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0);
if (!next) break; // out of memory, will have already set flag
// we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner)
jsvSetLastChild(var, jsvGetRef(next));
jsvUnLock(var);
var = next;
}
}
jsvUnLock(var);
// return
return first;
}
JsVar *jsvNewFromInteger(JsVarInt value) {
JsVar *var = jsvNewWithFlags(JSV_INTEGER);
if (!var) return 0; // no memory
var->varData.integer = value;
return var;
}
JsVar *jsvNewFromBool(bool value) {
JsVar *var = jsvNewWithFlags(JSV_BOOLEAN);
if (!var) return 0; // no memory
var->varData.integer = value ? 1 : 0;
return var;
}
JsVar *jsvNewFromFloat(JsVarFloat value) {
JsVar *var = jsvNewWithFlags(JSV_FLOAT);
if (!var) return 0; // no memory
var->varData.floating = value;
return var;
}
JsVar *jsvNewFromLongInteger(long long value) {
if (value>=-2147483648LL && value<=2147483647LL)
return jsvNewFromInteger((JsVarInt)value);
else
return jsvNewFromFloat((JsVarFloat)value);
}
JsVar *jsvMakeIntoVariableName(JsVar *var, JsVar *valueOrZero) {
if (!var) return 0;
assert(jsvGetRefs(var)==0); // make sure it's unused
assert(jsvIsSimpleInt(var) || jsvIsString(var));
JsVarFlags varType = (var->flags & JSV_VARTYPEMASK);
if (varType==JSV_INTEGER) {
int t = JSV_NAME_INT;
if ((jsvIsInt(valueOrZero) || jsvIsBoolean(valueOrZero)) && !jsvIsPin(valueOrZero)) {
JsVarInt v = valueOrZero->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
t = jsvIsInt(valueOrZero) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL;
jsvSetFirstChild(var, (JsVarRef)v);
valueOrZero = 0;
}
}
var->flags = (JsVarFlags)(var->flags & ~JSV_VARTYPEMASK) | t;
} else if (varType>=_JSV_STRING_START && varType<=_JSV_STRING_END) {
if (jsvGetCharactersInVar(var) > JSVAR_DATA_STRING_NAME_LEN) {
/* Argh. String is too large to fit in a JSV_NAME! We must chomp make
* new STRINGEXTs to put the data in
*/
JsvStringIterator it;
jsvStringIteratorNew(&it, var, JSVAR_DATA_STRING_NAME_LEN);
JsVar *startExt = jsvNewWithFlags(JSV_STRING_EXT_0);
JsVar *ext = jsvLockAgainSafe(startExt);
size_t nChars = 0;
while (ext && jsvStringIteratorHasChar(&it)) {
if (nChars >= JSVAR_DATA_STRING_MAX_LEN) {
jsvSetCharactersInVar(ext, nChars);
JsVar *ext2 = jsvNewWithFlags(JSV_STRING_EXT_0);
if (ext2) {
jsvSetLastChild(ext, jsvGetRef(ext2));
}
jsvUnLock(ext);
ext = ext2;
nChars = 0;
}
ext->varData.str[nChars++] = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
if (ext) {
jsvSetCharactersInVar(ext, nChars);
jsvUnLock(ext);
}
jsvSetCharactersInVar(var, JSVAR_DATA_STRING_NAME_LEN);
// Free any old stringexts
JsVarRef oldRef = jsvGetLastChild(var);
while (oldRef) {
JsVar *v = jsvGetAddressOf(oldRef);
oldRef = jsvGetLastChild(v);
jsvFreePtrInternal(v);
}
// set up new stringexts
jsvSetLastChild(var, jsvGetRef(startExt));
jsvSetNextSibling(var, 0);
jsvSetPrevSibling(var, 0);
jsvSetFirstChild(var, 0);
jsvUnLock(startExt);
}
size_t t = JSV_NAME_STRING_0;
if (jsvIsInt(valueOrZero) && !jsvIsPin(valueOrZero)) {
JsVarInt v = valueOrZero->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
t = JSV_NAME_STRING_INT_0;
jsvSetFirstChild(var, (JsVarRef)v);
valueOrZero = 0;
}
} else
jsvSetFirstChild(var, 0);
var->flags = (var->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (t+jsvGetCharactersInVar(var));
} else assert(0);
if (valueOrZero)
jsvSetFirstChild(var, jsvGetRef(jsvRef(valueOrZero)));
return var;
}
void jsvMakeFunctionParameter(JsVar *v) {
assert(jsvIsString(v));
if (!jsvIsName(v)) jsvMakeIntoVariableName(v,0);
v->flags = (JsVarFlags)(v->flags | JSV_NATIVE);
}
JsVar *jsvNewFromPin(int pin) {
JsVar *v = jsvNewFromInteger((JsVarInt)pin);
if (v) {
v->flags = (JsVarFlags)((v->flags & ~JSV_VARTYPEMASK) | JSV_PIN);
}
return v;
}
JsVar *jsvNewObject() {
return jsvNewWithFlags(JSV_OBJECT);
}
JsVar *jsvNewEmptyArray() {
return jsvNewWithFlags(JSV_ARRAY);
}
/// Create an array containing the given elements
JsVar *jsvNewArray(JsVar **elements, int elementCount) {
JsVar *arr = jsvNewEmptyArray();
if (!arr) return 0;
int i;
for (i=0;i<elementCount;i++)
jsvArrayPush(arr, elements[i]);
return arr;
}
JsVar *jsvNewNativeFunction(void (*ptr)(void), unsigned short argTypes) {
JsVar *func = jsvNewWithFlags(JSV_FUNCTION | JSV_NATIVE);
if (!func) return 0;
func->varData.native.ptr = ptr;
func->varData.native.argTypes = argTypes;
return func;
}
JsVar *jsvNewNativeString(char *ptr, size_t len) {
if (len>JSV_NATIVE_STR_MAX_LENGTH) len=JSV_NATIVE_STR_MAX_LENGTH; // crop string to what we can store in nativeStr.len
JsVar *str = jsvNewWithFlags(JSV_NATIVE_STRING);
if (!str) return 0;
str->varData.nativeStr.ptr = ptr;
str->varData.nativeStr.len = (uint16_t)len;
return str;
}
void *jsvGetNativeFunctionPtr(const JsVar *function) {
/* see descriptions in jsvar.h. If we have a child called JSPARSE_FUNCTION_CODE_NAME
* then we execute code straight from that */
JsVar *flatString = jsvFindChildFromString((JsVar*)function, JSPARSE_FUNCTION_CODE_NAME, 0);
if (flatString) {
flatString = jsvSkipNameAndUnLock(flatString);
void *v = (void*)((size_t)function->varData.native.ptr + (char*)jsvGetFlatStringPointer(flatString));
jsvUnLock(flatString);
return v;
} else
return (void *)function->varData.native.ptr;
}
/// Create a new ArrayBuffer backed by the given string. If length is not specified, it will be worked out
JsVar *jsvNewArrayBufferFromString(JsVar *str, unsigned int lengthOrZero) {
JsVar *arr = jsvNewWithFlags(JSV_ARRAYBUFFER);
if (!arr) return 0;
jsvSetFirstChild(arr, jsvGetRef(jsvRef(str)));
arr->varData.arraybuffer.type = ARRAYBUFFERVIEW_ARRAYBUFFER;
assert(arr->varData.arraybuffer.byteOffset == 0);
if (lengthOrZero==0) lengthOrZero = (unsigned int)jsvGetStringLength(str);
arr->varData.arraybuffer.length = (unsigned short)lengthOrZero;
return arr;
}
bool jsvIsBasicVarEqual(JsVar *a, JsVar *b) {
// quick checks
if (a==b) return true;
if (!a || !b) return false; // one of them is undefined
// OPT: would this be useful as compare instead?
assert(jsvIsBasic(a) && jsvIsBasic(b));
if (jsvIsNumeric(a) && jsvIsNumeric(b)) {
if (jsvIsIntegerish(a)) {
if (jsvIsIntegerish(b)) {
return a->varData.integer == b->varData.integer;
} else {
assert(jsvIsFloat(b));
return a->varData.integer == b->varData.floating;
}
} else {
assert(jsvIsFloat(a));
if (jsvIsIntegerish(b)) {
return a->varData.floating == b->varData.integer;
} else {
assert(jsvIsFloat(b));
return a->varData.floating == b->varData.floating;
}
}
} else if (jsvIsString(a) && jsvIsString(b)) {
JsvStringIterator ita, itb;
jsvStringIteratorNew(&ita, a, 0);
jsvStringIteratorNew(&itb, b, 0);
while (true) {
char a = jsvStringIteratorGetChar(&ita);
char b = jsvStringIteratorGetChar(&itb);
if (a != b) {
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return false;
}
if (!a) { // equal, but end of string
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return true;
}
jsvStringIteratorNext(&ita);
jsvStringIteratorNext(&itb);
}
// we never get here
return false; // make compiler happy
} else {
//TODO: are there any other combinations we should check here?? String v int?
return false;
}
}
bool jsvIsEqual(JsVar *a, JsVar *b) {
if (jsvIsBasic(a) && jsvIsBasic(b))
return jsvIsBasicVarEqual(a,b);
return jsvGetRef(a)==jsvGetRef(b);
}
/// Get a const string representing this variable - if we can. Otherwise return 0
const char *jsvGetConstString(const JsVar *v) {
if (jsvIsUndefined(v)) {
return "undefined";
} else if (jsvIsNull(v)) {
return "null";
} else if (jsvIsBoolean(v)) {
return jsvGetBool(v) ? "true" : "false";
}
return 0;
}
/// Return the 'type' of the JS variable (eg. JS's typeof operator)
const char *jsvGetTypeOf(const JsVar *v) {
if (jsvIsUndefined(v)) return "undefined";
if (jsvIsNull(v) || jsvIsObject(v) ||
jsvIsArray(v) || jsvIsArrayBuffer(v)) return "object";
if (jsvIsFunction(v)) return "function";
if (jsvIsString(v)) return "string";
if (jsvIsBoolean(v)) return "boolean";
if (jsvIsNumeric(v)) return "number";
return "?";
}
/// Return the JsVar, or if it's an object and has a valueOf function, call that
JsVar *jsvGetValueOf(JsVar *v) {
if (!jsvIsObject(v)) return jsvLockAgainSafe(v);
JsVar *valueOf = jspGetNamedField(v, "valueOf", false);
if (!jsvIsFunction(valueOf)) {
jsvUnLock(valueOf);
return jsvLockAgain(v);
}
v = jspeFunctionCall(valueOf, 0, v, false, 0, 0);
jsvUnLock(valueOf);
return v;
}
/** Save this var as a string to the given buffer, and return how long it was (return val doesn't include terminating 0)
If the buffer length is exceeded, the returned value will == len */
size_t jsvGetString(const JsVar *v, char *str, size_t len) {
const char *s = jsvGetConstString(v);
if (s) {
strncpy(str, s, len);
str[len-1] = 0;
return strlen(s);
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, str, 10);
return strlen(str);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, str, len);
return strlen(str);
} else if (jsvHasCharacterData(v)) {
assert(!jsvIsStringExt(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=1) {
*str = 0;
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
} else {
// Try and get as a JsVar string, and try again
JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
if (stringVar) {
size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
jsvUnLock(stringVar);
return l;
} else {
str[0] = 0;
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
return 0;
}
}
}
/// Get len bytes of string data from this string. Does not error if string len is not equal to len
size_t jsvGetStringChars(const JsVar *v, size_t startChar, char *str, size_t len) {
assert(jsvHasCharacterData(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, startChar);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=0) {
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
}
/// Set the Data in this string. This must JUST overwrite - not extend or shrink
void jsvSetString(JsVar *v, const char *str, size_t len) {
assert(jsvHasCharacterData(v));
// the iterator checks, so it is safe not to assert if the length is different
//assert(len == jsvGetStringLength(v));
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
size_t i;
for (i=0;i<len;i++) {
jsvStringIteratorSetChar(&it, str[i]);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
}
/** If var is a string, lock and return it, else
* create a new string. unlockVar means this will auto-unlock 'var' */
JsVar *jsvAsString(JsVar *v, bool unlockVar) {
JsVar *str = 0;
// If it is string-ish, but not quite a string, copy it
if (jsvHasCharacterData(v) && jsvIsName(v)) {
str = jsvNewFromStringVar(v,0,JSVAPPENDSTRINGVAR_MAXLENGTH);
} else if (jsvIsString(v)) { // If it is a string - just return a reference
str = jsvLockAgain(v);
} else if (jsvIsObject(v)) { // If it is an object and we can call toString on it
JsVar *toStringFn = jspGetNamedField(v, "toString", false);
if (toStringFn && toStringFn->varData.native.ptr != (void (*)(void))jswrap_object_toString) {
// Function found and it's not the default one - execute it
JsVar *result = jspExecuteFunction(toStringFn,v,0,0);
jsvUnLock(toStringFn);
str = jsvAsString(result, true);
} else {
jsvUnLock(toStringFn);
str = jsvNewFromString("[object Object]");
}
} else {
const char *constChar = jsvGetConstString(v);
assert(JS_NUMBER_BUFFER_SIZE>=10);
char buf[JS_NUMBER_BUFFER_SIZE];
if (constChar) {
// if we could get this as a simple const char, do that..
str = jsvNewFromString(constChar);
} else if (jsvIsPin(v)) {
jshGetPinString(buf, (Pin)v->varData.integer);
str = jsvNewFromString(buf);
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, buf, 10);
str = jsvNewFromString(buf);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, buf, sizeof(buf));
str = jsvNewFromString(buf);
} else if (jsvIsArray(v) || jsvIsArrayBuffer(v)) {
JsVar *filler = jsvNewFromString(",");
str = jsvArrayJoin(v, filler);
jsvUnLock(filler);
} else if (jsvIsFunction(v)) {
str = jsvNewFromEmptyString();
if (str) jsfGetJSON(v, str, JSON_NONE);
} else {
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
str = 0;
}
}
if (unlockVar) jsvUnLock(v);
return str;
}
JsVar *jsvAsFlatString(JsVar *var) {
if (jsvIsFlatString(var)) return jsvLockAgain(var);
JsVar *str = jsvAsString(var, false);
size_t len = jsvGetStringLength(str);
JsVar *flat = jsvNewFlatStringOfLength((unsigned int)len);
if (flat) {
JsvStringIterator src;
JsvStringIterator dst;
jsvStringIteratorNew(&src, str, 0);
jsvStringIteratorNew(&dst, flat, 0);
while (len--) {
jsvStringIteratorSetChar(&dst, jsvStringIteratorGetChar(&src));
if (len>0) {
jsvStringIteratorNext(&src);
jsvStringIteratorNext(&dst);
}
}
jsvStringIteratorFree(&src);
jsvStringIteratorFree(&dst);
}
jsvUnLock(str);
return flat;
}
/** Given a JsVar meant to be an index to an array, convert it to
* the actual variable type we'll use to access the array. For example
* a["0"] is actually translated to a[0]
*/
JsVar *jsvAsArrayIndex(JsVar *index) {
if (jsvIsSimpleInt(index)) {
return jsvLockAgain(index); // we're ok!
} else if (jsvIsString(index)) {
/* Index filtering (bug #19) - if we have an array index A that is:
is_string(A) && int_to_string(string_to_int(A)) == A
then convert it to an integer. Shouldn't be too nasty for performance
as we only do this when accessing an array with a string */
if (jsvIsStringNumericStrict(index)) {
JsVar *i = jsvNewFromInteger(jsvGetInteger(index));
JsVar *is = jsvAsString(i, false);
if (jsvCompareString(index,is,0,0,false)==0) {
// two items are identical - use the integer
jsvUnLock(is);
return i;
} else {
// not identical, use as a string
jsvUnLock2(i,is);
}
}
} else if (jsvIsFloat(index)) {
// if it's a float that is actually integral, return an integer...
JsVarFloat v = jsvGetFloat(index);
JsVarInt vi = jsvGetInteger(index);
if (v == vi) return jsvNewFromInteger(vi);
}
// else if it's not a simple numeric type, convert it to a string
return jsvAsString(index, false);
}
/** Same as jsvAsArrayIndex, but ensures that 'index' is unlocked */
JsVar *jsvAsArrayIndexAndUnLock(JsVar *a) {
JsVar *b = jsvAsArrayIndex(a);
jsvUnLock(a);
return b;
}
/// Returns true if the string is empty - faster than jsvGetStringLength(v)==0
bool jsvIsEmptyString(JsVar *v) {
if (!jsvHasCharacterData(v)) return true;
return jsvGetCharactersInVar(v)==0;
}
size_t jsvGetStringLength(const JsVar *v) {
size_t strLength = 0;
const JsVar *var = v;
JsVar *newVar = 0;
if (!jsvHasCharacterData(v)) return 0;
while (var) {
JsVarRef ref = jsvGetLastChild(var);
strLength += jsvGetCharactersInVar(var);
// Go to next
jsvUnLock(newVar); // note use of if (ref), not var
var = newVar = ref ? jsvLock(ref) : 0;
}
jsvUnLock(newVar); // note use of if (ref), not var
return strLength;
}
size_t jsvGetFlatStringBlocks(const JsVar *v) {
assert(jsvIsFlatString(v));
return ((size_t)v->varData.integer+sizeof(JsVar)-1) / sizeof(JsVar);
}
char *jsvGetFlatStringPointer(JsVar *v) {
assert(jsvIsFlatString(v));
if (!jsvIsFlatString(v)) return 0;
return (char*)(v+1); // pointer to the next JsVar
}
JsVar *jsvGetFlatStringFromPointer(char *v) {
JsVar *secondVar = (JsVar*)v;
JsVar *flatStr = secondVar-1;
assert(jsvIsFlatString(flatStr));
return flatStr;
}
/// If the variable points to a *flat* area of memory, return a pointer (and set length). Otherwise return 0.
char *jsvGetDataPointer(JsVar *v, size_t *len) {
assert(len);
if (jsvIsArrayBuffer(v)) {
/* Arraybuffers generally use some kind of string to store their data.
* Find it, then call ourselves again to figure out if we can get a
* raw pointer to it. */
JsVar *d = jsvGetArrayBufferBackingString(v);
char *r = jsvGetDataPointer(d, len);
jsvUnLock(d);
if (r) {
r += v->varData.arraybuffer.byteOffset;
*len = v->varData.arraybuffer.length;
}
return r;
}
if (jsvIsNativeString(v)) {
*len = v->varData.nativeStr.len;
return (char*)v->varData.nativeStr.ptr;
}
if (jsvIsFlatString(v)) {
*len = jsvGetStringLength(v);
return jsvGetFlatStringPointer(v);
}
return 0;
}
// IN A STRING get the number of lines in the string (min=1)
size_t jsvGetLinesInString(JsVar *v) {
size_t lines = 1;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (jsvStringIteratorGetChar(&it)=='\n') lines++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return lines;
}
// IN A STRING Get the number of characters on a line - lines start at 1
size_t jsvGetCharsOnLine(JsVar *v, size_t line) {
size_t currentLine = 1;
size_t chars = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (jsvStringIteratorGetChar(&it)=='\n') {
currentLine++;
if (currentLine > line) break;
} else if (currentLine==line) chars++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return chars;
}
// IN A STRING, get the 1-based line and column of the given character. Both values must be non-null
void jsvGetLineAndCol(JsVar *v, size_t charIdx, size_t *line, size_t *col) {
size_t x = 1;
size_t y = 1;
size_t n = 0;
assert(line && col);
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if (n==charIdx) {
jsvStringIteratorFree(&it);
*line = y;
*col = x;
return;
}
x++;
if (ch=='\n') {
x=1; y++;
}
n++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
// uh-oh - not found
*line = y;
*col = x;
}
// IN A STRING, get a character index from a line and column
size_t jsvGetIndexFromLineAndCol(JsVar *v, size_t line, size_t col) {
size_t x = 1;
size_t y = 1;
size_t n = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if ((y==line && x>=col) || y>line) {
jsvStringIteratorFree(&it);
return (y>line) ? (n-1) : n;
}
x++;
if (ch=='\n') {
x=1; y++;
}
n++;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return n;
}
void jsvAppendString(JsVar *var, const char *str) {
assert(jsvIsString(var));
JsvStringIterator dst;
jsvStringIteratorNew(&dst, var, 0);
jsvStringIteratorGotoEnd(&dst);
// now start appending
/* This isn't as fast as something single-purpose, but it's not that bad,
* and is less likely to break :) */
while (*str)
jsvStringIteratorAppend(&dst, *(str++));
jsvStringIteratorFree(&dst);
}
// Append the given string to this one - but does not use null-terminated strings
void jsvAppendStringBuf(JsVar *var, const char *str, size_t length) {
assert(jsvIsString(var));
JsvStringIterator dst;
jsvStringIteratorNew(&dst, var, 0);
jsvStringIteratorGotoEnd(&dst);
// now start appending
/* This isn't as fast as something single-purpose, but it's not that bad,
* and is less likely to break :) */
while (length) {
jsvStringIteratorAppend(&dst, *(str++));
length--;
}
jsvStringIteratorFree(&dst);
}
/// Special version of append designed for use with vcbprintf_callback (See jsvAppendPrintf)
void jsvStringIteratorPrintfCallback(const char *str, void *user_data) {
while (*str)
jsvStringIteratorAppend((JsvStringIterator *)user_data, *(str++));
}
void jsvAppendPrintf(JsVar *var, const char *fmt, ...) {
JsvStringIterator it;
jsvStringIteratorNew(&it, var, 0);
jsvStringIteratorGotoEnd(&it);
va_list argp;
va_start(argp, fmt);
vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp);
va_end(argp);
jsvStringIteratorFree(&it);
}
JsVar *jsvVarPrintf( const char *fmt, ...) {
JsVar *str = jsvNewFromEmptyString();
if (!str) return 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
jsvStringIteratorGotoEnd(&it);
va_list argp;
va_start(argp, fmt);
vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp);
va_end(argp);
jsvStringIteratorFree(&it);
return str;
}
/** Append str to var. Both must be strings. stridx = start char or str, maxLength = max number of characters (can be JSVAPPENDSTRINGVAR_MAXLENGTH) */
void jsvAppendStringVar(JsVar *var, const JsVar *str, size_t stridx, size_t maxLength) {
assert(jsvIsString(var));
JsvStringIterator dst;
jsvStringIteratorNew(&dst, var, 0);
jsvStringIteratorGotoEnd(&dst);
// now start appending
/* This isn't as fast as something single-purpose, but it's not that bad,
* and is less likely to break :) */
JsvStringIterator it;
jsvStringIteratorNewConst(&it, str, stridx);
while (jsvStringIteratorHasChar(&it) && (maxLength-->0)) {
char ch = jsvStringIteratorGetChar(&it);
jsvStringIteratorAppend(&dst, ch);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
jsvStringIteratorFree(&dst);
}
/** Create a new variable from a substring. argument must be a string. stridx = start char or str, maxLength = max number of characters (can be JSVAPPENDSTRINGVAR_MAXLENGTH) */
JsVar *jsvNewFromStringVar(const JsVar *str, size_t stridx, size_t maxLength) {
JsVar *var = jsvNewFromEmptyString();
if (var) jsvAppendStringVar(var, str, stridx, maxLength);
return var;
}
/** Append all of str to var. Both must be strings. */
void jsvAppendStringVarComplete(JsVar *var, const JsVar *str) {
jsvAppendStringVar(var, str, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
}
char jsvGetCharInString(JsVar *v, size_t idx) {
if (!jsvIsString(v)) return 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, v, idx);
char ch = jsvStringIteratorGetChar(&it);
jsvStringIteratorFree(&it);
return ch;
}
/// Get the index of a character in a string, or -1
int jsvGetStringIndexOf(JsVar *str, char ch) {
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
while (jsvStringIteratorHasChar(&it)) {
if (jsvStringIteratorGetChar(&it) == ch) {
int idx = (int)jsvStringIteratorGetIndex(&it);
jsvStringIteratorFree(&it);
return idx;
};
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return -1;
}
/** Does this string contain only Numeric characters (with optional '-'/'+' at the front)? NOT '.'/'e' and similar (allowDecimalPoint is for '.' only) */
bool jsvIsStringNumericInt(const JsVar *var, bool allowDecimalPoint) {
assert(jsvIsString(var));
JsvStringIterator it;
jsvStringIteratorNewConst(&it, var, 0); // we know it's non const
// skip whitespace
while (jsvStringIteratorHasChar(&it) && isWhitespace(jsvStringIteratorGetChar(&it)))
jsvStringIteratorNext(&it);
// skip a minus. if there was one
if (jsvStringIteratorGetChar(&it)=='-' || jsvStringIteratorGetChar(&it)=='+')
jsvStringIteratorNext(&it);
int radix = 0;
if (jsvStringIteratorGetChar(&it)=='0') {
jsvStringIteratorNext(&it);
char buf[3];
buf[0] = '0';
buf[1] = jsvStringIteratorGetChar(&it);
buf[2] = 0;
const char *p = buf;
radix = getRadix(&p,0,0);
if (p>&buf[1]) jsvStringIteratorNext(&it);
}
if (radix==0) radix=10;
// now check...
int chars=0;
while (jsvStringIteratorHasChar(&it)) {
chars++;
char ch = jsvStringIteratorGetChar(&it);
if (ch=='.' && allowDecimalPoint) {
allowDecimalPoint = false; // there can be only one
} else {
int n = chtod(ch);
if (n<0 || n>=radix) {
jsvStringIteratorFree(&it);
return false;
}
}
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return chars>0;
}
/** Does this string contain only Numeric characters? This is for arrays
* and makes the assertion that int_to_string(string_to_int(var))==var */
bool jsvIsStringNumericStrict(const JsVar *var) {
assert(jsvIsString(var));
JsvStringIterator it;
jsvStringIteratorNewConst(&it, var, 0); // we know it's non const
bool hadNonZero = false;
bool hasLeadingZero = false;
int chars = 0;
while (jsvStringIteratorHasChar(&it)) {
chars++;
char ch = jsvStringIteratorGetChar(&it);
if (!isNumeric(ch)) {
// test for leading zero ensures int_to_string(string_to_int(var))==var
jsvStringIteratorFree(&it);
return false;
}
if (!hadNonZero && ch=='0') hasLeadingZero=true;
if (ch!='0') hadNonZero=true;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return chars>0 && (!hasLeadingZero || chars==1);
}
JsVarInt jsvGetInteger(const JsVar *v) {
if (!v) return 0; // undefined
/* strtol understands about hex and octal */
if (jsvIsNull(v)) return 0;
if (jsvIsUndefined(v)) return 0;
if (jsvIsIntegerish(v) || jsvIsArrayBufferName(v)) return v->varData.integer;
if (jsvIsArray(v) || jsvIsArrayBuffer(v)) {
JsVarInt l = jsvGetLength((JsVar *)v);
if (l==0) return 0; // 0 length, return 0
if (l==1) {
if (jsvIsArrayBuffer(v))
return jsvGetIntegerAndUnLock(jsvArrayBufferGet((JsVar*)v,0));
return jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jsvGetArrayItem(v,0)));
}
}
if (jsvIsFloat(v)) {
if (isfinite(v->varData.floating))
return (JsVarInt)(long long)v->varData.floating;
return 0;
}
if (jsvIsString(v) && jsvIsStringNumericInt(v, true/* allow decimal point*/)) {
char buf[32];
if (jsvGetString(v, buf, sizeof(buf))==sizeof(buf))
jsExceptionHere(JSET_ERROR, "String too big to convert to integer\n");
else
return (JsVarInt)stringToInt(buf);
}
return 0;
}
long long jsvGetLongInteger(const JsVar *v) {
if (jsvIsInt(v)) return jsvGetInteger(v);
return (long long)jsvGetFloat(v);
}
long long jsvGetLongIntegerAndUnLock(JsVar *v) {
long long i = jsvGetLongInteger(v);
jsvUnLock(v);
return i;
}
void jsvSetInteger(JsVar *v, JsVarInt value) {
assert(jsvIsInt(v));
v->varData.integer = value;
}
/**
* Get the boolean value of a variable.
* From a JavaScript variable, we determine its boolean value. The rules
* are:
*
* * If integer, true if value is not 0.
* * If float, true if value is not 0.0.
* * If function, array or object, always true.
* * If string, true if length of string is greater than 0.
*/
bool jsvGetBool(const JsVar *v) {
if (jsvIsString(v))
return jsvGetStringLength((JsVar*)v)!=0;
if (jsvIsFunction(v) || jsvIsArray(v) || jsvIsObject(v) || jsvIsArrayBuffer(v))
return true;
if (jsvIsFloat(v)) {
JsVarFloat f = jsvGetFloat(v);
return !isnan(f) && f!=0.0;
}
return jsvGetInteger(v)!=0;
}
JsVarFloat jsvGetFloat(const JsVar *v) {
if (!v) return NAN; // undefined
if (jsvIsFloat(v)) return v->varData.floating;
if (jsvIsIntegerish(v)) return (JsVarFloat)v->varData.integer;
if (jsvIsArray(v) || jsvIsArrayBuffer(v)) {
JsVarInt l = jsvGetLength(v);
if (l==0) return 0; // zero element array==0 (not undefined)
if (l==1) {
if (jsvIsArrayBuffer(v))
return jsvGetFloatAndUnLock(jsvArrayBufferGet((JsVar*)v,0));
return jsvGetFloatAndUnLock(jsvSkipNameAndUnLock(jsvGetArrayItem(v,0)));
}
}
if (jsvIsString(v)) {
char buf[64];
if (jsvGetString(v, buf, sizeof(buf))==sizeof(buf)) {
jsExceptionHere(JSET_ERROR, "String too big to convert to float\n");
} else {
if (buf[0]==0) return 0; // empty string -> 0
if (!strcmp(buf,"Infinity")) return INFINITY;
if (!strcmp(buf,"-Infinity")) return -INFINITY;
return stringToFloat(buf);
}
}
return NAN;
}
/// Convert the given variable to a number
JsVar *jsvAsNumber(JsVar *var) {
// stuff that we can just keep
if (jsvIsInt(var) || jsvIsFloat(var)) return jsvLockAgain(var);
// stuff that can be converted to an int
if (jsvIsBoolean(var) ||
jsvIsPin(var) ||
jsvIsNull(var) ||
jsvIsBoolean(var) ||
jsvIsArrayBufferName(var))
return jsvNewFromInteger(jsvGetInteger(var));
if (jsvIsString(var) && (jsvIsEmptyString(var) || jsvIsStringNumericInt(var, false/* no decimal pt - handle that with GetFloat */))) {
// handle strings like this, in case they're too big for an int
char buf[64];
if (jsvGetString(var, buf, sizeof(buf))==sizeof(buf)) {
jsExceptionHere(JSET_ERROR, "String too big to convert to integer\n");
return jsvNewFromFloat(NAN);
} else
return jsvNewFromLongInteger(stringToInt(buf));
}
// Else just try and get a float
return jsvNewFromFloat(jsvGetFloat(var));
}
JsVarInt jsvGetIntegerAndUnLock(JsVar *v) { return _jsvGetIntegerAndUnLock(v); }
JsVarFloat jsvGetFloatAndUnLock(JsVar *v) { return _jsvGetFloatAndUnLock(v); }
bool jsvGetBoolAndUnLock(JsVar *v) { return _jsvGetBoolAndUnLock(v); }
/** Get the item at the given location in the array buffer and return the result */
size_t jsvGetArrayBufferLength(const JsVar *arrayBuffer) {
assert(jsvIsArrayBuffer(arrayBuffer));
return arrayBuffer->varData.arraybuffer.length;
}
/** Get the String the contains the data for this arrayBuffer */
JsVar *jsvGetArrayBufferBackingString(JsVar *arrayBuffer) {
jsvLockAgain(arrayBuffer);
while (jsvIsArrayBuffer(arrayBuffer)) {
JsVar *s = jsvLock(jsvGetFirstChild(arrayBuffer));
jsvUnLock(arrayBuffer);
arrayBuffer = s;
}
assert(jsvIsString(arrayBuffer));
return arrayBuffer;
}
/** Get the item at the given location in the array buffer and return the result */
JsVar *jsvArrayBufferGet(JsVar *arrayBuffer, size_t idx) {
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, arrayBuffer, idx);
JsVar *v = jsvArrayBufferIteratorGetValue(&it);
jsvArrayBufferIteratorFree(&it);
return v;
}
/** Set the item at the given location in the array buffer */
void jsvArrayBufferSet(JsVar *arrayBuffer, size_t idx, JsVar *value) {
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, arrayBuffer, idx);
jsvArrayBufferIteratorSetValue(&it, value);
jsvArrayBufferIteratorFree(&it);
}
/** Given an integer name that points to an arraybuffer or an arraybufferview, evaluate it and return the result */
JsVar *jsvArrayBufferGetFromName(JsVar *name) {
assert(jsvIsArrayBufferName(name));
size_t idx = (size_t)jsvGetInteger(name);
JsVar *arrayBuffer = jsvLock(jsvGetFirstChild(name));
JsVar *value = jsvArrayBufferGet(arrayBuffer, idx);
jsvUnLock(arrayBuffer);
return value;
}
JsVar *jsvGetFunctionArgumentLength(JsVar *functionScope) {
JsVar *args = jsvNewEmptyArray();
if (!args) return 0; // out of memory
JsvObjectIterator it;
jsvObjectIteratorNew(&it, functionScope);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *idx = jsvObjectIteratorGetKey(&it);
if (jsvIsFunctionParameter(idx)) {
JsVar *val = jsvSkipOneName(idx);
jsvArrayPushAndUnLock(args, val);
}
jsvUnLock(idx);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
return args;
}
/** Is this variable actually defined? eg, can we pass it into `jsvSkipName`
* without getting a ReferenceError? This also returns false if the variable
* if ok, but has the value `undefined`. */
bool jsvIsVariableDefined(JsVar *a) {
return !jsvIsName(a) ||
jsvIsNameWithValue(a) ||
(jsvGetFirstChild(a)!=0);
}
/** If a is a name skip it and go to what it points to - and so on.
* ALWAYS locks - so must unlock what it returns. It MAY
* return 0. Throws a ReferenceError if variable is not defined,
* but you can check if it will with jsvIsReferenceError */
JsVar *jsvSkipName(JsVar *a) {
if (!a) return 0;
if (jsvIsArrayBufferName(a)) return jsvArrayBufferGetFromName(a);
if (jsvIsNameInt(a)) return jsvNewFromInteger((JsVarInt)jsvGetFirstChildSigned(a));
if (jsvIsNameIntBool(a)) return jsvNewFromBool(jsvGetFirstChild(a)!=0);
JsVar *pa = jsvLockAgain(a);
while (jsvIsName(pa)) {
JsVarRef n = jsvGetFirstChild(pa);
jsvUnLock(pa);
if (!n) {
if (pa==a && jsvGetRefs(a)==0 && !jsvIsNewChild(a)) {
jsExceptionHere(JSET_REFERENCEERROR, "%q is not defined", a);
}
return 0;
}
pa = jsvLock(n);
assert(pa!=a);
}
return pa;
}
/** If a is a name skip it and go to what it points to.
* ALWAYS locks - so must unlock what it returns. It MAY
* return 0. Throws a ReferenceError if variable is not defined,
* but you can check if it will with jsvIsReferenceError */
JsVar *jsvSkipOneName(JsVar *a) {
if (!a) return 0;
if (jsvIsArrayBufferName(a)) return jsvArrayBufferGetFromName(a);
if (jsvIsNameInt(a)) return jsvNewFromInteger((JsVarInt)jsvGetFirstChildSigned(a));
if (jsvIsNameIntBool(a)) return jsvNewFromBool(jsvGetFirstChild(a)!=0);
JsVar *pa = jsvLockAgain(a);
if (jsvIsName(pa)) {
JsVarRef n = jsvGetFirstChild(pa);
jsvUnLock(pa);
if (!n) {
if (pa==a && jsvGetRefs(a)==0 && !jsvIsNewChild(a)) {
jsExceptionHere(JSET_REFERENCEERROR, "%q is not defined", a);
}
return 0;
}
pa = jsvLock(n);
assert(pa!=a);
}
return pa;
}
/** If a is a's child is a name skip it and go to what it points to.
* ALWAYS locks - so must unlock what it returns. */
JsVar *jsvSkipToLastName(JsVar *a) {
assert(jsvIsName(a));
a = jsvLockAgain(a);
while (true) {
if (!jsvGetFirstChild(a)) return a;
JsVar *child = jsvLock(jsvGetFirstChild(a));
if (jsvIsName(child)) {
jsvUnLock(a);
a = child;
} else {
jsvUnLock(child);
return a;
}
}
return 0; // not called
}
/** Same as jsvSkipName, but ensures that 'a' is unlocked */
JsVar *jsvSkipNameAndUnLock(JsVar *a) {
JsVar *b = jsvSkipName(a);
jsvUnLock(a);
return b;
}
/** Same as jsvSkipOneName, but ensures that 'a' is unlocked */
JsVar *jsvSkipOneNameAndUnLock(JsVar *a) {
JsVar *b = jsvSkipOneName(a);
jsvUnLock(a);
return b;
}
bool jsvIsStringEqualOrStartsWithOffset(JsVar *var, const char *str, bool isStartsWith, size_t startIdx, bool ignoreCase) {
if (!jsvHasCharacterData(var)) {
return 0; // not a string so not equal!
}
JsvStringIterator it;
jsvStringIteratorNew(&it, var, startIdx);
if (ignoreCase) {
while (jsvStringIteratorHasChar(&it) && *str &&
jsvStringCharToLower(jsvStringIteratorGetChar(&it)) == jsvStringCharToLower(*str)) {
str++;
jsvStringIteratorNext(&it);
}
} else {
while (jsvStringIteratorHasChar(&it) && *str &&
jsvStringIteratorGetChar(&it) == *str) {
str++;
jsvStringIteratorNext(&it);
}
}
bool eq = (isStartsWith && !*str) ||
jsvStringIteratorGetChar(&it)==*str; // should both be 0 if equal
jsvStringIteratorFree(&it);
return eq;
}
/*
jsvIsStringEqualOrStartsWith(A, B, false) is a proper A==B
jsvIsStringEqualOrStartsWith(A, B, true) is A.startsWith(B)
*/
bool jsvIsStringEqualOrStartsWith(JsVar *var, const char *str, bool isStartsWith) {
return jsvIsStringEqualOrStartsWithOffset(var, str, isStartsWith, 0, false);
}
// Also see jsvIsBasicVarEqual
bool jsvIsStringEqual(JsVar *var, const char *str) {
return jsvIsStringEqualOrStartsWith(var, str, false);
}
// Also see jsvIsBasicVarEqual
bool jsvIsStringIEqualAndUnLock(JsVar *var, const char *str) {
bool b = jsvIsStringEqualOrStartsWithOffset(var, str, false, 0, true);
jsvUnLock(var);
return b;
}
/** Compare 2 strings, starting from the given character positions. equalAtEndOfString means that
* if one of the strings ends (even if the other hasn't), we treat them as equal.
* For a basic strcmp, do: jsvCompareString(a,b,0,0,false)
* */
int jsvCompareString(JsVar *va, JsVar *vb, size_t starta, size_t startb, bool equalAtEndOfString) {
JsvStringIterator ita, itb;
jsvStringIteratorNew(&ita, va, starta);
jsvStringIteratorNew(&itb, vb, startb);
// step to first positions
while (true) {
int ca = jsvStringIteratorGetCharOrMinusOne(&ita);
int cb = jsvStringIteratorGetCharOrMinusOne(&itb);
if (ca != cb) {
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
if ((ca<0 || cb<0) && equalAtEndOfString) return 0;
return ca - cb;
}
if (ca < 0) { // both equal, but end of string
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return 0;
}
jsvStringIteratorNext(&ita);
jsvStringIteratorNext(&itb);
}
// never get here, but the compiler warns...
return true;
}
/** Return a new string containing just the characters that are
* shared between two strings. */
JsVar *jsvGetCommonCharacters(JsVar *va, JsVar *vb) {
JsVar *v = jsvNewFromEmptyString();
if (!v) return 0;
JsvStringIterator ita, itb;
jsvStringIteratorNew(&ita, va, 0);
jsvStringIteratorNew(&itb, vb, 0);
int ca = jsvStringIteratorGetCharOrMinusOne(&ita);
int cb = jsvStringIteratorGetCharOrMinusOne(&itb);
while (ca>0 && cb>0 && ca == cb) {
jsvAppendCharacter(v, (char)ca);
jsvStringIteratorNext(&ita);
jsvStringIteratorNext(&itb);
ca = jsvStringIteratorGetCharOrMinusOne(&ita);
cb = jsvStringIteratorGetCharOrMinusOne(&itb);
}
jsvStringIteratorFree(&ita);
jsvStringIteratorFree(&itb);
return v;
}
/** Compare 2 integers, >0 if va>vb, <0 if va<vb. If compared with a non-integer, that gets put later */
int jsvCompareInteger(JsVar *va, JsVar *vb) {
if (jsvIsInt(va) && jsvIsInt(vb))
return (int)(jsvGetInteger(va) - jsvGetInteger(vb));
else if (jsvIsInt(va))
return -1;
else if (jsvIsInt(vb))
return 1;
else
return 0;
}
/** Copy only a name, not what it points to. ALTHOUGH the link to what it points to is maintained unless linkChildren=false
If keepAsName==false, this will be converted into a normal variable */
JsVar *jsvCopyNameOnly(JsVar *src, bool linkChildren, bool keepAsName) {
assert(jsvIsName(src));
JsVarFlags flags = src->flags;
JsVar *dst = 0;
if (!keepAsName) {
JsVarFlags t = src->flags & JSV_VARTYPEMASK;
if (t>=_JSV_NAME_INT_START && t<=_JSV_NAME_INT_END) {
flags = (flags & ~JSV_VARTYPEMASK) | JSV_INTEGER;
} else {
assert((JSV_NAME_STRING_INT_0 < JSV_NAME_STRING_0) &&
(JSV_NAME_STRING_0 < JSV_STRING_0) &&
(JSV_STRING_0 < JSV_STRING_EXT_0)); // this relies on ordering
assert(t>=JSV_NAME_STRING_INT_0 && t<=JSV_NAME_STRING_MAX);
if (jsvGetLastChild(src)) {
/* it's not a simple name string - it has STRING_EXT bits on the end.
* Because the max length of NAME and STRING is different we must just
* copy */
dst = jsvNewFromStringVar(src, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
if (!dst) return 0;
} else {
flags = (flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_STRING_0 + jsvGetCharactersInVar(src));
}
}
}
if (!dst) {
dst = jsvNewWithFlags(flags & JSV_VARIABLEINFOMASK);
if (!dst) return 0; // out of memory
memcpy(&dst->varData, &src->varData, JSVAR_DATA_STRING_NAME_LEN);
assert(jsvGetLastChild(dst) == 0);
assert(jsvGetFirstChild(dst) == 0);
assert(jsvGetPrevSibling(dst) == 0);
assert(jsvGetNextSibling(dst) == 0);
// Copy extra string data if there was any
if (jsvHasStringExt(src)) {
// If it had extra string data it should have been handled above
assert(keepAsName || !jsvGetLastChild(src));
// copy extra bits of string if there were any
if (jsvGetLastChild(src)) {
JsVar *child = jsvLock(jsvGetLastChild(src));
JsVar *childCopy = jsvCopy(child, true);
if (childCopy) { // could be out of memory
jsvSetLastChild(dst, jsvGetRef(childCopy)); // no ref for stringext
jsvUnLock(childCopy);
}
jsvUnLock(child);
}
} else {
assert(jsvIsBasic(src)); // in case we missed something!
}
}
// Copy LINK of what it points to
if (linkChildren && jsvGetFirstChild(src)) {
if (jsvIsNameWithValue(src))
jsvSetFirstChild(dst, jsvGetFirstChild(src));
else
jsvSetFirstChild(dst, jsvRefRef(jsvGetFirstChild(src)));
}
return dst;
}
JsVar *jsvCopy(JsVar *src, bool copyChildren) {
if (jsvIsFlatString(src)) {
// Copy a Flat String into a non-flat string - it's just safer
return jsvNewFromStringVar(src, 0, JSVAPPENDSTRINGVAR_MAXLENGTH);
}
JsVar *dst = jsvNewWithFlags(src->flags & JSV_VARIABLEINFOMASK);
if (!dst) return 0; // out of memory
if (!jsvIsStringExt(src)) {
memcpy(&dst->varData, &src->varData, (jsvIsBasicString(src)||jsvIsNativeString(src)) ? JSVAR_DATA_STRING_LEN : JSVAR_DATA_STRING_NAME_LEN);
if (!(jsvIsBasicString(src)||jsvIsNativeString(src))) {
assert(jsvGetPrevSibling(dst) == 0);
assert(jsvGetNextSibling(dst) == 0);
assert(jsvGetFirstChild(dst) == 0);
}
assert(jsvGetLastChild(dst) == 0);
} else {
// stringexts use the extra pointers after varData to store characters
// see jsvGetMaxCharactersInVar
memcpy(&dst->varData, &src->varData, JSVAR_DATA_STRING_MAX_LEN);
assert(jsvGetLastChild(dst) == 0);
}
// Copy what names point to
if (copyChildren && jsvIsName(src)) {
if (jsvGetFirstChild(src)) {
if (jsvIsNameWithValue(src)) {
// name_int/etc don't need references
jsvSetFirstChild(dst, jsvGetFirstChild(src));
} else {
JsVar *child = jsvLock(jsvGetFirstChild(src));
JsVar *childCopy = jsvRef(jsvCopy(child, true));
jsvUnLock(child);
if (childCopy) { // could have been out of memory
jsvSetFirstChild(dst, jsvGetRef(childCopy));
jsvUnLock(childCopy);
}
}
}
}
if (jsvHasStringExt(src)) {
// copy extra bits of string if there were any
if (jsvGetLastChild(src)) {
JsVar *child = jsvLock(jsvGetLastChild(src));
JsVar *childCopy = jsvCopy(child, true);
if (childCopy) {// could be out of memory
jsvSetLastChild(dst, jsvGetRef(childCopy)); // no ref for stringext
jsvUnLock(childCopy);
}
jsvUnLock(child);
}
} else if (jsvHasChildren(src)) {
if (copyChildren) {
// Copy children..
JsVarRef vr;
vr = jsvGetFirstChild(src);
while (vr) {
JsVar *name = jsvLock(vr);
JsVar *child = jsvCopyNameOnly(name, true/*link children*/, true/*keep as name*/); // NO DEEP COPY!
if (child) { // could have been out of memory
jsvAddName(dst, child);
jsvUnLock(child);
}
vr = jsvGetNextSibling(name);
jsvUnLock(name);
}
}
} else {
assert(jsvIsBasic(src)); // in case we missed something!
}
return dst;
}
void jsvAddName(JsVar *parent, JsVar *namedChild) {
namedChild = jsvRef(namedChild); // ref here VERY important as adding to structure!
assert(jsvIsName(namedChild));
// update array length
if (jsvIsArray(parent) && jsvIsInt(namedChild)) {
JsVarInt index = namedChild->varData.integer;
if (index >= jsvGetArrayLength(parent)) {
jsvSetArrayLength(parent, index + 1, false);
}
}
if (jsvGetLastChild(parent)) { // we have children already
JsVar *insertAfter = jsvLock(jsvGetLastChild(parent));
if (jsvIsArray(parent)) {
// we must insert in order - so step back until we get the right place
while (insertAfter && jsvCompareInteger(namedChild, insertAfter)<0) {
JsVarRef prev = jsvGetPrevSibling(insertAfter);
jsvUnLock(insertAfter);
insertAfter = prev ? jsvLock(prev) : 0;
}
}
if (insertAfter) {
if (jsvGetNextSibling(insertAfter)) {
// great, we're in the middle...
JsVar *insertBefore = jsvLock(jsvGetNextSibling(insertAfter));
jsvSetPrevSibling(insertBefore, jsvGetRef(namedChild));
jsvSetNextSibling(namedChild, jsvGetRef(insertBefore));
jsvUnLock(insertBefore);
} else {
// We're at the end - just set up the parent
jsvSetLastChild(parent, jsvGetRef(namedChild));
}
jsvSetNextSibling(insertAfter, jsvGetRef(namedChild));
jsvSetPrevSibling(namedChild, jsvGetRef(insertAfter));
jsvUnLock(insertAfter);
} else { // Insert right at the beginning of the array
// Link 2 children together
JsVar *firstChild = jsvLock(jsvGetFirstChild(parent));
jsvSetPrevSibling(firstChild, jsvGetRef(namedChild));
jsvUnLock(firstChild);
jsvSetNextSibling(namedChild, jsvGetFirstChild(parent));
// finally set the new child as the first one
jsvSetFirstChild(parent, jsvGetRef(namedChild));
}
} else { // we have no children - just add it
JsVarRef r = jsvGetRef(namedChild);
jsvSetFirstChild(parent, r);
jsvSetLastChild(parent, r);
}
}
JsVar *jsvAddNamedChild(JsVar *parent, JsVar *child, const char *name) {
JsVar *namedChild = jsvMakeIntoVariableName(jsvNewFromString(name), child);
if (!namedChild) return 0; // Out of memory
jsvAddName(parent, namedChild);
return namedChild;
}
JsVar *jsvSetNamedChild(JsVar *parent, JsVar *child, const char *name) {
JsVar *namedChild = jsvFindChildFromString(parent, name, true);
if (namedChild) // could be out of memory
return jsvSetValueOfName(namedChild, child);
return 0;
}
JsVar *jsvSetValueOfName(JsVar *name, JsVar *src) {
assert(name && jsvIsName(name));
assert(name!=src); // no infinite loops!
// all is fine, so replace the existing child...
/* Existing child may be null in the case of Z = 0 where
* we create 'Z' and pass it down to '=' to have the value
* filled in (or it may be undefined). */
if (jsvIsNameWithValue(name)) {
if (jsvIsString(name))
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_NAME_STRING_0 + jsvGetCharactersInVar(name));
else
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | JSV_NAME_INT;
jsvSetFirstChild(name, 0);
} else if (jsvGetFirstChild(name))
jsvUnRefRef(jsvGetFirstChild(name)); // free existing
if (src) {
if (jsvIsInt(name)) {
if ((jsvIsInt(src) || jsvIsBoolean(src)) && !jsvIsPin(src)) {
JsVarInt v = src->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (jsvIsInt(src) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL);
jsvSetFirstChild(name, (JsVarRef)v);
return name;
}
}
} else if (jsvIsString(name)) {
if (jsvIsInt(src) && !jsvIsPin(src)) {
JsVarInt v = src->varData.integer;
if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) {
name->flags = (name->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (JSV_NAME_STRING_INT_0 + jsvGetCharactersInVar(name));
jsvSetFirstChild(name, (JsVarRef)v);
return name;
}
}
}
// we can link to a name if we want (so can remove the assert!)
jsvSetFirstChild(name, jsvGetRef(jsvRef(src)));
} else
jsvSetFirstChild(name, 0);
return name;
}
JsVar *jsvFindChildFromString(JsVar *parent, const char *name, bool addIfNotFound) {
/* Pull out first 4 bytes, and ensure that everything
* is 0 padded so that we can do a nice speedy check. */
char fastCheck[4];
fastCheck[0] = name[0];
if (name[0]) {
fastCheck[1] = name[1];
if (name[1]) {
fastCheck[2] = name[2];
if (name[2]) {
fastCheck[3] = name[3];
} else {
fastCheck[3] = 0;
}
} else {
fastCheck[2] = 0;
fastCheck[3] = 0;
}
} else {
fastCheck[1] = 0;
fastCheck[2] = 0;
fastCheck[3] = 0;
}
assert(jsvHasChildren(parent));
JsVarRef childref = jsvGetFirstChild(parent);
while (childref) {
// Don't Lock here, just use GetAddressOf - to try and speed up the finding
// TODO: We can do this now, but when/if we move to cacheing vars, it'll break
JsVar *child = jsvGetAddressOf(childref);
if (*(int*)fastCheck==*(int*)child->varData.str && // speedy check of first 4 bytes
jsvIsStringEqual(child, name)) {
// found it! unlock parent but leave child locked
return jsvLockAgain(child);
}
childref = jsvGetNextSibling(child);
}
JsVar *child = 0;
if (addIfNotFound) {
child = jsvMakeIntoVariableName(jsvNewFromString(name), 0);
if (child) // could be out of memory
jsvAddName(parent, child);
}
return child;
}
/// See jsvIsNewChild - for fields that don't exist yet
JsVar *jsvCreateNewChild(JsVar *parent, JsVar *index, JsVar *child) {
JsVar *newChild = jsvAsName(index);
if (!newChild) return 0;
assert(!jsvGetFirstChild(newChild));
if (child) jsvSetValueOfName(newChild, child);
assert(!jsvGetNextSibling(newChild) && !jsvGetPrevSibling(newChild));
// by setting the siblings as the same, we signal that if set,
// we should be made a member of the given object
JsVarRef r = jsvGetRef(jsvRef(jsvRef(parent)));
jsvSetNextSibling(newChild, r);
jsvSetPrevSibling(newChild, r);
return newChild;
}
/** Try and turn the supplied variable into a name. If not, make a new one. This locks again. */
JsVar *jsvAsName(JsVar *var) {
if (!var) return 0;
if (jsvGetRefs(var) == 0) {
// Not reffed - great! let's just use it
if (!jsvIsName(var))
var = jsvMakeIntoVariableName(var, 0);
return jsvLockAgain(var);
} else { // it was reffed, we must add a new one
return jsvMakeIntoVariableName(jsvCopy(var, false), 0);
}
}
/** Non-recursive finding */
JsVar *jsvFindChildFromVar(JsVar *parent, JsVar *childName, bool addIfNotFound) {
JsVar *child;
JsVarRef childref = jsvGetFirstChild(parent);
while (childref) {
child = jsvLock(childref);
if (jsvIsBasicVarEqual(child, childName)) {
// found it! unlock parent but leave child locked
return child;
}
childref = jsvGetNextSibling(child);
jsvUnLock(child);
}
child = 0;
if (addIfNotFound && childName) {
child = jsvAsName(childName);
jsvAddName(parent, child);
}
return child;
}
void jsvRemoveChild(JsVar *parent, JsVar *child) {
assert(jsvHasChildren(parent));
assert(jsvIsName(child));
JsVarRef childref = jsvGetRef(child);
bool wasChild = false;
// unlink from parent
if (jsvGetFirstChild(parent) == childref) {
jsvSetFirstChild(parent, jsvGetNextSibling(child));
wasChild = true;
}
if (jsvGetLastChild(parent) == childref) {
jsvSetLastChild(parent, jsvGetPrevSibling(child));
wasChild = true;
// If this was an array and we were the last
// element, update the length
if (jsvIsArray(parent)) {
JsVarInt l = 0;
// get index of last child
if (jsvGetLastChild(parent))
l = jsvGetIntegerAndUnLock(jsvLock(jsvGetLastChild(parent)))+1;
// set it
jsvSetArrayLength(parent, l, false);
}
}
// unlink from child list
if (jsvGetPrevSibling(child)) {
JsVar *v = jsvLock(jsvGetPrevSibling(child));
assert(jsvGetNextSibling(v) == jsvGetRef(child));
jsvSetNextSibling(v, jsvGetNextSibling(child));
jsvUnLock(v);
wasChild = true;
}
if (jsvGetNextSibling(child)) {
JsVar *v = jsvLock(jsvGetNextSibling(child));
assert(jsvGetPrevSibling(v) == jsvGetRef(child));
jsvSetPrevSibling(v, jsvGetPrevSibling(child));
jsvUnLock(v);
wasChild = true;
}
jsvSetPrevSibling(child, 0);
jsvSetNextSibling(child, 0);
if (wasChild)
jsvUnRef(child);
}
void jsvRemoveAllChildren(JsVar *parent) {
assert(jsvHasChildren(parent));
while (jsvGetFirstChild(parent)) {
JsVar *v = jsvLock(jsvGetFirstChild(parent));
jsvRemoveChild(parent, v);
jsvUnLock(v);
}
}
/// Check if the given name is a child of the parent
bool jsvIsChild(JsVar *parent, JsVar *child) {
assert(jsvIsArray(parent) || jsvIsObject(parent));
assert(jsvIsName(child));
JsVarRef childref = jsvGetRef(child);
JsVarRef indexref;
indexref = jsvGetFirstChild(parent);
while (indexref) {
if (indexref == childref) return true;
// get next
JsVar *indexVar = jsvLock(indexref);
indexref = jsvGetNextSibling(indexVar);
jsvUnLock(indexVar);
}
return false; // not found undefined
}
/// Get the named child of an object. If createChild!=0 then create the child
JsVar *jsvObjectGetChild(JsVar *obj, const char *name, JsVarFlags createChild) {
if (!obj) return 0;
assert(jsvHasChildren(obj));
JsVar *childName = jsvFindChildFromString(obj, name, createChild!=0);
JsVar *child = jsvSkipName(childName);
if (!child && createChild && childName!=0/*out of memory?*/) {
child = jsvNewWithFlags(createChild);
jsvSetValueOfName(childName, child);
jsvUnLock(childName);
return child;
}
jsvUnLock(childName);
return child;
}
/// Set the named child of an object, and return the child (so you can choose to unlock it if you want)
JsVar *jsvObjectSetChild(JsVar *obj, const char *name, JsVar *child) {
assert(jsvHasChildren(obj));
if (!jsvHasChildren(obj)) return 0;
// child can actually be a name (for instance if it is a named function)
JsVar *childName = jsvFindChildFromString(obj, name, true);
if (!childName) return 0; // out of memory
jsvSetValueOfName(childName, child);
jsvUnLock(childName);
return child;
}
/// Set the named child of an object, and return the child (so you can choose to unlock it if you want)
JsVar *jsvObjectSetChildVar(JsVar *obj, JsVar *name, JsVar *child) {
assert(jsvHasChildren(obj));
if (!jsvHasChildren(obj)) return 0;
// child can actually be a name (for instance if it is a named function)
JsVar *childName = jsvFindChildFromVar(obj, name, true);
if (!childName) return 0; // out of memory
jsvSetValueOfName(childName, child);
jsvUnLock(childName);
return child;
}
void jsvObjectSetChildAndUnLock(JsVar *obj, const char *name, JsVar *child) {
jsvUnLock(jsvObjectSetChild(obj, name, child));
}
void jsvObjectRemoveChild(JsVar *obj, const char *name) {
JsVar *child = jsvFindChildFromString(obj, name, false);
if (child) {
jsvRemoveChild(obj, child);
jsvUnLock(child);
}
}
/** Set the named child of an object, and return the child (so you can choose to unlock it if you want).
* If the child is 0, the 'name' is also removed from the object */
JsVar *jsvObjectSetOrRemoveChild(JsVar *obj, const char *name, JsVar *child) {
if (child)
jsvObjectSetChild(obj, name, child);
else
jsvObjectRemoveChild(obj, name);
return child;
}
/** Append all keys from the source object to the target object. Will ignore hidden/internal fields */
void jsvObjectAppendAll(JsVar *target, JsVar *source) {
assert(jsvIsObject(target));
assert(jsvIsObject(source));
JsvObjectIterator it;
jsvObjectIteratorNew(&it, source);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *k = jsvObjectIteratorGetKey(&it);
JsVar *v = jsvSkipName(k);
if (!jsvIsInternalObjectKey(k))
jsvObjectSetChildVar(target, k, v);
jsvUnLock2(k,v);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
}
int jsvGetChildren(const JsVar *v) {
//OPT: could length be stored as the value of the array?
int children = 0;
JsVarRef childref = jsvGetFirstChild(v);
while (childref) {
JsVar *child = jsvLock(childref);
children++;
childref = jsvGetNextSibling(child);
jsvUnLock(child);
}
return children;
}
/// Get the first child's name from an object,array or function
JsVar *jsvGetFirstName(JsVar *v) {
assert(jsvHasChildren(v));
if (!jsvGetFirstChild(v)) return 0;
return jsvLock(jsvGetFirstChild(v));
}
JsVarInt jsvGetArrayLength(const JsVar *arr) {
if (!arr) return 0;
assert(jsvIsArray(arr));
return arr->varData.integer;
}
JsVarInt jsvSetArrayLength(JsVar *arr, JsVarInt length, bool truncate) {
assert(jsvIsArray(arr));
if (truncate && length < arr->varData.integer) {
// @TODO implement truncation here
}
arr->varData.integer = length;
return length;
}
JsVarInt jsvGetLength(const JsVar *src) {
if (jsvIsArray(src)) {
return jsvGetArrayLength(src);
} else if (jsvIsArrayBuffer(src)) {
return (JsVarInt)jsvGetArrayBufferLength(src);
} else if (jsvIsString(src)) {
return (JsVarInt)jsvGetStringLength(src);
} else if (jsvIsObject(src) || jsvIsFunction(src)) {
return jsvGetChildren(src);
} else {
return 1;
}
}
/** Count the amount of JsVars used. Mostly useful for debugging */
static size_t _jsvCountJsVarsUsedRecursive(JsVar *v, bool resetRecursionFlag) {
if (!v) return 0;
// Use IS_RECURSING flag to stop recursion
if (resetRecursionFlag) {
if (!(v->flags & JSV_IS_RECURSING))
return 0;
v->flags &= ~JSV_IS_RECURSING;
} else {
if (v->flags & JSV_IS_RECURSING)
return 0;
v->flags |= JSV_IS_RECURSING;
}
size_t count = 1;
if (jsvHasSingleChild(v) || jsvHasChildren(v)) {
JsVarRef childref = jsvGetFirstChild(v);
while (childref) {
JsVar *child = jsvLock(childref);
count += _jsvCountJsVarsUsedRecursive(child, resetRecursionFlag);
if (jsvHasChildren(v)) childref = jsvGetNextSibling(child);
else childref = 0;
jsvUnLock(child);
}
} else if (jsvIsFlatString(v))
count += jsvGetFlatStringBlocks(v);
if (jsvHasCharacterData(v)) {
JsVarRef childref = jsvGetLastChild(v);
while (childref) {
JsVar *child = jsvLock(childref);
count++;
childref = jsvGetLastChild(child);
jsvUnLock(child);
}
}
if (jsvIsName(v) && !jsvIsNameWithValue(v) && jsvGetFirstChild(v)) {
JsVar *child = jsvLock(jsvGetFirstChild(v));
count += _jsvCountJsVarsUsedRecursive(child, resetRecursionFlag);
jsvUnLock(child);
}
return count;
}
/** Count the amount of JsVars used. Mostly useful for debugging */
size_t jsvCountJsVarsUsed(JsVar *v) {
// we do this so we don't count the same item twice, but don't use too much memory
size_t c = _jsvCountJsVarsUsedRecursive(v, false);
_jsvCountJsVarsUsedRecursive(v, true);
return c;
}
JsVar *jsvGetArrayIndex(const JsVar *arr, JsVarInt index) {
JsVarRef childref = jsvGetLastChild(arr);
JsVarInt lastArrayIndex = 0;
// Look at last non-string element!
while (childref) {
JsVar *child = jsvLock(childref);
if (jsvIsInt(child)) {
lastArrayIndex = child->varData.integer;
// it was the last element... sorted!
if (lastArrayIndex == index) {
return child;
}
jsvUnLock(child);
break;
}
// if not an int, keep going
childref = jsvGetPrevSibling(child);
jsvUnLock(child);
}
// it's not in this array - don't search the whole lot...
if (index > lastArrayIndex)
return 0;
// otherwise is it more than halfway through?
if (index > lastArrayIndex/2) {
// it's in the final half of the array (probably) - search backwards
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsInt(child));
if (child->varData.integer == index) {
return child;
}
childref = jsvGetPrevSibling(child);
jsvUnLock(child);
}
} else {
// it's in the first half of the array (probably) - search forwards
childref = jsvGetFirstChild(arr);
while (childref) {
JsVar *child = jsvLock(childref);
assert(jsvIsInt(child));
if (child->varData.integer == index) {
return child;
}
childref = jsvGetNextSibling(child);
jsvUnLock(child);
}
}
return 0; // undefined
}
JsVar *jsvGetArrayItem(const JsVar *arr, JsVarInt index) {
return jsvSkipNameAndUnLock(jsvGetArrayIndex(arr,index));
}
void jsvSetArrayItem(JsVar *arr, JsVarInt index, JsVar *item) {
JsVar *indexVar = jsvGetArrayIndex(arr, index);
if (indexVar) {
jsvSetValueOfName(indexVar, item);
} else {
indexVar = jsvMakeIntoVariableName(jsvNewFromInteger(index), item);
jsvAddName(arr, indexVar);
}
jsvUnLock(indexVar);
}
// Get all elements from arr and put them in itemPtr (unless it'd overflow).
// Makes sure all of itemPtr either contains a JsVar or 0
void jsvGetArrayItems(JsVar *arr, unsigned int itemCount, JsVar **itemPtr) {
JsvObjectIterator it;
jsvObjectIteratorNew(&it, arr);
unsigned int i = 0;
while (jsvObjectIteratorHasValue(&it)) {
if (i<itemCount)
itemPtr[i++] = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
while (i<itemCount)
itemPtr[i++] = 0; // just ensure we don't end up with bad data
}
/// Get the index of the value in the array (matchExact==use pointer not equality check, matchIntegerIndices = don't check non-integers)
JsVar *jsvGetIndexOfFull(JsVar *arr, JsVar *value, bool matchExact, bool matchIntegerIndices, int startIdx) {
JsVarRef indexref;
assert(jsvIsArray(arr) || jsvIsObject(arr));
indexref = jsvGetFirstChild(arr);
while (indexref) {
JsVar *childIndex = jsvLock(indexref);
if (!matchIntegerIndices ||
(jsvIsInt(childIndex) && jsvGetInteger(childIndex)>=startIdx)) {
assert(jsvIsName(childIndex));
JsVar *childValue = jsvSkipName(childIndex);
if (childValue==value ||
(!matchExact && jsvMathsOpTypeEqual(childValue, value))) {
jsvUnLock(childValue);
return childIndex;
}
jsvUnLock(childValue);
}
indexref = jsvGetNextSibling(childIndex);
jsvUnLock(childIndex);
}
return 0; // undefined
}
/// Get the index of the value in the array or object (matchExact==use pointer, not equality check)
JsVar *jsvGetIndexOf(JsVar *arr, JsVar *value, bool matchExact) {
return jsvGetIndexOfFull(arr, value, matchExact, false, 0);
}
/// Adds new elements to the end of an array, and returns the new length. initialValue is the item index when no items are currently in the array.
JsVarInt jsvArrayAddToEnd(JsVar *arr, JsVar *value, JsVarInt initialValue) {
assert(jsvIsArray(arr));
JsVarInt index = initialValue;
if (jsvGetLastChild(arr)) {
JsVar *last = jsvLock(jsvGetLastChild(arr));
index = jsvGetInteger(last)+1;
jsvUnLock(last);
}
JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(index), value);
if (!idx) return 0; // out of memory - error flag will have been set already
jsvAddName(arr, idx);
jsvUnLock(idx);
return index+1;
}
/// Adds new elements to the end of an array, and returns the new length
JsVarInt jsvArrayPush(JsVar *arr, JsVar *value) {
assert(jsvIsArray(arr));
JsVarInt index = jsvGetArrayLength(arr);
JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(index), value);
if (!idx) return 0; // out of memory - error flag will have been set already
jsvAddName(arr, idx);
jsvUnLock(idx);
return jsvGetArrayLength(arr);
}
/// Adds a new element to the end of an array, unlocks it, and returns the new length
JsVarInt jsvArrayPushAndUnLock(JsVar *arr, JsVar *value) {
JsVarInt l = jsvArrayPush(arr, value);
jsvUnLock(value);
return l;
}
/// Append all values from the source array to the target array
void jsvArrayPushAll(JsVar *target, JsVar *source, bool checkDuplicates) {
assert(jsvIsArray(target));
assert(jsvIsArray(source));
JsvObjectIterator it;
jsvObjectIteratorNew(&it, source);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *v = jsvObjectIteratorGetValue(&it);
bool add = true;
if (checkDuplicates) {
JsVar *idx = jsvGetIndexOf(target, v, false);
if (idx) {
add = false;
jsvUnLock(idx);
}
}
if (add) jsvArrayPush(target, v);
jsvUnLock(v);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
}
/// Removes the last element of an array, and returns that element (or 0 if empty). includes the NAME
JsVar *jsvArrayPop(JsVar *arr) {
assert(jsvIsArray(arr));
JsVar *child = 0;
JsVarInt length = jsvGetArrayLength(arr);
if (length > 0) {
length--;
if (jsvGetLastChild(arr)) {
// find last child with an integer key
JsVarRef ref = jsvGetLastChild(arr);
child = jsvLock(ref);
while (child && !jsvIsInt(child)) {
ref = jsvGetPrevSibling(child);
jsvUnLock(child);
if (ref) {
child = jsvLock(ref);
} else {
child = 0;
}
}
// check if the last integer key really is the last element
if (child) {
if (jsvGetInteger(child) == length) {
// child is the last element - remove it
jsvRemoveChild(arr, child);
} else {
// child is not the last element
jsvUnLock(child);
child = 0;
}
}
}
// and finally shrink the array
jsvSetArrayLength(arr, length, false);
}
return child;
}
/// Removes the first element of an array, and returns that element (or 0 if empty). DOES NOT RENUMBER.
JsVar *jsvArrayPopFirst(JsVar *arr) {
assert(jsvIsArray(arr));
if (jsvGetFirstChild(arr)) {
JsVar *child = jsvLock(jsvGetFirstChild(arr));
if (jsvGetFirstChild(arr) == jsvGetLastChild(arr))
jsvSetLastChild(arr, 0); // if 1 item in array
jsvSetFirstChild(arr, jsvGetNextSibling(child)); // unlink from end of array
jsvUnRef(child); // as no longer in array
if (jsvGetNextSibling(child)) {
JsVar *v = jsvLock(jsvGetNextSibling(child));
jsvSetPrevSibling(v, 0);
jsvUnLock(v);
}
jsvSetNextSibling(child, 0);
return child; // and return it
} else {
// no children!
return 0;
}
}
/// Adds a new variable element to the end of an array (IF it was not already there). Return true if successful
void jsvArrayAddUnique(JsVar *arr, JsVar *v) {
JsVar *idx = jsvGetIndexOf(arr, v, false); // did it already exist?
if (!idx) {
jsvArrayPush(arr, v); // if 0, it failed
} else {
jsvUnLock(idx);
}
}
/// Join all elements of an array together into a string
JsVar *jsvArrayJoin(JsVar *arr, JsVar *filler) {
JsVar *str = jsvNewFromEmptyString();
if (!str) return 0; // out of memory
JsvIterator it;
jsvIteratorNew(&it, arr, JSIF_EVERY_ARRAY_ELEMENT);
bool first = true;
while (!jspIsInterrupted() && jsvIteratorHasElement(&it)) {
JsVar *key = jsvIteratorGetKey(&it);
if (jsvIsInt(key)) {
// add the filler
if (filler && !first)
jsvAppendStringVarComplete(str, filler);
first = false;
// add the value
JsVar *value = jsvIteratorGetValue(&it);
if (value && !jsvIsNull(value)) {
JsVar *valueStr = jsvAsString(value, false);
if (valueStr) { // could be out of memory
jsvAppendStringVarComplete(str, valueStr);
jsvUnLock(valueStr);
}
}
jsvUnLock(value);
}
jsvUnLock(key);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
return str;
}
/// Insert a new element before beforeIndex, DOES NOT UPDATE INDICES
void jsvArrayInsertBefore(JsVar *arr, JsVar *beforeIndex, JsVar *element) {
if (beforeIndex) {
JsVar *idxVar = jsvMakeIntoVariableName(jsvNewFromInteger(0), element);
if (!idxVar) return; // out of memory
JsVarRef idxRef = jsvGetRef(jsvRef(idxVar));
JsVarRef prev = jsvGetPrevSibling(beforeIndex);
if (prev) {
JsVar *prevVar = jsvRef(jsvLock(prev));
jsvSetInteger(idxVar, jsvGetInteger(prevVar)+1); // update index number
jsvSetNextSibling(prevVar, idxRef);
jsvUnLock(prevVar);
jsvSetPrevSibling(idxVar, prev);
} else {
jsvSetPrevSibling(idxVar, 0);
jsvSetFirstChild(arr, idxRef);
}
jsvSetPrevSibling(beforeIndex, idxRef);
jsvSetNextSibling(idxVar, jsvGetRef(jsvRef(beforeIndex)));
jsvUnLock(idxVar);
} else
jsvArrayPush(arr, element);
}
/** Same as jsvMathsOpPtr, but if a or b are a name, skip them
* and go to what they point to. Also handle the case where
* they may be objects with valueOf functions. */
JsVar *jsvMathsOpSkipNames(JsVar *a, JsVar *b, int op) {
JsVar *pa = jsvSkipName(a);
JsVar *pb = jsvSkipName(b);
JsVar *oa = jsvGetValueOf(pa);
JsVar *ob = jsvGetValueOf(pb);
jsvUnLock2(pa, pb);
JsVar *res = jsvMathsOp(oa,ob,op);
jsvUnLock2(oa, ob);
return res;
}
JsVar *jsvMathsOpError(int op, const char *datatype) {
char opName[32];
jslTokenAsString(op, opName, sizeof(opName));
jsError("Operation %s not supported on the %s datatype", opName, datatype);
return 0;
}
bool jsvMathsOpTypeEqual(JsVar *a, JsVar *b) {
// check type first, then call again to check data
bool eql = (a==0) == (b==0);
if (a && b) {
// Check whether both are numbers, otherwise check the variable
// type flags themselves
eql = ((jsvIsInt(a)||jsvIsFloat(a)) && (jsvIsInt(b)||jsvIsFloat(b))) ||
((a->flags & JSV_VARTYPEMASK) == (b->flags & JSV_VARTYPEMASK));
}
if (eql) {
JsVar *contents = jsvMathsOp(a,b, LEX_EQUAL);
if (!jsvGetBool(contents)) eql = false;
jsvUnLock(contents);
} else {
/* Make sure we don't get in the situation where we have two equal
* strings with a check that fails because they were stored differently */
assert(!(jsvIsString(a) && jsvIsString(b) && jsvIsBasicVarEqual(a,b)));
}
return eql;
}
JsVar *jsvMathsOp(JsVar *a, JsVar *b, int op) {
// Type equality check
if (op == LEX_TYPEEQUAL || op == LEX_NTYPEEQUAL) {
bool eql = jsvMathsOpTypeEqual(a,b);
if (op == LEX_TYPEEQUAL)
return jsvNewFromBool(eql);
else
return jsvNewFromBool(!eql);
}
bool needsInt = op=='&' || op=='|' || op=='^' || op==LEX_LSHIFT || op==LEX_RSHIFT || op==LEX_RSHIFTUNSIGNED;
bool needsNumeric = needsInt || op=='*' || op=='/' || op=='%' || op=='-';
bool isCompare = op==LEX_EQUAL || op==LEX_NEQUAL || op=='<' || op==LEX_LEQUAL || op=='>'|| op==LEX_GEQUAL;
if (isCompare) {
if (jsvIsNumeric(a) && jsvIsString(b)) {
needsNumeric = true;
needsInt = jsvIsIntegerish(a) && jsvIsStringNumericInt(b, false);
} else if (jsvIsNumeric(b) && jsvIsString(a)) {
needsNumeric = true;
needsInt = jsvIsIntegerish(b) && jsvIsStringNumericInt(a, false);
}
}
// do maths...
if (jsvIsUndefined(a) && jsvIsUndefined(b)) {
if (op == LEX_EQUAL)
return jsvNewFromBool(true);
else if (op == LEX_NEQUAL)
return jsvNewFromBool(false);
else
return 0; // undefined
} else if (needsNumeric ||
((jsvIsNumeric(a) || jsvIsUndefined(a) || jsvIsNull(a)) &&
(jsvIsNumeric(b) || jsvIsUndefined(b) || jsvIsNull(b)))) {
if (needsInt || (jsvIsIntegerish(a) && jsvIsIntegerish(b))) {
// note that int+undefined should be handled as a double
// use ints
JsVarInt da = jsvGetInteger(a);
JsVarInt db = jsvGetInteger(b);
switch (op) {
case '+': return jsvNewFromLongInteger((long long)da + (long long)db);
case '-': return jsvNewFromLongInteger((long long)da - (long long)db);
case '*': return jsvNewFromLongInteger((long long)da * (long long)db);
case '/': return jsvNewFromFloat((JsVarFloat)da/(JsVarFloat)db);
case '&': return jsvNewFromInteger(da&db);
case '|': return jsvNewFromInteger(da|db);
case '^': return jsvNewFromInteger(da^db);
case '%': return db ? jsvNewFromInteger(da%db) : jsvNewFromFloat(NAN);
case LEX_LSHIFT: return jsvNewFromInteger(da << db);
case LEX_RSHIFT: return jsvNewFromInteger(da >> db);
case LEX_RSHIFTUNSIGNED: return jsvNewFromInteger((JsVarInt)(((JsVarIntUnsigned)da) >> db));
case LEX_EQUAL: return jsvNewFromBool(da==db && jsvIsNull(a)==jsvIsNull(b));
case LEX_NEQUAL: return jsvNewFromBool(da!=db || jsvIsNull(a)!=jsvIsNull(b));
case '<': return jsvNewFromBool(da<db);
case LEX_LEQUAL: return jsvNewFromBool(da<=db);
case '>': return jsvNewFromBool(da>db);
case LEX_GEQUAL: return jsvNewFromBool(da>=db);
default: return jsvMathsOpError(op, "Integer");
}
} else {
// use doubles
JsVarFloat da = jsvGetFloat(a);
JsVarFloat db = jsvGetFloat(b);
switch (op) {
case '+': return jsvNewFromFloat(da+db);
case '-': return jsvNewFromFloat(da-db);
case '*': return jsvNewFromFloat(da*db);
case '/': return jsvNewFromFloat(da/db);
case '%': return jsvNewFromFloat(jswrap_math_mod(da, db));
case LEX_EQUAL:
case LEX_NEQUAL: { bool equal = da==db;
if ((jsvIsNull(a) && jsvIsUndefined(b)) ||
(jsvIsNull(b) && jsvIsUndefined(a))) equal = true; // JS quirk :)
return jsvNewFromBool((op==LEX_EQUAL) ? equal : ((bool)!equal));
}
case '<': return jsvNewFromBool(da<db);
case LEX_LEQUAL: return jsvNewFromBool(da<=db);
case '>': return jsvNewFromBool(da>db);
case LEX_GEQUAL: return jsvNewFromBool(da>=db);
default: return jsvMathsOpError(op, "Double");
}
}
} else if ((jsvIsArray(a) || jsvIsObject(a) || jsvIsFunction(a) ||
jsvIsArray(b) || jsvIsObject(b) || jsvIsFunction(b)) &&
jsvIsArray(a)==jsvIsArray(b) && // Fix #283 - convert to string and test if only one is an array
(op == LEX_EQUAL || op==LEX_NEQUAL)) {
bool equal = a==b;
if (jsvIsNativeFunction(a) || jsvIsNativeFunction(b)) {
// even if one is not native, the contents will be different
equal = a && b &&
a->varData.native.ptr == b->varData.native.ptr &&
a->varData.native.argTypes == b->varData.native.argTypes &&
jsvGetFirstChild(a) == jsvGetFirstChild(b);
}
/* Just check pointers */
switch (op) {
case LEX_EQUAL: return jsvNewFromBool(equal);
case LEX_NEQUAL: return jsvNewFromBool(!equal);
default: return jsvMathsOpError(op, jsvIsArray(a)?"Array":"Object");
}
} else {
JsVar *da = jsvAsString(a, false);
JsVar *db = jsvAsString(b, false);
if (!da || !db) { // out of memory
jsvUnLock2(da, db);
return 0;
}
if (op=='+') {
JsVar *v = jsvCopy(da, false);
// TODO: can we be fancy and not copy da if we know it isn't reffed? what about locks?
if (v) // could be out of memory
jsvAppendStringVarComplete(v, db);
jsvUnLock2(da, db);
return v;
}
int cmp = jsvCompareString(da,db,0,0,false);
jsvUnLock2(da, db);
// use strings
switch (op) {
case LEX_EQUAL: return jsvNewFromBool(cmp==0);
case LEX_NEQUAL: return jsvNewFromBool(cmp!=0);
case '<': return jsvNewFromBool(cmp<0);
case LEX_LEQUAL: return jsvNewFromBool(cmp<=0);
case '>': return jsvNewFromBool(cmp>0);
case LEX_GEQUAL: return jsvNewFromBool(cmp>=0);
default: return jsvMathsOpError(op, "String");
}
}
}
JsVar *jsvNegateAndUnLock(JsVar *v) {
JsVar *zero = jsvNewFromInteger(0);
JsVar *res = jsvMathsOpSkipNames(zero, v, '-');
jsvUnLock2(zero, v);
return res;
}
/** If the given element is found, return the path to it as a string of
* the form 'foo.bar', else return 0. If we would have returned a.b and
* ignoreParent is a, don't! */
JsVar *jsvGetPathTo(JsVar *root, JsVar *element, int maxDepth, JsVar *ignoreParent) {
if (maxDepth<=0) return 0;
JsvIterator it;
jsvIteratorNew(&it, root, JSIF_DEFINED_ARRAY_ElEMENTS);
while (jsvIteratorHasElement(&it)) {
JsVar *el = jsvIteratorGetValue(&it);
if (el == element && root != ignoreParent) {
// if we found it - send the key name back!
JsVar *name = jsvAsString(jsvIteratorGetKey(&it), true);
jsvIteratorFree(&it);
return name;
} else if (jsvIsObject(el) || jsvIsArray(el) || jsvIsFunction(el)) {
// recursively search
JsVar *n = jsvGetPathTo(el, element, maxDepth-1, ignoreParent);
if (n) {
// we found it! Append our name onto it as well
JsVar *keyName = jsvIteratorGetKey(&it);
JsVar *name = jsvVarPrintf(jsvIsObject(el) ? "%v.%v" : "%v[%q]",keyName,n);
jsvUnLock2(keyName, n);
jsvIteratorFree(&it);
return name;
}
}
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
return 0;
}
void jsvTraceLockInfo(JsVar *v) {
jsiConsolePrintf("#%d[r%d,l%d] ",jsvGetRef(v),jsvGetRefs(v),jsvGetLocks(v));
}
/** Get the lowest level at which searchRef appears */
int _jsvTraceGetLowestLevel(JsVar *var, JsVar *searchVar) {
if (var == searchVar) return 0;
int found = -1;
// Use IS_RECURSING flag to stop recursion
if (var->flags & JSV_IS_RECURSING)
return -1;
var->flags |= JSV_IS_RECURSING;
if (jsvHasSingleChild(var) && jsvGetFirstChild(var)) {
JsVar *child = jsvLock(jsvGetFirstChild(var));
int f = _jsvTraceGetLowestLevel(child, searchVar);
jsvUnLock(child);
if (f>=0 && (found<0 || f<found)) found=f+1;
}
if (jsvHasChildren(var)) {
JsVarRef childRef = jsvGetFirstChild(var);
while (childRef) {
JsVar *child = jsvLock(childRef);
int f = _jsvTraceGetLowestLevel(child, searchVar);
if (f>=0 && (found<0 || f<found)) found=f+1;
childRef = jsvGetNextSibling(child);
jsvUnLock(child);
}
}
var->flags &= ~JSV_IS_RECURSING;
return found; // searchRef not found
}
void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
// If this data is available elsewhere in the tree (but nearer the root)
// then don't print it. This makes the dump significantly more readable!
// It also stops us getting in recursive loops ...
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)?jswGetBasicObjectName(var):"unknown ArrayBuffer"); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
// print a value if it was stored in here as well...
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
/** Write debug info for this Var out to the console */
void jsvTrace(JsVar *var, int indent) {
_jsvTrace(var,indent,var,0);
jsiConsolePrintf("\n");
}
/** Recursively mark the variable */
static void jsvGarbageCollectMarkUsed(JsVar *var) {
var->flags &= (JsVarFlags)~JSV_GARBAGE_COLLECT;
if (jsvHasCharacterData(var)) {
// non-recursively scan strings
JsVarRef child = jsvGetLastChild(var);
while (child) {
JsVar *childVar;
childVar = jsvGetAddressOf(child);
childVar->flags &= (JsVarFlags)~JSV_GARBAGE_COLLECT;
child = jsvGetLastChild(childVar);
}
}
// intentionally no else
if (jsvHasSingleChild(var)) {
if (jsvGetFirstChild(var)) {
JsVar *childVar = jsvGetAddressOf(jsvGetFirstChild(var));
if (childVar->flags & JSV_GARBAGE_COLLECT)
jsvGarbageCollectMarkUsed(childVar);
}
} else if (jsvHasChildren(var)) {
JsVarRef child = jsvGetFirstChild(var);
while (child) {
JsVar *childVar;
childVar = jsvGetAddressOf(child);
if (childVar->flags & JSV_GARBAGE_COLLECT)
jsvGarbageCollectMarkUsed(childVar);
child = jsvGetNextSibling(childVar);
}
}
}
/** Run a garbage collection sweep - return nonzero if things have been freed */
int jsvGarbageCollect() {
if (isMemoryBusy) return false;
isMemoryBusy = MEMBUSY_GC;
JsVarRef i;
// Add GC flags to anything that is currently used
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { // if it is not unused
var->flags |= (JsVarFlags)JSV_GARBAGE_COLLECT;
// if we have a flat string, skip that many blocks
if (jsvIsFlatString(var))
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
/* recursively remove anything that is referenced from a var that is locked. */
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags & JSV_GARBAGE_COLLECT) && // not already GC'd
jsvGetLocks(var)>0) // or it is locked
jsvGarbageCollectMarkUsed(var);
// if we have a flat string, skip that many blocks
if (jsvIsFlatString(var))
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
/* now sweep for things that we can GC!
* Also update the free list - this means that every new variable that
* gets allocated gets allocated towards the start of memory, which
* hopefully helps compact everything towards the start. */
unsigned int freedCount = 0;
jsVarFirstEmpty = 0;
JsVar *lastEmpty = 0;
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if (var->flags & JSV_GARBAGE_COLLECT) {
if (jsvIsFlatString(var)) {
// If we're a flat string, there are more blocks to free.
unsigned int count = (unsigned int)jsvGetFlatStringBlocks(var);
freedCount+=count;
// Free the first block
var->flags = JSV_UNUSED;
// add this to our free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
// free subsequent blocks
while (count-- > 0) {
i++;
var = jsvGetAddressOf((JsVarRef)(i));
var->flags = JSV_UNUSED;
// add this to our free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
}
} else {
// otherwise just free 1 block
if (jsvHasSingleChild(var)) {
/* If this had a child that wasn't listed for GC then we need to
* unref it. Everything else is fine because it'll disappear anyway.
* We don't have to check if we should free this other variable
* here because we know the GC picked up it was referenced from
* somewhere else. */
JsVarRef ch = jsvGetFirstChild(var);
if (ch) {
JsVar *child = jsvGetAddressOf(ch); // not locked
if (child->flags!=JSV_UNUSED && // not already GC'd!
!(child->flags&JSV_GARBAGE_COLLECT)) // not marked for GC
jsvUnRef(child);
}
}
/* Sanity checks here. We're making sure that any variables that are
* linked from this one have either already been garbage collected or
* are marked for GC */
assert(!jsvHasChildren(var) || !jsvGetFirstChild(var) ||
jsvGetAddressOf(jsvGetFirstChild(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetFirstChild(var))->flags&JSV_GARBAGE_COLLECT));
assert(!jsvHasChildren(var) || !jsvGetLastChild(var) ||
jsvGetAddressOf(jsvGetLastChild(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetLastChild(var))->flags&JSV_GARBAGE_COLLECT));
assert(!jsvIsName(var) || !jsvGetPrevSibling(var) ||
jsvGetAddressOf(jsvGetPrevSibling(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetPrevSibling(var))->flags&JSV_GARBAGE_COLLECT));
assert(!jsvIsName(var) || !jsvGetNextSibling(var) ||
jsvGetAddressOf(jsvGetNextSibling(var))->flags==JSV_UNUSED ||
(jsvGetAddressOf(jsvGetNextSibling(var))->flags&JSV_GARBAGE_COLLECT));
// free!
var->flags = JSV_UNUSED;
// add this to our free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
freedCount++;
}
} else if (jsvIsFlatString(var)) {
// if we have a flat string, skip forward that many blocks
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
} else if (var->flags == JSV_UNUSED) {
// this is already free - add it to the free list
if (lastEmpty) jsvSetNextSibling(lastEmpty, i);
else jsVarFirstEmpty = i;
lastEmpty = var;
}
}
if (lastEmpty) jsvSetNextSibling(lastEmpty, 0);
isMemoryBusy = MEM_NOT_BUSY;
return (int)freedCount;
}
#ifndef RELEASE
// Dump any locked variables that aren't referenced from `global` - for debugging memory leaks
void jsvDumpLockedVars() {
jsvGarbageCollect();
if (isMemoryBusy) return;
isMemoryBusy = MEMBUSY_SYSTEM;
JsVarRef i;
// clear garbage collect flags
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) { // if it is not unused
var->flags |= (JsVarFlags)JSV_GARBAGE_COLLECT;
// if we have a flat string, skip that many blocks
if (jsvIsFlatString(var))
i = (JsVarRef)(i+jsvGetFlatStringBlocks(var));
}
}
// Add global
jsvGarbageCollectMarkUsed(execInfo.root);
// Now dump any that aren't used!
for (i=1;i<=jsVarsSize;i++) {
JsVar *var = jsvGetAddressOf(i);
if ((var->flags&JSV_VARTYPEMASK) != JSV_UNUSED) {
if (var->flags & JSV_GARBAGE_COLLECT) {
jsvGarbageCollectMarkUsed(var);
jsvTrace(var, 0);
}
}
}
isMemoryBusy = MEM_NOT_BUSY;
}
// Dump the free list - in order
void jsvDumpFreeList() {
JsVarRef ref = jsVarFirstEmpty;
int n = 0;
while (ref) {
jsiConsolePrintf("%5d ", (int)ref);
if (++n >= 16) {
n = 0;
jsiConsolePrintf("\n");
}
JsVar *v = jsvGetAddressOf(ref);
ref = jsvGetNextSibling(v);
}
jsiConsolePrintf("\n");
}
#endif
/** Remove whitespace to the right of a string - on MULTIPLE LINES */
JsVar *jsvStringTrimRight(JsVar *srcString) {
JsvStringIterator src, dst;
JsVar *dstString = jsvNewFromEmptyString();
jsvStringIteratorNew(&src, srcString, 0);
jsvStringIteratorNew(&dst, dstString, 0);
int spaces = 0;
while (jsvStringIteratorHasChar(&src)) {
char ch = jsvStringIteratorGetChar(&src);
jsvStringIteratorNext(&src);
if (ch==' ') spaces++;
else if (ch=='\n') {
spaces = 0;
jsvStringIteratorAppend(&dst, ch);
} else {
for (;spaces>0;spaces--)
jsvStringIteratorAppend(&dst, ' ');
jsvStringIteratorAppend(&dst, ch);
}
}
jsvStringIteratorFree(&src);
jsvStringIteratorFree(&dst);
return dstString;
}
/// If v is the key of a function, return true if it is internal and shouldn't be visible to the user
bool jsvIsInternalFunctionKey(JsVar *v) {
return (jsvIsString(v) && (
v->varData.str[0]==JS_HIDDEN_CHAR)
) ||
jsvIsFunctionParameter(v);
}
/// If v is the key of an object, return true if it is internal and shouldn't be visible to the user
bool jsvIsInternalObjectKey(JsVar *v) {
return (jsvIsString(v) && (
v->varData.str[0]==JS_HIDDEN_CHAR ||
jsvIsStringEqual(v, JSPARSE_INHERITS_VAR) ||
jsvIsStringEqual(v, JSPARSE_CONSTRUCTOR_VAR)
));
}
/// Get the correct checker function for the given variable. see jsvIsInternalFunctionKey/jsvIsInternalObjectKey
JsvIsInternalChecker jsvGetInternalFunctionCheckerFor(JsVar *v) {
if (jsvIsFunction(v)) return jsvIsInternalFunctionKey;
if (jsvIsObject(v)) return jsvIsInternalObjectKey;
return 0;
}
/** Using 'configs', this reads 'object' into the given pointers, returns true on success.
* If object is not undefined and not an object, an error is raised.
* If there are fields that are not in the list of configs, an error is raised
*/
bool jsvReadConfigObject(JsVar *object, jsvConfigObject *configs, int nConfigs) {
if (jsvIsUndefined(object)) return true;
if (!jsvIsObject(object)) {
jsExceptionHere(JSET_ERROR, "Expecting an Object, or undefined");
return false;
}
// Ok, it's an object
JsvObjectIterator it;
jsvObjectIteratorNew(&it, object);
bool ok = true;
while (ok && jsvObjectIteratorHasValue(&it)) {
JsVar *key = jsvObjectIteratorGetKey(&it);
bool found = false;
int i;
for (i=0;i<nConfigs;i++) {
if (jsvIsStringEqual(key, configs[i].name)) {
found = true;
if (configs[i].ptr) {
JsVar *val = jsvObjectIteratorGetValue(&it);
switch (configs[i].type) {
case 0: break;
case JSV_OBJECT:
case JSV_STRING_0:
case JSV_ARRAY:
case JSV_FUNCTION:
*((JsVar**)configs[i].ptr) = jsvLockAgain(val); break;
case JSV_PIN: *((Pin*)configs[i].ptr) = jshGetPinFromVar(val); break;
case JSV_BOOLEAN: *((bool*)configs[i].ptr) = jsvGetBool(val); break;
case JSV_INTEGER: *((JsVarInt*)configs[i].ptr) = jsvGetInteger(val); break;
case JSV_FLOAT: *((JsVarFloat*)configs[i].ptr) = jsvGetFloat(val); break;
default: assert(0); break;
}
jsvUnLock(val);
}
}
}
if (!found) {
jsExceptionHere(JSET_ERROR, "Unknown option %q", key);
ok = false;
}
jsvUnLock(key);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
return ok;
}
/// Is the variable an instance of the given class. Eg. `jsvIsInstanceOf(e, "Error")` - does a simple, non-recursive check that doesn't take account of builtins like String
bool jsvIsInstanceOf(JsVar *var, const char *constructorName) {
bool isInst = false;
if (!jsvHasChildren(var)) return false;
JsVar *proto = jsvObjectGetChild(var, JSPARSE_INHERITS_VAR, 0);
if (jsvIsObject(proto)) {
JsVar *constr = jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0);
if (constr)
isInst = jspIsConstructor(constr, constructorName);
jsvUnLock(constr);
}
jsvUnLock(proto);
return isInst;
}
JsVar *jsvNewTypedArray(JsVarDataArrayBufferViewType type, JsVarInt length) {
JsVar *lenVar = jsvNewFromInteger(length);
if (!lenVar) return 0;
JsVar *array = jswrap_typedarray_constructor(type, lenVar,0,0);
jsvUnLock(lenVar);
return array;
}
#ifndef SAVE_ON_FLASH
JsVar *jsvNewDataViewWithData(JsVarInt length, unsigned char *data) {
JsVar *buf = jswrap_arraybuffer_constructor(length);
if (!buf) return 0;
JsVar *view = jswrap_dataview_constructor(buf, 0, 0);
if (!view) {
jsvUnLock(buf);
return 0;
}
if (data) {
JsVar *arrayBufferData = jsvGetArrayBufferBackingString(buf);
if (arrayBufferData)
jsvSetString(arrayBufferData, (char *)data, (size_t)length);
jsvUnLock(arrayBufferData);
}
jsvUnLock(buf);
return view;
}
#endif
JsVar *jsvNewArrayBufferWithPtr(unsigned int length, char **ptr) {
assert(ptr);
*ptr=0;
JsVar *backingString = jsvNewFlatStringOfLength(length);
if (!backingString) return 0;
JsVar *arr = jsvNewArrayBufferFromString(backingString, length);
if (!arr) {
jsvUnLock(backingString);
return 0;
}
*ptr = jsvGetFlatStringPointer(backingString);
jsvUnLock(backingString);
return arr;
}
JsVar *jsvNewArrayBufferWithData(JsVarInt length, unsigned char *data) {
assert(data);
JsVar *dst = 0;
JsVar *arr = jsvNewArrayBufferWithPtr((unsigned int)length, (char**)&dst);
if (!dst) {
jsvUnLock(arr);
return 0;
}
memcpy(dst, data, (size_t)length);
return arr;
}
void *jsvMalloc(size_t size) {
/** Allocate flat string, return pointer to its first element.
* As we drop the pointer here, it's left locked. jsvGetFlatStringPointer
* is also safe if 0 is passed in. */
JsVar *flatStr = jsvNewFlatStringOfLength((unsigned int)size);
if (!flatStr) {
jsErrorFlags |= JSERR_LOW_MEMORY;
// Not allocated - try and free any command history/etc
while (jsiFreeMoreMemory());
// Garbage collect
jsvGarbageCollect();
// Try again
flatStr = jsvNewFlatStringOfLength((unsigned int)size);
}
// intentionally no jsvUnLock - see above
void *p = (void*)jsvGetFlatStringPointer(flatStr);
if (p) {
//jsiConsolePrintf("jsvMalloc var %d-%d at %d (%d bytes)\n", jsvGetRef(flatStr), jsvGetRef(flatStr)+jsvGetFlatStringBlocks(flatStr), p, size);
memset(p,0,size);
}
return p;
}
void jsvFree(void *ptr) {
JsVar *flatStr = jsvGetFlatStringFromPointer((char *)ptr);
//jsiConsolePrintf("jsvFree var %d at %d (%d bytes)\n", jsvGetRef(flatStr), ptr, jsvGetLength(flatStr));
jsvUnLock(flatStr);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_160_4 |
crossvul-cpp_data_good_118_0 | /*
* PowerPC version
* Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)
*
* Derived from "arch/m68k/kernel/ptrace.c"
* Copyright (C) 1994 by Hamish Macdonald
* Taken from linux/kernel/ptrace.c and modified for M680x0.
* linux/kernel/ptrace.c is by Ross Biro 1/23/92, edited by Linus Torvalds
*
* Modified by Cort Dougan (cort@hq.fsmlabs.com)
* and Paul Mackerras (paulus@samba.org).
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file README.legal in the main directory of
* this archive for more details.
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/regset.h>
#include <linux/tracehook.h>
#include <linux/elf.h>
#include <linux/user.h>
#include <linux/security.h>
#include <linux/signal.h>
#include <linux/seccomp.h>
#include <linux/audit.h>
#include <trace/syscall.h>
#include <linux/hw_breakpoint.h>
#include <linux/perf_event.h>
#include <linux/context_tracking.h>
#include <linux/uaccess.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/switch_to.h>
#include <asm/tm.h>
#include <asm/asm-prototypes.h>
#define CREATE_TRACE_POINTS
#include <trace/events/syscalls.h>
/*
* The parameter save area on the stack is used to store arguments being passed
* to callee function and is located at fixed offset from stack pointer.
*/
#ifdef CONFIG_PPC32
#define PARAMETER_SAVE_AREA_OFFSET 24 /* bytes */
#else /* CONFIG_PPC32 */
#define PARAMETER_SAVE_AREA_OFFSET 48 /* bytes */
#endif
struct pt_regs_offset {
const char *name;
int offset;
};
#define STR(s) #s /* convert to string */
#define REG_OFFSET_NAME(r) {.name = #r, .offset = offsetof(struct pt_regs, r)}
#define GPR_OFFSET_NAME(num) \
{.name = STR(r##num), .offset = offsetof(struct pt_regs, gpr[num])}, \
{.name = STR(gpr##num), .offset = offsetof(struct pt_regs, gpr[num])}
#define REG_OFFSET_END {.name = NULL, .offset = 0}
#define TVSO(f) (offsetof(struct thread_vr_state, f))
#define TFSO(f) (offsetof(struct thread_fp_state, f))
#define TSO(f) (offsetof(struct thread_struct, f))
static const struct pt_regs_offset regoffset_table[] = {
GPR_OFFSET_NAME(0),
GPR_OFFSET_NAME(1),
GPR_OFFSET_NAME(2),
GPR_OFFSET_NAME(3),
GPR_OFFSET_NAME(4),
GPR_OFFSET_NAME(5),
GPR_OFFSET_NAME(6),
GPR_OFFSET_NAME(7),
GPR_OFFSET_NAME(8),
GPR_OFFSET_NAME(9),
GPR_OFFSET_NAME(10),
GPR_OFFSET_NAME(11),
GPR_OFFSET_NAME(12),
GPR_OFFSET_NAME(13),
GPR_OFFSET_NAME(14),
GPR_OFFSET_NAME(15),
GPR_OFFSET_NAME(16),
GPR_OFFSET_NAME(17),
GPR_OFFSET_NAME(18),
GPR_OFFSET_NAME(19),
GPR_OFFSET_NAME(20),
GPR_OFFSET_NAME(21),
GPR_OFFSET_NAME(22),
GPR_OFFSET_NAME(23),
GPR_OFFSET_NAME(24),
GPR_OFFSET_NAME(25),
GPR_OFFSET_NAME(26),
GPR_OFFSET_NAME(27),
GPR_OFFSET_NAME(28),
GPR_OFFSET_NAME(29),
GPR_OFFSET_NAME(30),
GPR_OFFSET_NAME(31),
REG_OFFSET_NAME(nip),
REG_OFFSET_NAME(msr),
REG_OFFSET_NAME(ctr),
REG_OFFSET_NAME(link),
REG_OFFSET_NAME(xer),
REG_OFFSET_NAME(ccr),
#ifdef CONFIG_PPC64
REG_OFFSET_NAME(softe),
#else
REG_OFFSET_NAME(mq),
#endif
REG_OFFSET_NAME(trap),
REG_OFFSET_NAME(dar),
REG_OFFSET_NAME(dsisr),
REG_OFFSET_END,
};
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
static void flush_tmregs_to_thread(struct task_struct *tsk)
{
/*
* If task is not current, it will have been flushed already to
* it's thread_struct during __switch_to().
*
* A reclaim flushes ALL the state or if not in TM save TM SPRs
* in the appropriate thread structures from live.
*/
if ((!cpu_has_feature(CPU_FTR_TM)) || (tsk != current))
return;
if (MSR_TM_SUSPENDED(mfmsr())) {
tm_reclaim_current(TM_CAUSE_SIGNAL);
} else {
tm_enable();
tm_save_sprs(&(tsk->thread));
}
}
#else
static inline void flush_tmregs_to_thread(struct task_struct *tsk) { }
#endif
/**
* regs_query_register_offset() - query register offset from its name
* @name: the name of a register
*
* regs_query_register_offset() returns the offset of a register in struct
* pt_regs from its name. If the name is invalid, this returns -EINVAL;
*/
int regs_query_register_offset(const char *name)
{
const struct pt_regs_offset *roff;
for (roff = regoffset_table; roff->name != NULL; roff++)
if (!strcmp(roff->name, name))
return roff->offset;
return -EINVAL;
}
/**
* regs_query_register_name() - query register name from its offset
* @offset: the offset of a register in struct pt_regs.
*
* regs_query_register_name() returns the name of a register from its
* offset in struct pt_regs. If the @offset is invalid, this returns NULL;
*/
const char *regs_query_register_name(unsigned int offset)
{
const struct pt_regs_offset *roff;
for (roff = regoffset_table; roff->name != NULL; roff++)
if (roff->offset == offset)
return roff->name;
return NULL;
}
/*
* does not yet catch signals sent when the child dies.
* in exit.c or in signal.c.
*/
/*
* Set of msr bits that gdb can change on behalf of a process.
*/
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
#define MSR_DEBUGCHANGE 0
#else
#define MSR_DEBUGCHANGE (MSR_SE | MSR_BE)
#endif
/*
* Max register writeable via put_reg
*/
#ifdef CONFIG_PPC32
#define PT_MAX_PUT_REG PT_MQ
#else
#define PT_MAX_PUT_REG PT_CCR
#endif
static unsigned long get_user_msr(struct task_struct *task)
{
return task->thread.regs->msr | task->thread.fpexc_mode;
}
static int set_user_msr(struct task_struct *task, unsigned long msr)
{
task->thread.regs->msr &= ~MSR_DEBUGCHANGE;
task->thread.regs->msr |= msr & MSR_DEBUGCHANGE;
return 0;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
static unsigned long get_user_ckpt_msr(struct task_struct *task)
{
return task->thread.ckpt_regs.msr | task->thread.fpexc_mode;
}
static int set_user_ckpt_msr(struct task_struct *task, unsigned long msr)
{
task->thread.ckpt_regs.msr &= ~MSR_DEBUGCHANGE;
task->thread.ckpt_regs.msr |= msr & MSR_DEBUGCHANGE;
return 0;
}
static int set_user_ckpt_trap(struct task_struct *task, unsigned long trap)
{
task->thread.ckpt_regs.trap = trap & 0xfff0;
return 0;
}
#endif
#ifdef CONFIG_PPC64
static int get_user_dscr(struct task_struct *task, unsigned long *data)
{
*data = task->thread.dscr;
return 0;
}
static int set_user_dscr(struct task_struct *task, unsigned long dscr)
{
task->thread.dscr = dscr;
task->thread.dscr_inherit = 1;
return 0;
}
#else
static int get_user_dscr(struct task_struct *task, unsigned long *data)
{
return -EIO;
}
static int set_user_dscr(struct task_struct *task, unsigned long dscr)
{
return -EIO;
}
#endif
/*
* We prevent mucking around with the reserved area of trap
* which are used internally by the kernel.
*/
static int set_user_trap(struct task_struct *task, unsigned long trap)
{
task->thread.regs->trap = trap & 0xfff0;
return 0;
}
/*
* Get contents of register REGNO in task TASK.
*/
int ptrace_get_reg(struct task_struct *task, int regno, unsigned long *data)
{
if ((task->thread.regs == NULL) || !data)
return -EIO;
if (regno == PT_MSR) {
*data = get_user_msr(task);
return 0;
}
if (regno == PT_DSCR)
return get_user_dscr(task, data);
if (regno < (sizeof(struct pt_regs) / sizeof(unsigned long))) {
*data = ((unsigned long *)task->thread.regs)[regno];
return 0;
}
return -EIO;
}
/*
* Write contents of register REGNO in task TASK.
*/
int ptrace_put_reg(struct task_struct *task, int regno, unsigned long data)
{
if (task->thread.regs == NULL)
return -EIO;
if (regno == PT_MSR)
return set_user_msr(task, data);
if (regno == PT_TRAP)
return set_user_trap(task, data);
if (regno == PT_DSCR)
return set_user_dscr(task, data);
if (regno <= PT_MAX_PUT_REG) {
((unsigned long *)task->thread.regs)[regno] = data;
return 0;
}
return -EIO;
}
static int gpr_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int i, ret;
if (target->thread.regs == NULL)
return -EIO;
if (!FULL_REGS(target->thread.regs)) {
/* We have a partial register set. Fill 14-31 with bogus values */
for (i = 14; i < 32; i++)
target->thread.regs->gpr[i] = NV_REG_POISON;
}
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
target->thread.regs,
0, offsetof(struct pt_regs, msr));
if (!ret) {
unsigned long msr = get_user_msr(target);
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &msr,
offsetof(struct pt_regs, msr),
offsetof(struct pt_regs, msr) +
sizeof(msr));
}
BUILD_BUG_ON(offsetof(struct pt_regs, orig_gpr3) !=
offsetof(struct pt_regs, msr) + sizeof(long));
if (!ret)
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.regs->orig_gpr3,
offsetof(struct pt_regs, orig_gpr3),
sizeof(struct pt_regs));
if (!ret)
ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf,
sizeof(struct pt_regs), -1);
return ret;
}
static int gpr_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
unsigned long reg;
int ret;
if (target->thread.regs == NULL)
return -EIO;
CHECK_FULL_REGS(target->thread.regs);
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
target->thread.regs,
0, PT_MSR * sizeof(reg));
if (!ret && count > 0) {
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, ®,
PT_MSR * sizeof(reg),
(PT_MSR + 1) * sizeof(reg));
if (!ret)
ret = set_user_msr(target, reg);
}
BUILD_BUG_ON(offsetof(struct pt_regs, orig_gpr3) !=
offsetof(struct pt_regs, msr) + sizeof(long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.regs->orig_gpr3,
PT_ORIG_R3 * sizeof(reg),
(PT_MAX_PUT_REG + 1) * sizeof(reg));
if (PT_MAX_PUT_REG + 1 < PT_TRAP && !ret)
ret = user_regset_copyin_ignore(
&pos, &count, &kbuf, &ubuf,
(PT_MAX_PUT_REG + 1) * sizeof(reg),
PT_TRAP * sizeof(reg));
if (!ret && count > 0) {
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, ®,
PT_TRAP * sizeof(reg),
(PT_TRAP + 1) * sizeof(reg));
if (!ret)
ret = set_user_trap(target, reg);
}
if (!ret)
ret = user_regset_copyin_ignore(
&pos, &count, &kbuf, &ubuf,
(PT_TRAP + 1) * sizeof(reg), -1);
return ret;
}
/*
* Regardless of transactions, 'fp_state' holds the current running
* value of all FPR registers and 'ckfp_state' holds the last checkpointed
* value of all FPR registers for the current transaction.
*
* Userspace interface buffer layout:
*
* struct data {
* u64 fpr[32];
* u64 fpscr;
* };
*/
static int fpr_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
#ifdef CONFIG_VSX
u64 buf[33];
int i;
flush_fp_to_thread(target);
/* copy to local buffer then write that out */
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.TS_FPR(i);
buf[32] = target->thread.fp_state.fpscr;
return user_regset_copyout(&pos, &count, &kbuf, &ubuf, buf, 0, -1);
#else
BUILD_BUG_ON(offsetof(struct thread_fp_state, fpscr) !=
offsetof(struct thread_fp_state, fpr[32]));
flush_fp_to_thread(target);
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.fp_state, 0, -1);
#endif
}
/*
* Regardless of transactions, 'fp_state' holds the current running
* value of all FPR registers and 'ckfp_state' holds the last checkpointed
* value of all FPR registers for the current transaction.
*
* Userspace interface buffer layout:
*
* struct data {
* u64 fpr[32];
* u64 fpscr;
* };
*
*/
static int fpr_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
#ifdef CONFIG_VSX
u64 buf[33];
int i;
flush_fp_to_thread(target);
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.TS_FPR(i);
buf[32] = target->thread.fp_state.fpscr;
/* copy to local buffer then write that out */
i = user_regset_copyin(&pos, &count, &kbuf, &ubuf, buf, 0, -1);
if (i)
return i;
for (i = 0; i < 32 ; i++)
target->thread.TS_FPR(i) = buf[i];
target->thread.fp_state.fpscr = buf[32];
return 0;
#else
BUILD_BUG_ON(offsetof(struct thread_fp_state, fpscr) !=
offsetof(struct thread_fp_state, fpr[32]));
flush_fp_to_thread(target);
return user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.fp_state, 0, -1);
#endif
}
#ifdef CONFIG_ALTIVEC
/*
* Get/set all the altivec registers vr0..vr31, vscr, vrsave, in one go.
* The transfer totals 34 quadword. Quadwords 0-31 contain the
* corresponding vector registers. Quadword 32 contains the vscr as the
* last word (offset 12) within that quadword. Quadword 33 contains the
* vrsave as the first word (offset 0) within the quadword.
*
* This definition of the VMX state is compatible with the current PPC32
* ptrace interface. This allows signal handling and ptrace to use the
* same structures. This also simplifies the implementation of a bi-arch
* (combined (32- and 64-bit) gdb.
*/
static int vr_active(struct task_struct *target,
const struct user_regset *regset)
{
flush_altivec_to_thread(target);
return target->thread.used_vr ? regset->n : 0;
}
/*
* Regardless of transactions, 'vr_state' holds the current running
* value of all the VMX registers and 'ckvr_state' holds the last
* checkpointed value of all the VMX registers for the current
* transaction to fall back on in case it aborts.
*
* Userspace interface buffer layout:
*
* struct data {
* vector128 vr[32];
* vector128 vscr;
* vector128 vrsave;
* };
*/
static int vr_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
flush_altivec_to_thread(target);
BUILD_BUG_ON(offsetof(struct thread_vr_state, vscr) !=
offsetof(struct thread_vr_state, vr[32]));
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.vr_state, 0,
33 * sizeof(vector128));
if (!ret) {
/*
* Copy out only the low-order word of vrsave.
*/
union {
elf_vrreg_t reg;
u32 word;
} vrsave;
memset(&vrsave, 0, sizeof(vrsave));
vrsave.word = target->thread.vrsave;
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vrsave,
33 * sizeof(vector128), -1);
}
return ret;
}
/*
* Regardless of transactions, 'vr_state' holds the current running
* value of all the VMX registers and 'ckvr_state' holds the last
* checkpointed value of all the VMX registers for the current
* transaction to fall back on in case it aborts.
*
* Userspace interface buffer layout:
*
* struct data {
* vector128 vr[32];
* vector128 vscr;
* vector128 vrsave;
* };
*/
static int vr_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
flush_altivec_to_thread(target);
BUILD_BUG_ON(offsetof(struct thread_vr_state, vscr) !=
offsetof(struct thread_vr_state, vr[32]));
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.vr_state, 0,
33 * sizeof(vector128));
if (!ret && count > 0) {
/*
* We use only the first word of vrsave.
*/
union {
elf_vrreg_t reg;
u32 word;
} vrsave;
memset(&vrsave, 0, sizeof(vrsave));
vrsave.word = target->thread.vrsave;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &vrsave,
33 * sizeof(vector128), -1);
if (!ret)
target->thread.vrsave = vrsave.word;
}
return ret;
}
#endif /* CONFIG_ALTIVEC */
#ifdef CONFIG_VSX
/*
* Currently to set and and get all the vsx state, you need to call
* the fp and VMX calls as well. This only get/sets the lower 32
* 128bit VSX registers.
*/
static int vsr_active(struct task_struct *target,
const struct user_regset *regset)
{
flush_vsx_to_thread(target);
return target->thread.used_vsr ? regset->n : 0;
}
/*
* Regardless of transactions, 'fp_state' holds the current running
* value of all FPR registers and 'ckfp_state' holds the last
* checkpointed value of all FPR registers for the current
* transaction.
*
* Userspace interface buffer layout:
*
* struct data {
* u64 vsx[32];
* };
*/
static int vsr_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
u64 buf[32];
int ret, i;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
flush_vsx_to_thread(target);
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.fp_state.fpr[i][TS_VSRLOWOFFSET];
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
buf, 0, 32 * sizeof(double));
return ret;
}
/*
* Regardless of transactions, 'fp_state' holds the current running
* value of all FPR registers and 'ckfp_state' holds the last
* checkpointed value of all FPR registers for the current
* transaction.
*
* Userspace interface buffer layout:
*
* struct data {
* u64 vsx[32];
* };
*/
static int vsr_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
u64 buf[32];
int ret,i;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
flush_vsx_to_thread(target);
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.fp_state.fpr[i][TS_VSRLOWOFFSET];
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
buf, 0, 32 * sizeof(double));
if (!ret)
for (i = 0; i < 32 ; i++)
target->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = buf[i];
return ret;
}
#endif /* CONFIG_VSX */
#ifdef CONFIG_SPE
/*
* For get_evrregs/set_evrregs functions 'data' has the following layout:
*
* struct {
* u32 evr[32];
* u64 acc;
* u32 spefscr;
* }
*/
static int evr_active(struct task_struct *target,
const struct user_regset *regset)
{
flush_spe_to_thread(target);
return target->thread.used_spe ? regset->n : 0;
}
static int evr_get(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
flush_spe_to_thread(target);
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.evr,
0, sizeof(target->thread.evr));
BUILD_BUG_ON(offsetof(struct thread_struct, acc) + sizeof(u64) !=
offsetof(struct thread_struct, spefscr));
if (!ret)
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.acc,
sizeof(target->thread.evr), -1);
return ret;
}
static int evr_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
flush_spe_to_thread(target);
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.evr,
0, sizeof(target->thread.evr));
BUILD_BUG_ON(offsetof(struct thread_struct, acc) + sizeof(u64) !=
offsetof(struct thread_struct, spefscr));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.acc,
sizeof(target->thread.evr), -1);
return ret;
}
#endif /* CONFIG_SPE */
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
/**
* tm_cgpr_active - get active number of registers in CGPR
* @target: The target task.
* @regset: The user regset structure.
*
* This function checks for the active number of available
* regisers in transaction checkpointed GPR category.
*/
static int tm_cgpr_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return 0;
return regset->n;
}
/**
* tm_cgpr_get - get CGPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy from.
* @ubuf: User buffer to copy into.
*
* This function gets transaction checkpointed GPR registers.
*
* When the transaction is active, 'ckpt_regs' holds all the checkpointed
* GPR register values for the current transaction to fall back on if it
* aborts in between. This function gets those checkpointed GPR registers.
* The userspace interface buffer layout is as follows.
*
* struct data {
* struct pt_regs ckpt_regs;
* };
*/
static int tm_cgpr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.ckpt_regs,
0, offsetof(struct pt_regs, msr));
if (!ret) {
unsigned long msr = get_user_ckpt_msr(target);
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &msr,
offsetof(struct pt_regs, msr),
offsetof(struct pt_regs, msr) +
sizeof(msr));
}
BUILD_BUG_ON(offsetof(struct pt_regs, orig_gpr3) !=
offsetof(struct pt_regs, msr) + sizeof(long));
if (!ret)
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.ckpt_regs.orig_gpr3,
offsetof(struct pt_regs, orig_gpr3),
sizeof(struct pt_regs));
if (!ret)
ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf,
sizeof(struct pt_regs), -1);
return ret;
}
/*
* tm_cgpr_set - set the CGPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy into.
* @ubuf: User buffer to copy from.
*
* This function sets in transaction checkpointed GPR registers.
*
* When the transaction is active, 'ckpt_regs' holds the checkpointed
* GPR register values for the current transaction to fall back on if it
* aborts in between. This function sets those checkpointed GPR registers.
* The userspace interface buffer layout is as follows.
*
* struct data {
* struct pt_regs ckpt_regs;
* };
*/
static int tm_cgpr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
unsigned long reg;
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.ckpt_regs,
0, PT_MSR * sizeof(reg));
if (!ret && count > 0) {
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, ®,
PT_MSR * sizeof(reg),
(PT_MSR + 1) * sizeof(reg));
if (!ret)
ret = set_user_ckpt_msr(target, reg);
}
BUILD_BUG_ON(offsetof(struct pt_regs, orig_gpr3) !=
offsetof(struct pt_regs, msr) + sizeof(long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.ckpt_regs.orig_gpr3,
PT_ORIG_R3 * sizeof(reg),
(PT_MAX_PUT_REG + 1) * sizeof(reg));
if (PT_MAX_PUT_REG + 1 < PT_TRAP && !ret)
ret = user_regset_copyin_ignore(
&pos, &count, &kbuf, &ubuf,
(PT_MAX_PUT_REG + 1) * sizeof(reg),
PT_TRAP * sizeof(reg));
if (!ret && count > 0) {
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, ®,
PT_TRAP * sizeof(reg),
(PT_TRAP + 1) * sizeof(reg));
if (!ret)
ret = set_user_ckpt_trap(target, reg);
}
if (!ret)
ret = user_regset_copyin_ignore(
&pos, &count, &kbuf, &ubuf,
(PT_TRAP + 1) * sizeof(reg), -1);
return ret;
}
/**
* tm_cfpr_active - get active number of registers in CFPR
* @target: The target task.
* @regset: The user regset structure.
*
* This function checks for the active number of available
* regisers in transaction checkpointed FPR category.
*/
static int tm_cfpr_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return 0;
return regset->n;
}
/**
* tm_cfpr_get - get CFPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy from.
* @ubuf: User buffer to copy into.
*
* This function gets in transaction checkpointed FPR registers.
*
* When the transaction is active 'ckfp_state' holds the checkpointed
* values for the current transaction to fall back on if it aborts
* in between. This function gets those checkpointed FPR registers.
* The userspace interface buffer layout is as follows.
*
* struct data {
* u64 fpr[32];
* u64 fpscr;
*};
*/
static int tm_cfpr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
u64 buf[33];
int i;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
/* copy to local buffer then write that out */
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.TS_CKFPR(i);
buf[32] = target->thread.ckfp_state.fpscr;
return user_regset_copyout(&pos, &count, &kbuf, &ubuf, buf, 0, -1);
}
/**
* tm_cfpr_set - set CFPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy into.
* @ubuf: User buffer to copy from.
*
* This function sets in transaction checkpointed FPR registers.
*
* When the transaction is active 'ckfp_state' holds the checkpointed
* FPR register values for the current transaction to fall back on
* if it aborts in between. This function sets these checkpointed
* FPR registers. The userspace interface buffer layout is as follows.
*
* struct data {
* u64 fpr[32];
* u64 fpscr;
*};
*/
static int tm_cfpr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
u64 buf[33];
int i;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
for (i = 0; i < 32; i++)
buf[i] = target->thread.TS_CKFPR(i);
buf[32] = target->thread.ckfp_state.fpscr;
/* copy to local buffer then write that out */
i = user_regset_copyin(&pos, &count, &kbuf, &ubuf, buf, 0, -1);
if (i)
return i;
for (i = 0; i < 32 ; i++)
target->thread.TS_CKFPR(i) = buf[i];
target->thread.ckfp_state.fpscr = buf[32];
return 0;
}
/**
* tm_cvmx_active - get active number of registers in CVMX
* @target: The target task.
* @regset: The user regset structure.
*
* This function checks for the active number of available
* regisers in checkpointed VMX category.
*/
static int tm_cvmx_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return 0;
return regset->n;
}
/**
* tm_cvmx_get - get CMVX registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy from.
* @ubuf: User buffer to copy into.
*
* This function gets in transaction checkpointed VMX registers.
*
* When the transaction is active 'ckvr_state' and 'ckvrsave' hold
* the checkpointed values for the current transaction to fall
* back on if it aborts in between. The userspace interface buffer
* layout is as follows.
*
* struct data {
* vector128 vr[32];
* vector128 vscr;
* vector128 vrsave;
*};
*/
static int tm_cvmx_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
BUILD_BUG_ON(TVSO(vscr) != TVSO(vr[32]));
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
/* Flush the state */
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.ckvr_state, 0,
33 * sizeof(vector128));
if (!ret) {
/*
* Copy out only the low-order word of vrsave.
*/
union {
elf_vrreg_t reg;
u32 word;
} vrsave;
memset(&vrsave, 0, sizeof(vrsave));
vrsave.word = target->thread.ckvrsave;
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vrsave,
33 * sizeof(vector128), -1);
}
return ret;
}
/**
* tm_cvmx_set - set CMVX registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy into.
* @ubuf: User buffer to copy from.
*
* This function sets in transaction checkpointed VMX registers.
*
* When the transaction is active 'ckvr_state' and 'ckvrsave' hold
* the checkpointed values for the current transaction to fall
* back on if it aborts in between. The userspace interface buffer
* layout is as follows.
*
* struct data {
* vector128 vr[32];
* vector128 vscr;
* vector128 vrsave;
*};
*/
static int tm_cvmx_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
BUILD_BUG_ON(TVSO(vscr) != TVSO(vr[32]));
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.ckvr_state, 0,
33 * sizeof(vector128));
if (!ret && count > 0) {
/*
* We use only the low-order word of vrsave.
*/
union {
elf_vrreg_t reg;
u32 word;
} vrsave;
memset(&vrsave, 0, sizeof(vrsave));
vrsave.word = target->thread.ckvrsave;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &vrsave,
33 * sizeof(vector128), -1);
if (!ret)
target->thread.ckvrsave = vrsave.word;
}
return ret;
}
/**
* tm_cvsx_active - get active number of registers in CVSX
* @target: The target task.
* @regset: The user regset structure.
*
* This function checks for the active number of available
* regisers in transaction checkpointed VSX category.
*/
static int tm_cvsx_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return 0;
flush_vsx_to_thread(target);
return target->thread.used_vsr ? regset->n : 0;
}
/**
* tm_cvsx_get - get CVSX registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy from.
* @ubuf: User buffer to copy into.
*
* This function gets in transaction checkpointed VSX registers.
*
* When the transaction is active 'ckfp_state' holds the checkpointed
* values for the current transaction to fall back on if it aborts
* in between. This function gets those checkpointed VSX registers.
* The userspace interface buffer layout is as follows.
*
* struct data {
* u64 vsx[32];
*};
*/
static int tm_cvsx_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
u64 buf[32];
int ret, i;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
/* Flush the state */
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
flush_vsx_to_thread(target);
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.ckfp_state.fpr[i][TS_VSRLOWOFFSET];
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
buf, 0, 32 * sizeof(double));
return ret;
}
/**
* tm_cvsx_set - set CFPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy into.
* @ubuf: User buffer to copy from.
*
* This function sets in transaction checkpointed VSX registers.
*
* When the transaction is active 'ckfp_state' holds the checkpointed
* VSX register values for the current transaction to fall back on
* if it aborts in between. This function sets these checkpointed
* FPR registers. The userspace interface buffer layout is as follows.
*
* struct data {
* u64 vsx[32];
*};
*/
static int tm_cvsx_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
u64 buf[32];
int ret, i;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
/* Flush the state */
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
flush_vsx_to_thread(target);
for (i = 0; i < 32 ; i++)
buf[i] = target->thread.ckfp_state.fpr[i][TS_VSRLOWOFFSET];
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
buf, 0, 32 * sizeof(double));
if (!ret)
for (i = 0; i < 32 ; i++)
target->thread.ckfp_state.fpr[i][TS_VSRLOWOFFSET] = buf[i];
return ret;
}
/**
* tm_spr_active - get active number of registers in TM SPR
* @target: The target task.
* @regset: The user regset structure.
*
* This function checks the active number of available
* regisers in the transactional memory SPR category.
*/
static int tm_spr_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
return regset->n;
}
/**
* tm_spr_get - get the TM related SPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy from.
* @ubuf: User buffer to copy into.
*
* This function gets transactional memory related SPR registers.
* The userspace interface buffer layout is as follows.
*
* struct {
* u64 tm_tfhar;
* u64 tm_texasr;
* u64 tm_tfiar;
* };
*/
static int tm_spr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
/* Build tests */
BUILD_BUG_ON(TSO(tm_tfhar) + sizeof(u64) != TSO(tm_texasr));
BUILD_BUG_ON(TSO(tm_texasr) + sizeof(u64) != TSO(tm_tfiar));
BUILD_BUG_ON(TSO(tm_tfiar) + sizeof(u64) != TSO(ckpt_regs));
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
/* Flush the states */
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
/* TFHAR register */
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_tfhar, 0, sizeof(u64));
/* TEXASR register */
if (!ret)
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_texasr, sizeof(u64),
2 * sizeof(u64));
/* TFIAR register */
if (!ret)
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_tfiar,
2 * sizeof(u64), 3 * sizeof(u64));
return ret;
}
/**
* tm_spr_set - set the TM related SPR registers
* @target: The target task.
* @regset: The user regset structure.
* @pos: The buffer position.
* @count: Number of bytes to copy.
* @kbuf: Kernel buffer to copy into.
* @ubuf: User buffer to copy from.
*
* This function sets transactional memory related SPR registers.
* The userspace interface buffer layout is as follows.
*
* struct {
* u64 tm_tfhar;
* u64 tm_texasr;
* u64 tm_tfiar;
* };
*/
static int tm_spr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
/* Build tests */
BUILD_BUG_ON(TSO(tm_tfhar) + sizeof(u64) != TSO(tm_texasr));
BUILD_BUG_ON(TSO(tm_texasr) + sizeof(u64) != TSO(tm_tfiar));
BUILD_BUG_ON(TSO(tm_tfiar) + sizeof(u64) != TSO(ckpt_regs));
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
/* Flush the states */
flush_tmregs_to_thread(target);
flush_fp_to_thread(target);
flush_altivec_to_thread(target);
/* TFHAR register */
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_tfhar, 0, sizeof(u64));
/* TEXASR register */
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_texasr, sizeof(u64),
2 * sizeof(u64));
/* TFIAR register */
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_tfiar,
2 * sizeof(u64), 3 * sizeof(u64));
return ret;
}
static int tm_tar_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (MSR_TM_ACTIVE(target->thread.regs->msr))
return regset->n;
return 0;
}
static int tm_tar_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_tar, 0, sizeof(u64));
return ret;
}
static int tm_tar_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_tar, 0, sizeof(u64));
return ret;
}
static int tm_ppr_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (MSR_TM_ACTIVE(target->thread.regs->msr))
return regset->n;
return 0;
}
static int tm_ppr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_ppr, 0, sizeof(u64));
return ret;
}
static int tm_ppr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_ppr, 0, sizeof(u64));
return ret;
}
static int tm_dscr_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (MSR_TM_ACTIVE(target->thread.regs->msr))
return regset->n;
return 0;
}
static int tm_dscr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_dscr, 0, sizeof(u64));
return ret;
}
static int tm_dscr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
if (!cpu_has_feature(CPU_FTR_TM))
return -ENODEV;
if (!MSR_TM_ACTIVE(target->thread.regs->msr))
return -ENODATA;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tm_dscr, 0, sizeof(u64));
return ret;
}
#endif /* CONFIG_PPC_TRANSACTIONAL_MEM */
#ifdef CONFIG_PPC64
static int ppr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.ppr, 0, sizeof(u64));
}
static int ppr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
return user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.ppr, 0, sizeof(u64));
}
static int dscr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.dscr, 0, sizeof(u64));
}
static int dscr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
return user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.dscr, 0, sizeof(u64));
}
#endif
#ifdef CONFIG_PPC_BOOK3S_64
static int tar_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.tar, 0, sizeof(u64));
}
static int tar_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
return user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.tar, 0, sizeof(u64));
}
static int ebb_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
if (target->thread.used_ebb)
return regset->n;
return 0;
}
static int ebb_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
/* Build tests */
BUILD_BUG_ON(TSO(ebbrr) + sizeof(unsigned long) != TSO(ebbhr));
BUILD_BUG_ON(TSO(ebbhr) + sizeof(unsigned long) != TSO(bescr));
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
if (!target->thread.used_ebb)
return -ENODATA;
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.ebbrr, 0, 3 * sizeof(unsigned long));
}
static int ebb_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret = 0;
/* Build tests */
BUILD_BUG_ON(TSO(ebbrr) + sizeof(unsigned long) != TSO(ebbhr));
BUILD_BUG_ON(TSO(ebbhr) + sizeof(unsigned long) != TSO(bescr));
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
if (target->thread.used_ebb)
return -ENODATA;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.ebbrr, 0, sizeof(unsigned long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.ebbhr, sizeof(unsigned long),
2 * sizeof(unsigned long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.bescr,
2 * sizeof(unsigned long), 3 * sizeof(unsigned long));
return ret;
}
static int pmu_active(struct task_struct *target,
const struct user_regset *regset)
{
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
return regset->n;
}
static int pmu_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
/* Build tests */
BUILD_BUG_ON(TSO(siar) + sizeof(unsigned long) != TSO(sdar));
BUILD_BUG_ON(TSO(sdar) + sizeof(unsigned long) != TSO(sier));
BUILD_BUG_ON(TSO(sier) + sizeof(unsigned long) != TSO(mmcr2));
BUILD_BUG_ON(TSO(mmcr2) + sizeof(unsigned long) != TSO(mmcr0));
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&target->thread.siar, 0,
5 * sizeof(unsigned long));
}
static int pmu_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret = 0;
/* Build tests */
BUILD_BUG_ON(TSO(siar) + sizeof(unsigned long) != TSO(sdar));
BUILD_BUG_ON(TSO(sdar) + sizeof(unsigned long) != TSO(sier));
BUILD_BUG_ON(TSO(sier) + sizeof(unsigned long) != TSO(mmcr2));
BUILD_BUG_ON(TSO(mmcr2) + sizeof(unsigned long) != TSO(mmcr0));
if (!cpu_has_feature(CPU_FTR_ARCH_207S))
return -ENODEV;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.siar, 0,
sizeof(unsigned long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.sdar, sizeof(unsigned long),
2 * sizeof(unsigned long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.sier, 2 * sizeof(unsigned long),
3 * sizeof(unsigned long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.mmcr2, 3 * sizeof(unsigned long),
4 * sizeof(unsigned long));
if (!ret)
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&target->thread.mmcr0, 4 * sizeof(unsigned long),
5 * sizeof(unsigned long));
return ret;
}
#endif
/*
* These are our native regset flavors.
*/
enum powerpc_regset {
REGSET_GPR,
REGSET_FPR,
#ifdef CONFIG_ALTIVEC
REGSET_VMX,
#endif
#ifdef CONFIG_VSX
REGSET_VSX,
#endif
#ifdef CONFIG_SPE
REGSET_SPE,
#endif
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
REGSET_TM_CGPR, /* TM checkpointed GPR registers */
REGSET_TM_CFPR, /* TM checkpointed FPR registers */
REGSET_TM_CVMX, /* TM checkpointed VMX registers */
REGSET_TM_CVSX, /* TM checkpointed VSX registers */
REGSET_TM_SPR, /* TM specific SPR registers */
REGSET_TM_CTAR, /* TM checkpointed TAR register */
REGSET_TM_CPPR, /* TM checkpointed PPR register */
REGSET_TM_CDSCR, /* TM checkpointed DSCR register */
#endif
#ifdef CONFIG_PPC64
REGSET_PPR, /* PPR register */
REGSET_DSCR, /* DSCR register */
#endif
#ifdef CONFIG_PPC_BOOK3S_64
REGSET_TAR, /* TAR register */
REGSET_EBB, /* EBB registers */
REGSET_PMR, /* Performance Monitor Registers */
#endif
};
static const struct user_regset native_regsets[] = {
[REGSET_GPR] = {
.core_note_type = NT_PRSTATUS, .n = ELF_NGREG,
.size = sizeof(long), .align = sizeof(long),
.get = gpr_get, .set = gpr_set
},
[REGSET_FPR] = {
.core_note_type = NT_PRFPREG, .n = ELF_NFPREG,
.size = sizeof(double), .align = sizeof(double),
.get = fpr_get, .set = fpr_set
},
#ifdef CONFIG_ALTIVEC
[REGSET_VMX] = {
.core_note_type = NT_PPC_VMX, .n = 34,
.size = sizeof(vector128), .align = sizeof(vector128),
.active = vr_active, .get = vr_get, .set = vr_set
},
#endif
#ifdef CONFIG_VSX
[REGSET_VSX] = {
.core_note_type = NT_PPC_VSX, .n = 32,
.size = sizeof(double), .align = sizeof(double),
.active = vsr_active, .get = vsr_get, .set = vsr_set
},
#endif
#ifdef CONFIG_SPE
[REGSET_SPE] = {
.core_note_type = NT_PPC_SPE, .n = 35,
.size = sizeof(u32), .align = sizeof(u32),
.active = evr_active, .get = evr_get, .set = evr_set
},
#endif
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
[REGSET_TM_CGPR] = {
.core_note_type = NT_PPC_TM_CGPR, .n = ELF_NGREG,
.size = sizeof(long), .align = sizeof(long),
.active = tm_cgpr_active, .get = tm_cgpr_get, .set = tm_cgpr_set
},
[REGSET_TM_CFPR] = {
.core_note_type = NT_PPC_TM_CFPR, .n = ELF_NFPREG,
.size = sizeof(double), .align = sizeof(double),
.active = tm_cfpr_active, .get = tm_cfpr_get, .set = tm_cfpr_set
},
[REGSET_TM_CVMX] = {
.core_note_type = NT_PPC_TM_CVMX, .n = ELF_NVMX,
.size = sizeof(vector128), .align = sizeof(vector128),
.active = tm_cvmx_active, .get = tm_cvmx_get, .set = tm_cvmx_set
},
[REGSET_TM_CVSX] = {
.core_note_type = NT_PPC_TM_CVSX, .n = ELF_NVSX,
.size = sizeof(double), .align = sizeof(double),
.active = tm_cvsx_active, .get = tm_cvsx_get, .set = tm_cvsx_set
},
[REGSET_TM_SPR] = {
.core_note_type = NT_PPC_TM_SPR, .n = ELF_NTMSPRREG,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_spr_active, .get = tm_spr_get, .set = tm_spr_set
},
[REGSET_TM_CTAR] = {
.core_note_type = NT_PPC_TM_CTAR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_tar_active, .get = tm_tar_get, .set = tm_tar_set
},
[REGSET_TM_CPPR] = {
.core_note_type = NT_PPC_TM_CPPR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_ppr_active, .get = tm_ppr_get, .set = tm_ppr_set
},
[REGSET_TM_CDSCR] = {
.core_note_type = NT_PPC_TM_CDSCR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_dscr_active, .get = tm_dscr_get, .set = tm_dscr_set
},
#endif
#ifdef CONFIG_PPC64
[REGSET_PPR] = {
.core_note_type = NT_PPC_PPR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.get = ppr_get, .set = ppr_set
},
[REGSET_DSCR] = {
.core_note_type = NT_PPC_DSCR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.get = dscr_get, .set = dscr_set
},
#endif
#ifdef CONFIG_PPC_BOOK3S_64
[REGSET_TAR] = {
.core_note_type = NT_PPC_TAR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.get = tar_get, .set = tar_set
},
[REGSET_EBB] = {
.core_note_type = NT_PPC_EBB, .n = ELF_NEBB,
.size = sizeof(u64), .align = sizeof(u64),
.active = ebb_active, .get = ebb_get, .set = ebb_set
},
[REGSET_PMR] = {
.core_note_type = NT_PPC_PMU, .n = ELF_NPMU,
.size = sizeof(u64), .align = sizeof(u64),
.active = pmu_active, .get = pmu_get, .set = pmu_set
},
#endif
};
static const struct user_regset_view user_ppc_native_view = {
.name = UTS_MACHINE, .e_machine = ELF_ARCH, .ei_osabi = ELF_OSABI,
.regsets = native_regsets, .n = ARRAY_SIZE(native_regsets)
};
#ifdef CONFIG_PPC64
#include <linux/compat.h>
static int gpr32_get_common(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf,
unsigned long *regs)
{
compat_ulong_t *k = kbuf;
compat_ulong_t __user *u = ubuf;
compat_ulong_t reg;
pos /= sizeof(reg);
count /= sizeof(reg);
if (kbuf)
for (; count > 0 && pos < PT_MSR; --count)
*k++ = regs[pos++];
else
for (; count > 0 && pos < PT_MSR; --count)
if (__put_user((compat_ulong_t) regs[pos++], u++))
return -EFAULT;
if (count > 0 && pos == PT_MSR) {
reg = get_user_msr(target);
if (kbuf)
*k++ = reg;
else if (__put_user(reg, u++))
return -EFAULT;
++pos;
--count;
}
if (kbuf)
for (; count > 0 && pos < PT_REGS_COUNT; --count)
*k++ = regs[pos++];
else
for (; count > 0 && pos < PT_REGS_COUNT; --count)
if (__put_user((compat_ulong_t) regs[pos++], u++))
return -EFAULT;
kbuf = k;
ubuf = u;
pos *= sizeof(reg);
count *= sizeof(reg);
return user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf,
PT_REGS_COUNT * sizeof(reg), -1);
}
static int gpr32_set_common(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf,
unsigned long *regs)
{
const compat_ulong_t *k = kbuf;
const compat_ulong_t __user *u = ubuf;
compat_ulong_t reg;
pos /= sizeof(reg);
count /= sizeof(reg);
if (kbuf)
for (; count > 0 && pos < PT_MSR; --count)
regs[pos++] = *k++;
else
for (; count > 0 && pos < PT_MSR; --count) {
if (__get_user(reg, u++))
return -EFAULT;
regs[pos++] = reg;
}
if (count > 0 && pos == PT_MSR) {
if (kbuf)
reg = *k++;
else if (__get_user(reg, u++))
return -EFAULT;
set_user_msr(target, reg);
++pos;
--count;
}
if (kbuf) {
for (; count > 0 && pos <= PT_MAX_PUT_REG; --count)
regs[pos++] = *k++;
for (; count > 0 && pos < PT_TRAP; --count, ++pos)
++k;
} else {
for (; count > 0 && pos <= PT_MAX_PUT_REG; --count) {
if (__get_user(reg, u++))
return -EFAULT;
regs[pos++] = reg;
}
for (; count > 0 && pos < PT_TRAP; --count, ++pos)
if (__get_user(reg, u++))
return -EFAULT;
}
if (count > 0 && pos == PT_TRAP) {
if (kbuf)
reg = *k++;
else if (__get_user(reg, u++))
return -EFAULT;
set_user_trap(target, reg);
++pos;
--count;
}
kbuf = k;
ubuf = u;
pos *= sizeof(reg);
count *= sizeof(reg);
return user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf,
(PT_TRAP + 1) * sizeof(reg), -1);
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
static int tm_cgpr32_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return gpr32_get_common(target, regset, pos, count, kbuf, ubuf,
&target->thread.ckpt_regs.gpr[0]);
}
static int tm_cgpr32_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
return gpr32_set_common(target, regset, pos, count, kbuf, ubuf,
&target->thread.ckpt_regs.gpr[0]);
}
#endif /* CONFIG_PPC_TRANSACTIONAL_MEM */
static int gpr32_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int i;
if (target->thread.regs == NULL)
return -EIO;
if (!FULL_REGS(target->thread.regs)) {
/*
* We have a partial register set.
* Fill 14-31 with bogus values.
*/
for (i = 14; i < 32; i++)
target->thread.regs->gpr[i] = NV_REG_POISON;
}
return gpr32_get_common(target, regset, pos, count, kbuf, ubuf,
&target->thread.regs->gpr[0]);
}
static int gpr32_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
if (target->thread.regs == NULL)
return -EIO;
CHECK_FULL_REGS(target->thread.regs);
return gpr32_set_common(target, regset, pos, count, kbuf, ubuf,
&target->thread.regs->gpr[0]);
}
/*
* These are the regset flavors matching the CONFIG_PPC32 native set.
*/
static const struct user_regset compat_regsets[] = {
[REGSET_GPR] = {
.core_note_type = NT_PRSTATUS, .n = ELF_NGREG,
.size = sizeof(compat_long_t), .align = sizeof(compat_long_t),
.get = gpr32_get, .set = gpr32_set
},
[REGSET_FPR] = {
.core_note_type = NT_PRFPREG, .n = ELF_NFPREG,
.size = sizeof(double), .align = sizeof(double),
.get = fpr_get, .set = fpr_set
},
#ifdef CONFIG_ALTIVEC
[REGSET_VMX] = {
.core_note_type = NT_PPC_VMX, .n = 34,
.size = sizeof(vector128), .align = sizeof(vector128),
.active = vr_active, .get = vr_get, .set = vr_set
},
#endif
#ifdef CONFIG_SPE
[REGSET_SPE] = {
.core_note_type = NT_PPC_SPE, .n = 35,
.size = sizeof(u32), .align = sizeof(u32),
.active = evr_active, .get = evr_get, .set = evr_set
},
#endif
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
[REGSET_TM_CGPR] = {
.core_note_type = NT_PPC_TM_CGPR, .n = ELF_NGREG,
.size = sizeof(long), .align = sizeof(long),
.active = tm_cgpr_active,
.get = tm_cgpr32_get, .set = tm_cgpr32_set
},
[REGSET_TM_CFPR] = {
.core_note_type = NT_PPC_TM_CFPR, .n = ELF_NFPREG,
.size = sizeof(double), .align = sizeof(double),
.active = tm_cfpr_active, .get = tm_cfpr_get, .set = tm_cfpr_set
},
[REGSET_TM_CVMX] = {
.core_note_type = NT_PPC_TM_CVMX, .n = ELF_NVMX,
.size = sizeof(vector128), .align = sizeof(vector128),
.active = tm_cvmx_active, .get = tm_cvmx_get, .set = tm_cvmx_set
},
[REGSET_TM_CVSX] = {
.core_note_type = NT_PPC_TM_CVSX, .n = ELF_NVSX,
.size = sizeof(double), .align = sizeof(double),
.active = tm_cvsx_active, .get = tm_cvsx_get, .set = tm_cvsx_set
},
[REGSET_TM_SPR] = {
.core_note_type = NT_PPC_TM_SPR, .n = ELF_NTMSPRREG,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_spr_active, .get = tm_spr_get, .set = tm_spr_set
},
[REGSET_TM_CTAR] = {
.core_note_type = NT_PPC_TM_CTAR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_tar_active, .get = tm_tar_get, .set = tm_tar_set
},
[REGSET_TM_CPPR] = {
.core_note_type = NT_PPC_TM_CPPR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_ppr_active, .get = tm_ppr_get, .set = tm_ppr_set
},
[REGSET_TM_CDSCR] = {
.core_note_type = NT_PPC_TM_CDSCR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.active = tm_dscr_active, .get = tm_dscr_get, .set = tm_dscr_set
},
#endif
#ifdef CONFIG_PPC64
[REGSET_PPR] = {
.core_note_type = NT_PPC_PPR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.get = ppr_get, .set = ppr_set
},
[REGSET_DSCR] = {
.core_note_type = NT_PPC_DSCR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.get = dscr_get, .set = dscr_set
},
#endif
#ifdef CONFIG_PPC_BOOK3S_64
[REGSET_TAR] = {
.core_note_type = NT_PPC_TAR, .n = 1,
.size = sizeof(u64), .align = sizeof(u64),
.get = tar_get, .set = tar_set
},
[REGSET_EBB] = {
.core_note_type = NT_PPC_EBB, .n = ELF_NEBB,
.size = sizeof(u64), .align = sizeof(u64),
.active = ebb_active, .get = ebb_get, .set = ebb_set
},
#endif
};
static const struct user_regset_view user_ppc_compat_view = {
.name = "ppc", .e_machine = EM_PPC, .ei_osabi = ELF_OSABI,
.regsets = compat_regsets, .n = ARRAY_SIZE(compat_regsets)
};
#endif /* CONFIG_PPC64 */
const struct user_regset_view *task_user_regset_view(struct task_struct *task)
{
#ifdef CONFIG_PPC64
if (test_tsk_thread_flag(task, TIF_32BIT))
return &user_ppc_compat_view;
#endif
return &user_ppc_native_view;
}
void user_enable_single_step(struct task_struct *task)
{
struct pt_regs *regs = task->thread.regs;
if (regs != NULL) {
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
task->thread.debug.dbcr0 &= ~DBCR0_BT;
task->thread.debug.dbcr0 |= DBCR0_IDM | DBCR0_IC;
regs->msr |= MSR_DE;
#else
regs->msr &= ~MSR_BE;
regs->msr |= MSR_SE;
#endif
}
set_tsk_thread_flag(task, TIF_SINGLESTEP);
}
void user_enable_block_step(struct task_struct *task)
{
struct pt_regs *regs = task->thread.regs;
if (regs != NULL) {
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
task->thread.debug.dbcr0 &= ~DBCR0_IC;
task->thread.debug.dbcr0 = DBCR0_IDM | DBCR0_BT;
regs->msr |= MSR_DE;
#else
regs->msr &= ~MSR_SE;
regs->msr |= MSR_BE;
#endif
}
set_tsk_thread_flag(task, TIF_SINGLESTEP);
}
void user_disable_single_step(struct task_struct *task)
{
struct pt_regs *regs = task->thread.regs;
if (regs != NULL) {
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
/*
* The logic to disable single stepping should be as
* simple as turning off the Instruction Complete flag.
* And, after doing so, if all debug flags are off, turn
* off DBCR0(IDM) and MSR(DE) .... Torez
*/
task->thread.debug.dbcr0 &= ~(DBCR0_IC|DBCR0_BT);
/*
* Test to see if any of the DBCR_ACTIVE_EVENTS bits are set.
*/
if (!DBCR_ACTIVE_EVENTS(task->thread.debug.dbcr0,
task->thread.debug.dbcr1)) {
/*
* All debug events were off.....
*/
task->thread.debug.dbcr0 &= ~DBCR0_IDM;
regs->msr &= ~MSR_DE;
}
#else
regs->msr &= ~(MSR_SE | MSR_BE);
#endif
}
clear_tsk_thread_flag(task, TIF_SINGLESTEP);
}
#ifdef CONFIG_HAVE_HW_BREAKPOINT
void ptrace_triggered(struct perf_event *bp,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event_attr attr;
/*
* Disable the breakpoint request here since ptrace has defined a
* one-shot behaviour for breakpoint exceptions in PPC64.
* The SIGTRAP signal is generated automatically for us in do_dabr().
* We don't have to do anything about that here
*/
attr = bp->attr;
attr.disabled = true;
modify_user_hw_breakpoint(bp, &attr);
}
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
static int ptrace_set_debugreg(struct task_struct *task, unsigned long addr,
unsigned long data)
{
#ifdef CONFIG_HAVE_HW_BREAKPOINT
int ret;
struct thread_struct *thread = &(task->thread);
struct perf_event *bp;
struct perf_event_attr attr;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
#ifndef CONFIG_PPC_ADV_DEBUG_REGS
struct arch_hw_breakpoint hw_brk;
#endif
/* For ppc64 we support one DABR and no IABR's at the moment (ppc64).
* For embedded processors we support one DAC and no IAC's at the
* moment.
*/
if (addr > 0)
return -EINVAL;
/* The bottom 3 bits in dabr are flags */
if ((data & ~0x7UL) >= TASK_SIZE)
return -EIO;
#ifndef CONFIG_PPC_ADV_DEBUG_REGS
/* For processors using DABR (i.e. 970), the bottom 3 bits are flags.
* It was assumed, on previous implementations, that 3 bits were
* passed together with the data address, fitting the design of the
* DABR register, as follows:
*
* bit 0: Read flag
* bit 1: Write flag
* bit 2: Breakpoint translation
*
* Thus, we use them here as so.
*/
/* Ensure breakpoint translation bit is set */
if (data && !(data & HW_BRK_TYPE_TRANSLATE))
return -EIO;
hw_brk.address = data & (~HW_BRK_TYPE_DABR);
hw_brk.type = (data & HW_BRK_TYPE_DABR) | HW_BRK_TYPE_PRIV_ALL;
hw_brk.len = 8;
#ifdef CONFIG_HAVE_HW_BREAKPOINT
bp = thread->ptrace_bps[0];
if ((!data) || !(hw_brk.type & HW_BRK_TYPE_RDWR)) {
if (bp) {
unregister_hw_breakpoint(bp);
thread->ptrace_bps[0] = NULL;
}
return 0;
}
if (bp) {
attr = bp->attr;
attr.bp_addr = hw_brk.address;
arch_bp_generic_fields(hw_brk.type, &attr.bp_type);
/* Enable breakpoint */
attr.disabled = false;
ret = modify_user_hw_breakpoint(bp, &attr);
if (ret) {
return ret;
}
thread->ptrace_bps[0] = bp;
thread->hw_brk = hw_brk;
return 0;
}
/* Create a new breakpoint request if one doesn't exist already */
hw_breakpoint_init(&attr);
attr.bp_addr = hw_brk.address;
arch_bp_generic_fields(hw_brk.type,
&attr.bp_type);
thread->ptrace_bps[0] = bp = register_user_hw_breakpoint(&attr,
ptrace_triggered, NULL, task);
if (IS_ERR(bp)) {
thread->ptrace_bps[0] = NULL;
return PTR_ERR(bp);
}
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
task->thread.hw_brk = hw_brk;
#else /* CONFIG_PPC_ADV_DEBUG_REGS */
/* As described above, it was assumed 3 bits were passed with the data
* address, but we will assume only the mode bits will be passed
* as to not cause alignment restrictions for DAC-based processors.
*/
/* DAC's hold the whole address without any mode flags */
task->thread.debug.dac1 = data & ~0x3UL;
if (task->thread.debug.dac1 == 0) {
dbcr_dac(task) &= ~(DBCR_DAC1R | DBCR_DAC1W);
if (!DBCR_ACTIVE_EVENTS(task->thread.debug.dbcr0,
task->thread.debug.dbcr1)) {
task->thread.regs->msr &= ~MSR_DE;
task->thread.debug.dbcr0 &= ~DBCR0_IDM;
}
return 0;
}
/* Read or Write bits must be set */
if (!(data & 0x3UL))
return -EINVAL;
/* Set the Internal Debugging flag (IDM bit 1) for the DBCR0
register */
task->thread.debug.dbcr0 |= DBCR0_IDM;
/* Check for write and read flags and set DBCR0
accordingly */
dbcr_dac(task) &= ~(DBCR_DAC1R|DBCR_DAC1W);
if (data & 0x1UL)
dbcr_dac(task) |= DBCR_DAC1R;
if (data & 0x2UL)
dbcr_dac(task) |= DBCR_DAC1W;
task->thread.regs->msr |= MSR_DE;
#endif /* CONFIG_PPC_ADV_DEBUG_REGS */
return 0;
}
/*
* Called by kernel/ptrace.c when detaching..
*
* Make sure single step bits etc are not set.
*/
void ptrace_disable(struct task_struct *child)
{
/* make sure the single step bit is not set. */
user_disable_single_step(child);
}
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
static long set_instruction_bp(struct task_struct *child,
struct ppc_hw_breakpoint *bp_info)
{
int slot;
int slot1_in_use = ((child->thread.debug.dbcr0 & DBCR0_IAC1) != 0);
int slot2_in_use = ((child->thread.debug.dbcr0 & DBCR0_IAC2) != 0);
int slot3_in_use = ((child->thread.debug.dbcr0 & DBCR0_IAC3) != 0);
int slot4_in_use = ((child->thread.debug.dbcr0 & DBCR0_IAC4) != 0);
if (dbcr_iac_range(child) & DBCR_IAC12MODE)
slot2_in_use = 1;
if (dbcr_iac_range(child) & DBCR_IAC34MODE)
slot4_in_use = 1;
if (bp_info->addr >= TASK_SIZE)
return -EIO;
if (bp_info->addr_mode != PPC_BREAKPOINT_MODE_EXACT) {
/* Make sure range is valid. */
if (bp_info->addr2 >= TASK_SIZE)
return -EIO;
/* We need a pair of IAC regsisters */
if ((!slot1_in_use) && (!slot2_in_use)) {
slot = 1;
child->thread.debug.iac1 = bp_info->addr;
child->thread.debug.iac2 = bp_info->addr2;
child->thread.debug.dbcr0 |= DBCR0_IAC1;
if (bp_info->addr_mode ==
PPC_BREAKPOINT_MODE_RANGE_EXCLUSIVE)
dbcr_iac_range(child) |= DBCR_IAC12X;
else
dbcr_iac_range(child) |= DBCR_IAC12I;
#if CONFIG_PPC_ADV_DEBUG_IACS > 2
} else if ((!slot3_in_use) && (!slot4_in_use)) {
slot = 3;
child->thread.debug.iac3 = bp_info->addr;
child->thread.debug.iac4 = bp_info->addr2;
child->thread.debug.dbcr0 |= DBCR0_IAC3;
if (bp_info->addr_mode ==
PPC_BREAKPOINT_MODE_RANGE_EXCLUSIVE)
dbcr_iac_range(child) |= DBCR_IAC34X;
else
dbcr_iac_range(child) |= DBCR_IAC34I;
#endif
} else
return -ENOSPC;
} else {
/* We only need one. If possible leave a pair free in
* case a range is needed later
*/
if (!slot1_in_use) {
/*
* Don't use iac1 if iac1-iac2 are free and either
* iac3 or iac4 (but not both) are free
*/
if (slot2_in_use || (slot3_in_use == slot4_in_use)) {
slot = 1;
child->thread.debug.iac1 = bp_info->addr;
child->thread.debug.dbcr0 |= DBCR0_IAC1;
goto out;
}
}
if (!slot2_in_use) {
slot = 2;
child->thread.debug.iac2 = bp_info->addr;
child->thread.debug.dbcr0 |= DBCR0_IAC2;
#if CONFIG_PPC_ADV_DEBUG_IACS > 2
} else if (!slot3_in_use) {
slot = 3;
child->thread.debug.iac3 = bp_info->addr;
child->thread.debug.dbcr0 |= DBCR0_IAC3;
} else if (!slot4_in_use) {
slot = 4;
child->thread.debug.iac4 = bp_info->addr;
child->thread.debug.dbcr0 |= DBCR0_IAC4;
#endif
} else
return -ENOSPC;
}
out:
child->thread.debug.dbcr0 |= DBCR0_IDM;
child->thread.regs->msr |= MSR_DE;
return slot;
}
static int del_instruction_bp(struct task_struct *child, int slot)
{
switch (slot) {
case 1:
if ((child->thread.debug.dbcr0 & DBCR0_IAC1) == 0)
return -ENOENT;
if (dbcr_iac_range(child) & DBCR_IAC12MODE) {
/* address range - clear slots 1 & 2 */
child->thread.debug.iac2 = 0;
dbcr_iac_range(child) &= ~DBCR_IAC12MODE;
}
child->thread.debug.iac1 = 0;
child->thread.debug.dbcr0 &= ~DBCR0_IAC1;
break;
case 2:
if ((child->thread.debug.dbcr0 & DBCR0_IAC2) == 0)
return -ENOENT;
if (dbcr_iac_range(child) & DBCR_IAC12MODE)
/* used in a range */
return -EINVAL;
child->thread.debug.iac2 = 0;
child->thread.debug.dbcr0 &= ~DBCR0_IAC2;
break;
#if CONFIG_PPC_ADV_DEBUG_IACS > 2
case 3:
if ((child->thread.debug.dbcr0 & DBCR0_IAC3) == 0)
return -ENOENT;
if (dbcr_iac_range(child) & DBCR_IAC34MODE) {
/* address range - clear slots 3 & 4 */
child->thread.debug.iac4 = 0;
dbcr_iac_range(child) &= ~DBCR_IAC34MODE;
}
child->thread.debug.iac3 = 0;
child->thread.debug.dbcr0 &= ~DBCR0_IAC3;
break;
case 4:
if ((child->thread.debug.dbcr0 & DBCR0_IAC4) == 0)
return -ENOENT;
if (dbcr_iac_range(child) & DBCR_IAC34MODE)
/* Used in a range */
return -EINVAL;
child->thread.debug.iac4 = 0;
child->thread.debug.dbcr0 &= ~DBCR0_IAC4;
break;
#endif
default:
return -EINVAL;
}
return 0;
}
static int set_dac(struct task_struct *child, struct ppc_hw_breakpoint *bp_info)
{
int byte_enable =
(bp_info->condition_mode >> PPC_BREAKPOINT_CONDITION_BE_SHIFT)
& 0xf;
int condition_mode =
bp_info->condition_mode & PPC_BREAKPOINT_CONDITION_MODE;
int slot;
if (byte_enable && (condition_mode == 0))
return -EINVAL;
if (bp_info->addr >= TASK_SIZE)
return -EIO;
if ((dbcr_dac(child) & (DBCR_DAC1R | DBCR_DAC1W)) == 0) {
slot = 1;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_READ)
dbcr_dac(child) |= DBCR_DAC1R;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_WRITE)
dbcr_dac(child) |= DBCR_DAC1W;
child->thread.debug.dac1 = (unsigned long)bp_info->addr;
#if CONFIG_PPC_ADV_DEBUG_DVCS > 0
if (byte_enable) {
child->thread.debug.dvc1 =
(unsigned long)bp_info->condition_value;
child->thread.debug.dbcr2 |=
((byte_enable << DBCR2_DVC1BE_SHIFT) |
(condition_mode << DBCR2_DVC1M_SHIFT));
}
#endif
#ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
} else if (child->thread.debug.dbcr2 & DBCR2_DAC12MODE) {
/* Both dac1 and dac2 are part of a range */
return -ENOSPC;
#endif
} else if ((dbcr_dac(child) & (DBCR_DAC2R | DBCR_DAC2W)) == 0) {
slot = 2;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_READ)
dbcr_dac(child) |= DBCR_DAC2R;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_WRITE)
dbcr_dac(child) |= DBCR_DAC2W;
child->thread.debug.dac2 = (unsigned long)bp_info->addr;
#if CONFIG_PPC_ADV_DEBUG_DVCS > 0
if (byte_enable) {
child->thread.debug.dvc2 =
(unsigned long)bp_info->condition_value;
child->thread.debug.dbcr2 |=
((byte_enable << DBCR2_DVC2BE_SHIFT) |
(condition_mode << DBCR2_DVC2M_SHIFT));
}
#endif
} else
return -ENOSPC;
child->thread.debug.dbcr0 |= DBCR0_IDM;
child->thread.regs->msr |= MSR_DE;
return slot + 4;
}
static int del_dac(struct task_struct *child, int slot)
{
if (slot == 1) {
if ((dbcr_dac(child) & (DBCR_DAC1R | DBCR_DAC1W)) == 0)
return -ENOENT;
child->thread.debug.dac1 = 0;
dbcr_dac(child) &= ~(DBCR_DAC1R | DBCR_DAC1W);
#ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
if (child->thread.debug.dbcr2 & DBCR2_DAC12MODE) {
child->thread.debug.dac2 = 0;
child->thread.debug.dbcr2 &= ~DBCR2_DAC12MODE;
}
child->thread.debug.dbcr2 &= ~(DBCR2_DVC1M | DBCR2_DVC1BE);
#endif
#if CONFIG_PPC_ADV_DEBUG_DVCS > 0
child->thread.debug.dvc1 = 0;
#endif
} else if (slot == 2) {
if ((dbcr_dac(child) & (DBCR_DAC2R | DBCR_DAC2W)) == 0)
return -ENOENT;
#ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
if (child->thread.debug.dbcr2 & DBCR2_DAC12MODE)
/* Part of a range */
return -EINVAL;
child->thread.debug.dbcr2 &= ~(DBCR2_DVC2M | DBCR2_DVC2BE);
#endif
#if CONFIG_PPC_ADV_DEBUG_DVCS > 0
child->thread.debug.dvc2 = 0;
#endif
child->thread.debug.dac2 = 0;
dbcr_dac(child) &= ~(DBCR_DAC2R | DBCR_DAC2W);
} else
return -EINVAL;
return 0;
}
#endif /* CONFIG_PPC_ADV_DEBUG_REGS */
#ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
static int set_dac_range(struct task_struct *child,
struct ppc_hw_breakpoint *bp_info)
{
int mode = bp_info->addr_mode & PPC_BREAKPOINT_MODE_MASK;
/* We don't allow range watchpoints to be used with DVC */
if (bp_info->condition_mode)
return -EINVAL;
/*
* Best effort to verify the address range. The user/supervisor bits
* prevent trapping in kernel space, but let's fail on an obvious bad
* range. The simple test on the mask is not fool-proof, and any
* exclusive range will spill over into kernel space.
*/
if (bp_info->addr >= TASK_SIZE)
return -EIO;
if (mode == PPC_BREAKPOINT_MODE_MASK) {
/*
* dac2 is a bitmask. Don't allow a mask that makes a
* kernel space address from a valid dac1 value
*/
if (~((unsigned long)bp_info->addr2) >= TASK_SIZE)
return -EIO;
} else {
/*
* For range breakpoints, addr2 must also be a valid address
*/
if (bp_info->addr2 >= TASK_SIZE)
return -EIO;
}
if (child->thread.debug.dbcr0 &
(DBCR0_DAC1R | DBCR0_DAC1W | DBCR0_DAC2R | DBCR0_DAC2W))
return -ENOSPC;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_READ)
child->thread.debug.dbcr0 |= (DBCR0_DAC1R | DBCR0_IDM);
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_WRITE)
child->thread.debug.dbcr0 |= (DBCR0_DAC1W | DBCR0_IDM);
child->thread.debug.dac1 = bp_info->addr;
child->thread.debug.dac2 = bp_info->addr2;
if (mode == PPC_BREAKPOINT_MODE_RANGE_INCLUSIVE)
child->thread.debug.dbcr2 |= DBCR2_DAC12M;
else if (mode == PPC_BREAKPOINT_MODE_RANGE_EXCLUSIVE)
child->thread.debug.dbcr2 |= DBCR2_DAC12MX;
else /* PPC_BREAKPOINT_MODE_MASK */
child->thread.debug.dbcr2 |= DBCR2_DAC12MM;
child->thread.regs->msr |= MSR_DE;
return 5;
}
#endif /* CONFIG_PPC_ADV_DEBUG_DAC_RANGE */
static long ppc_set_hwdebug(struct task_struct *child,
struct ppc_hw_breakpoint *bp_info)
{
#ifdef CONFIG_HAVE_HW_BREAKPOINT
int len = 0;
struct thread_struct *thread = &(child->thread);
struct perf_event *bp;
struct perf_event_attr attr;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
#ifndef CONFIG_PPC_ADV_DEBUG_REGS
struct arch_hw_breakpoint brk;
#endif
if (bp_info->version != 1)
return -ENOTSUPP;
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
/*
* Check for invalid flags and combinations
*/
if ((bp_info->trigger_type == 0) ||
(bp_info->trigger_type & ~(PPC_BREAKPOINT_TRIGGER_EXECUTE |
PPC_BREAKPOINT_TRIGGER_RW)) ||
(bp_info->addr_mode & ~PPC_BREAKPOINT_MODE_MASK) ||
(bp_info->condition_mode &
~(PPC_BREAKPOINT_CONDITION_MODE |
PPC_BREAKPOINT_CONDITION_BE_ALL)))
return -EINVAL;
#if CONFIG_PPC_ADV_DEBUG_DVCS == 0
if (bp_info->condition_mode != PPC_BREAKPOINT_CONDITION_NONE)
return -EINVAL;
#endif
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_EXECUTE) {
if ((bp_info->trigger_type != PPC_BREAKPOINT_TRIGGER_EXECUTE) ||
(bp_info->condition_mode != PPC_BREAKPOINT_CONDITION_NONE))
return -EINVAL;
return set_instruction_bp(child, bp_info);
}
if (bp_info->addr_mode == PPC_BREAKPOINT_MODE_EXACT)
return set_dac(child, bp_info);
#ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
return set_dac_range(child, bp_info);
#else
return -EINVAL;
#endif
#else /* !CONFIG_PPC_ADV_DEBUG_DVCS */
/*
* We only support one data breakpoint
*/
if ((bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_RW) == 0 ||
(bp_info->trigger_type & ~PPC_BREAKPOINT_TRIGGER_RW) != 0 ||
bp_info->condition_mode != PPC_BREAKPOINT_CONDITION_NONE)
return -EINVAL;
if ((unsigned long)bp_info->addr >= TASK_SIZE)
return -EIO;
brk.address = bp_info->addr & ~7UL;
brk.type = HW_BRK_TYPE_TRANSLATE;
brk.len = 8;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_READ)
brk.type |= HW_BRK_TYPE_READ;
if (bp_info->trigger_type & PPC_BREAKPOINT_TRIGGER_WRITE)
brk.type |= HW_BRK_TYPE_WRITE;
#ifdef CONFIG_HAVE_HW_BREAKPOINT
/*
* Check if the request is for 'range' breakpoints. We can
* support it if range < 8 bytes.
*/
if (bp_info->addr_mode == PPC_BREAKPOINT_MODE_RANGE_INCLUSIVE)
len = bp_info->addr2 - bp_info->addr;
else if (bp_info->addr_mode == PPC_BREAKPOINT_MODE_EXACT)
len = 1;
else
return -EINVAL;
bp = thread->ptrace_bps[0];
if (bp)
return -ENOSPC;
/* Create a new breakpoint request if one doesn't exist already */
hw_breakpoint_init(&attr);
attr.bp_addr = (unsigned long)bp_info->addr & ~HW_BREAKPOINT_ALIGN;
attr.bp_len = len;
arch_bp_generic_fields(brk.type, &attr.bp_type);
thread->ptrace_bps[0] = bp = register_user_hw_breakpoint(&attr,
ptrace_triggered, NULL, child);
if (IS_ERR(bp)) {
thread->ptrace_bps[0] = NULL;
return PTR_ERR(bp);
}
return 1;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
if (bp_info->addr_mode != PPC_BREAKPOINT_MODE_EXACT)
return -EINVAL;
if (child->thread.hw_brk.address)
return -ENOSPC;
child->thread.hw_brk = brk;
return 1;
#endif /* !CONFIG_PPC_ADV_DEBUG_DVCS */
}
static long ppc_del_hwdebug(struct task_struct *child, long data)
{
#ifdef CONFIG_HAVE_HW_BREAKPOINT
int ret = 0;
struct thread_struct *thread = &(child->thread);
struct perf_event *bp;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
int rc;
if (data <= 4)
rc = del_instruction_bp(child, (int)data);
else
rc = del_dac(child, (int)data - 4);
if (!rc) {
if (!DBCR_ACTIVE_EVENTS(child->thread.debug.dbcr0,
child->thread.debug.dbcr1)) {
child->thread.debug.dbcr0 &= ~DBCR0_IDM;
child->thread.regs->msr &= ~MSR_DE;
}
}
return rc;
#else
if (data != 1)
return -EINVAL;
#ifdef CONFIG_HAVE_HW_BREAKPOINT
bp = thread->ptrace_bps[0];
if (bp) {
unregister_hw_breakpoint(bp);
thread->ptrace_bps[0] = NULL;
} else
ret = -ENOENT;
return ret;
#else /* CONFIG_HAVE_HW_BREAKPOINT */
if (child->thread.hw_brk.address == 0)
return -ENOENT;
child->thread.hw_brk.address = 0;
child->thread.hw_brk.type = 0;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
return 0;
#endif
}
long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret = -EPERM;
void __user *datavp = (void __user *) data;
unsigned long __user *datalp = datavp;
switch (request) {
/* read the word at location addr in the USER area. */
case PTRACE_PEEKUSR: {
unsigned long index, tmp;
ret = -EIO;
/* convert to index and check */
#ifdef CONFIG_PPC32
index = addr >> 2;
if ((addr & 3) || (index > PT_FPSCR)
|| (child->thread.regs == NULL))
#else
index = addr >> 3;
if ((addr & 7) || (index > PT_FPSCR))
#endif
break;
CHECK_FULL_REGS(child->thread.regs);
if (index < PT_FPR0) {
ret = ptrace_get_reg(child, (int) index, &tmp);
if (ret)
break;
} else {
unsigned int fpidx = index - PT_FPR0;
flush_fp_to_thread(child);
if (fpidx < (PT_FPSCR - PT_FPR0))
memcpy(&tmp, &child->thread.TS_FPR(fpidx),
sizeof(long));
else
tmp = child->thread.fp_state.fpscr;
}
ret = put_user(tmp, datalp);
break;
}
/* write the word at location addr in the USER area */
case PTRACE_POKEUSR: {
unsigned long index;
ret = -EIO;
/* convert to index and check */
#ifdef CONFIG_PPC32
index = addr >> 2;
if ((addr & 3) || (index > PT_FPSCR)
|| (child->thread.regs == NULL))
#else
index = addr >> 3;
if ((addr & 7) || (index > PT_FPSCR))
#endif
break;
CHECK_FULL_REGS(child->thread.regs);
if (index < PT_FPR0) {
ret = ptrace_put_reg(child, index, data);
} else {
unsigned int fpidx = index - PT_FPR0;
flush_fp_to_thread(child);
if (fpidx < (PT_FPSCR - PT_FPR0))
memcpy(&child->thread.TS_FPR(fpidx), &data,
sizeof(long));
else
child->thread.fp_state.fpscr = data;
ret = 0;
}
break;
}
case PPC_PTRACE_GETHWDBGINFO: {
struct ppc_debug_info dbginfo;
dbginfo.version = 1;
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
dbginfo.num_instruction_bps = CONFIG_PPC_ADV_DEBUG_IACS;
dbginfo.num_data_bps = CONFIG_PPC_ADV_DEBUG_DACS;
dbginfo.num_condition_regs = CONFIG_PPC_ADV_DEBUG_DVCS;
dbginfo.data_bp_alignment = 4;
dbginfo.sizeof_condition = 4;
dbginfo.features = PPC_DEBUG_FEATURE_INSN_BP_RANGE |
PPC_DEBUG_FEATURE_INSN_BP_MASK;
#ifdef CONFIG_PPC_ADV_DEBUG_DAC_RANGE
dbginfo.features |=
PPC_DEBUG_FEATURE_DATA_BP_RANGE |
PPC_DEBUG_FEATURE_DATA_BP_MASK;
#endif
#else /* !CONFIG_PPC_ADV_DEBUG_REGS */
dbginfo.num_instruction_bps = 0;
dbginfo.num_data_bps = 1;
dbginfo.num_condition_regs = 0;
#ifdef CONFIG_PPC64
dbginfo.data_bp_alignment = 8;
#else
dbginfo.data_bp_alignment = 4;
#endif
dbginfo.sizeof_condition = 0;
#ifdef CONFIG_HAVE_HW_BREAKPOINT
dbginfo.features = PPC_DEBUG_FEATURE_DATA_BP_RANGE;
if (cpu_has_feature(CPU_FTR_DAWR))
dbginfo.features |= PPC_DEBUG_FEATURE_DATA_BP_DAWR;
#else
dbginfo.features = 0;
#endif /* CONFIG_HAVE_HW_BREAKPOINT */
#endif /* CONFIG_PPC_ADV_DEBUG_REGS */
if (!access_ok(VERIFY_WRITE, datavp,
sizeof(struct ppc_debug_info)))
return -EFAULT;
ret = __copy_to_user(datavp, &dbginfo,
sizeof(struct ppc_debug_info)) ?
-EFAULT : 0;
break;
}
case PPC_PTRACE_SETHWDEBUG: {
struct ppc_hw_breakpoint bp_info;
if (!access_ok(VERIFY_READ, datavp,
sizeof(struct ppc_hw_breakpoint)))
return -EFAULT;
ret = __copy_from_user(&bp_info, datavp,
sizeof(struct ppc_hw_breakpoint)) ?
-EFAULT : 0;
if (!ret)
ret = ppc_set_hwdebug(child, &bp_info);
break;
}
case PPC_PTRACE_DELHWDEBUG: {
ret = ppc_del_hwdebug(child, data);
break;
}
case PTRACE_GET_DEBUGREG: {
#ifndef CONFIG_PPC_ADV_DEBUG_REGS
unsigned long dabr_fake;
#endif
ret = -EINVAL;
/* We only support one DABR and no IABRS at the moment */
if (addr > 0)
break;
#ifdef CONFIG_PPC_ADV_DEBUG_REGS
ret = put_user(child->thread.debug.dac1, datalp);
#else
dabr_fake = ((child->thread.hw_brk.address & (~HW_BRK_TYPE_DABR)) |
(child->thread.hw_brk.type & HW_BRK_TYPE_DABR));
ret = put_user(dabr_fake, datalp);
#endif
break;
}
case PTRACE_SET_DEBUGREG:
ret = ptrace_set_debugreg(child, addr, data);
break;
#ifdef CONFIG_PPC64
case PTRACE_GETREGS64:
#endif
case PTRACE_GETREGS: /* Get all pt_regs from the child. */
return copy_regset_to_user(child, &user_ppc_native_view,
REGSET_GPR,
0, sizeof(struct pt_regs),
datavp);
#ifdef CONFIG_PPC64
case PTRACE_SETREGS64:
#endif
case PTRACE_SETREGS: /* Set all gp regs in the child. */
return copy_regset_from_user(child, &user_ppc_native_view,
REGSET_GPR,
0, sizeof(struct pt_regs),
datavp);
case PTRACE_GETFPREGS: /* Get the child FPU state (FPR0...31 + FPSCR) */
return copy_regset_to_user(child, &user_ppc_native_view,
REGSET_FPR,
0, sizeof(elf_fpregset_t),
datavp);
case PTRACE_SETFPREGS: /* Set the child FPU state (FPR0...31 + FPSCR) */
return copy_regset_from_user(child, &user_ppc_native_view,
REGSET_FPR,
0, sizeof(elf_fpregset_t),
datavp);
#ifdef CONFIG_ALTIVEC
case PTRACE_GETVRREGS:
return copy_regset_to_user(child, &user_ppc_native_view,
REGSET_VMX,
0, (33 * sizeof(vector128) +
sizeof(u32)),
datavp);
case PTRACE_SETVRREGS:
return copy_regset_from_user(child, &user_ppc_native_view,
REGSET_VMX,
0, (33 * sizeof(vector128) +
sizeof(u32)),
datavp);
#endif
#ifdef CONFIG_VSX
case PTRACE_GETVSRREGS:
return copy_regset_to_user(child, &user_ppc_native_view,
REGSET_VSX,
0, 32 * sizeof(double),
datavp);
case PTRACE_SETVSRREGS:
return copy_regset_from_user(child, &user_ppc_native_view,
REGSET_VSX,
0, 32 * sizeof(double),
datavp);
#endif
#ifdef CONFIG_SPE
case PTRACE_GETEVRREGS:
/* Get the child spe register state. */
return copy_regset_to_user(child, &user_ppc_native_view,
REGSET_SPE, 0, 35 * sizeof(u32),
datavp);
case PTRACE_SETEVRREGS:
/* Set the child spe register state. */
return copy_regset_from_user(child, &user_ppc_native_view,
REGSET_SPE, 0, 35 * sizeof(u32),
datavp);
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
#ifdef CONFIG_SECCOMP
static int do_seccomp(struct pt_regs *regs)
{
if (!test_thread_flag(TIF_SECCOMP))
return 0;
/*
* The ABI we present to seccomp tracers is that r3 contains
* the syscall return value and orig_gpr3 contains the first
* syscall parameter. This is different to the ptrace ABI where
* both r3 and orig_gpr3 contain the first syscall parameter.
*/
regs->gpr[3] = -ENOSYS;
/*
* We use the __ version here because we have already checked
* TIF_SECCOMP. If this fails, there is nothing left to do, we
* have already loaded -ENOSYS into r3, or seccomp has put
* something else in r3 (via SECCOMP_RET_ERRNO/TRACE).
*/
if (__secure_computing(NULL))
return -1;
/*
* The syscall was allowed by seccomp, restore the register
* state to what audit expects.
* Note that we use orig_gpr3, which means a seccomp tracer can
* modify the first syscall parameter (in orig_gpr3) and also
* allow the syscall to proceed.
*/
regs->gpr[3] = regs->orig_gpr3;
return 0;
}
#else
static inline int do_seccomp(struct pt_regs *regs) { return 0; }
#endif /* CONFIG_SECCOMP */
/**
* do_syscall_trace_enter() - Do syscall tracing on kernel entry.
* @regs: the pt_regs of the task to trace (current)
*
* Performs various types of tracing on syscall entry. This includes seccomp,
* ptrace, syscall tracepoints and audit.
*
* The pt_regs are potentially visible to userspace via ptrace, so their
* contents is ABI.
*
* One or more of the tracers may modify the contents of pt_regs, in particular
* to modify arguments or even the syscall number itself.
*
* It's also possible that a tracer can choose to reject the system call. In
* that case this function will return an illegal syscall number, and will put
* an appropriate return value in regs->r3.
*
* Return: the (possibly changed) syscall number.
*/
long do_syscall_trace_enter(struct pt_regs *regs)
{
user_exit();
/*
* The tracer may decide to abort the syscall, if so tracehook
* will return !0. Note that the tracer may also just change
* regs->gpr[0] to an invalid syscall number, that is handled
* below on the exit path.
*/
if (test_thread_flag(TIF_SYSCALL_TRACE) &&
tracehook_report_syscall_entry(regs))
goto skip;
/* Run seccomp after ptrace; allow it to set gpr[3]. */
if (do_seccomp(regs))
return -1;
/* Avoid trace and audit when syscall is invalid. */
if (regs->gpr[0] >= NR_syscalls)
goto skip;
if (unlikely(test_thread_flag(TIF_SYSCALL_TRACEPOINT)))
trace_sys_enter(regs, regs->gpr[0]);
#ifdef CONFIG_PPC64
if (!is_32bit_task())
audit_syscall_entry(regs->gpr[0], regs->gpr[3], regs->gpr[4],
regs->gpr[5], regs->gpr[6]);
else
#endif
audit_syscall_entry(regs->gpr[0],
regs->gpr[3] & 0xffffffff,
regs->gpr[4] & 0xffffffff,
regs->gpr[5] & 0xffffffff,
regs->gpr[6] & 0xffffffff);
/* Return the possibly modified but valid syscall number */
return regs->gpr[0];
skip:
/*
* If we are aborting explicitly, or if the syscall number is
* now invalid, set the return value to -ENOSYS.
*/
regs->gpr[3] = -ENOSYS;
return -1;
}
void do_syscall_trace_leave(struct pt_regs *regs)
{
int step;
audit_syscall_exit(regs);
if (unlikely(test_thread_flag(TIF_SYSCALL_TRACEPOINT)))
trace_sys_exit(regs, regs->result);
step = test_thread_flag(TIF_SINGLESTEP);
if (step || test_thread_flag(TIF_SYSCALL_TRACE))
tracehook_report_syscall_exit(regs, step);
user_enter();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_118_0 |
crossvul-cpp_data_good_5127_2 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W PPPP GGGG %
% W W P P G %
% W W W PPPP G GGG %
% WW WW P G G %
% W W P GGG %
% %
% %
% Read WordPerfect Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 2000 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/distort.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
typedef struct
{
unsigned char Red;
unsigned char Blue;
unsigned char Green;
} RGB_Record;
/* Default palette for WPG level 1 */
static const RGB_Record WPG1_Palette[256]={
{ 0, 0, 0}, { 0, 0,168},
{ 0,168, 0}, { 0,168,168},
{168, 0, 0}, {168, 0,168},
{168, 84, 0}, {168,168,168},
{ 84, 84, 84}, { 84, 84,252},
{ 84,252, 84}, { 84,252,252},
{252, 84, 84}, {252, 84,252},
{252,252, 84}, {252,252,252}, /*16*/
{ 0, 0, 0}, { 20, 20, 20},
{ 32, 32, 32}, { 44, 44, 44},
{ 56, 56, 56}, { 68, 68, 68},
{ 80, 80, 80}, { 96, 96, 96},
{112,112,112}, {128,128,128},
{144,144,144}, {160,160,160},
{180,180,180}, {200,200,200},
{224,224,224}, {252,252,252}, /*32*/
{ 0, 0,252}, { 64, 0,252},
{124, 0,252}, {188, 0,252},
{252, 0,252}, {252, 0,188},
{252, 0,124}, {252, 0, 64},
{252, 0, 0}, {252, 64, 0},
{252,124, 0}, {252,188, 0},
{252,252, 0}, {188,252, 0},
{124,252, 0}, { 64,252, 0}, /*48*/
{ 0,252, 0}, { 0,252, 64},
{ 0,252,124}, { 0,252,188},
{ 0,252,252}, { 0,188,252},
{ 0,124,252}, { 0, 64,252},
{124,124,252}, {156,124,252},
{188,124,252}, {220,124,252},
{252,124,252}, {252,124,220},
{252,124,188}, {252,124,156}, /*64*/
{252,124,124}, {252,156,124},
{252,188,124}, {252,220,124},
{252,252,124}, {220,252,124},
{188,252,124}, {156,252,124},
{124,252,124}, {124,252,156},
{124,252,188}, {124,252,220},
{124,252,252}, {124,220,252},
{124,188,252}, {124,156,252}, /*80*/
{180,180,252}, {196,180,252},
{216,180,252}, {232,180,252},
{252,180,252}, {252,180,232},
{252,180,216}, {252,180,196},
{252,180,180}, {252,196,180},
{252,216,180}, {252,232,180},
{252,252,180}, {232,252,180},
{216,252,180}, {196,252,180}, /*96*/
{180,220,180}, {180,252,196},
{180,252,216}, {180,252,232},
{180,252,252}, {180,232,252},
{180,216,252}, {180,196,252},
{0,0,112}, {28,0,112},
{56,0,112}, {84,0,112},
{112,0,112}, {112,0,84},
{112,0,56}, {112,0,28}, /*112*/
{112,0,0}, {112,28,0},
{112,56,0}, {112,84,0},
{112,112,0}, {84,112,0},
{56,112,0}, {28,112,0},
{0,112,0}, {0,112,28},
{0,112,56}, {0,112,84},
{0,112,112}, {0,84,112},
{0,56,112}, {0,28,112}, /*128*/
{56,56,112}, {68,56,112},
{84,56,112}, {96,56,112},
{112,56,112}, {112,56,96},
{112,56,84}, {112,56,68},
{112,56,56}, {112,68,56},
{112,84,56}, {112,96,56},
{112,112,56}, {96,112,56},
{84,112,56}, {68,112,56}, /*144*/
{56,112,56}, {56,112,69},
{56,112,84}, {56,112,96},
{56,112,112}, {56,96,112},
{56,84,112}, {56,68,112},
{80,80,112}, {88,80,112},
{96,80,112}, {104,80,112},
{112,80,112}, {112,80,104},
{112,80,96}, {112,80,88}, /*160*/
{112,80,80}, {112,88,80},
{112,96,80}, {112,104,80},
{112,112,80}, {104,112,80},
{96,112,80}, {88,112,80},
{80,112,80}, {80,112,88},
{80,112,96}, {80,112,104},
{80,112,112}, {80,114,112},
{80,96,112}, {80,88,112}, /*176*/
{0,0,64}, {16,0,64},
{32,0,64}, {48,0,64},
{64,0,64}, {64,0,48},
{64,0,32}, {64,0,16},
{64,0,0}, {64,16,0},
{64,32,0}, {64,48,0},
{64,64,0}, {48,64,0},
{32,64,0}, {16,64,0}, /*192*/
{0,64,0}, {0,64,16},
{0,64,32}, {0,64,48},
{0,64,64}, {0,48,64},
{0,32,64}, {0,16,64},
{32,32,64}, {40,32,64},
{48,32,64}, {56,32,64},
{64,32,64}, {64,32,56},
{64,32,48}, {64,32,40}, /*208*/
{64,32,32}, {64,40,32},
{64,48,32}, {64,56,32},
{64,64,32}, {56,64,32},
{48,64,32}, {40,64,32},
{32,64,32}, {32,64,40},
{32,64,48}, {32,64,56},
{32,64,64}, {32,56,64},
{32,48,64}, {32,40,64}, /*224*/
{44,44,64}, {48,44,64},
{52,44,64}, {60,44,64},
{64,44,64}, {64,44,60},
{64,44,52}, {64,44,48},
{64,44,44}, {64,48,44},
{64,52,44}, {64,60,44},
{64,64,44}, {60,64,44},
{52,64,44}, {48,64,44}, /*240*/
{44,64,44}, {44,64,48},
{44,64,52}, {44,64,60},
{44,64,64}, {44,60,64},
{44,55,64}, {44,48,64},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0},
{0,0,0}, {0,0,0} /*256*/
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W P G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWPG() returns True if the image format type, identified by the magick
% string, is WPG.
%
% The format of the IsWPG method is:
%
% unsigned int IsWPG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o status: Method IsWPG returns True if the image format type is WPG.
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static unsigned int IsWPG(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\377WPC",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
static void Rd_WP_DWORD(Image *image,size_t *d)
{
unsigned char
b;
b=ReadBlobByte(image);
*d=b;
if (b < 0xFFU)
return;
b=ReadBlobByte(image);
*d=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
if (*d < 0x8000)
return;
*d=(*d & 0x7FFF) << 16;
b=ReadBlobByte(image);
*d+=(size_t) b;
b=ReadBlobByte(image);
*d+=(size_t) b*256l;
return;
}
static void InsertRow(Image *image,unsigned char *p,ssize_t y,int bpp,
ExceptionInfo *exception)
{
int
bit;
Quantum
index;
register Quantum
*q;
ssize_t
x;
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
case 2: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,
exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 4: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 8: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL) break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
break;
case 24: /* Convert DirectColor scanline. */
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
}
/* Helper for WPG1 raster reader. */
#define InsertByte(b) \
{ \
BImgBuff[x]=b; \
x++; \
if((ssize_t) x>=ldblk) \
{ \
InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception); \
x=0; \
y++; \
} \
}
/* WPG1 raster reader. */
static int UnpackWPGRaster(Image *image,int bpp,ExceptionInfo *exception)
{
int
x,
y,
i;
unsigned char
bbuf,
*BImgBuff,
RunCount;
ssize_t
ldblk;
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
8*sizeof(*BImgBuff));
if(BImgBuff==NULL) return(-2);
while(y<(ssize_t) image->rows)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
bbuf=(unsigned char) c;
RunCount=bbuf & 0x7F;
if(bbuf & 0x80)
{
if(RunCount) /* repeat next byte runcount * */
{
bbuf=ReadBlobByte(image);
for(i=0;i<(int) RunCount;i++) InsertByte(bbuf);
}
else { /* read next byte as RunCount; repeat 0xFF runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
for(i=0;i<(int) RunCount;i++) InsertByte(0xFF);
}
}
else {
if(RunCount) /* next runcount byte are readed directly */
{
for(i=0;i < (int) RunCount;i++)
{
bbuf=ReadBlobByte(image);
InsertByte(bbuf);
}
}
else { /* repeat previous line runcount* */
c=ReadBlobByte(image);
if (c < 0)
break;
RunCount=(unsigned char) c;
if(x) { /* attempt to duplicate row from x position: */
/* I do not know what to do here */
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-3);
}
for(i=0;i < (int) RunCount;i++)
{
x=0;
y++; /* Here I need to duplicate previous row RUNCOUNT* */
if(y<2) continue;
if(y>(ssize_t) image->rows)
{
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(-4);
}
InsertRow(image,BImgBuff,y-1,bpp,exception);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(y <(ssize_t) image->rows ? -5 : 0);
}
/* Helper for WPG2 reader. */
#define InsertByte6(b) \
{ \
DisableMSCWarning(4310) \
if(XorMe)\
BImgBuff[x] = (unsigned char)~b;\
else\
BImgBuff[x] = b;\
RestoreMSCWarning \
x++; \
if((ssize_t) x >= ldblk) \
{ \
InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception); \
x=0; \
y++; \
} \
}
/* WPG2 raster reader. */
static int UnpackWPG2Raster(Image *image,int bpp,ExceptionInfo *exception)
{
int
RunCount,
XorMe = 0;
size_t
x,
y;
ssize_t
i,
ldblk;
unsigned int
SampleSize=1;
unsigned char
bbuf,
*BImgBuff,
SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
x=0;
y=0;
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff));
if(BImgBuff==NULL)
return(-2);
while( y< image->rows)
{
bbuf=ReadBlobByte(image);
switch(bbuf)
{
case 0x7D:
SampleSize=ReadBlobByte(image); /* DSZ */
if(SampleSize>8)
return(-2);
if(SampleSize<1)
return(-2);
break;
case 0x7E:
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG token XOR, please report!");
XorMe=!XorMe;
break;
case 0x7F:
RunCount=ReadBlobByte(image); /* BLK */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0);
}
break;
case 0xFD:
RunCount=ReadBlobByte(image); /* EXT */
if (RunCount < 0)
break;
for(i=0; i<= RunCount;i++)
for(bbuf=0; bbuf < SampleSize; bbuf++)
InsertByte6(SampleBuffer[bbuf]);
break;
case 0xFE:
RunCount=ReadBlobByte(image); /* RST */
if (RunCount < 0)
break;
if(x!=0)
{
(void) FormatLocaleFile(stderr,
"\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"
,(double) x);
return(-3);
}
{
/* duplicate the previous row RunCount x */
for(i=0;i<=RunCount;i++)
{
InsertRow(image,BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1),
bpp,exception);
y++;
}
}
break;
case 0xFF:
RunCount=ReadBlobByte(image); /* WHT */
if (RunCount < 0)
break;
for(i=0; i < SampleSize*(RunCount+1); i++)
{
InsertByte6(0xFF);
}
break;
default:
RunCount=bbuf & 0x7F;
if(bbuf & 0x80) /* REP */
{
for(i=0; i < SampleSize; i++)
SampleBuffer[i]=ReadBlobByte(image);
for(i=0;i<=RunCount;i++)
for(bbuf=0;bbuf<SampleSize;bbuf++)
InsertByte6(SampleBuffer[bbuf]);
}
else { /* NRP */
for(i=0; i< SampleSize*(RunCount+1);i++)
{
bbuf=ReadBlobByte(image);
InsertByte6(bbuf);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
}
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
return(0);
}
typedef float tCTM[3][3];
static unsigned LoadWPG2Flags(Image *image,char Precision,float *Angle,tCTM *CTM)
{
const unsigned char TPR=1,TRN=2,SKW=4,SCL=8,ROT=0x10,OID=0x20,LCK=0x80;
ssize_t x;
unsigned DenX;
unsigned Flags;
(void) memset(*CTM,0,sizeof(*CTM)); /*CTM.erase();CTM.resize(3,3);*/
(*CTM)[0][0]=1;
(*CTM)[1][1]=1;
(*CTM)[2][2]=1;
Flags=ReadBlobLSBShort(image);
if(Flags & LCK) (void) ReadBlobLSBLong(image); /*Edit lock*/
if(Flags & OID)
{
if(Precision==0)
{(void) ReadBlobLSBShort(image);} /*ObjectID*/
else
{(void) ReadBlobLSBLong(image);} /*ObjectID (Double precision)*/
}
if(Flags & ROT)
{
x=ReadBlobLSBLong(image); /*Rot Angle*/
if(Angle) *Angle=x/65536.0;
}
if(Flags & (ROT|SCL))
{
x=ReadBlobLSBLong(image); /*Sx*cos()*/
(*CTM)[0][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Sy*cos()*/
(*CTM)[1][1] = (float)x/0x10000;
}
if(Flags & (ROT|SKW))
{
x=ReadBlobLSBLong(image); /*Kx*sin()*/
(*CTM)[1][0] = (float)x/0x10000;
x=ReadBlobLSBLong(image); /*Ky*sin()*/
(*CTM)[0][1] = (float)x/0x10000;
}
if(Flags & TRN)
{
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Tx*/
if(x>=0) (*CTM)[0][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[0][2] = (float)x-(float)DenX/0x10000;
x=ReadBlobLSBLong(image); DenX=ReadBlobLSBShort(image); /*Ty*/
(*CTM)[1][2]=(float)x + ((x>=0)?1:-1)*(float)DenX/0x10000;
if(x>=0) (*CTM)[1][2] = (float)x+(float)DenX/0x10000;
else (*CTM)[1][2] = (float)x-(float)DenX/0x10000;
}
if(Flags & TPR)
{
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Px*/
(*CTM)[2][0] = x + (float)DenX/0x10000;;
x=ReadBlobLSBShort(image); DenX=ReadBlobLSBShort(image); /*Py*/
(*CTM)[2][1] = x + (float)DenX/0x10000;
}
return(Flags);
}
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MagickPathExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MagickPathExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MagickPathExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MagickPathExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) strncpy(clone_info->magick,magic_info->name,MagickPathExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MagickPathExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MagickPathExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MagickPathExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MagickPathExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadWPGImage reads an WPG X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadWPGImage method is:
%
% Image *ReadWPGImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadWPGImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or if
% the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp,exception) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk+1,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterWPGImage adds attributes for the WPG image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterWPGImage method is:
%
% size_t RegisterWPGImage(void)
%
*/
ModuleExport size_t RegisterWPGImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("WPG","WPG","Word Perfect Graphics");
entry->decoder=(DecodeImageHandler *) ReadWPGImage;
entry->magick=(IsImageFormatHandler *) IsWPG;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r W P G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterWPGImage removes format registrations made by the
% WPG module from the list of supported formats.
%
% The format of the UnregisterWPGImage method is:
%
% UnregisterWPGImage(void)
%
*/
ModuleExport void UnregisterWPGImage(void)
{
(void) UnregisterMagickInfo("WPG");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5127_2 |
crossvul-cpp_data_good_3508_0 | /*
Broadcom B43 wireless driver
DMA ringbuffer and descriptor allocation/management
Copyright (c) 2005, 2006 Michael Buesch <mb@bu3sch.de>
Some code in this file is derived from the b44.c driver
Copyright (C) 2002 David S. Miller
Copyright (C) Pekka Pietikainen
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 Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "b43.h"
#include "dma.h"
#include "main.h"
#include "debugfs.h"
#include "xmit.h"
#include <linux/dma-mapping.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/slab.h>
#include <asm/div64.h>
/* Required number of TX DMA slots per TX frame.
* This currently is 2, because we put the header and the ieee80211 frame
* into separate slots. */
#define TX_SLOTS_PER_FRAME 2
/* 32bit DMA ops. */
static
struct b43_dmadesc_generic *op32_idx2desc(struct b43_dmaring *ring,
int slot,
struct b43_dmadesc_meta **meta)
{
struct b43_dmadesc32 *desc;
*meta = &(ring->meta[slot]);
desc = ring->descbase;
desc = &(desc[slot]);
return (struct b43_dmadesc_generic *)desc;
}
static void op32_fill_descriptor(struct b43_dmaring *ring,
struct b43_dmadesc_generic *desc,
dma_addr_t dmaaddr, u16 bufsize,
int start, int end, int irq)
{
struct b43_dmadesc32 *descbase = ring->descbase;
int slot;
u32 ctl;
u32 addr;
u32 addrext;
slot = (int)(&(desc->dma32) - descbase);
B43_WARN_ON(!(slot >= 0 && slot < ring->nr_slots));
addr = (u32) (dmaaddr & ~SSB_DMA_TRANSLATION_MASK);
addrext = (u32) (dmaaddr & SSB_DMA_TRANSLATION_MASK)
>> SSB_DMA_TRANSLATION_SHIFT;
addr |= ssb_dma_translation(ring->dev->dev);
ctl = bufsize & B43_DMA32_DCTL_BYTECNT;
if (slot == ring->nr_slots - 1)
ctl |= B43_DMA32_DCTL_DTABLEEND;
if (start)
ctl |= B43_DMA32_DCTL_FRAMESTART;
if (end)
ctl |= B43_DMA32_DCTL_FRAMEEND;
if (irq)
ctl |= B43_DMA32_DCTL_IRQ;
ctl |= (addrext << B43_DMA32_DCTL_ADDREXT_SHIFT)
& B43_DMA32_DCTL_ADDREXT_MASK;
desc->dma32.control = cpu_to_le32(ctl);
desc->dma32.address = cpu_to_le32(addr);
}
static void op32_poke_tx(struct b43_dmaring *ring, int slot)
{
b43_dma_write(ring, B43_DMA32_TXINDEX,
(u32) (slot * sizeof(struct b43_dmadesc32)));
}
static void op32_tx_suspend(struct b43_dmaring *ring)
{
b43_dma_write(ring, B43_DMA32_TXCTL, b43_dma_read(ring, B43_DMA32_TXCTL)
| B43_DMA32_TXSUSPEND);
}
static void op32_tx_resume(struct b43_dmaring *ring)
{
b43_dma_write(ring, B43_DMA32_TXCTL, b43_dma_read(ring, B43_DMA32_TXCTL)
& ~B43_DMA32_TXSUSPEND);
}
static int op32_get_current_rxslot(struct b43_dmaring *ring)
{
u32 val;
val = b43_dma_read(ring, B43_DMA32_RXSTATUS);
val &= B43_DMA32_RXDPTR;
return (val / sizeof(struct b43_dmadesc32));
}
static void op32_set_current_rxslot(struct b43_dmaring *ring, int slot)
{
b43_dma_write(ring, B43_DMA32_RXINDEX,
(u32) (slot * sizeof(struct b43_dmadesc32)));
}
static const struct b43_dma_ops dma32_ops = {
.idx2desc = op32_idx2desc,
.fill_descriptor = op32_fill_descriptor,
.poke_tx = op32_poke_tx,
.tx_suspend = op32_tx_suspend,
.tx_resume = op32_tx_resume,
.get_current_rxslot = op32_get_current_rxslot,
.set_current_rxslot = op32_set_current_rxslot,
};
/* 64bit DMA ops. */
static
struct b43_dmadesc_generic *op64_idx2desc(struct b43_dmaring *ring,
int slot,
struct b43_dmadesc_meta **meta)
{
struct b43_dmadesc64 *desc;
*meta = &(ring->meta[slot]);
desc = ring->descbase;
desc = &(desc[slot]);
return (struct b43_dmadesc_generic *)desc;
}
static void op64_fill_descriptor(struct b43_dmaring *ring,
struct b43_dmadesc_generic *desc,
dma_addr_t dmaaddr, u16 bufsize,
int start, int end, int irq)
{
struct b43_dmadesc64 *descbase = ring->descbase;
int slot;
u32 ctl0 = 0, ctl1 = 0;
u32 addrlo, addrhi;
u32 addrext;
slot = (int)(&(desc->dma64) - descbase);
B43_WARN_ON(!(slot >= 0 && slot < ring->nr_slots));
addrlo = (u32) (dmaaddr & 0xFFFFFFFF);
addrhi = (((u64) dmaaddr >> 32) & ~SSB_DMA_TRANSLATION_MASK);
addrext = (((u64) dmaaddr >> 32) & SSB_DMA_TRANSLATION_MASK)
>> SSB_DMA_TRANSLATION_SHIFT;
addrhi |= (ssb_dma_translation(ring->dev->dev) << 1);
if (slot == ring->nr_slots - 1)
ctl0 |= B43_DMA64_DCTL0_DTABLEEND;
if (start)
ctl0 |= B43_DMA64_DCTL0_FRAMESTART;
if (end)
ctl0 |= B43_DMA64_DCTL0_FRAMEEND;
if (irq)
ctl0 |= B43_DMA64_DCTL0_IRQ;
ctl1 |= bufsize & B43_DMA64_DCTL1_BYTECNT;
ctl1 |= (addrext << B43_DMA64_DCTL1_ADDREXT_SHIFT)
& B43_DMA64_DCTL1_ADDREXT_MASK;
desc->dma64.control0 = cpu_to_le32(ctl0);
desc->dma64.control1 = cpu_to_le32(ctl1);
desc->dma64.address_low = cpu_to_le32(addrlo);
desc->dma64.address_high = cpu_to_le32(addrhi);
}
static void op64_poke_tx(struct b43_dmaring *ring, int slot)
{
b43_dma_write(ring, B43_DMA64_TXINDEX,
(u32) (slot * sizeof(struct b43_dmadesc64)));
}
static void op64_tx_suspend(struct b43_dmaring *ring)
{
b43_dma_write(ring, B43_DMA64_TXCTL, b43_dma_read(ring, B43_DMA64_TXCTL)
| B43_DMA64_TXSUSPEND);
}
static void op64_tx_resume(struct b43_dmaring *ring)
{
b43_dma_write(ring, B43_DMA64_TXCTL, b43_dma_read(ring, B43_DMA64_TXCTL)
& ~B43_DMA64_TXSUSPEND);
}
static int op64_get_current_rxslot(struct b43_dmaring *ring)
{
u32 val;
val = b43_dma_read(ring, B43_DMA64_RXSTATUS);
val &= B43_DMA64_RXSTATDPTR;
return (val / sizeof(struct b43_dmadesc64));
}
static void op64_set_current_rxslot(struct b43_dmaring *ring, int slot)
{
b43_dma_write(ring, B43_DMA64_RXINDEX,
(u32) (slot * sizeof(struct b43_dmadesc64)));
}
static const struct b43_dma_ops dma64_ops = {
.idx2desc = op64_idx2desc,
.fill_descriptor = op64_fill_descriptor,
.poke_tx = op64_poke_tx,
.tx_suspend = op64_tx_suspend,
.tx_resume = op64_tx_resume,
.get_current_rxslot = op64_get_current_rxslot,
.set_current_rxslot = op64_set_current_rxslot,
};
static inline int free_slots(struct b43_dmaring *ring)
{
return (ring->nr_slots - ring->used_slots);
}
static inline int next_slot(struct b43_dmaring *ring, int slot)
{
B43_WARN_ON(!(slot >= -1 && slot <= ring->nr_slots - 1));
if (slot == ring->nr_slots - 1)
return 0;
return slot + 1;
}
static inline int prev_slot(struct b43_dmaring *ring, int slot)
{
B43_WARN_ON(!(slot >= 0 && slot <= ring->nr_slots - 1));
if (slot == 0)
return ring->nr_slots - 1;
return slot - 1;
}
#ifdef CONFIG_B43_DEBUG
static void update_max_used_slots(struct b43_dmaring *ring,
int current_used_slots)
{
if (current_used_slots <= ring->max_used_slots)
return;
ring->max_used_slots = current_used_slots;
if (b43_debug(ring->dev, B43_DBG_DMAVERBOSE)) {
b43dbg(ring->dev->wl,
"max_used_slots increased to %d on %s ring %d\n",
ring->max_used_slots,
ring->tx ? "TX" : "RX", ring->index);
}
}
#else
static inline
void update_max_used_slots(struct b43_dmaring *ring, int current_used_slots)
{
}
#endif /* DEBUG */
/* Request a slot for usage. */
static inline int request_slot(struct b43_dmaring *ring)
{
int slot;
B43_WARN_ON(!ring->tx);
B43_WARN_ON(ring->stopped);
B43_WARN_ON(free_slots(ring) == 0);
slot = next_slot(ring, ring->current_slot);
ring->current_slot = slot;
ring->used_slots++;
update_max_used_slots(ring, ring->used_slots);
return slot;
}
static u16 b43_dmacontroller_base(enum b43_dmatype type, int controller_idx)
{
static const u16 map64[] = {
B43_MMIO_DMA64_BASE0,
B43_MMIO_DMA64_BASE1,
B43_MMIO_DMA64_BASE2,
B43_MMIO_DMA64_BASE3,
B43_MMIO_DMA64_BASE4,
B43_MMIO_DMA64_BASE5,
};
static const u16 map32[] = {
B43_MMIO_DMA32_BASE0,
B43_MMIO_DMA32_BASE1,
B43_MMIO_DMA32_BASE2,
B43_MMIO_DMA32_BASE3,
B43_MMIO_DMA32_BASE4,
B43_MMIO_DMA32_BASE5,
};
if (type == B43_DMA_64BIT) {
B43_WARN_ON(!(controller_idx >= 0 &&
controller_idx < ARRAY_SIZE(map64)));
return map64[controller_idx];
}
B43_WARN_ON(!(controller_idx >= 0 &&
controller_idx < ARRAY_SIZE(map32)));
return map32[controller_idx];
}
static inline
dma_addr_t map_descbuffer(struct b43_dmaring *ring,
unsigned char *buf, size_t len, int tx)
{
dma_addr_t dmaaddr;
if (tx) {
dmaaddr = dma_map_single(ring->dev->dev->dma_dev,
buf, len, DMA_TO_DEVICE);
} else {
dmaaddr = dma_map_single(ring->dev->dev->dma_dev,
buf, len, DMA_FROM_DEVICE);
}
return dmaaddr;
}
static inline
void unmap_descbuffer(struct b43_dmaring *ring,
dma_addr_t addr, size_t len, int tx)
{
if (tx) {
dma_unmap_single(ring->dev->dev->dma_dev,
addr, len, DMA_TO_DEVICE);
} else {
dma_unmap_single(ring->dev->dev->dma_dev,
addr, len, DMA_FROM_DEVICE);
}
}
static inline
void sync_descbuffer_for_cpu(struct b43_dmaring *ring,
dma_addr_t addr, size_t len)
{
B43_WARN_ON(ring->tx);
dma_sync_single_for_cpu(ring->dev->dev->dma_dev,
addr, len, DMA_FROM_DEVICE);
}
static inline
void sync_descbuffer_for_device(struct b43_dmaring *ring,
dma_addr_t addr, size_t len)
{
B43_WARN_ON(ring->tx);
dma_sync_single_for_device(ring->dev->dev->dma_dev,
addr, len, DMA_FROM_DEVICE);
}
static inline
void free_descriptor_buffer(struct b43_dmaring *ring,
struct b43_dmadesc_meta *meta)
{
if (meta->skb) {
dev_kfree_skb_any(meta->skb);
meta->skb = NULL;
}
}
static int alloc_ringmemory(struct b43_dmaring *ring)
{
gfp_t flags = GFP_KERNEL;
/* The specs call for 4K buffers for 30- and 32-bit DMA with 4K
* alignment and 8K buffers for 64-bit DMA with 8K alignment. Testing
* has shown that 4K is sufficient for the latter as long as the buffer
* does not cross an 8K boundary.
*
* For unknown reasons - possibly a hardware error - the BCM4311 rev
* 02, which uses 64-bit DMA, needs the ring buffer in very low memory,
* which accounts for the GFP_DMA flag below.
*
* The flags here must match the flags in free_ringmemory below!
*/
if (ring->type == B43_DMA_64BIT)
flags |= GFP_DMA;
ring->descbase = dma_alloc_coherent(ring->dev->dev->dma_dev,
B43_DMA_RINGMEMSIZE,
&(ring->dmabase), flags);
if (!ring->descbase) {
b43err(ring->dev->wl, "DMA ringmemory allocation failed\n");
return -ENOMEM;
}
memset(ring->descbase, 0, B43_DMA_RINGMEMSIZE);
return 0;
}
static void free_ringmemory(struct b43_dmaring *ring)
{
dma_free_coherent(ring->dev->dev->dma_dev, B43_DMA_RINGMEMSIZE,
ring->descbase, ring->dmabase);
}
/* Reset the RX DMA channel */
static int b43_dmacontroller_rx_reset(struct b43_wldev *dev, u16 mmio_base,
enum b43_dmatype type)
{
int i;
u32 value;
u16 offset;
might_sleep();
offset = (type == B43_DMA_64BIT) ? B43_DMA64_RXCTL : B43_DMA32_RXCTL;
b43_write32(dev, mmio_base + offset, 0);
for (i = 0; i < 10; i++) {
offset = (type == B43_DMA_64BIT) ? B43_DMA64_RXSTATUS :
B43_DMA32_RXSTATUS;
value = b43_read32(dev, mmio_base + offset);
if (type == B43_DMA_64BIT) {
value &= B43_DMA64_RXSTAT;
if (value == B43_DMA64_RXSTAT_DISABLED) {
i = -1;
break;
}
} else {
value &= B43_DMA32_RXSTATE;
if (value == B43_DMA32_RXSTAT_DISABLED) {
i = -1;
break;
}
}
msleep(1);
}
if (i != -1) {
b43err(dev->wl, "DMA RX reset timed out\n");
return -ENODEV;
}
return 0;
}
/* Reset the TX DMA channel */
static int b43_dmacontroller_tx_reset(struct b43_wldev *dev, u16 mmio_base,
enum b43_dmatype type)
{
int i;
u32 value;
u16 offset;
might_sleep();
for (i = 0; i < 10; i++) {
offset = (type == B43_DMA_64BIT) ? B43_DMA64_TXSTATUS :
B43_DMA32_TXSTATUS;
value = b43_read32(dev, mmio_base + offset);
if (type == B43_DMA_64BIT) {
value &= B43_DMA64_TXSTAT;
if (value == B43_DMA64_TXSTAT_DISABLED ||
value == B43_DMA64_TXSTAT_IDLEWAIT ||
value == B43_DMA64_TXSTAT_STOPPED)
break;
} else {
value &= B43_DMA32_TXSTATE;
if (value == B43_DMA32_TXSTAT_DISABLED ||
value == B43_DMA32_TXSTAT_IDLEWAIT ||
value == B43_DMA32_TXSTAT_STOPPED)
break;
}
msleep(1);
}
offset = (type == B43_DMA_64BIT) ? B43_DMA64_TXCTL : B43_DMA32_TXCTL;
b43_write32(dev, mmio_base + offset, 0);
for (i = 0; i < 10; i++) {
offset = (type == B43_DMA_64BIT) ? B43_DMA64_TXSTATUS :
B43_DMA32_TXSTATUS;
value = b43_read32(dev, mmio_base + offset);
if (type == B43_DMA_64BIT) {
value &= B43_DMA64_TXSTAT;
if (value == B43_DMA64_TXSTAT_DISABLED) {
i = -1;
break;
}
} else {
value &= B43_DMA32_TXSTATE;
if (value == B43_DMA32_TXSTAT_DISABLED) {
i = -1;
break;
}
}
msleep(1);
}
if (i != -1) {
b43err(dev->wl, "DMA TX reset timed out\n");
return -ENODEV;
}
/* ensure the reset is completed. */
msleep(1);
return 0;
}
/* Check if a DMA mapping address is invalid. */
static bool b43_dma_mapping_error(struct b43_dmaring *ring,
dma_addr_t addr,
size_t buffersize, bool dma_to_device)
{
if (unlikely(dma_mapping_error(ring->dev->dev->dma_dev, addr)))
return 1;
switch (ring->type) {
case B43_DMA_30BIT:
if ((u64)addr + buffersize > (1ULL << 30))
goto address_error;
break;
case B43_DMA_32BIT:
if ((u64)addr + buffersize > (1ULL << 32))
goto address_error;
break;
case B43_DMA_64BIT:
/* Currently we can't have addresses beyond
* 64bit in the kernel. */
break;
}
/* The address is OK. */
return 0;
address_error:
/* We can't support this address. Unmap it again. */
unmap_descbuffer(ring, addr, buffersize, dma_to_device);
return 1;
}
static bool b43_rx_buffer_is_poisoned(struct b43_dmaring *ring, struct sk_buff *skb)
{
unsigned char *f = skb->data + ring->frameoffset;
return ((f[0] & f[1] & f[2] & f[3] & f[4] & f[5] & f[6] & f[7]) == 0xFF);
}
static void b43_poison_rx_buffer(struct b43_dmaring *ring, struct sk_buff *skb)
{
struct b43_rxhdr_fw4 *rxhdr;
unsigned char *frame;
/* This poisons the RX buffer to detect DMA failures. */
rxhdr = (struct b43_rxhdr_fw4 *)(skb->data);
rxhdr->frame_len = 0;
B43_WARN_ON(ring->rx_buffersize < ring->frameoffset + sizeof(struct b43_plcp_hdr6) + 2);
frame = skb->data + ring->frameoffset;
memset(frame, 0xFF, sizeof(struct b43_plcp_hdr6) + 2 /* padding */);
}
static int setup_rx_descbuffer(struct b43_dmaring *ring,
struct b43_dmadesc_generic *desc,
struct b43_dmadesc_meta *meta, gfp_t gfp_flags)
{
dma_addr_t dmaaddr;
struct sk_buff *skb;
B43_WARN_ON(ring->tx);
skb = __dev_alloc_skb(ring->rx_buffersize, gfp_flags);
if (unlikely(!skb))
return -ENOMEM;
b43_poison_rx_buffer(ring, skb);
dmaaddr = map_descbuffer(ring, skb->data, ring->rx_buffersize, 0);
if (b43_dma_mapping_error(ring, dmaaddr, ring->rx_buffersize, 0)) {
/* ugh. try to realloc in zone_dma */
gfp_flags |= GFP_DMA;
dev_kfree_skb_any(skb);
skb = __dev_alloc_skb(ring->rx_buffersize, gfp_flags);
if (unlikely(!skb))
return -ENOMEM;
b43_poison_rx_buffer(ring, skb);
dmaaddr = map_descbuffer(ring, skb->data,
ring->rx_buffersize, 0);
if (b43_dma_mapping_error(ring, dmaaddr, ring->rx_buffersize, 0)) {
b43err(ring->dev->wl, "RX DMA buffer allocation failed\n");
dev_kfree_skb_any(skb);
return -EIO;
}
}
meta->skb = skb;
meta->dmaaddr = dmaaddr;
ring->ops->fill_descriptor(ring, desc, dmaaddr,
ring->rx_buffersize, 0, 0, 0);
return 0;
}
/* Allocate the initial descbuffers.
* This is used for an RX ring only.
*/
static int alloc_initial_descbuffers(struct b43_dmaring *ring)
{
int i, err = -ENOMEM;
struct b43_dmadesc_generic *desc;
struct b43_dmadesc_meta *meta;
for (i = 0; i < ring->nr_slots; i++) {
desc = ring->ops->idx2desc(ring, i, &meta);
err = setup_rx_descbuffer(ring, desc, meta, GFP_KERNEL);
if (err) {
b43err(ring->dev->wl,
"Failed to allocate initial descbuffers\n");
goto err_unwind;
}
}
mb();
ring->used_slots = ring->nr_slots;
err = 0;
out:
return err;
err_unwind:
for (i--; i >= 0; i--) {
desc = ring->ops->idx2desc(ring, i, &meta);
unmap_descbuffer(ring, meta->dmaaddr, ring->rx_buffersize, 0);
dev_kfree_skb(meta->skb);
}
goto out;
}
/* Do initial setup of the DMA controller.
* Reset the controller, write the ring busaddress
* and switch the "enable" bit on.
*/
static int dmacontroller_setup(struct b43_dmaring *ring)
{
int err = 0;
u32 value;
u32 addrext;
u32 trans = ssb_dma_translation(ring->dev->dev);
if (ring->tx) {
if (ring->type == B43_DMA_64BIT) {
u64 ringbase = (u64) (ring->dmabase);
addrext = ((ringbase >> 32) & SSB_DMA_TRANSLATION_MASK)
>> SSB_DMA_TRANSLATION_SHIFT;
value = B43_DMA64_TXENABLE;
value |= (addrext << B43_DMA64_TXADDREXT_SHIFT)
& B43_DMA64_TXADDREXT_MASK;
b43_dma_write(ring, B43_DMA64_TXCTL, value);
b43_dma_write(ring, B43_DMA64_TXRINGLO,
(ringbase & 0xFFFFFFFF));
b43_dma_write(ring, B43_DMA64_TXRINGHI,
((ringbase >> 32) &
~SSB_DMA_TRANSLATION_MASK)
| (trans << 1));
} else {
u32 ringbase = (u32) (ring->dmabase);
addrext = (ringbase & SSB_DMA_TRANSLATION_MASK)
>> SSB_DMA_TRANSLATION_SHIFT;
value = B43_DMA32_TXENABLE;
value |= (addrext << B43_DMA32_TXADDREXT_SHIFT)
& B43_DMA32_TXADDREXT_MASK;
b43_dma_write(ring, B43_DMA32_TXCTL, value);
b43_dma_write(ring, B43_DMA32_TXRING,
(ringbase & ~SSB_DMA_TRANSLATION_MASK)
| trans);
}
} else {
err = alloc_initial_descbuffers(ring);
if (err)
goto out;
if (ring->type == B43_DMA_64BIT) {
u64 ringbase = (u64) (ring->dmabase);
addrext = ((ringbase >> 32) & SSB_DMA_TRANSLATION_MASK)
>> SSB_DMA_TRANSLATION_SHIFT;
value = (ring->frameoffset << B43_DMA64_RXFROFF_SHIFT);
value |= B43_DMA64_RXENABLE;
value |= (addrext << B43_DMA64_RXADDREXT_SHIFT)
& B43_DMA64_RXADDREXT_MASK;
b43_dma_write(ring, B43_DMA64_RXCTL, value);
b43_dma_write(ring, B43_DMA64_RXRINGLO,
(ringbase & 0xFFFFFFFF));
b43_dma_write(ring, B43_DMA64_RXRINGHI,
((ringbase >> 32) &
~SSB_DMA_TRANSLATION_MASK)
| (trans << 1));
b43_dma_write(ring, B43_DMA64_RXINDEX, ring->nr_slots *
sizeof(struct b43_dmadesc64));
} else {
u32 ringbase = (u32) (ring->dmabase);
addrext = (ringbase & SSB_DMA_TRANSLATION_MASK)
>> SSB_DMA_TRANSLATION_SHIFT;
value = (ring->frameoffset << B43_DMA32_RXFROFF_SHIFT);
value |= B43_DMA32_RXENABLE;
value |= (addrext << B43_DMA32_RXADDREXT_SHIFT)
& B43_DMA32_RXADDREXT_MASK;
b43_dma_write(ring, B43_DMA32_RXCTL, value);
b43_dma_write(ring, B43_DMA32_RXRING,
(ringbase & ~SSB_DMA_TRANSLATION_MASK)
| trans);
b43_dma_write(ring, B43_DMA32_RXINDEX, ring->nr_slots *
sizeof(struct b43_dmadesc32));
}
}
out:
return err;
}
/* Shutdown the DMA controller. */
static void dmacontroller_cleanup(struct b43_dmaring *ring)
{
if (ring->tx) {
b43_dmacontroller_tx_reset(ring->dev, ring->mmio_base,
ring->type);
if (ring->type == B43_DMA_64BIT) {
b43_dma_write(ring, B43_DMA64_TXRINGLO, 0);
b43_dma_write(ring, B43_DMA64_TXRINGHI, 0);
} else
b43_dma_write(ring, B43_DMA32_TXRING, 0);
} else {
b43_dmacontroller_rx_reset(ring->dev, ring->mmio_base,
ring->type);
if (ring->type == B43_DMA_64BIT) {
b43_dma_write(ring, B43_DMA64_RXRINGLO, 0);
b43_dma_write(ring, B43_DMA64_RXRINGHI, 0);
} else
b43_dma_write(ring, B43_DMA32_RXRING, 0);
}
}
static void free_all_descbuffers(struct b43_dmaring *ring)
{
struct b43_dmadesc_generic *desc;
struct b43_dmadesc_meta *meta;
int i;
if (!ring->used_slots)
return;
for (i = 0; i < ring->nr_slots; i++) {
desc = ring->ops->idx2desc(ring, i, &meta);
if (!meta->skb || b43_dma_ptr_is_poisoned(meta->skb)) {
B43_WARN_ON(!ring->tx);
continue;
}
if (ring->tx) {
unmap_descbuffer(ring, meta->dmaaddr,
meta->skb->len, 1);
} else {
unmap_descbuffer(ring, meta->dmaaddr,
ring->rx_buffersize, 0);
}
free_descriptor_buffer(ring, meta);
}
}
static u64 supported_dma_mask(struct b43_wldev *dev)
{
u32 tmp;
u16 mmio_base;
tmp = b43_read32(dev, SSB_TMSHIGH);
if (tmp & SSB_TMSHIGH_DMA64)
return DMA_BIT_MASK(64);
mmio_base = b43_dmacontroller_base(0, 0);
b43_write32(dev, mmio_base + B43_DMA32_TXCTL, B43_DMA32_TXADDREXT_MASK);
tmp = b43_read32(dev, mmio_base + B43_DMA32_TXCTL);
if (tmp & B43_DMA32_TXADDREXT_MASK)
return DMA_BIT_MASK(32);
return DMA_BIT_MASK(30);
}
static enum b43_dmatype dma_mask_to_engine_type(u64 dmamask)
{
if (dmamask == DMA_BIT_MASK(30))
return B43_DMA_30BIT;
if (dmamask == DMA_BIT_MASK(32))
return B43_DMA_32BIT;
if (dmamask == DMA_BIT_MASK(64))
return B43_DMA_64BIT;
B43_WARN_ON(1);
return B43_DMA_30BIT;
}
/* Main initialization function. */
static
struct b43_dmaring *b43_setup_dmaring(struct b43_wldev *dev,
int controller_index,
int for_tx,
enum b43_dmatype type)
{
struct b43_dmaring *ring;
int i, err;
dma_addr_t dma_test;
ring = kzalloc(sizeof(*ring), GFP_KERNEL);
if (!ring)
goto out;
ring->nr_slots = B43_RXRING_SLOTS;
if (for_tx)
ring->nr_slots = B43_TXRING_SLOTS;
ring->meta = kcalloc(ring->nr_slots, sizeof(struct b43_dmadesc_meta),
GFP_KERNEL);
if (!ring->meta)
goto err_kfree_ring;
for (i = 0; i < ring->nr_slots; i++)
ring->meta->skb = B43_DMA_PTR_POISON;
ring->type = type;
ring->dev = dev;
ring->mmio_base = b43_dmacontroller_base(type, controller_index);
ring->index = controller_index;
if (type == B43_DMA_64BIT)
ring->ops = &dma64_ops;
else
ring->ops = &dma32_ops;
if (for_tx) {
ring->tx = 1;
ring->current_slot = -1;
} else {
if (ring->index == 0) {
ring->rx_buffersize = B43_DMA0_RX_BUFFERSIZE;
ring->frameoffset = B43_DMA0_RX_FRAMEOFFSET;
} else
B43_WARN_ON(1);
}
#ifdef CONFIG_B43_DEBUG
ring->last_injected_overflow = jiffies;
#endif
if (for_tx) {
/* Assumption: B43_TXRING_SLOTS can be divided by TX_SLOTS_PER_FRAME */
BUILD_BUG_ON(B43_TXRING_SLOTS % TX_SLOTS_PER_FRAME != 0);
ring->txhdr_cache = kcalloc(ring->nr_slots / TX_SLOTS_PER_FRAME,
b43_txhdr_size(dev),
GFP_KERNEL);
if (!ring->txhdr_cache)
goto err_kfree_meta;
/* test for ability to dma to txhdr_cache */
dma_test = dma_map_single(dev->dev->dma_dev,
ring->txhdr_cache,
b43_txhdr_size(dev),
DMA_TO_DEVICE);
if (b43_dma_mapping_error(ring, dma_test,
b43_txhdr_size(dev), 1)) {
/* ugh realloc */
kfree(ring->txhdr_cache);
ring->txhdr_cache = kcalloc(ring->nr_slots / TX_SLOTS_PER_FRAME,
b43_txhdr_size(dev),
GFP_KERNEL | GFP_DMA);
if (!ring->txhdr_cache)
goto err_kfree_meta;
dma_test = dma_map_single(dev->dev->dma_dev,
ring->txhdr_cache,
b43_txhdr_size(dev),
DMA_TO_DEVICE);
if (b43_dma_mapping_error(ring, dma_test,
b43_txhdr_size(dev), 1)) {
b43err(dev->wl,
"TXHDR DMA allocation failed\n");
goto err_kfree_txhdr_cache;
}
}
dma_unmap_single(dev->dev->dma_dev,
dma_test, b43_txhdr_size(dev),
DMA_TO_DEVICE);
}
err = alloc_ringmemory(ring);
if (err)
goto err_kfree_txhdr_cache;
err = dmacontroller_setup(ring);
if (err)
goto err_free_ringmemory;
out:
return ring;
err_free_ringmemory:
free_ringmemory(ring);
err_kfree_txhdr_cache:
kfree(ring->txhdr_cache);
err_kfree_meta:
kfree(ring->meta);
err_kfree_ring:
kfree(ring);
ring = NULL;
goto out;
}
#define divide(a, b) ({ \
typeof(a) __a = a; \
do_div(__a, b); \
__a; \
})
#define modulo(a, b) ({ \
typeof(a) __a = a; \
do_div(__a, b); \
})
/* Main cleanup function. */
static void b43_destroy_dmaring(struct b43_dmaring *ring,
const char *ringname)
{
if (!ring)
return;
#ifdef CONFIG_B43_DEBUG
{
/* Print some statistics. */
u64 failed_packets = ring->nr_failed_tx_packets;
u64 succeed_packets = ring->nr_succeed_tx_packets;
u64 nr_packets = failed_packets + succeed_packets;
u64 permille_failed = 0, average_tries = 0;
if (nr_packets)
permille_failed = divide(failed_packets * 1000, nr_packets);
if (nr_packets)
average_tries = divide(ring->nr_total_packet_tries * 100, nr_packets);
b43dbg(ring->dev->wl, "DMA-%u %s: "
"Used slots %d/%d, Failed frames %llu/%llu = %llu.%01llu%%, "
"Average tries %llu.%02llu\n",
(unsigned int)(ring->type), ringname,
ring->max_used_slots,
ring->nr_slots,
(unsigned long long)failed_packets,
(unsigned long long)nr_packets,
(unsigned long long)divide(permille_failed, 10),
(unsigned long long)modulo(permille_failed, 10),
(unsigned long long)divide(average_tries, 100),
(unsigned long long)modulo(average_tries, 100));
}
#endif /* DEBUG */
/* Device IRQs are disabled prior entering this function,
* so no need to take care of concurrency with rx handler stuff.
*/
dmacontroller_cleanup(ring);
free_all_descbuffers(ring);
free_ringmemory(ring);
kfree(ring->txhdr_cache);
kfree(ring->meta);
kfree(ring);
}
#define destroy_ring(dma, ring) do { \
b43_destroy_dmaring((dma)->ring, __stringify(ring)); \
(dma)->ring = NULL; \
} while (0)
void b43_dma_free(struct b43_wldev *dev)
{
struct b43_dma *dma;
if (b43_using_pio_transfers(dev))
return;
dma = &dev->dma;
destroy_ring(dma, rx_ring);
destroy_ring(dma, tx_ring_AC_BK);
destroy_ring(dma, tx_ring_AC_BE);
destroy_ring(dma, tx_ring_AC_VI);
destroy_ring(dma, tx_ring_AC_VO);
destroy_ring(dma, tx_ring_mcast);
}
static int b43_dma_set_mask(struct b43_wldev *dev, u64 mask)
{
u64 orig_mask = mask;
bool fallback = 0;
int err;
/* Try to set the DMA mask. If it fails, try falling back to a
* lower mask, as we can always also support a lower one. */
while (1) {
err = dma_set_mask(dev->dev->dma_dev, mask);
if (!err) {
err = dma_set_coherent_mask(dev->dev->dma_dev, mask);
if (!err)
break;
}
if (mask == DMA_BIT_MASK(64)) {
mask = DMA_BIT_MASK(32);
fallback = 1;
continue;
}
if (mask == DMA_BIT_MASK(32)) {
mask = DMA_BIT_MASK(30);
fallback = 1;
continue;
}
b43err(dev->wl, "The machine/kernel does not support "
"the required %u-bit DMA mask\n",
(unsigned int)dma_mask_to_engine_type(orig_mask));
return -EOPNOTSUPP;
}
if (fallback) {
b43info(dev->wl, "DMA mask fallback from %u-bit to %u-bit\n",
(unsigned int)dma_mask_to_engine_type(orig_mask),
(unsigned int)dma_mask_to_engine_type(mask));
}
return 0;
}
int b43_dma_init(struct b43_wldev *dev)
{
struct b43_dma *dma = &dev->dma;
int err;
u64 dmamask;
enum b43_dmatype type;
dmamask = supported_dma_mask(dev);
type = dma_mask_to_engine_type(dmamask);
err = b43_dma_set_mask(dev, dmamask);
if (err)
return err;
err = -ENOMEM;
/* setup TX DMA channels. */
dma->tx_ring_AC_BK = b43_setup_dmaring(dev, 0, 1, type);
if (!dma->tx_ring_AC_BK)
goto out;
dma->tx_ring_AC_BE = b43_setup_dmaring(dev, 1, 1, type);
if (!dma->tx_ring_AC_BE)
goto err_destroy_bk;
dma->tx_ring_AC_VI = b43_setup_dmaring(dev, 2, 1, type);
if (!dma->tx_ring_AC_VI)
goto err_destroy_be;
dma->tx_ring_AC_VO = b43_setup_dmaring(dev, 3, 1, type);
if (!dma->tx_ring_AC_VO)
goto err_destroy_vi;
dma->tx_ring_mcast = b43_setup_dmaring(dev, 4, 1, type);
if (!dma->tx_ring_mcast)
goto err_destroy_vo;
/* setup RX DMA channel. */
dma->rx_ring = b43_setup_dmaring(dev, 0, 0, type);
if (!dma->rx_ring)
goto err_destroy_mcast;
/* No support for the TX status DMA ring. */
B43_WARN_ON(dev->dev->id.revision < 5);
b43dbg(dev->wl, "%u-bit DMA initialized\n",
(unsigned int)type);
err = 0;
out:
return err;
err_destroy_mcast:
destroy_ring(dma, tx_ring_mcast);
err_destroy_vo:
destroy_ring(dma, tx_ring_AC_VO);
err_destroy_vi:
destroy_ring(dma, tx_ring_AC_VI);
err_destroy_be:
destroy_ring(dma, tx_ring_AC_BE);
err_destroy_bk:
destroy_ring(dma, tx_ring_AC_BK);
return err;
}
/* Generate a cookie for the TX header. */
static u16 generate_cookie(struct b43_dmaring *ring, int slot)
{
u16 cookie;
/* Use the upper 4 bits of the cookie as
* DMA controller ID and store the slot number
* in the lower 12 bits.
* Note that the cookie must never be 0, as this
* is a special value used in RX path.
* It can also not be 0xFFFF because that is special
* for multicast frames.
*/
cookie = (((u16)ring->index + 1) << 12);
B43_WARN_ON(slot & ~0x0FFF);
cookie |= (u16)slot;
return cookie;
}
/* Inspect a cookie and find out to which controller/slot it belongs. */
static
struct b43_dmaring *parse_cookie(struct b43_wldev *dev, u16 cookie, int *slot)
{
struct b43_dma *dma = &dev->dma;
struct b43_dmaring *ring = NULL;
switch (cookie & 0xF000) {
case 0x1000:
ring = dma->tx_ring_AC_BK;
break;
case 0x2000:
ring = dma->tx_ring_AC_BE;
break;
case 0x3000:
ring = dma->tx_ring_AC_VI;
break;
case 0x4000:
ring = dma->tx_ring_AC_VO;
break;
case 0x5000:
ring = dma->tx_ring_mcast;
break;
}
*slot = (cookie & 0x0FFF);
if (unlikely(!ring || *slot < 0 || *slot >= ring->nr_slots)) {
b43dbg(dev->wl, "TX-status contains "
"invalid cookie: 0x%04X\n", cookie);
return NULL;
}
return ring;
}
static int dma_tx_fragment(struct b43_dmaring *ring,
struct sk_buff *skb)
{
const struct b43_dma_ops *ops = ring->ops;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct b43_private_tx_info *priv_info = b43_get_priv_tx_info(info);
u8 *header;
int slot, old_top_slot, old_used_slots;
int err;
struct b43_dmadesc_generic *desc;
struct b43_dmadesc_meta *meta;
struct b43_dmadesc_meta *meta_hdr;
u16 cookie;
size_t hdrsize = b43_txhdr_size(ring->dev);
/* Important note: If the number of used DMA slots per TX frame
* is changed here, the TX_SLOTS_PER_FRAME definition at the top of
* the file has to be updated, too!
*/
old_top_slot = ring->current_slot;
old_used_slots = ring->used_slots;
/* Get a slot for the header. */
slot = request_slot(ring);
desc = ops->idx2desc(ring, slot, &meta_hdr);
memset(meta_hdr, 0, sizeof(*meta_hdr));
header = &(ring->txhdr_cache[(slot / TX_SLOTS_PER_FRAME) * hdrsize]);
cookie = generate_cookie(ring, slot);
err = b43_generate_txhdr(ring->dev, header,
skb, info, cookie);
if (unlikely(err)) {
ring->current_slot = old_top_slot;
ring->used_slots = old_used_slots;
return err;
}
meta_hdr->dmaaddr = map_descbuffer(ring, (unsigned char *)header,
hdrsize, 1);
if (b43_dma_mapping_error(ring, meta_hdr->dmaaddr, hdrsize, 1)) {
ring->current_slot = old_top_slot;
ring->used_slots = old_used_slots;
return -EIO;
}
ops->fill_descriptor(ring, desc, meta_hdr->dmaaddr,
hdrsize, 1, 0, 0);
/* Get a slot for the payload. */
slot = request_slot(ring);
desc = ops->idx2desc(ring, slot, &meta);
memset(meta, 0, sizeof(*meta));
meta->skb = skb;
meta->is_last_fragment = 1;
priv_info->bouncebuffer = NULL;
meta->dmaaddr = map_descbuffer(ring, skb->data, skb->len, 1);
/* create a bounce buffer in zone_dma on mapping failure. */
if (b43_dma_mapping_error(ring, meta->dmaaddr, skb->len, 1)) {
priv_info->bouncebuffer = kmemdup(skb->data, skb->len,
GFP_ATOMIC | GFP_DMA);
if (!priv_info->bouncebuffer) {
ring->current_slot = old_top_slot;
ring->used_slots = old_used_slots;
err = -ENOMEM;
goto out_unmap_hdr;
}
meta->dmaaddr = map_descbuffer(ring, priv_info->bouncebuffer, skb->len, 1);
if (b43_dma_mapping_error(ring, meta->dmaaddr, skb->len, 1)) {
kfree(priv_info->bouncebuffer);
priv_info->bouncebuffer = NULL;
ring->current_slot = old_top_slot;
ring->used_slots = old_used_slots;
err = -EIO;
goto out_unmap_hdr;
}
}
ops->fill_descriptor(ring, desc, meta->dmaaddr, skb->len, 0, 1, 1);
if (info->flags & IEEE80211_TX_CTL_SEND_AFTER_DTIM) {
/* Tell the firmware about the cookie of the last
* mcast frame, so it can clear the more-data bit in it. */
b43_shm_write16(ring->dev, B43_SHM_SHARED,
B43_SHM_SH_MCASTCOOKIE, cookie);
}
/* Now transfer the whole frame. */
wmb();
ops->poke_tx(ring, next_slot(ring, slot));
return 0;
out_unmap_hdr:
unmap_descbuffer(ring, meta_hdr->dmaaddr,
hdrsize, 1);
return err;
}
static inline int should_inject_overflow(struct b43_dmaring *ring)
{
#ifdef CONFIG_B43_DEBUG
if (unlikely(b43_debug(ring->dev, B43_DBG_DMAOVERFLOW))) {
/* Check if we should inject another ringbuffer overflow
* to test handling of this situation in the stack. */
unsigned long next_overflow;
next_overflow = ring->last_injected_overflow + HZ;
if (time_after(jiffies, next_overflow)) {
ring->last_injected_overflow = jiffies;
b43dbg(ring->dev->wl,
"Injecting TX ring overflow on "
"DMA controller %d\n", ring->index);
return 1;
}
}
#endif /* CONFIG_B43_DEBUG */
return 0;
}
/* Static mapping of mac80211's queues (priorities) to b43 DMA rings. */
static struct b43_dmaring *select_ring_by_priority(struct b43_wldev *dev,
u8 queue_prio)
{
struct b43_dmaring *ring;
if (dev->qos_enabled) {
/* 0 = highest priority */
switch (queue_prio) {
default:
B43_WARN_ON(1);
/* fallthrough */
case 0:
ring = dev->dma.tx_ring_AC_VO;
break;
case 1:
ring = dev->dma.tx_ring_AC_VI;
break;
case 2:
ring = dev->dma.tx_ring_AC_BE;
break;
case 3:
ring = dev->dma.tx_ring_AC_BK;
break;
}
} else
ring = dev->dma.tx_ring_AC_BE;
return ring;
}
int b43_dma_tx(struct b43_wldev *dev, struct sk_buff *skb)
{
struct b43_dmaring *ring;
struct ieee80211_hdr *hdr;
int err = 0;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
hdr = (struct ieee80211_hdr *)skb->data;
if (info->flags & IEEE80211_TX_CTL_SEND_AFTER_DTIM) {
/* The multicast ring will be sent after the DTIM */
ring = dev->dma.tx_ring_mcast;
/* Set the more-data bit. Ucode will clear it on
* the last frame for us. */
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_MOREDATA);
} else {
/* Decide by priority where to put this frame. */
ring = select_ring_by_priority(
dev, skb_get_queue_mapping(skb));
}
B43_WARN_ON(!ring->tx);
if (unlikely(ring->stopped)) {
/* We get here only because of a bug in mac80211.
* Because of a race, one packet may be queued after
* the queue is stopped, thus we got called when we shouldn't.
* For now, just refuse the transmit. */
if (b43_debug(dev, B43_DBG_DMAVERBOSE))
b43err(dev->wl, "Packet after queue stopped\n");
err = -ENOSPC;
goto out;
}
if (unlikely(WARN_ON(free_slots(ring) < TX_SLOTS_PER_FRAME))) {
/* If we get here, we have a real error with the queue
* full, but queues not stopped. */
b43err(dev->wl, "DMA queue overflow\n");
err = -ENOSPC;
goto out;
}
/* Assign the queue number to the ring (if not already done before)
* so TX status handling can use it. The queue to ring mapping is
* static, so we don't need to store it per frame. */
ring->queue_prio = skb_get_queue_mapping(skb);
err = dma_tx_fragment(ring, skb);
if (unlikely(err == -ENOKEY)) {
/* Drop this packet, as we don't have the encryption key
* anymore and must not transmit it unencrypted. */
dev_kfree_skb_any(skb);
err = 0;
goto out;
}
if (unlikely(err)) {
b43err(dev->wl, "DMA tx mapping failure\n");
goto out;
}
if ((free_slots(ring) < TX_SLOTS_PER_FRAME) ||
should_inject_overflow(ring)) {
/* This TX ring is full. */
ieee80211_stop_queue(dev->wl->hw, skb_get_queue_mapping(skb));
ring->stopped = 1;
if (b43_debug(dev, B43_DBG_DMAVERBOSE)) {
b43dbg(dev->wl, "Stopped TX ring %d\n", ring->index);
}
}
out:
return err;
}
void b43_dma_handle_txstatus(struct b43_wldev *dev,
const struct b43_txstatus *status)
{
const struct b43_dma_ops *ops;
struct b43_dmaring *ring;
struct b43_dmadesc_generic *desc;
struct b43_dmadesc_meta *meta;
int slot, firstused;
bool frame_succeed;
ring = parse_cookie(dev, status->cookie, &slot);
if (unlikely(!ring))
return;
B43_WARN_ON(!ring->tx);
/* Sanity check: TX packets are processed in-order on one ring.
* Check if the slot deduced from the cookie really is the first
* used slot. */
firstused = ring->current_slot - ring->used_slots + 1;
if (firstused < 0)
firstused = ring->nr_slots + firstused;
if (unlikely(slot != firstused)) {
/* This possibly is a firmware bug and will result in
* malfunction, memory leaks and/or stall of DMA functionality. */
b43dbg(dev->wl, "Out of order TX status report on DMA ring %d. "
"Expected %d, but got %d\n",
ring->index, firstused, slot);
return;
}
ops = ring->ops;
while (1) {
B43_WARN_ON(slot < 0 || slot >= ring->nr_slots);
desc = ops->idx2desc(ring, slot, &meta);
if (b43_dma_ptr_is_poisoned(meta->skb)) {
b43dbg(dev->wl, "Poisoned TX slot %d (first=%d) "
"on ring %d\n",
slot, firstused, ring->index);
break;
}
if (meta->skb) {
struct b43_private_tx_info *priv_info =
b43_get_priv_tx_info(IEEE80211_SKB_CB(meta->skb));
unmap_descbuffer(ring, meta->dmaaddr, meta->skb->len, 1);
kfree(priv_info->bouncebuffer);
priv_info->bouncebuffer = NULL;
} else {
unmap_descbuffer(ring, meta->dmaaddr,
b43_txhdr_size(dev), 1);
}
if (meta->is_last_fragment) {
struct ieee80211_tx_info *info;
if (unlikely(!meta->skb)) {
/* This is a scatter-gather fragment of a frame, so
* the skb pointer must not be NULL. */
b43dbg(dev->wl, "TX status unexpected NULL skb "
"at slot %d (first=%d) on ring %d\n",
slot, firstused, ring->index);
break;
}
info = IEEE80211_SKB_CB(meta->skb);
/*
* Call back to inform the ieee80211 subsystem about
* the status of the transmission.
*/
frame_succeed = b43_fill_txstatus_report(dev, info, status);
#ifdef CONFIG_B43_DEBUG
if (frame_succeed)
ring->nr_succeed_tx_packets++;
else
ring->nr_failed_tx_packets++;
ring->nr_total_packet_tries += status->frame_count;
#endif /* DEBUG */
ieee80211_tx_status(dev->wl->hw, meta->skb);
/* skb will be freed by ieee80211_tx_status().
* Poison our pointer. */
meta->skb = B43_DMA_PTR_POISON;
} else {
/* No need to call free_descriptor_buffer here, as
* this is only the txhdr, which is not allocated.
*/
if (unlikely(meta->skb)) {
b43dbg(dev->wl, "TX status unexpected non-NULL skb "
"at slot %d (first=%d) on ring %d\n",
slot, firstused, ring->index);
break;
}
}
/* Everything unmapped and free'd. So it's not used anymore. */
ring->used_slots--;
if (meta->is_last_fragment) {
/* This is the last scatter-gather
* fragment of the frame. We are done. */
break;
}
slot = next_slot(ring, slot);
}
if (ring->stopped) {
B43_WARN_ON(free_slots(ring) < TX_SLOTS_PER_FRAME);
ieee80211_wake_queue(dev->wl->hw, ring->queue_prio);
ring->stopped = 0;
if (b43_debug(dev, B43_DBG_DMAVERBOSE)) {
b43dbg(dev->wl, "Woke up TX ring %d\n", ring->index);
}
}
}
static void dma_rx(struct b43_dmaring *ring, int *slot)
{
const struct b43_dma_ops *ops = ring->ops;
struct b43_dmadesc_generic *desc;
struct b43_dmadesc_meta *meta;
struct b43_rxhdr_fw4 *rxhdr;
struct sk_buff *skb;
u16 len;
int err;
dma_addr_t dmaaddr;
desc = ops->idx2desc(ring, *slot, &meta);
sync_descbuffer_for_cpu(ring, meta->dmaaddr, ring->rx_buffersize);
skb = meta->skb;
rxhdr = (struct b43_rxhdr_fw4 *)skb->data;
len = le16_to_cpu(rxhdr->frame_len);
if (len == 0) {
int i = 0;
do {
udelay(2);
barrier();
len = le16_to_cpu(rxhdr->frame_len);
} while (len == 0 && i++ < 5);
if (unlikely(len == 0)) {
dmaaddr = meta->dmaaddr;
goto drop_recycle_buffer;
}
}
if (unlikely(b43_rx_buffer_is_poisoned(ring, skb))) {
/* Something went wrong with the DMA.
* The device did not touch the buffer and did not overwrite the poison. */
b43dbg(ring->dev->wl, "DMA RX: Dropping poisoned buffer.\n");
dmaaddr = meta->dmaaddr;
goto drop_recycle_buffer;
}
if (unlikely(len + ring->frameoffset > ring->rx_buffersize)) {
/* The data did not fit into one descriptor buffer
* and is split over multiple buffers.
* This should never happen, as we try to allocate buffers
* big enough. So simply ignore this packet.
*/
int cnt = 0;
s32 tmp = len;
while (1) {
desc = ops->idx2desc(ring, *slot, &meta);
/* recycle the descriptor buffer. */
b43_poison_rx_buffer(ring, meta->skb);
sync_descbuffer_for_device(ring, meta->dmaaddr,
ring->rx_buffersize);
*slot = next_slot(ring, *slot);
cnt++;
tmp -= ring->rx_buffersize;
if (tmp <= 0)
break;
}
b43err(ring->dev->wl, "DMA RX buffer too small "
"(len: %u, buffer: %u, nr-dropped: %d)\n",
len, ring->rx_buffersize, cnt);
goto drop;
}
dmaaddr = meta->dmaaddr;
err = setup_rx_descbuffer(ring, desc, meta, GFP_ATOMIC);
if (unlikely(err)) {
b43dbg(ring->dev->wl, "DMA RX: setup_rx_descbuffer() failed\n");
goto drop_recycle_buffer;
}
unmap_descbuffer(ring, dmaaddr, ring->rx_buffersize, 0);
skb_put(skb, len + ring->frameoffset);
skb_pull(skb, ring->frameoffset);
b43_rx(ring->dev, skb, rxhdr);
drop:
return;
drop_recycle_buffer:
/* Poison and recycle the RX buffer. */
b43_poison_rx_buffer(ring, skb);
sync_descbuffer_for_device(ring, dmaaddr, ring->rx_buffersize);
}
void b43_dma_rx(struct b43_dmaring *ring)
{
const struct b43_dma_ops *ops = ring->ops;
int slot, current_slot;
int used_slots = 0;
B43_WARN_ON(ring->tx);
current_slot = ops->get_current_rxslot(ring);
B43_WARN_ON(!(current_slot >= 0 && current_slot < ring->nr_slots));
slot = ring->current_slot;
for (; slot != current_slot; slot = next_slot(ring, slot)) {
dma_rx(ring, &slot);
update_max_used_slots(ring, ++used_slots);
}
ops->set_current_rxslot(ring, slot);
ring->current_slot = slot;
}
static void b43_dma_tx_suspend_ring(struct b43_dmaring *ring)
{
B43_WARN_ON(!ring->tx);
ring->ops->tx_suspend(ring);
}
static void b43_dma_tx_resume_ring(struct b43_dmaring *ring)
{
B43_WARN_ON(!ring->tx);
ring->ops->tx_resume(ring);
}
void b43_dma_tx_suspend(struct b43_wldev *dev)
{
b43_power_saving_ctl_bits(dev, B43_PS_AWAKE);
b43_dma_tx_suspend_ring(dev->dma.tx_ring_AC_BK);
b43_dma_tx_suspend_ring(dev->dma.tx_ring_AC_BE);
b43_dma_tx_suspend_ring(dev->dma.tx_ring_AC_VI);
b43_dma_tx_suspend_ring(dev->dma.tx_ring_AC_VO);
b43_dma_tx_suspend_ring(dev->dma.tx_ring_mcast);
}
void b43_dma_tx_resume(struct b43_wldev *dev)
{
b43_dma_tx_resume_ring(dev->dma.tx_ring_mcast);
b43_dma_tx_resume_ring(dev->dma.tx_ring_AC_VO);
b43_dma_tx_resume_ring(dev->dma.tx_ring_AC_VI);
b43_dma_tx_resume_ring(dev->dma.tx_ring_AC_BE);
b43_dma_tx_resume_ring(dev->dma.tx_ring_AC_BK);
b43_power_saving_ctl_bits(dev, 0);
}
static void direct_fifo_rx(struct b43_wldev *dev, enum b43_dmatype type,
u16 mmio_base, bool enable)
{
u32 ctl;
if (type == B43_DMA_64BIT) {
ctl = b43_read32(dev, mmio_base + B43_DMA64_RXCTL);
ctl &= ~B43_DMA64_RXDIRECTFIFO;
if (enable)
ctl |= B43_DMA64_RXDIRECTFIFO;
b43_write32(dev, mmio_base + B43_DMA64_RXCTL, ctl);
} else {
ctl = b43_read32(dev, mmio_base + B43_DMA32_RXCTL);
ctl &= ~B43_DMA32_RXDIRECTFIFO;
if (enable)
ctl |= B43_DMA32_RXDIRECTFIFO;
b43_write32(dev, mmio_base + B43_DMA32_RXCTL, ctl);
}
}
/* Enable/Disable Direct FIFO Receive Mode (PIO) on a RX engine.
* This is called from PIO code, so DMA structures are not available. */
void b43_dma_direct_fifo_rx(struct b43_wldev *dev,
unsigned int engine_index, bool enable)
{
enum b43_dmatype type;
u16 mmio_base;
type = dma_mask_to_engine_type(supported_dma_mask(dev));
mmio_base = b43_dmacontroller_base(type, engine_index);
direct_fifo_rx(dev, type, mmio_base, enable);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3508_0 |
crossvul-cpp_data_bad_2819_1 | /*
* logger.c - logger plugin for WeeChat: save buffer lines to disk files
*
* Copyright (C) 2003-2017 Sébastien Helleu <flashcode@flashtux.org>
*
* This file is part of WeeChat, the extensible chat client.
*
* WeeChat is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* WeeChat is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WeeChat. If not, see <http://www.gnu.org/licenses/>.
*/
/* this define is needed for strptime() (not on OpenBSD/Sun) */
#if !defined(__OpenBSD__) && !defined(__sun)
#define _XOPEN_SOURCE 700
#endif
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <time.h>
#include "../weechat-plugin.h"
#include "logger.h"
#include "logger-buffer.h"
#include "logger-config.h"
#include "logger-info.h"
#include "logger-tail.h"
WEECHAT_PLUGIN_NAME(LOGGER_PLUGIN_NAME);
WEECHAT_PLUGIN_DESCRIPTION(N_("Log buffers to files"));
WEECHAT_PLUGIN_AUTHOR("Sébastien Helleu <flashcode@flashtux.org>");
WEECHAT_PLUGIN_VERSION(WEECHAT_VERSION);
WEECHAT_PLUGIN_LICENSE(WEECHAT_LICENSE);
WEECHAT_PLUGIN_PRIORITY(13000);
struct t_weechat_plugin *weechat_logger_plugin = NULL;
struct t_hook *logger_timer = NULL; /* timer to flush log files */
/*
* Gets logger file path option.
*
* Special vars are replaced:
* - "%h" (at beginning of string): WeeChat home
* - "~": user home
* - date/time specifiers (see man strftime)
*
* Note: result must be freed after use.
*/
char *
logger_get_file_path ()
{
char *path, *path2;
int length;
time_t seconds;
struct tm *date_tmp;
path = NULL;
path2 = NULL;
/* replace %h and "~", evaluate path */
path = weechat_string_eval_path_home (
weechat_config_string (logger_config_file_path), NULL, NULL, NULL);
if (!path)
goto end;
/* replace date/time specifiers in path */
length = strlen (path) + 256 + 1;
path2 = malloc (length);
if (!path2)
goto end;
seconds = time (NULL);
date_tmp = localtime (&seconds);
path2[0] = '\0';
strftime (path2, length - 1, path, date_tmp);
if (weechat_logger_plugin->debug)
{
weechat_printf_date_tags (NULL, 0, "no_log",
"%s: file path = \"%s\"",
LOGGER_PLUGIN_NAME, path2);
}
end:
if (path)
free (path);
return path2;
}
/*
* Creates logger directory.
*
* Returns:
* 1: OK
* 0: error
*/
int
logger_create_directory ()
{
int rc;
char *file_path;
rc = 1;
file_path = logger_get_file_path ();
if (file_path)
{
if (!weechat_mkdir_parents (file_path, 0700))
rc = 0;
free (file_path);
}
else
rc = 0;
return rc;
}
/*
* Builds full name of buffer.
*
* Note: result must be freed after use.
*/
char *
logger_build_option_name (struct t_gui_buffer *buffer)
{
const char *plugin_name, *name;
char *option_name;
int length;
if (!buffer)
return NULL;
plugin_name = weechat_buffer_get_string (buffer, "plugin");
name = weechat_buffer_get_string (buffer, "name");
length = strlen (plugin_name) + 1 + strlen (name) + 1;
option_name = malloc (length);
if (!option_name)
return NULL;
snprintf (option_name, length, "%s.%s", plugin_name, name);
return option_name;
}
/*
* Gets logging level for buffer.
*
* Returns level between 0 and 9 (0 = logging disabled).
*/
int
logger_get_level_for_buffer (struct t_gui_buffer *buffer)
{
const char *no_log;
char *name, *option_name, *ptr_end;
struct t_config_option *ptr_option;
/* no log for buffer if local variable "no_log" is defined for buffer */
no_log = weechat_buffer_get_string (buffer, "localvar_no_log");
if (no_log && no_log[0])
return 0;
name = logger_build_option_name (buffer);
if (!name)
return LOGGER_LEVEL_DEFAULT;
option_name = strdup (name);
if (option_name)
{
ptr_end = option_name + strlen (option_name);
while (ptr_end >= option_name)
{
ptr_option = logger_config_get_level (option_name);
if (ptr_option)
{
free (option_name);
free (name);
return weechat_config_integer (ptr_option);
}
ptr_end--;
while ((ptr_end >= option_name) && (ptr_end[0] != '.'))
{
ptr_end--;
}
if ((ptr_end >= option_name) && (ptr_end[0] == '.'))
ptr_end[0] = '\0';
}
ptr_option = logger_config_get_level (option_name);
free (option_name);
free (name);
if (ptr_option)
return weechat_config_integer (ptr_option);
}
else
free (name);
/* nothing found => return default level */
return LOGGER_LEVEL_DEFAULT;
}
/*
* Gets filename mask for a buffer.
*
* First tries with all arguments, then removes one by one to find mask (from
* specific to general mask).
*/
const char *
logger_get_mask_for_buffer (struct t_gui_buffer *buffer)
{
char *name, *option_name, *ptr_end;
struct t_config_option *ptr_option;
name = logger_build_option_name (buffer);
if (!name)
return NULL;
option_name = strdup (name);
if (option_name)
{
ptr_end = option_name + strlen (option_name);
while (ptr_end >= option_name)
{
ptr_option = logger_config_get_mask (option_name);
if (ptr_option)
{
free (option_name);
free (name);
return weechat_config_string (ptr_option);
}
ptr_end--;
while ((ptr_end >= option_name) && (ptr_end[0] != '.'))
{
ptr_end--;
}
if ((ptr_end >= option_name) && (ptr_end[0] == '.'))
ptr_end[0] = '\0';
}
ptr_option = logger_config_get_mask (option_name);
free (option_name);
free (name);
if (ptr_option)
return weechat_config_string (ptr_option);
}
else
free (name);
/* nothing found => return default mask (if set) */
if (weechat_config_string (logger_config_file_mask)
&& weechat_config_string (logger_config_file_mask)[0])
return weechat_config_string (logger_config_file_mask);
/* no default mask set */
return NULL;
}
/*
* Gets expanded mask for a buffer.
*
* Special vars are replaced:
* - local variables of buffer ($plugin, $name, ..)
* - date/time specifiers (see man strftime)
*
* Note: result must be freed after use.
*/
char *
logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask)
{
char *mask2, *mask_decoded, *mask_decoded2, *mask_decoded3, *mask_decoded4;
char *mask_decoded5;
const char *dir_separator;
int length;
time_t seconds;
struct tm *date_tmp;
mask2 = NULL;
mask_decoded = NULL;
mask_decoded2 = NULL;
mask_decoded3 = NULL;
mask_decoded4 = NULL;
mask_decoded5 = NULL;
dir_separator = weechat_info_get ("dir_separator", "");
if (!dir_separator)
return NULL;
/*
* we first replace directory separator (commonly '/') by \01 because
* buffer mask can contain this char, and will be replaced by replacement
* char ('_' by default)
*/
mask2 = weechat_string_replace (mask, dir_separator, "\01");
if (!mask2)
goto end;
mask_decoded = weechat_buffer_string_replace_local_var (buffer, mask2);
if (!mask_decoded)
goto end;
mask_decoded2 = weechat_string_replace (mask_decoded,
dir_separator,
weechat_config_string (logger_config_file_replacement_char));
if (!mask_decoded2)
goto end;
#ifdef __CYGWIN__
mask_decoded3 = weechat_string_replace (mask_decoded2, "\\",
weechat_config_string (logger_config_file_replacement_char));
#else
mask_decoded3 = strdup (mask_decoded2);
#endif /* __CYGWIN__ */
if (!mask_decoded3)
goto end;
/* restore directory separator */
mask_decoded4 = weechat_string_replace (mask_decoded3,
"\01", dir_separator);
if (!mask_decoded4)
goto end;
/* replace date/time specifiers in mask */
length = strlen (mask_decoded4) + 256 + 1;
mask_decoded5 = malloc (length);
if (!mask_decoded5)
goto end;
seconds = time (NULL);
date_tmp = localtime (&seconds);
mask_decoded5[0] = '\0';
strftime (mask_decoded5, length - 1, mask_decoded4, date_tmp);
/* convert to lower case? */
if (weechat_config_boolean (logger_config_file_name_lower_case))
weechat_string_tolower (mask_decoded5);
if (weechat_logger_plugin->debug)
{
weechat_printf_date_tags (NULL, 0, "no_log",
"%s: buffer = \"%s\", mask = \"%s\", "
"decoded mask = \"%s\"",
LOGGER_PLUGIN_NAME,
weechat_buffer_get_string (buffer, "name"),
mask, mask_decoded5);
}
end:
if (mask2)
free (mask2);
if (mask_decoded)
free (mask_decoded);
if (mask_decoded2)
free (mask_decoded2);
if (mask_decoded3)
free (mask_decoded3);
if (mask_decoded4)
free (mask_decoded4);
return mask_decoded5;
}
/*
* Builds log filename for a buffer.
*
* Note: result must be freed after use.
*/
char *
logger_get_filename (struct t_gui_buffer *buffer)
{
char *res, *mask_expanded, *file_path;
const char *mask;
const char *dir_separator, *weechat_dir;
int length;
res = NULL;
mask_expanded = NULL;
file_path = NULL;
dir_separator = weechat_info_get ("dir_separator", "");
if (!dir_separator)
return NULL;
weechat_dir = weechat_info_get ("weechat_dir", "");
if (!weechat_dir)
return NULL;
/* get filename mask for buffer */
mask = logger_get_mask_for_buffer (buffer);
if (!mask)
{
weechat_printf_date_tags (
NULL, 0, "no_log",
_("%s%s: unable to find filename mask for buffer "
"\"%s\", logging is disabled for this buffer"),
weechat_prefix ("error"), LOGGER_PLUGIN_NAME,
weechat_buffer_get_string (buffer, "name"));
return NULL;
}
mask_expanded = logger_get_mask_expanded (buffer, mask);
if (!mask_expanded)
goto end;
file_path = logger_get_file_path ();
if (!file_path)
goto end;
/* build string with path + mask */
length = strlen (file_path) + strlen (dir_separator) +
strlen (mask_expanded) + 1;
res = malloc (length);
if (res)
{
snprintf (res, length, "%s%s%s",
file_path,
(file_path[strlen (file_path) - 1] == dir_separator[0]) ? "" : dir_separator,
mask_expanded);
}
end:
if (mask_expanded)
free (mask_expanded);
if (file_path)
free (file_path);
return res;
}
/*
* Sets log filename for a logger buffer.
*/
void
logger_set_log_filename (struct t_logger_buffer *logger_buffer)
{
char *log_filename, *pos_last_sep;
const char *dir_separator;
struct t_logger_buffer *ptr_logger_buffer;
/* get log filename for buffer */
log_filename = logger_get_filename (logger_buffer->buffer);
if (!log_filename)
{
weechat_printf_date_tags (NULL, 0, "no_log",
_("%s%s: not enough memory"),
weechat_prefix ("error"),
LOGGER_PLUGIN_NAME);
return;
}
/* log file is already used by another buffer? */
ptr_logger_buffer = logger_buffer_search_log_filename (log_filename);
if (ptr_logger_buffer)
{
weechat_printf_date_tags (
NULL, 0, "no_log",
_("%s%s: unable to start logging for buffer "
"\"%s\": filename \"%s\" is already used by "
"another buffer (check your log settings)"),
weechat_prefix ("error"),
LOGGER_PLUGIN_NAME,
weechat_buffer_get_string (logger_buffer->buffer, "name"),
log_filename);
free (log_filename);
return;
}
/* create directory for path in "log_filename" */
dir_separator = weechat_info_get ("dir_separator", "");
if (dir_separator)
{
pos_last_sep = strrchr (log_filename, dir_separator[0]);
if (pos_last_sep)
{
pos_last_sep[0] = '\0';
weechat_mkdir_parents (log_filename, 0700);
pos_last_sep[0] = dir_separator[0];
}
}
/* set log filename */
logger_buffer->log_filename = log_filename;
}
/*
* Writes a line to log file.
*/
void
logger_write_line (struct t_logger_buffer *logger_buffer,
const char *format, ...)
{
char *message, buf_time[256], buf_beginning[1024];
const char *charset;
time_t seconds;
struct tm *date_tmp;
int log_level;
charset = weechat_info_get ("charset_terminal", "");
if (!logger_buffer->log_file)
{
log_level = logger_get_level_for_buffer (logger_buffer->buffer);
if (log_level == 0)
{
logger_buffer_free (logger_buffer);
return;
}
if (!logger_create_directory ())
{
weechat_printf_date_tags (
NULL, 0, "no_log",
_("%s%s: unable to create directory for logs "
"(\"%s\")"),
weechat_prefix ("error"), LOGGER_PLUGIN_NAME,
weechat_config_string (logger_config_file_path));
logger_buffer_free (logger_buffer);
return;
}
if (!logger_buffer->log_filename)
logger_set_log_filename (logger_buffer);
if (!logger_buffer->log_filename)
{
logger_buffer_free (logger_buffer);
return;
}
logger_buffer->log_file =
fopen (logger_buffer->log_filename, "a");
if (!logger_buffer->log_file)
{
weechat_printf_date_tags (
NULL, 0, "no_log",
_("%s%s: unable to write log file \"%s\": %s"),
weechat_prefix ("error"), LOGGER_PLUGIN_NAME,
logger_buffer->log_filename, strerror (errno));
logger_buffer_free (logger_buffer);
return;
}
if (weechat_config_boolean (logger_config_file_info_lines)
&& logger_buffer->write_start_info_line)
{
buf_time[0] = '\0';
seconds = time (NULL);
date_tmp = localtime (&seconds);
if (date_tmp)
{
strftime (buf_time, sizeof (buf_time) - 1,
weechat_config_string (logger_config_file_time_format),
date_tmp);
}
snprintf (buf_beginning, sizeof (buf_beginning),
_("%s\t**** Beginning of log ****"),
buf_time);
message = (charset) ?
weechat_iconv_from_internal (charset, buf_beginning) : NULL;
fprintf (logger_buffer->log_file,
"%s\n", (message) ? message : buf_beginning);
if (message)
free (message);
logger_buffer->flush_needed = 1;
}
logger_buffer->write_start_info_line = 0;
}
weechat_va_format (format);
if (vbuffer)
{
message = (charset) ?
weechat_iconv_from_internal (charset, vbuffer) : NULL;
fprintf (logger_buffer->log_file,
"%s\n", (message) ? message : vbuffer);
if (message)
free (message);
logger_buffer->flush_needed = 1;
if (!logger_timer)
{
fflush (logger_buffer->log_file);
logger_buffer->flush_needed = 0;
}
free (vbuffer);
}
}
/*
* Stops log for a logger buffer.
*/
void
logger_stop (struct t_logger_buffer *logger_buffer, int write_info_line)
{
time_t seconds;
struct tm *date_tmp;
char buf_time[256];
if (!logger_buffer)
return;
if (logger_buffer->log_enabled && logger_buffer->log_file)
{
if (write_info_line && weechat_config_boolean (logger_config_file_info_lines))
{
buf_time[0] = '\0';
seconds = time (NULL);
date_tmp = localtime (&seconds);
if (date_tmp)
{
strftime (buf_time, sizeof (buf_time) - 1,
weechat_config_string (logger_config_file_time_format),
date_tmp);
}
logger_write_line (logger_buffer,
_("%s\t**** End of log ****"),
buf_time);
}
fclose (logger_buffer->log_file);
logger_buffer->log_file = NULL;
}
logger_buffer_free (logger_buffer);
}
/*
* Ends log for all buffers.
*/
void
logger_stop_all (int write_info_line)
{
while (logger_buffers)
{
logger_stop (logger_buffers, write_info_line);
}
}
/*
* Starts logging for a buffer.
*/
void
logger_start_buffer (struct t_gui_buffer *buffer, int write_info_line)
{
struct t_logger_buffer *ptr_logger_buffer;
int log_level, log_enabled;
if (!buffer)
return;
log_level = logger_get_level_for_buffer (buffer);
log_enabled = weechat_config_boolean (logger_config_file_auto_log)
&& (log_level > 0);
ptr_logger_buffer = logger_buffer_search_buffer (buffer);
/* logging is disabled for buffer */
if (!log_enabled)
{
/* stop logger if it is active */
if (ptr_logger_buffer)
logger_stop (ptr_logger_buffer, 1);
}
else
{
/* logging is enabled for buffer */
if (ptr_logger_buffer)
ptr_logger_buffer->log_level = log_level;
else
{
ptr_logger_buffer = logger_buffer_add (buffer, log_level);
if (ptr_logger_buffer)
{
if (ptr_logger_buffer->log_filename)
{
if (ptr_logger_buffer->log_file)
{
fclose (ptr_logger_buffer->log_file);
ptr_logger_buffer->log_file = NULL;
}
}
}
}
if (ptr_logger_buffer)
ptr_logger_buffer->write_start_info_line = write_info_line;
}
}
/*
* Starts logging for all buffers.
*/
void
logger_start_buffer_all (int write_info_line)
{
struct t_infolist *ptr_infolist;
ptr_infolist = weechat_infolist_get ("buffer", NULL, NULL);
if (ptr_infolist)
{
while (weechat_infolist_next (ptr_infolist))
{
logger_start_buffer (weechat_infolist_pointer (ptr_infolist,
"pointer"),
write_info_line);
}
weechat_infolist_free (ptr_infolist);
}
}
/*
* Displays logging status for buffers.
*/
void
logger_list ()
{
struct t_infolist *ptr_infolist;
struct t_logger_buffer *ptr_logger_buffer;
struct t_gui_buffer *ptr_buffer;
char status[128];
weechat_printf (NULL, "");
weechat_printf (NULL, _("Logging on buffers:"));
ptr_infolist = weechat_infolist_get ("buffer", NULL, NULL);
if (ptr_infolist)
{
while (weechat_infolist_next (ptr_infolist))
{
ptr_buffer = weechat_infolist_pointer (ptr_infolist, "pointer");
if (ptr_buffer)
{
ptr_logger_buffer = logger_buffer_search_buffer (ptr_buffer);
if (ptr_logger_buffer)
{
snprintf (status, sizeof (status),
_("logging (level: %d)"),
ptr_logger_buffer->log_level);
}
else
{
snprintf (status, sizeof (status), "%s", _("not logging"));
}
weechat_printf (NULL,
" %s[%s%d%s]%s (%s) %s%s%s: %s%s%s%s",
weechat_color("chat_delimiters"),
weechat_color("chat"),
weechat_infolist_integer (ptr_infolist, "number"),
weechat_color("chat_delimiters"),
weechat_color("chat"),
weechat_infolist_string (ptr_infolist, "plugin_name"),
weechat_color("chat_buffer"),
weechat_infolist_string (ptr_infolist, "name"),
weechat_color("chat"),
status,
(ptr_logger_buffer) ? " (" : "",
(ptr_logger_buffer) ?
((ptr_logger_buffer->log_filename) ?
ptr_logger_buffer->log_filename : _("log not started")) : "",
(ptr_logger_buffer) ? ")" : "");
}
}
weechat_infolist_free (ptr_infolist);
}
}
/*
* Enables/disables logging on a buffer.
*/
void
logger_set_buffer (struct t_gui_buffer *buffer, const char *value)
{
char *name;
struct t_config_option *ptr_option;
name = logger_build_option_name (buffer);
if (!name)
return;
if (logger_config_set_level (name, value) != WEECHAT_CONFIG_OPTION_SET_ERROR)
{
ptr_option = logger_config_get_level (name);
if (ptr_option)
{
weechat_printf (NULL, _("%s: \"%s\" => level %d"),
LOGGER_PLUGIN_NAME, name,
weechat_config_integer (ptr_option));
}
}
free (name);
}
/*
* Flushes all log files.
*/
void
logger_flush ()
{
struct t_logger_buffer *ptr_logger_buffer;
for (ptr_logger_buffer = logger_buffers; ptr_logger_buffer;
ptr_logger_buffer = ptr_logger_buffer->next_buffer)
{
if (ptr_logger_buffer->log_file && ptr_logger_buffer->flush_needed)
{
if (weechat_logger_plugin->debug >= 2)
{
weechat_printf_date_tags (NULL, 0, "no_log",
"%s: flush file %s",
LOGGER_PLUGIN_NAME,
ptr_logger_buffer->log_filename);
}
fflush (ptr_logger_buffer->log_file);
ptr_logger_buffer->flush_needed = 0;
}
}
}
/*
* Callback for command "/logger".
*/
int
logger_command_cb (const void *pointer, void *data,
struct t_gui_buffer *buffer,
int argc, char **argv, char **argv_eol)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) argv_eol;
if ((argc == 1)
|| ((argc == 2) && (weechat_strcasecmp (argv[1], "list") == 0)))
{
logger_list ();
return WEECHAT_RC_OK;
}
if (weechat_strcasecmp (argv[1], "set") == 0)
{
if (argc > 2)
logger_set_buffer (buffer, argv[2]);
return WEECHAT_RC_OK;
}
if (weechat_strcasecmp (argv[1], "flush") == 0)
{
logger_flush ();
return WEECHAT_RC_OK;
}
if (weechat_strcasecmp (argv[1], "disable") == 0)
{
logger_set_buffer (buffer, "0");
return WEECHAT_RC_OK;
}
WEECHAT_COMMAND_ERROR;
}
/*
* Callback for signal "buffer_opened".
*/
int
logger_buffer_opened_signal_cb (const void *pointer, void *data,
const char *signal,
const char *type_data, void *signal_data)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
logger_start_buffer (signal_data, 1);
return WEECHAT_RC_OK;
}
/*
* Callback for signal "buffer_closing".
*/
int
logger_buffer_closing_signal_cb (const void *pointer, void *data,
const char *signal,
const char *type_data, void *signal_data)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
logger_stop (logger_buffer_search_buffer (signal_data), 1);
return WEECHAT_RC_OK;
}
/*
* Callback for signal "buffer_renamed".
*/
int
logger_buffer_renamed_signal_cb (const void *pointer, void *data,
const char *signal,
const char *type_data, void *signal_data)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
logger_stop (logger_buffer_search_buffer (signal_data), 1);
logger_start_buffer (signal_data, 1);
return WEECHAT_RC_OK;
}
/*
* Displays backlog for a buffer (by reading end of log file).
*/
void
logger_backlog (struct t_gui_buffer *buffer, const char *filename, int lines)
{
const char *charset;
struct t_logger_line *last_lines, *ptr_lines;
char *pos_message, *pos_tab, *error, *message;
time_t datetime, time_now;
struct tm tm_line;
int num_lines;
charset = weechat_info_get ("charset_terminal", "");
weechat_buffer_set (buffer, "print_hooks_enabled", "0");
num_lines = 0;
last_lines = logger_tail_file (filename, lines);
ptr_lines = last_lines;
while (ptr_lines)
{
datetime = 0;
pos_message = strchr (ptr_lines->data, '\t');
if (pos_message)
{
/* initialize structure, because strptime does not do it */
memset (&tm_line, 0, sizeof (struct tm));
/*
* we get current time to initialize daylight saving time in
* structure tm_line, otherwise printed time will be shifted
* and will not use DST used on machine
*/
time_now = time (NULL);
localtime_r (&time_now, &tm_line);
pos_message[0] = '\0';
error = strptime (ptr_lines->data,
weechat_config_string (logger_config_file_time_format),
&tm_line);
if (error && !error[0] && (tm_line.tm_year > 0))
datetime = mktime (&tm_line);
pos_message[0] = '\t';
}
pos_message = (pos_message && (datetime != 0)) ?
pos_message + 1 : ptr_lines->data;
message = (charset) ?
weechat_iconv_to_internal (charset, pos_message) : strdup (pos_message);
if (message)
{
pos_tab = strchr (message, '\t');
if (pos_tab)
pos_tab[0] = '\0';
weechat_printf_date_tags (buffer, datetime,
"no_highlight,notify_none,logger_backlog",
"%s%s%s%s%s",
weechat_color (weechat_config_string (logger_config_color_backlog_line)),
message,
(pos_tab) ? "\t" : "",
(pos_tab) ? weechat_color (weechat_config_string (logger_config_color_backlog_line)) : "",
(pos_tab) ? pos_tab + 1 : "");
if (pos_tab)
pos_tab[0] = '\t';
free (message);
}
num_lines++;
ptr_lines = ptr_lines->next_line;
}
if (last_lines)
logger_tail_free (last_lines);
if (num_lines > 0)
{
weechat_printf_date_tags (buffer, datetime,
"no_highlight,notify_none,logger_backlog_end",
_("%s===\t%s========== End of backlog (%d lines) =========="),
weechat_color (weechat_config_string (logger_config_color_backlog_end)),
weechat_color (weechat_config_string (logger_config_color_backlog_end)),
num_lines);
weechat_buffer_set (buffer, "unread", "");
}
weechat_buffer_set (buffer, "print_hooks_enabled", "1");
}
/*
* Callback for signal "logger_backlog".
*/
int
logger_backlog_signal_cb (const void *pointer, void *data,
const char *signal,
const char *type_data, void *signal_data)
{
struct t_logger_buffer *ptr_logger_buffer;
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
if (weechat_config_integer (logger_config_look_backlog) >= 0)
{
ptr_logger_buffer = logger_buffer_search_buffer (signal_data);
if (ptr_logger_buffer && ptr_logger_buffer->log_enabled)
{
if (!ptr_logger_buffer->log_filename)
logger_set_log_filename (ptr_logger_buffer);
if (ptr_logger_buffer->log_filename)
{
ptr_logger_buffer->log_enabled = 0;
logger_backlog (signal_data,
ptr_logger_buffer->log_filename,
weechat_config_integer (logger_config_look_backlog));
ptr_logger_buffer->log_enabled = 1;
}
}
}
return WEECHAT_RC_OK;
}
/*
* Callback for signal "logger_start".
*/
int
logger_start_signal_cb (const void *pointer, void *data,
const char *signal, const char *type_data,
void *signal_data)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
logger_start_buffer (signal_data, 1);
return WEECHAT_RC_OK;
}
/*
* Callback for signal "logger_stop".
*/
int
logger_stop_signal_cb (const void *pointer, void *data,
const char *signal, const char *type_data,
void *signal_data)
{
struct t_logger_buffer *ptr_logger_buffer;
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
ptr_logger_buffer = logger_buffer_search_buffer (signal_data);
if (ptr_logger_buffer)
logger_stop (ptr_logger_buffer, 0);
return WEECHAT_RC_OK;
}
/*
* Adjusts log filenames for all buffers.
*
* Filename can change if configuration option is changed, or if day of system
* date has changed.
*/
void
logger_adjust_log_filenames ()
{
struct t_infolist *ptr_infolist;
struct t_logger_buffer *ptr_logger_buffer;
struct t_gui_buffer *ptr_buffer;
char *log_filename;
ptr_infolist = weechat_infolist_get ("buffer", NULL, NULL);
if (ptr_infolist)
{
while (weechat_infolist_next (ptr_infolist))
{
ptr_buffer = weechat_infolist_pointer (ptr_infolist, "pointer");
ptr_logger_buffer = logger_buffer_search_buffer (ptr_buffer);
if (ptr_logger_buffer && ptr_logger_buffer->log_filename)
{
log_filename = logger_get_filename (ptr_logger_buffer->buffer);
if (log_filename)
{
if (strcmp (log_filename, ptr_logger_buffer->log_filename) != 0)
{
/*
* log filename has changed (probably due to day
* change),then we'll use new filename
*/
logger_stop (ptr_logger_buffer, 1);
logger_start_buffer (ptr_buffer, 1);
}
free (log_filename);
}
}
}
weechat_infolist_free (ptr_infolist);
}
}
/*
* Callback for signal "day_changed".
*/
int
logger_day_changed_signal_cb (const void *pointer, void *data,
const char *signal,
const char *type_data, void *signal_data)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
(void) signal_data;
logger_adjust_log_filenames ();
return WEECHAT_RC_OK;
}
/*
* Gets info with tags of line: log level and if prefix is a nick.
*/
void
logger_get_line_tag_info (int tags_count, const char **tags,
int *log_level, int *prefix_is_nick)
{
int i, log_level_set, prefix_is_nick_set;
if (log_level)
*log_level = LOGGER_LEVEL_DEFAULT;
if (prefix_is_nick)
*prefix_is_nick = 0;
log_level_set = 0;
prefix_is_nick_set = 0;
for (i = 0; i < tags_count; i++)
{
if (log_level && !log_level_set)
{
if (strcmp (tags[i], "no_log") == 0)
{
/* log disabled on line: set level to -1 */
*log_level = -1;
log_level_set = 1;
}
else if (strncmp (tags[i], "log", 3) == 0)
{
/* set log level for line */
if (isdigit ((unsigned char)tags[i][3]))
{
*log_level = (tags[i][3] - '0');
log_level_set = 1;
}
}
}
if (prefix_is_nick && !prefix_is_nick_set)
{
if (strncmp (tags[i], "prefix_nick", 11) == 0)
{
*prefix_is_nick = 1;
prefix_is_nick_set = 1;
}
}
}
}
/*
* Callback for print hooked.
*/
int
logger_print_cb (const void *pointer, void *data,
struct t_gui_buffer *buffer, time_t date,
int tags_count, const char **tags,
int displayed, int highlight,
const char *prefix, const char *message)
{
struct t_logger_buffer *ptr_logger_buffer;
struct tm *date_tmp;
char buf_time[256];
int line_log_level, prefix_is_nick;
/* make C compiler happy */
(void) pointer;
(void) data;
(void) displayed;
(void) highlight;
logger_get_line_tag_info (tags_count, tags, &line_log_level,
&prefix_is_nick);
if (line_log_level >= 0)
{
ptr_logger_buffer = logger_buffer_search_buffer (buffer);
if (ptr_logger_buffer
&& ptr_logger_buffer->log_enabled
&& (date > 0)
&& (line_log_level <= ptr_logger_buffer->log_level))
{
buf_time[0] = '\0';
date_tmp = localtime (&date);
if (date_tmp)
{
strftime (buf_time, sizeof (buf_time) - 1,
weechat_config_string (logger_config_file_time_format),
date_tmp);
}
logger_write_line (ptr_logger_buffer,
"%s\t%s%s%s\t%s",
buf_time,
(prefix && prefix_is_nick) ? weechat_config_string (logger_config_file_nick_prefix) : "",
(prefix) ? prefix : "",
(prefix && prefix_is_nick) ? weechat_config_string (logger_config_file_nick_suffix) : "",
message);
}
}
return WEECHAT_RC_OK;
}
/*
* Callback for logger timer.
*/
int
logger_timer_cb (const void *pointer, void *data, int remaining_calls)
{
/* make C compiler happy */
(void) pointer;
(void) data;
(void) remaining_calls;
logger_flush ();
return WEECHAT_RC_OK;
}
/*
* Initializes logger plugin.
*/
int
weechat_plugin_init (struct t_weechat_plugin *plugin, int argc, char *argv[])
{
/* make C compiler happy */
(void) argc;
(void) argv;
weechat_plugin = plugin;
if (!logger_config_init ())
return WEECHAT_RC_ERROR;
logger_config_read ();
/* command /logger */
weechat_hook_command (
"logger",
N_("logger plugin configuration"),
N_("list"
" || set <level>"
" || flush"
" || disable"),
N_(" list: show logging status for opened buffers\n"
" set: set logging level on current buffer\n"
" level: level for messages to be logged (0 = logging disabled, "
"1 = a few messages (most important) .. 9 = all messages)\n"
" flush: write all log files now\n"
"disable: disable logging on current buffer (set level to 0)\n"
"\n"
"Options \"logger.level.*\" and \"logger.mask.*\" can be used to set "
"level or mask for a buffer, or buffers beginning with name.\n"
"\n"
"Log levels used by IRC plugin:\n"
" 1: user message, notice, private\n"
" 2: nick change\n"
" 3: server message\n"
" 4: join/part/quit\n"
" 9: all other messages\n"
"\n"
"Examples:\n"
" set level to 5 for current buffer:\n"
" /logger set 5\n"
" disable logging for current buffer:\n"
" /logger disable\n"
" set level to 3 for all IRC buffers:\n"
" /set logger.level.irc 3\n"
" disable logging for main WeeChat buffer:\n"
" /set logger.level.core.weechat 0\n"
" use a directory per IRC server and a file per channel inside:\n"
" /set logger.mask.irc \"$server/$channel.weechatlog\""),
"list"
" || set 1|2|3|4|5|6|7|8|9"
" || flush"
" || disable",
&logger_command_cb, NULL, NULL);
logger_start_buffer_all (1);
weechat_hook_signal ("buffer_opened",
&logger_buffer_opened_signal_cb, NULL, NULL);
weechat_hook_signal ("buffer_closing",
&logger_buffer_closing_signal_cb, NULL, NULL);
weechat_hook_signal ("buffer_renamed",
&logger_buffer_renamed_signal_cb, NULL, NULL);
weechat_hook_signal ("logger_backlog",
&logger_backlog_signal_cb, NULL, NULL);
weechat_hook_signal ("logger_start",
&logger_start_signal_cb, NULL, NULL);
weechat_hook_signal ("logger_stop",
&logger_stop_signal_cb, NULL, NULL);
weechat_hook_signal ("day_changed",
&logger_day_changed_signal_cb, NULL, NULL);
weechat_hook_print (NULL, NULL, NULL, 1, &logger_print_cb, NULL, NULL);
logger_info_init ();
return WEECHAT_RC_OK;
}
/*
* Ends logger plugin.
*/
int
weechat_plugin_end (struct t_weechat_plugin *plugin)
{
/* make C compiler happy */
(void) plugin;
if (logger_timer)
{
weechat_unhook (logger_timer);
logger_timer = NULL;
}
logger_config_write ();
logger_stop_all (1);
logger_config_free ();
return WEECHAT_RC_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2819_1 |
crossvul-cpp_data_good_726_0 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2015-2016, Linaro Limited
* Copyright (c) 2014, STMicroelectronics International N.V.
*/
#include <assert.h>
#include <bench.h>
#include <compiler.h>
#include <initcall.h>
#include <io.h>
#include <kernel/linker.h>
#include <kernel/msg_param.h>
#include <kernel/panic.h>
#include <kernel/tee_misc.h>
#include <mm/core_memprot.h>
#include <mm/core_mmu.h>
#include <mm/mobj.h>
#include <optee_msg.h>
#include <sm/optee_smc.h>
#include <string.h>
#include <tee/entry_std.h>
#include <tee/tee_cryp_utl.h>
#include <tee/uuid.h>
#include <util.h>
#define SHM_CACHE_ATTRS \
(uint32_t)(core_mmu_is_shm_cached() ? OPTEE_SMC_SHM_CACHED : 0)
/* Sessions opened from normal world */
static struct tee_ta_session_head tee_open_sessions =
TAILQ_HEAD_INITIALIZER(tee_open_sessions);
static struct mobj *shm_mobj;
#ifdef CFG_SECURE_DATA_PATH
static struct mobj **sdp_mem_mobjs;
#endif
static unsigned int session_pnum;
static bool param_mem_from_mobj(struct param_mem *mem, struct mobj *mobj,
const paddr_t pa, const size_t sz)
{
paddr_t b;
if (mobj_get_pa(mobj, 0, 0, &b) != TEE_SUCCESS)
panic("mobj_get_pa failed");
if (!core_is_buffer_inside(pa, MAX(sz, 1UL), b, mobj->size))
return false;
mem->mobj = mobj;
mem->offs = pa - b;
mem->size = sz;
return true;
}
/* fill 'struct param_mem' structure if buffer matches a valid memory object */
static TEE_Result set_tmem_param(const struct optee_msg_param_tmem *tmem,
uint32_t attr, struct param_mem *mem)
{
struct mobj __maybe_unused **mobj;
paddr_t pa = READ_ONCE(tmem->buf_ptr);
size_t sz = READ_ONCE(tmem->size);
/* NULL Memory Rerefence? */
if (!pa && !sz) {
mem->mobj = NULL;
mem->offs = 0;
mem->size = 0;
return TEE_SUCCESS;
}
/* Non-contigous buffer from non sec DDR? */
if (attr & OPTEE_MSG_ATTR_NONCONTIG) {
uint64_t shm_ref = READ_ONCE(tmem->shm_ref);
mem->mobj = msg_param_mobj_from_noncontig(pa, sz, shm_ref,
false);
if (!mem->mobj)
return TEE_ERROR_BAD_PARAMETERS;
mem->offs = 0;
mem->size = sz;
return TEE_SUCCESS;
}
/* Belongs to nonsecure shared memory? */
if (param_mem_from_mobj(mem, shm_mobj, pa, sz))
return TEE_SUCCESS;
#ifdef CFG_SECURE_DATA_PATH
/* Belongs to SDP memories? */
for (mobj = sdp_mem_mobjs; *mobj; mobj++)
if (param_mem_from_mobj(mem, *mobj, pa, sz))
return TEE_SUCCESS;
#endif
return TEE_ERROR_BAD_PARAMETERS;
}
static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem,
struct param_mem *mem)
{
size_t req_size = 0;
uint64_t shm_ref = READ_ONCE(rmem->shm_ref);
mem->mobj = mobj_reg_shm_get_by_cookie(shm_ref);
if (!mem->mobj)
return TEE_ERROR_BAD_PARAMETERS;
mem->offs = READ_ONCE(rmem->offs);
mem->size = READ_ONCE(rmem->size);
/*
* Check that the supplied offset and size is covered by the
* previously verified MOBJ.
*/
if (ADD_OVERFLOW(mem->offs, mem->size, &req_size) ||
mem->mobj->size < req_size)
return TEE_ERROR_SECURITY;
return TEE_SUCCESS;
}
static TEE_Result copy_in_params(const struct optee_msg_param *params,
uint32_t num_params,
struct tee_ta_param *ta_param,
uint64_t *saved_attr)
{
TEE_Result res;
size_t n;
uint8_t pt[TEE_NUM_PARAMS] = { 0 };
if (num_params > TEE_NUM_PARAMS)
return TEE_ERROR_BAD_PARAMETERS;
memset(ta_param, 0, sizeof(*ta_param));
for (n = 0; n < num_params; n++) {
uint32_t attr;
saved_attr[n] = READ_ONCE(params[n].attr);
if (saved_attr[n] & OPTEE_MSG_ATTR_META)
return TEE_ERROR_BAD_PARAMETERS;
attr = saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK;
switch (attr) {
case OPTEE_MSG_ATTR_TYPE_NONE:
pt[n] = TEE_PARAM_TYPE_NONE;
break;
case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT:
case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:
pt[n] = TEE_PARAM_TYPE_VALUE_INPUT + attr -
OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
ta_param->u[n].val.a = READ_ONCE(params[n].u.value.a);
ta_param->u[n].val.b = READ_ONCE(params[n].u.value.b);
break;
case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
res = set_tmem_param(¶ms[n].u.tmem, saved_attr[n],
&ta_param->u[n].mem);
if (res)
return res;
pt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr -
OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
break;
case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
res = set_rmem_param(¶ms[n].u.rmem,
&ta_param->u[n].mem);
if (res)
return res;
pt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr -
OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
break;
default:
return TEE_ERROR_BAD_PARAMETERS;
}
}
ta_param->types = TEE_PARAM_TYPES(pt[0], pt[1], pt[2], pt[3]);
return TEE_SUCCESS;
}
static void cleanup_shm_refs(const uint64_t *saved_attr,
struct tee_ta_param *param, uint32_t num_params)
{
size_t n;
for (n = 0; n < num_params; n++) {
switch (saved_attr[n]) {
case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
if (saved_attr[n] & OPTEE_MSG_ATTR_NONCONTIG)
mobj_free(param->u[n].mem.mobj);
break;
case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
mobj_reg_shm_put(param->u[n].mem.mobj);
break;
default:
break;
}
}
}
static void copy_out_param(struct tee_ta_param *ta_param, uint32_t num_params,
struct optee_msg_param *params, uint64_t *saved_attr)
{
size_t n;
for (n = 0; n < num_params; n++) {
switch (TEE_PARAM_TYPE_GET(ta_param->types, n)) {
case TEE_PARAM_TYPE_MEMREF_OUTPUT:
case TEE_PARAM_TYPE_MEMREF_INOUT:
switch (saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK) {
case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:
params[n].u.tmem.size = ta_param->u[n].mem.size;
break;
case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:
case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:
params[n].u.rmem.size = ta_param->u[n].mem.size;
break;
default:
break;
}
break;
case TEE_PARAM_TYPE_VALUE_OUTPUT:
case TEE_PARAM_TYPE_VALUE_INOUT:
params[n].u.value.a = ta_param->u[n].val.a;
params[n].u.value.b = ta_param->u[n].val.b;
break;
default:
break;
}
}
}
/*
* Extracts mandatory parameter for open session.
*
* Returns
* false : mandatory parameter wasn't found or malformatted
* true : paramater found and OK
*/
static TEE_Result get_open_session_meta(size_t num_params,
struct optee_msg_param *params,
size_t *num_meta, TEE_UUID *uuid,
TEE_Identity *clnt_id)
{
const uint32_t req_attr = OPTEE_MSG_ATTR_META |
OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
if (num_params < 2)
return TEE_ERROR_BAD_PARAMETERS;
if (params[0].attr != req_attr || params[1].attr != req_attr)
return TEE_ERROR_BAD_PARAMETERS;
tee_uuid_from_octets(uuid, (void *)¶ms[0].u.value);
clnt_id->login = params[1].u.value.c;
switch (clnt_id->login) {
case TEE_LOGIN_PUBLIC:
memset(&clnt_id->uuid, 0, sizeof(clnt_id->uuid));
break;
case TEE_LOGIN_USER:
case TEE_LOGIN_GROUP:
case TEE_LOGIN_APPLICATION:
case TEE_LOGIN_APPLICATION_USER:
case TEE_LOGIN_APPLICATION_GROUP:
tee_uuid_from_octets(&clnt_id->uuid,
(void *)¶ms[1].u.value);
break;
default:
return TEE_ERROR_BAD_PARAMETERS;
}
*num_meta = 2;
return TEE_SUCCESS;
}
static void entry_open_session(struct thread_smc_args *smc_args,
struct optee_msg_arg *arg, uint32_t num_params)
{
TEE_Result res;
TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;
struct tee_ta_session *s = NULL;
TEE_Identity clnt_id;
TEE_UUID uuid;
struct tee_ta_param param;
size_t num_meta;
uint64_t saved_attr[TEE_NUM_PARAMS] = { 0 };
res = get_open_session_meta(num_params, arg->params, &num_meta, &uuid,
&clnt_id);
if (res != TEE_SUCCESS)
goto out;
res = copy_in_params(arg->params + num_meta, num_params - num_meta,
¶m, saved_attr);
if (res != TEE_SUCCESS)
goto cleanup_shm_refs;
res = tee_ta_open_session(&err_orig, &s, &tee_open_sessions, &uuid,
&clnt_id, TEE_TIMEOUT_INFINITE, ¶m);
if (res != TEE_SUCCESS)
s = NULL;
copy_out_param(¶m, num_params - num_meta, arg->params + num_meta,
saved_attr);
/*
* The occurrence of open/close session command is usually
* un-predictable, using this property to increase randomness
* of prng
*/
plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION,
&session_pnum);
cleanup_shm_refs:
cleanup_shm_refs(saved_attr, ¶m, num_params - num_meta);
out:
if (s)
arg->session = (vaddr_t)s;
else
arg->session = 0;
arg->ret = res;
arg->ret_origin = err_orig;
smc_args->a0 = OPTEE_SMC_RETURN_OK;
}
static void entry_close_session(struct thread_smc_args *smc_args,
struct optee_msg_arg *arg, uint32_t num_params)
{
TEE_Result res;
struct tee_ta_session *s;
if (num_params) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION,
&session_pnum);
s = (struct tee_ta_session *)(vaddr_t)arg->session;
res = tee_ta_close_session(s, &tee_open_sessions, NSAPP_IDENTITY);
out:
arg->ret = res;
arg->ret_origin = TEE_ORIGIN_TEE;
smc_args->a0 = OPTEE_SMC_RETURN_OK;
}
static void entry_invoke_command(struct thread_smc_args *smc_args,
struct optee_msg_arg *arg, uint32_t num_params)
{
TEE_Result res;
TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;
struct tee_ta_session *s;
struct tee_ta_param param = { 0 };
uint64_t saved_attr[TEE_NUM_PARAMS] = { 0 };
bm_timestamp();
res = copy_in_params(arg->params, num_params, ¶m, saved_attr);
if (res != TEE_SUCCESS)
goto out;
s = tee_ta_get_session(arg->session, true, &tee_open_sessions);
if (!s) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_ta_invoke_command(&err_orig, s, NSAPP_IDENTITY,
TEE_TIMEOUT_INFINITE, arg->func, ¶m);
bm_timestamp();
tee_ta_put_session(s);
copy_out_param(¶m, num_params, arg->params, saved_attr);
out:
cleanup_shm_refs(saved_attr, ¶m, num_params);
arg->ret = res;
arg->ret_origin = err_orig;
smc_args->a0 = OPTEE_SMC_RETURN_OK;
}
static void entry_cancel(struct thread_smc_args *smc_args,
struct optee_msg_arg *arg, uint32_t num_params)
{
TEE_Result res;
TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;
struct tee_ta_session *s;
if (num_params) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
s = tee_ta_get_session(arg->session, false, &tee_open_sessions);
if (!s) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_ta_cancel_command(&err_orig, s, NSAPP_IDENTITY);
tee_ta_put_session(s);
out:
arg->ret = res;
arg->ret_origin = err_orig;
smc_args->a0 = OPTEE_SMC_RETURN_OK;
}
static void register_shm(struct thread_smc_args *smc_args,
struct optee_msg_arg *arg, uint32_t num_params)
{
arg->ret = TEE_ERROR_BAD_PARAMETERS;
smc_args->a0 = OPTEE_SMC_RETURN_OK;
if (num_params != 1 ||
(arg->params[0].attr !=
(OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG)))
return;
struct optee_msg_param_tmem *tmem = &arg->params[0].u.tmem;
struct mobj *mobj = msg_param_mobj_from_noncontig(tmem->buf_ptr,
tmem->size,
tmem->shm_ref, false);
if (!mobj)
return;
mobj_reg_shm_unguard(mobj);
arg->ret = TEE_SUCCESS;
}
static void unregister_shm(struct thread_smc_args *smc_args,
struct optee_msg_arg *arg, uint32_t num_params)
{
if (num_params == 1) {
uint64_t cookie = arg->params[0].u.rmem.shm_ref;
TEE_Result res = mobj_reg_shm_release_by_cookie(cookie);
if (res)
EMSG("Can't find mapping with given cookie");
arg->ret = res;
} else {
arg->ret = TEE_ERROR_BAD_PARAMETERS;
arg->ret_origin = TEE_ORIGIN_TEE;
}
smc_args->a0 = OPTEE_SMC_RETURN_OK;
}
static struct mobj *map_cmd_buffer(paddr_t parg, uint32_t *num_params)
{
struct mobj *mobj;
struct optee_msg_arg *arg;
size_t args_size;
assert(!(parg & SMALL_PAGE_MASK));
/* mobj_mapped_shm_alloc checks if parg resides in nonsec ddr */
mobj = mobj_mapped_shm_alloc(&parg, 1, 0, 0);
if (!mobj)
return NULL;
arg = mobj_get_va(mobj, 0);
if (!arg) {
mobj_free(mobj);
return NULL;
}
*num_params = READ_ONCE(arg->num_params);
args_size = OPTEE_MSG_GET_ARG_SIZE(*num_params);
if (args_size > SMALL_PAGE_SIZE) {
EMSG("Command buffer spans across page boundary");
mobj_free(mobj);
return NULL;
}
return mobj;
}
static struct mobj *get_cmd_buffer(paddr_t parg, uint32_t *num_params)
{
struct optee_msg_arg *arg;
size_t args_size;
arg = phys_to_virt(parg, MEM_AREA_NSEC_SHM);
if (!arg)
return NULL;
*num_params = READ_ONCE(arg->num_params);
args_size = OPTEE_MSG_GET_ARG_SIZE(*num_params);
return mobj_shm_alloc(parg, args_size, 0);
}
/*
* Note: this function is weak just to make it possible to exclude it from
* the unpaged area.
*/
void __weak tee_entry_std(struct thread_smc_args *smc_args)
{
paddr_t parg;
struct optee_msg_arg *arg = NULL; /* fix gcc warning */
uint32_t num_params = 0; /* fix gcc warning */
struct mobj *mobj;
if (smc_args->a0 != OPTEE_SMC_CALL_WITH_ARG) {
EMSG("Unknown SMC 0x%" PRIx64, (uint64_t)smc_args->a0);
DMSG("Expected 0x%x\n", OPTEE_SMC_CALL_WITH_ARG);
smc_args->a0 = OPTEE_SMC_RETURN_EBADCMD;
return;
}
parg = (uint64_t)smc_args->a1 << 32 | smc_args->a2;
/* Check if this region is in static shared space */
if (core_pbuf_is(CORE_MEM_NSEC_SHM, parg,
sizeof(struct optee_msg_arg))) {
mobj = get_cmd_buffer(parg, &num_params);
} else {
if (parg & SMALL_PAGE_MASK) {
smc_args->a0 = OPTEE_SMC_RETURN_EBADADDR;
return;
}
mobj = map_cmd_buffer(parg, &num_params);
}
if (!mobj || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg)) {
EMSG("Bad arg address 0x%" PRIxPA, parg);
smc_args->a0 = OPTEE_SMC_RETURN_EBADADDR;
mobj_free(mobj);
return;
}
arg = mobj_get_va(mobj, 0);
assert(arg && mobj_is_nonsec(mobj));
/* Enable foreign interrupts for STD calls */
thread_set_foreign_intr(true);
switch (arg->cmd) {
case OPTEE_MSG_CMD_OPEN_SESSION:
entry_open_session(smc_args, arg, num_params);
break;
case OPTEE_MSG_CMD_CLOSE_SESSION:
entry_close_session(smc_args, arg, num_params);
break;
case OPTEE_MSG_CMD_INVOKE_COMMAND:
entry_invoke_command(smc_args, arg, num_params);
break;
case OPTEE_MSG_CMD_CANCEL:
entry_cancel(smc_args, arg, num_params);
break;
case OPTEE_MSG_CMD_REGISTER_SHM:
register_shm(smc_args, arg, num_params);
break;
case OPTEE_MSG_CMD_UNREGISTER_SHM:
unregister_shm(smc_args, arg, num_params);
break;
default:
EMSG("Unknown cmd 0x%x\n", arg->cmd);
smc_args->a0 = OPTEE_SMC_RETURN_EBADCMD;
}
mobj_free(mobj);
}
static TEE_Result default_mobj_init(void)
{
shm_mobj = mobj_phys_alloc(default_nsec_shm_paddr,
default_nsec_shm_size, SHM_CACHE_ATTRS,
CORE_MEM_NSEC_SHM);
if (!shm_mobj)
panic("Failed to register shared memory");
#ifdef CFG_SECURE_DATA_PATH
sdp_mem_mobjs = core_sdp_mem_create_mobjs();
if (!sdp_mem_mobjs)
panic("Failed to register SDP memory");
#endif
return TEE_SUCCESS;
}
driver_init_late(default_mobj_init);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_726_0 |
crossvul-cpp_data_good_2131_5 | /*
* HID driver for some sunplus "special" devices
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2006-2007 Jiri Kosina
* Copyright (c) 2008 Jiri Slaby
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 112 && rdesc[104] == 0x26 && rdesc[105] == 0x80 &&
rdesc[106] == 0x03) {
hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n");
rdesc[105] = rdesc[110] = 0x03;
rdesc[106] = rdesc[111] = 0x21;
}
return rdesc;
}
#define sp_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int sp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
struct hid_field *field, struct hid_usage *usage,
unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER)
return 0;
switch (usage->hid & HID_USAGE) {
case 0x2003: sp_map_key_clear(KEY_ZOOMIN); break;
case 0x2103: sp_map_key_clear(KEY_ZOOMOUT); break;
default:
return 0;
}
return 1;
}
static const struct hid_device_id sp_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_SUNPLUS, USB_DEVICE_ID_SUNPLUS_WDESKTOP) },
{ }
};
MODULE_DEVICE_TABLE(hid, sp_devices);
static struct hid_driver sp_driver = {
.name = "sunplus",
.id_table = sp_devices,
.report_fixup = sp_report_fixup,
.input_mapping = sp_input_mapping,
};
module_hid_driver(sp_driver);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2131_5 |
crossvul-cpp_data_good_4798_1 | /* $Id$ */
/* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of
* the image data through additional options listed below
*
* Original code:
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
* Additions (c) Richard Nolde 2006-2010
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT
* HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
* ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
*
* Some portions of the current code are derived from tiffcp, primarly in
* the areas of lowlevel reading and writing of TAGS, scanlines and tiles though
* some of the original functions have been extended to support arbitrary bit
* depths. These functions are presented at the top of this file.
*
* Add support for the options below to extract sections of image(s)
* and to modify the whole image or selected portions of each image by
* rotations, mirroring, and colorscale/colormap inversion of selected
* types of TIFF images when appropriate. Some color model dependent
* functions are restricted to bilevel or 8 bit per sample data.
* See the man page for the full explanations.
*
* New Options:
* -h Display the syntax guide.
* -v Report the version and last build date for tiffcrop and libtiff.
* -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1
* Specify a series of coordinates to define rectangular
* regions by the top left and lower right corners.
* -e c|d|i|m|s export mode for images and selections from input images
* combined All images and selections are written to a single file (default)
* with multiple selections from one image combined into a single image
* divided All images and selections are written to a single file
* with each selection from one image written to a new image
* image Each input image is written to a new file (numeric filename sequence)
* with multiple selections from the image combined into one image
* multiple Each input image is written to a new file (numeric filename sequence)
* with each selection from the image written to a new image
* separated Individual selections from each image are written to separate files
* -U units [in, cm, px ] inches, centimeters or pixels
* -H # Set horizontal resolution of output images to #
* -V # Set vertical resolution of output images to #
* -J # Horizontal margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -K # Vertical margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -X # Horizontal dimension of region to extract expressed in current
* units
* -Y # Vertical dimension of region to extract expressed in current
* units
* -O orient Orientation for output image, portrait, landscape, auto
* -P page Page size for output image segments, eg letter, legal, tabloid,
* etc.
* -S cols:rows Divide the image into equal sized segments using cols across
* and rows down
* -E t|l|r|b Edge to use as origin
* -m #,#,#,# Margins from edges for selection: top, left, bottom, right
* (commas separated)
* -Z #:#,#:# Zones of the image designated as zone X of Y,
* eg 1:3 would be first of three equal portions measured
* from reference edge
* -N odd|even|#,#-#,#|last
* Select sequences and/or ranges of images within file
* to process. The words odd or even may be used to specify
* all odd or even numbered images the word last may be used
* in place of a number in the sequence to indicate the final
* image in the file without knowing how many images there are.
* -R # Rotate image or crop selection by 90,180,or 270 degrees
* clockwise
* -F h|v Flip (mirror) image or crop selection horizontally
* or vertically
* -I [black|white|data|both]
* Invert color space, eg dark to light for bilevel and grayscale images
* If argument is white or black, set the PHOTOMETRIC_INTERPRETATION
* tag to MinIsBlack or MinIsWhite without altering the image data
* If the argument is data or both, the image data are modified:
* both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,
* data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag
* -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N
* Dump raw data for input and/or output images to individual files
* in raw (binary) format or text (ASCII) representing binary data
* as strings of 1s and 0s. The filename arguments are used as stems
* from which individual files are created for each image. Text format
* includes annotations for image parameters and scanline info. Level
* selects which functions dump data, with higher numbers selecting
* lower level, scanline level routines. Debug reports a limited set
* of messages to monitor progess without enabling dump logs.
*/
static char tiffcrop_version_id[] = "2.4";
static char tiffcrop_rev_date[] = "12-13-2010";
#include "tif_config.h"
#include "tiffiop.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <sys/stat.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#ifndef HAVE_GETOPT
extern int getopt(int argc, char * const argv[], const char *optstring);
#endif
#ifdef NEED_LIBPORT
# include "libport.h"
#endif
#include "tiffio.h"
#if defined(VMS)
# define unlink delete
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#define TIFF_UINT32_MAX 0xFFFFFFFFU
#ifndef streq
#define streq(a,b) (strcmp((a),(b)) == 0)
#endif
#define strneq(a,b,n) (strncmp((a),(b),(n)) == 0)
#define TRUE 1
#define FALSE 0
#ifndef TIFFhowmany
#define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y)))
#define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)
#endif
/*
* Definitions and data structures required to support cropping and image
* manipulations.
*/
#define EDGE_TOP 1
#define EDGE_LEFT 2
#define EDGE_BOTTOM 3
#define EDGE_RIGHT 4
#define EDGE_CENTER 5
#define MIRROR_HORIZ 1
#define MIRROR_VERT 2
#define MIRROR_BOTH 3
#define ROTATECW_90 8
#define ROTATECW_180 16
#define ROTATECW_270 32
#define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270)
#define CROP_NONE 0
#define CROP_MARGINS 1
#define CROP_WIDTH 2
#define CROP_LENGTH 4
#define CROP_ZONES 8
#define CROP_REGIONS 16
#define CROP_ROTATE 32
#define CROP_MIRROR 64
#define CROP_INVERT 128
/* Modes for writing out images and selections */
#define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */
#define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */
#define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */
#define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */
#define FILE_PER_SELECTION 4 /* One file per selection */
#define COMPOSITE_IMAGES 0 /* Selections combined into one image */
#define SEPARATED_IMAGES 1 /* Selections saved to separate images */
#define STRIP 1
#define TILE 2
#define MAX_REGIONS 8 /* number of regions to extract from a single page */
#define MAX_OUTBUFFS 8 /* must match larger of zones or regions */
#define MAX_SECTIONS 32 /* number of sections per page to write to output */
#define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */
#define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */
#define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */
#define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */
#define DUMP_NONE 0
#define DUMP_TEXT 1
#define DUMP_RAW 2
/* Offsets into buffer for margins and fixed width and length segments */
struct offset {
uint32 tmargin;
uint32 lmargin;
uint32 bmargin;
uint32 rmargin;
uint32 crop_width;
uint32 crop_length;
uint32 startx;
uint32 endx;
uint32 starty;
uint32 endy;
};
/* Description of a zone within the image. Position 1 of 3 zones would be
* the first third of the image. These are computed after margins and
* width/length requests are applied so that you can extract multiple
* zones from within a larger region for OCR or barcode recognition.
*/
struct buffinfo {
uint32 size; /* size of this buffer */
unsigned char *buffer; /* address of the allocated buffer */
};
struct zone {
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
};
struct pageseg {
uint32 x1; /* index of left edge */
uint32 x2; /* index of right edge */
uint32 y1; /* index of top edge */
uint32 y2; /* index of bottom edge */
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
uint32 buffsize; /* size of buffer needed to hold the cropped zone */
};
struct coordpairs {
double X1; /* index of left edge in current units */
double X2; /* index of right edge in current units */
double Y1; /* index of top edge in current units */
double Y2; /* index of bottom edge in current units */
};
struct region {
uint32 x1; /* pixel offset of left edge */
uint32 x2; /* pixel offset of right edge */
uint32 y1; /* pixel offset of top edge */
uint32 y2; /* picel offset of bottom edge */
uint32 width; /* width in pixels */
uint32 length; /* length in pixels */
uint32 buffsize; /* size of buffer needed to hold the cropped region */
unsigned char *buffptr; /* address of start of the region */
};
/* Cropping parameters from command line and image data
* Note: This should be renamed to proc_opts and expanded to include all current globals
* if possible, but each function that accesses global variables will have to be redone.
*/
struct crop_mask {
double width; /* Selection width for master crop region in requested units */
double length; /* Selection length for master crop region in requesed units */
double margins[4]; /* Top, left, bottom, right margins */
float xres; /* Horizontal resolution read from image*/
float yres; /* Vertical resolution read from image */
uint32 combined_width; /* Width of combined cropped zones */
uint32 combined_length; /* Length of combined cropped zones */
uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */
uint16 img_mode; /* Composite or separate images created from zones or regions */
uint16 exp_mode; /* Export input images or selections to one or more files */
uint16 crop_mode; /* Crop options to be applied */
uint16 res_unit; /* Resolution unit for margins and selections */
uint16 edge_ref; /* Reference edge for sections extraction and combination */
uint16 rotation; /* Clockwise rotation of the extracted region or image */
uint16 mirror; /* Mirror extracted region or image horizontally or vertically */
uint16 invert; /* Invert the color map of image or region */
uint16 photometric; /* Status of photometric interpretation for inverted image */
uint16 selections; /* Number of regions or zones selected */
uint16 regions; /* Number of regions delimited by corner coordinates */
struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */
uint16 zones; /* Number of zones delimited by Ordinal:Total requested */
struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */
struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */
};
#define MAX_PAPERNAMES 49
#define MAX_PAPERNAME_LENGTH 15
#define DEFAULT_RESUNIT RESUNIT_INCH
#define DEFAULT_PAGE_HEIGHT 14.0
#define DEFAULT_PAGE_WIDTH 8.5
#define DEFAULT_RESOLUTION 300
#define DEFAULT_PAPER_SIZE "legal"
#define ORIENTATION_NONE 0
#define ORIENTATION_PORTRAIT 1
#define ORIENTATION_LANDSCAPE 2
#define ORIENTATION_SEASCAPE 4
#define ORIENTATION_AUTO 16
#define PAGE_MODE_NONE 0
#define PAGE_MODE_RESOLUTION 1
#define PAGE_MODE_PAPERSIZE 2
#define PAGE_MODE_MARGINS 4
#define PAGE_MODE_ROWSCOLS 8
#define INVERT_DATA_ONLY 10
#define INVERT_DATA_AND_TAG 11
struct paperdef {
char name[MAX_PAPERNAME_LENGTH];
double width;
double length;
double asratio;
};
/* European page sizes corrected from update sent by
* thomas . jarosch @ intra2net . com on 5/7/2010
* Paper Size Width Length Aspect Ratio */
struct paperdef PaperTable[MAX_PAPERNAMES] = {
{"default", 8.500, 14.000, 0.607},
{"pa4", 8.264, 11.000, 0.751},
{"letter", 8.500, 11.000, 0.773},
{"legal", 8.500, 14.000, 0.607},
{"half-letter", 8.500, 5.514, 1.542},
{"executive", 7.264, 10.528, 0.690},
{"tabloid", 11.000, 17.000, 0.647},
{"11x17", 11.000, 17.000, 0.647},
{"ledger", 17.000, 11.000, 1.545},
{"archa", 9.000, 12.000, 0.750},
{"archb", 12.000, 18.000, 0.667},
{"archc", 18.000, 24.000, 0.750},
{"archd", 24.000, 36.000, 0.667},
{"arche", 36.000, 48.000, 0.750},
{"csheet", 17.000, 22.000, 0.773},
{"dsheet", 22.000, 34.000, 0.647},
{"esheet", 34.000, 44.000, 0.773},
{"superb", 11.708, 17.042, 0.687},
{"commercial", 4.139, 9.528, 0.434},
{"monarch", 3.889, 7.528, 0.517},
{"envelope-dl", 4.333, 8.681, 0.499},
{"envelope-c5", 6.389, 9.028, 0.708},
{"europostcard", 4.139, 5.833, 0.710},
{"a0", 33.110, 46.811, 0.707},
{"a1", 23.386, 33.110, 0.706},
{"a2", 16.535, 23.386, 0.707},
{"a3", 11.693, 16.535, 0.707},
{"a4", 8.268, 11.693, 0.707},
{"a5", 5.827, 8.268, 0.705},
{"a6", 4.134, 5.827, 0.709},
{"a7", 2.913, 4.134, 0.705},
{"a8", 2.047, 2.913, 0.703},
{"a9", 1.457, 2.047, 0.712},
{"a10", 1.024, 1.457, 0.703},
{"b0", 39.370, 55.669, 0.707},
{"b1", 27.835, 39.370, 0.707},
{"b2", 19.685, 27.835, 0.707},
{"b3", 13.898, 19.685, 0.706},
{"b4", 9.843, 13.898, 0.708},
{"b5", 6.929, 9.843, 0.704},
{"b6", 4.921, 6.929, 0.710},
{"c0", 36.102, 51.063, 0.707},
{"c1", 25.512, 36.102, 0.707},
{"c2", 18.031, 25.512, 0.707},
{"c3", 12.756, 18.031, 0.707},
{"c4", 9.016, 12.756, 0.707},
{"c5", 6.378, 9.016, 0.707},
{"c6", 4.488, 6.378, 0.704},
{"", 0.000, 0.000, 1.000}
};
/* Structure to define input image parameters */
struct image_data {
float xres;
float yres;
uint32 width;
uint32 length;
uint16 res_unit;
uint16 bps;
uint16 spp;
uint16 planar;
uint16 photometric;
uint16 orientation;
uint16 compression;
uint16 adjustments;
};
/* Structure to define the output image modifiers */
struct pagedef {
char name[16];
double width; /* width in pixels */
double length; /* length in pixels */
double hmargin; /* margins to subtract from width of sections */
double vmargin; /* margins to subtract from height of sections */
double hres; /* horizontal resolution for output */
double vres; /* vertical resolution for output */
uint32 mode; /* bitmask of modifiers to page format */
uint16 res_unit; /* resolution unit for output image */
unsigned int rows; /* number of section rows */
unsigned int cols; /* number of section cols */
unsigned int orient; /* portrait, landscape, seascape, auto */
};
struct dump_opts {
int debug;
int format;
int level;
char mode[4];
char infilename[PATH_MAX + 1];
char outfilename[PATH_MAX + 1];
FILE *infile;
FILE *outfile;
};
/* globals */
static int outtiled = -1;
static uint32 tilewidth = 0;
static uint32 tilelength = 0;
static uint16 config = 0;
static uint16 compression = 0;
static uint16 predictor = 0;
static uint16 fillorder = 0;
static uint32 rowsperstrip = 0;
static uint32 g3opts = 0;
static int ignore = FALSE; /* if true, ignore read errors */
static uint32 defg3opts = (uint32) -1;
static int quality = 100; /* JPEG quality */
/* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */
static int jpegcolormode = JPEGCOLORMODE_RGB;
static uint16 defcompression = (uint16) -1;
static uint16 defpredictor = (uint16) -1;
static int pageNum = 0;
static int little_endian = 1;
/* Functions adapted from tiffcp with additions or significant modifications */
static int readContigStripsIntoBuffer (TIFF*, uint8*);
static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int writeBufferToContigStrips (TIFF*, uint8*, uint32);
static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t,
uint16, uint16, struct dump_opts *);
static int processCompressOptions(char*);
static void usage(void);
/* All other functions by Richard Nolde, not found in tiffcp */
static void initImageData (struct image_data *);
static void initCropMasks (struct crop_mask *);
static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []);
static void initDumpOptions(struct dump_opts *);
/* Command line and file naming functions */
void process_command_opts (int, char *[], char *, char *, uint32 *,
uint16 *, uint16 *, uint32 *, uint32 *, uint32 *,
struct crop_mask *, struct pagedef *,
struct dump_opts *,
unsigned int *, unsigned int *);
static int update_output_file (TIFF **, char *, int, char *, unsigned int *);
/* * High level functions for whole image manipulation */
static int get_page_geometry (char *, struct pagedef*);
static int computeInputPixelOffsets(struct crop_mask *, struct image_data *,
struct offset *);
static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *);
static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **);
static int correct_orientation(struct image_data *, unsigned char **);
static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *);
static int processCropSelections(struct image_data *, struct crop_mask *,
unsigned char **, struct buffinfo []);
static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *,
struct dump_opts *, struct buffinfo [],
char *, char *, unsigned int*, unsigned int);
/* Section functions */
static int createImageSection(uint32, unsigned char **);
static int extractImageSection(struct image_data *, struct pageseg *,
unsigned char *, unsigned char *);
static int writeSingleSection(TIFF *, TIFF *, struct image_data *,
struct dump_opts *, uint32, uint32,
double, double, unsigned char *);
static int writeImageSections(TIFF *, TIFF *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *, unsigned char *,
unsigned char **);
/* Whole image functions */
static int createCroppedImage(struct image_data *, struct crop_mask *,
unsigned char **, unsigned char **);
static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image,
struct dump_opts * dump,
uint32, uint32, unsigned char *, int, int);
/* Image manipulation functions */
static int rotateContigSamples8bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples16bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples24bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples32bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *,
unsigned char **);
static int mirrorImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
static int invertImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
/* Functions to reverse the sequence of samples in a scanline */
static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *);
/* Functions for manipulating individual samples in an image */
static int extractSeparateRegion(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *, int);
static int extractCompositeRegions(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *);
static int extractContigSamples8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesBytes (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32,
uint32, uint32, tsample_t, uint16,
uint16, uint16, struct dump_opts *);
/* Functions to combine separate planes into interleaved planes */
static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, tsample_t, uint16,
FILE *, int, int);
static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, uint32, uint32,
tsample_t, uint16, FILE *, int, int);
/* Dump functions for debugging */
static void dump_info (FILE *, int, char *, char *, ...);
static int dump_data (FILE *, int, char *, unsigned char *, uint32);
static int dump_byte (FILE *, int, char *, unsigned char);
static int dump_short (FILE *, int, char *, uint16);
static int dump_long (FILE *, int, char *, uint32);
static int dump_wide (FILE *, int, char *, uint64);
static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *);
/* End function declarations */
/* Functions derived in whole or in part from tiffcp */
/* The following functions are taken largely intact from tiffcp */
static char* usage_info[] = {
"usage: tiffcrop [options] source1 ... sourceN destination",
"where options are:",
" -h Print this syntax listing",
" -v Print tiffcrop version identifier and last revision date",
" ",
" -a Append to output instead of overwriting",
" -d offset Set initial directory offset, counting first image as one, not zero",
" -p contig Pack samples contiguously (e.g. RGBRGB...)",
" -p separate Store samples separately (e.g. RRR...GGG...BBB...)",
" -s Write output in strips",
" -t Write output in tiles",
" -i Ignore read errors",
" ",
" -r # Make each strip have no more than # rows",
" -w # Set output tile width (pixels)",
" -l # Set output tile length (pixels)",
" ",
" -f lsb2msb Force lsb-to-msb FillOrder for output",
" -f msb2lsb Force msb-to-lsb FillOrder for output",
"",
" -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts] Compress output with deflate encoding",
" -c jpeg[:opts] Compress output with JPEG encoding",
" -c packbits Compress output with packbits encoding",
" -c g3[:opts] Compress output with CCITT Group 3 encoding",
" -c g4 Compress output with CCITT Group 4 encoding",
" -c none Use no compression algorithm on output",
" ",
"Group 3 options:",
" 1d Use default CCITT Group 3 1D-encoding",
" 2d Use optional CCITT Group 3 2D-encoding",
" fill Byte-align EOL codes",
"For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs",
" ",
"JPEG options:",
" # Set compression quality level (0-100, default 100)",
" raw Output color image as raw YCbCr",
" rgb Output color image as RGB",
"For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality",
" ",
"LZW and deflate options:",
" # Set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
" ",
"Page and selection options:",
" -N odd|even|#,#-#,#|last sequences and ranges of images within file to process",
" The words odd or even may be used to specify all odd or even numbered images.",
" The word last may be used in place of a number in the sequence to indicate.",
" The final image in the file without knowing how many images there are.",
" Numbers are counted from one even though TIFF IFDs are counted from zero.",
" ",
" -E t|l|r|b edge to use as origin for width and length of crop region",
" -U units [in, cm, px ] inches, centimeters or pixels",
" ",
" -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas",
" -X # horizontal dimension of region to extract expressed in current units",
" -Y # vertical dimension of region to extract expressed in current units",
" -Z #:#,#:# zones of the image designated as position X of Y,",
" eg 1:3 would be first of three equal portions measured from reference edge",
" -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1",
" regions of the image designated by upper left and lower right coordinates",
"",
"Export grouping options:",
" -e c|d|i|m|s export mode for images and selections from input images.",
" When exporting a composite image from multiple zones or regions",
" (combined and image modes), the selections must have equal sizes",
" for the axis perpendicular to the edge specified with -E.",
" c|combined All images and selections are written to a single file (default).",
" with multiple selections from one image combined into a single image.",
" d|divided All images and selections are written to a single file",
" with each selection from one image written to a new image.",
" i|image Each input image is written to a new file (numeric filename sequence)",
" with multiple selections from the image combined into one image.",
" m|multiple Each input image is written to a new file (numeric filename sequence)",
" with each selection from the image written to a new image.",
" s|separated Individual selections from each image are written to separate files.",
"",
"Output options:",
" -H # Set horizontal resolution of output images to #",
" -V # Set vertical resolution of output images to #",
" -J # Set horizontal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" -K # Set verticalal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" ",
" -O orient orientation for output image, portrait, landscape, auto",
" -P page page size for output image segments, eg letter, legal, tabloid, etc",
" use #.#x#.# to specify a custom page size in the currently defined units",
" where #.# represents the width and length",
" -S cols:rows Divide the image into equal sized segments using cols across and rows down.",
" ",
" -F hor|vert|both",
" flip (mirror) image or region horizontally, vertically, or both",
" -R # [90,180,or 270] degrees clockwise rotation of image or extracted region",
" -I [black|white|data|both]",
" invert color space, eg dark to light for bilevel and grayscale images",
" If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ",
" tag to MinIsBlack or MinIsWhite without altering the image data",
" If the argument is data or both, the image data are modified:",
" both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,",
" data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag",
" ",
"-D opt1:value1,opt2:value2,opt3:value3:opt4:value4",
" Debug/dump program progress and/or data to non-TIFF files.",
" Options include the following and must be joined as a comma",
" separate list. The use of this option is generally limited to",
" program debugging and development of future options.",
" ",
" debug:N Display limited program progress indicators where larger N",
" increase the level of detail. Note: Tiffcrop may be compiled with",
" -DDEVELMODE to enable additional very low level debug reporting.",
"",
" Format:txt|raw Format any logged data as ASCII text or raw binary ",
" values. ASCII text dumps include strings of ones and zeroes",
" representing the binary values in the image data plus identifying headers.",
" ",
" level:N Specify the level of detail presented in the dump files.",
" This can vary from dumps of the entire input or output image data to dumps",
" of data processed by specific functions. Current range of levels is 1 to 3.",
" ",
" input:full-path-to-directory/input-dumpname",
" ",
" output:full-path-to-directory/output-dumpnaem",
" ",
" When dump files are being written, each image will be written to a separate",
" file with the name built by adding a numeric sequence value to the dumpname",
" and an extension of .txt for ASCII dumps or .bin for binary dumps.",
" ",
" The four debug/dump options are independent, though it makes little sense to",
" specify a dump file without specifying a detail level.",
" ",
NULL
};
/* This function could be modified to pass starting sample offset
* and number of samples as args to select fewer than spp
* from input image. These would then be passed to individual
* extractContigSampleXX routines.
*/
static int readContigTilesIntoBuffer (TIFF* in, uint8* buf,
uint32 imagelength,
uint32 imagewidth,
uint32 tw, uint32 tl,
tsample_t spp, uint16 bps)
{
int status = 1;
tsample_t sample = 0;
tsample_t count = spp;
uint32 row, col, trow;
uint32 nrow, ncol;
uint32 dst_rowsize, shift_width;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 trailing_bits, prev_trailing_bits;
uint32 tile_rowsize = TIFFTileRowSize(in);
uint32 src_offset, dst_offset;
uint32 row_offset, col_offset;
uint8 *bufp = (uint8*) buf;
unsigned char *src = NULL;
unsigned char *dst = NULL;
tsize_t tbytes = 0, tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(in);
unsigned char *tilebuf = NULL;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
tile_buffsize = tilesize;
if (tilesize == 0 || tile_rowsize == 0)
{
TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
exit(-1);
}
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("readContigTilesIntoBuffer",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != (tile_buffsize / tile_rowsize))
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
}
/* Add 3 padding bytes for extractContigSamplesShifted32bits */
if( (size_t) tile_buffsize > 0xFFFFFFFFU - 3U )
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
tilebuf = _TIFFmalloc(tile_buffsize + 3);
if (tilebuf == 0)
return 0;
tilebuf[tile_buffsize] = 0;
tilebuf[tile_buffsize+1] = 0;
tilebuf[tile_buffsize+2] = 0;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
if (tbytes < tilesize && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu",
(unsigned long) col, (unsigned long) row, (unsigned long)tbytes,
(unsigned long)tilesize);
status = 0;
_TIFFfree(tilebuf);
return status;
}
row_offset = row * dst_rowsize;
col_offset = ((col * bps * spp) + 7)/ 8;
bufp = buf + row_offset + col_offset;
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
/* Each tile scanline will start on a byte boundary but it
* has to be merged into the scanline for the entire
* image buffer and the previous segment may not have
* ended on a byte boundary
*/
/* Optimization for common bit depths, all samples */
if (((bps % 8) == 0) && (count == spp))
{
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
_TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
bufp += (imagewidth * bps * spp) / 8;
}
}
else
{
/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
prev_trailing_bits = trailing_bits = 0;
trailing_bits = (ncol * bps * spp) % 8;
/* for (trow = 0; tl < nrow; trow++) */
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
src = tilebuf + src_offset;
dst_offset = (row + trow) * dst_rowsize;
dst = buf + dst_offset + col_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
spp, bps, count, 0, ncol))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps);
return 1;
}
}
prev_trailing_bits += trailing_bits;
/* if (prev_trailing_bits > 7) */
/* prev_trailing_bits-= 8; */
}
}
}
_TIFFfree(tilebuf);
return status;
}
static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf,
uint32 imagelength, uint32 imagewidth,
uint32 tw, uint32 tl,
uint16 spp, uint16 bps)
{
int i, status = 1, sample;
int shift_width, bytes_per_pixel;
uint16 bytes_per_sample;
uint32 row, col; /* Current row and col of image */
uint32 nrow, ncol; /* Number of rows and cols in current tile */
uint32 row_offset, col_offset; /* Output buffer offsets */
tsize_t tbytes = 0, tilesize = TIFFTileSize(in);
tsample_t s;
uint8* bufp = (uint8*)obuf;
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *tbuff = NULL;
bytes_per_sample = (bps + 7) / 8;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
srcbuffs[sample] = NULL;
tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8);
if (!tbuff)
{
TIFFError ("readSeparateTilesIntoBuffer",
"Unable to allocate tile read buffer for sample %d", sample);
for (i = 0; i < sample; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[sample] = tbuff;
}
/* Each tile contains only the data for a single plane
* arranged in scanlines of tw * bytes_per_sample bytes.
*/
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
for (s = 0; s < spp && s < MAX_SAMPLES; s++)
{ /* Read each plane of a tile set into srcbuffs[s] */
tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s);
if (tbytes < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile for row %lu col %lu, "
"sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
status = 0;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
}
/* Tiles on the right edge may be padded out to tw
* which must be a multiple of 16.
* Ncol represents the visible (non padding) portion.
*/
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
row_offset = row * (((imagewidth * spp * bps) + 7) / 8);
col_offset = ((col * spp * bps) + 7) / 8;
bufp = obuf + row_offset + col_offset;
if ((bps % 8) == 0)
{
if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth,
tw, spp, bps, NULL, 0, 0))
{
status = 0;
break;
}
}
else
{
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (shift_width)
{
case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps);
status = 0;
break;
}
}
}
}
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength)
{
uint32 row, nrows, rowsperstrip;
tstrip_t strip = 0;
tsize_t stripsize;
TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (row = 0; row < imagelength; row += rowsperstrip)
{
nrows = (row + rowsperstrip > imagelength) ?
imagelength - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
return 1;
}
buf += stripsize;
}
return 0;
}
/* Abandon plans to modify code so that plannar orientation separate images
* do not have all samples for each channel written before all samples
* for the next channel have been abandoned.
* Libtiff internals seem to depend on all data for a given sample
* being contiguous within a strip or tile when PLANAR_CONFIG is
* separate. All strips or tiles of a given plane are written
* before any strips or tiles of a different plane are stored.
*/
static int
writeBufferToSeparateStrips (TIFF* out, uint8* buf,
uint32 length, uint32 width, uint16 spp,
struct dump_opts *dump)
{
uint8 *src;
uint16 bps;
uint32 row, nrows, rowsize, rowsperstrip;
uint32 bytes_per_sample;
tsample_t s;
tstrip_t strip = 0;
tsize_t stripsize = TIFFStripSize(out);
tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out);
tsize_t total_bytes = 0;
tdata_t obuf;
(void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
(void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
bytes_per_sample = (bps + 7) / 8;
if( width == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / width ||
bps * spp * width > TIFF_UINT32_MAX - 7U )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (bps * spp * width) + 7");
return 1;
}
rowsize = ((bps * spp * width) + 7U) / 8; /* source has interleaved samples */
if( bytes_per_sample == 0 ||
rowsperstrip > TIFF_UINT32_MAX / bytes_per_sample ||
rowsperstrip * bytes_per_sample > TIFF_UINT32_MAX / (width + 1) )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing rowsperstrip * "
"bytes_per_sample * (width + 1)");
return 1;
}
rowstripsize = rowsperstrip * bytes_per_sample * (width + 1);
obuf = _TIFFmalloc (rowstripsize);
if (obuf == NULL)
return 1;
for (s = 0; s < spp; s++)
{
for (row = 0; row < length; row += rowsperstrip)
{
nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
src = buf + (row * rowsize);
total_bytes += stripsize;
memset (obuf, '\0', rowstripsize);
if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump))
{
_TIFFfree(obuf);
return 1;
}
if ((dump->outfile != NULL) && (dump->level == 1))
{
dump_info(dump->outfile, dump->format,"",
"Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d",
s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf);
dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf);
}
if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
_TIFFfree(obuf);
return 1;
}
}
}
_TIFFfree(obuf);
return 0;
}
/* Extract all planes from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts* dump)
{
uint16 bps;
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint32 tile_rowsize = TIFFTileRowSize(out);
uint8* bufp = (uint8*) buf;
tsize_t tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(out);
unsigned char *tilebuf = NULL;
if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
!TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
!TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
return 1;
if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
{
TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero");
exit(-1);
}
tile_buffsize = tilesize;
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("writeBufferToContigTiles",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != tile_buffsize / tile_rowsize)
{
TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size");
exit(-1);
}
}
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7U )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
tilebuf = _TIFFmalloc(tile_buffsize);
if (tilebuf == 0)
return 1;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,
tw, 0, spp, spp, bps, dump) > 0)
{
TIFFError("writeBufferToContigTiles",
"Unable to extract data to tile for row %lu, col %lu",
(unsigned long) row, (unsigned long)col);
_TIFFfree(tilebuf);
return 1;
}
if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
{
TIFFError("writeBufferToContigTiles",
"Cannot write tile at %lu %lu",
(unsigned long) col, (unsigned long) row);
_TIFFfree(tilebuf);
return 1;
}
}
}
_TIFFfree(tilebuf);
return 0;
} /* end writeBufferToContigTiles */
/* Extract each plane from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts * dump)
{
tdata_t obuf = _TIFFmalloc(TIFFTileSize(out));
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint16 bps;
tsample_t s;
uint8* bufp = (uint8*) buf;
if (obuf == NULL)
return 1;
TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7 )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
_TIFFfree(obuf);
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
for (s = 0; s < spp; s++)
{
if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,
tw, s, 1, spp, bps, dump) > 0)
{
TIFFError("writeBufferToSeparateTiles",
"Unable to extract data to tile for row %lu, col %lu sample %d",
(unsigned long) row, (unsigned long)col, (int)s);
_TIFFfree(obuf);
return 1;
}
if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
{
TIFFError("writeBufferToseparateTiles",
"Cannot write tile at %lu %lu sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
_TIFFfree(obuf);
return 1;
}
}
}
}
_TIFFfree(obuf);
return 0;
} /* end writeBufferToSeparateTiles */
static void
processG3Options(char* cp)
{
if( (cp = strchr(cp, ':')) ) {
if (defg3opts == (uint32) -1)
defg3opts = 0;
do {
cp++;
if (strneq(cp, "1d", 2))
defg3opts &= ~GROUP3OPT_2DENCODING;
else if (strneq(cp, "2d", 2))
defg3opts |= GROUP3OPT_2DENCODING;
else if (strneq(cp, "fill", 4))
defg3opts |= GROUP3OPT_FILLBITS;
else
usage();
} while( (cp = strchr(cp, ':')) );
}
}
static int
processCompressOptions(char* opt)
{
char* cp = NULL;
if (strneq(opt, "none",4))
{
defcompression = COMPRESSION_NONE;
}
else if (streq(opt, "packbits"))
{
defcompression = COMPRESSION_PACKBITS;
}
else if (strneq(opt, "jpeg", 4))
{
cp = strchr(opt, ':');
defcompression = COMPRESSION_JPEG;
while (cp)
{
if (isdigit((int)cp[1]))
quality = atoi(cp + 1);
else if (strneq(cp + 1, "raw", 3 ))
jpegcolormode = JPEGCOLORMODE_RAW;
else if (strneq(cp + 1, "rgb", 3 ))
jpegcolormode = JPEGCOLORMODE_RGB;
else
usage();
cp = strchr(cp + 1, ':');
}
}
else if (strneq(opt, "g3", 2))
{
processG3Options(opt);
defcompression = COMPRESSION_CCITTFAX3;
}
else if (streq(opt, "g4"))
{
defcompression = COMPRESSION_CCITTFAX4;
}
else if (strneq(opt, "lzw", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_LZW;
}
else if (strneq(opt, "zip", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_ADOBE_DEFLATE;
}
else
return (0);
return (1);
}
static void
usage(void)
{
int i;
fprintf(stderr, "\n%s\n", TIFFGetVersion());
for (i = 0; usage_info[i] != NULL; i++)
fprintf(stderr, "%s\n", usage_info[i]);
exit(-1);
}
#define CopyField(tag, v) \
if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
#define CopyField2(tag, v1, v2) \
if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
#define CopyField3(tag, v1, v2, v3) \
if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
#define CopyField4(tag, v1, v2, v3, v4) \
if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
static void
cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
{
switch (type) {
case TIFF_SHORT:
if (count == 1) {
uint16 shortv;
CopyField(tag, shortv);
} else if (count == 2) {
uint16 shortv1, shortv2;
CopyField2(tag, shortv1, shortv2);
} else if (count == 4) {
uint16 *tr, *tg, *tb, *ta;
CopyField4(tag, tr, tg, tb, ta);
} else if (count == (uint16) -1) {
uint16 shortv1;
uint16* shortav;
CopyField2(tag, shortv1, shortav);
}
break;
case TIFF_LONG:
{ uint32 longv;
CopyField(tag, longv);
}
break;
case TIFF_RATIONAL:
if (count == 1) {
float floatv;
CopyField(tag, floatv);
} else if (count == (uint16) -1) {
float* floatav;
CopyField(tag, floatav);
}
break;
case TIFF_ASCII:
{ char* stringv;
CopyField(tag, stringv);
}
break;
case TIFF_DOUBLE:
if (count == 1) {
double doublev;
CopyField(tag, doublev);
} else if (count == (uint16) -1) {
double* doubleav;
CopyField(tag, doubleav);
}
break;
default:
TIFFError(TIFFFileName(in),
"Data type %d is not supported, tag %d skipped",
tag, type);
}
}
static struct cpTag {
uint16 tag;
uint16 count;
TIFFDataType type;
} tags[] = {
{ TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
{ TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
{ TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
{ TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
{ TIFFTAG_MAKE, 1, TIFF_ASCII },
{ TIFFTAG_MODEL, 1, TIFF_ASCII },
{ TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_PAGENAME, 1, TIFF_ASCII },
{ TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
{ TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
{ TIFFTAG_DATETIME, 1, TIFF_ASCII },
{ TIFFTAG_ARTIST, 1, TIFF_ASCII },
{ TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
{ TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL },
{ TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
{ TIFFTAG_INKSET, 1, TIFF_SHORT },
{ TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
{ TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
{ TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
{ TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
{ TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
{ TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
{ TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_STONITS, 1, TIFF_DOUBLE },
};
#define NTAGS (sizeof (tags) / sizeof (tags[0]))
#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
/* Functions written by Richard Nolde, with exceptions noted. */
void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum,
uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth,
uint32 *deftilelength, uint32 *defrowsperstrip,
struct crop_mask *crop_data, struct pagedef *page,
struct dump_opts *dump,
unsigned int *imagelist, unsigned int *image_count )
{
int c, good_args = 0;
char *opt_offset = NULL; /* Position in string of value sought */
char *opt_ptr = NULL; /* Pointer to next token in option set */
char *sep = NULL; /* Pointer to a token separator */
unsigned int i, j, start, end;
#if !HAVE_DECL_OPTARG
extern int optind;
extern char* optarg;
#endif
*mp++ = 'w';
*mp = '\0';
while ((c = getopt(argc, argv,
"ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1)
{
good_args++;
switch (c) {
case 'a': mode[0] = 'a'; /* append to output */
break;
case 'c': if (!processCompressOptions(optarg)) /* compression scheme */
{
TIFFError ("Unknown compression option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */
if (start == 0)
{
TIFFError ("","Directory offset must be greater than zero");
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
*dirnum = start - 1;
break;
case 'e': switch (tolower((int) optarg[0])) /* image export modes*/
{
case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Composite */
case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Divided */
case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Image */
case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Multiple */
case 's': crop_data->exp_mode = FILE_PER_SELECTION;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Sections */
default: TIFFError ("Unknown export mode","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'f': if (streq(optarg, "lsb2msb")) /* fill order */
*deffillorder = FILLORDER_LSB2MSB;
else if (streq(optarg, "msb2lsb"))
*deffillorder = FILLORDER_MSB2LSB;
else
{
TIFFError ("Unknown fill order", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'h': usage();
break;
case 'i': ignore = TRUE; /* ignore errors */
break;
case 'l': outtiled = TRUE; /* tile length */
*deftilelength = atoi(optarg);
break;
case 'p': /* planar configuration */
if (streq(optarg, "separate"))
*defconfig = PLANARCONFIG_SEPARATE;
else if (streq(optarg, "contig"))
*defconfig = PLANARCONFIG_CONTIG;
else
{
TIFFError ("Unkown planar configuration", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'r': /* rows/strip */
*defrowsperstrip = atol(optarg);
break;
case 's': /* generate stripped output */
outtiled = FALSE;
break;
case 't': /* generate tiled output */
outtiled = TRUE;
break;
case 'v': TIFFError("Library Release", "%s", TIFFGetVersion());
TIFFError ("Tiffcrop version", "%s, last updated: %s",
tiffcrop_version_id, tiffcrop_rev_date);
TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler");
TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc");
TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde");
exit (0);
break;
case 'w': /* tile width */
outtiled = TRUE;
*deftilewidth = atoi(optarg);
break;
case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */
crop_data->crop_mode |= CROP_REGIONS;
for (i = 0, opt_ptr = strtok (optarg, ":");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ":")), i++)
{
crop_data->regions++;
if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf",
&crop_data->corners[i].X1, &crop_data->corners[i].Y1,
&crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4)
{
TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);;
}
break;
/* options for file open modes */
case 'B': *mp++ = 'b'; *mp = '\0';
break;
case 'L': *mp++ = 'l'; *mp = '\0';
break;
case 'M': *mp++ = 'm'; *mp = '\0';
break;
case 'C': *mp++ = 'c'; *mp = '\0';
break;
/* options for Debugging / data dump */
case 'D': for (i = 0, opt_ptr = strtok (optarg, ",");
(opt_ptr != NULL);
(opt_ptr = strtok (NULL, ",")), i++)
{
opt_offset = strpbrk(opt_ptr, ":=");
if (opt_offset == NULL)
{
TIFFError("Invalid dump option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
*opt_offset = '\0';
/* convert option to lowercase */
end = strlen (opt_ptr);
for (i = 0; i < end; i++)
*(opt_ptr + i) = tolower((int) *(opt_ptr + i));
/* Look for dump format specification */
if (strncmp(opt_ptr, "for", 3) == 0)
{
/* convert value to lowercase */
end = strlen (opt_offset + 1);
for (i = 1; i <= end; i++)
*(opt_offset + i) = tolower((int) *(opt_offset + i));
/* check dump format value */
if (strncmp (opt_offset + 1, "txt", 3) == 0)
{
dump->format = DUMP_TEXT;
strcpy (dump->mode, "w");
}
else
{
if (strncmp(opt_offset + 1, "raw", 3) == 0)
{
dump->format = DUMP_RAW;
strcpy (dump->mode, "wb");
}
else
{
TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
}
else
{ /* Look for dump level specification */
if (strncmp (opt_ptr, "lev", 3) == 0)
dump->level = atoi(opt_offset + 1);
/* Look for input data dump file name */
if (strncmp (opt_ptr, "in", 2) == 0)
{
strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20);
dump->infilename[PATH_MAX - 20] = '\0';
}
/* Look for output data dump file name */
if (strncmp (opt_ptr, "out", 3) == 0)
{
strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20);
dump->outfilename[PATH_MAX - 20] = '\0';
}
if (strncmp (opt_ptr, "deb", 3) == 0)
dump->debug = atoi(opt_offset + 1);
}
}
if ((strlen(dump->infilename)) || (strlen(dump->outfilename)))
{
if (dump->level == 1)
TIFFError("","Defaulting to dump level 1, no data.");
if (dump->format == DUMP_NONE)
{
TIFFError("", "You must specify a dump format for dump files");
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
break;
/* image manipulation routine options */
case 'm': /* margins to exclude from selection, uppercase M was already used */
/* order of values must be TOP, LEFT, BOTTOM, RIGHT */
crop_data->crop_mode |= CROP_MARGINS;
for (i = 0, opt_ptr = strtok (optarg, ",:");
((opt_ptr != NULL) && (i < 4));
(opt_ptr = strtok (NULL, ",:")), i++)
{
crop_data->margins[i] = atof(opt_ptr);
}
break;
case 'E': /* edge reference */
switch (tolower((int) optarg[0]))
{
case 't': crop_data->edge_ref = EDGE_TOP;
break;
case 'b': crop_data->edge_ref = EDGE_BOTTOM;
break;
case 'l': crop_data->edge_ref = EDGE_LEFT;
break;
case 'r': crop_data->edge_ref = EDGE_RIGHT;
break;
default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'F': /* flip eg mirror image or cropped segment, M was already used */
crop_data->crop_mode |= CROP_MIRROR;
switch (tolower((int) optarg[0]))
{
case 'h': crop_data->mirror = MIRROR_HORIZ;
break;
case 'v': crop_data->mirror = MIRROR_VERT;
break;
case 'b': crop_data->mirror = MIRROR_BOTH;
break;
default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'H': /* set horizontal resolution to new value */
page->hres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'I': /* invert the color space, eg black to white */
crop_data->crop_mode |= CROP_INVERT;
/* The PHOTOMETIC_INTERPRETATION tag may be updated */
if (streq(optarg, "black"))
{
crop_data->photometric = PHOTOMETRIC_MINISBLACK;
continue;
}
if (streq(optarg, "white"))
{
crop_data->photometric = PHOTOMETRIC_MINISWHITE;
continue;
}
if (streq(optarg, "data"))
{
crop_data->photometric = INVERT_DATA_ONLY;
continue;
}
if (streq(optarg, "both"))
{
crop_data->photometric = INVERT_DATA_AND_TAG;
continue;
}
TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
break;
case 'J': /* horizontal margin for sectioned ouput pages */
page->hmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'K': /* vertical margin for sectioned ouput pages*/
page->vmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'N': /* list of images to process */
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_IMAGES));
(opt_ptr = strtok (NULL, ",")))
{ /* We do not know how many images are in file yet
* so we build a list to include the maximum allowed
* and follow it until we hit the end of the file.
* Image count is not accurate for odd, even, last
* so page numbers won't be valid either.
*/
if (streq(opt_ptr, "odd"))
{
for (j = 1; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = (MAX_IMAGES - 1) / 2;
break;
}
else
{
if (streq(opt_ptr, "even"))
{
for (j = 2; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = MAX_IMAGES / 2;
break;
}
else
{
if (streq(opt_ptr, "last"))
imagelist[i++] = MAX_IMAGES;
else /* single value between commas */
{
sep = strpbrk(opt_ptr, ":-");
if (!sep)
imagelist[i++] = atoi(opt_ptr);
else
{
*sep = '\0';
start = atoi (opt_ptr);
if (!strcmp((sep + 1), "last"))
end = MAX_IMAGES;
else
end = atoi (sep + 1);
for (j = start; j <= end && j - start + i < MAX_IMAGES; j++)
imagelist[i++] = j;
}
}
}
}
}
*image_count = i;
break;
case 'O': /* page orientation */
switch (tolower((int) optarg[0]))
{
case 'a': page->orient = ORIENTATION_AUTO;
break;
case 'p': page->orient = ORIENTATION_PORTRAIT;
break;
case 'l': page->orient = ORIENTATION_LANDSCAPE;
break;
default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'P': /* page size selection */
if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2)
{
strcpy (page->name, "Custom");
page->mode |= PAGE_MODE_PAPERSIZE;
break;
}
if (get_page_geometry (optarg, page))
{
if (!strcmp(optarg, "list"))
{
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (-1);
}
TIFFError ("Invalid paper size", "%s", optarg);
TIFFError ("", "Select one of:");
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (-1);
}
else
{
page->mode |= PAGE_MODE_PAPERSIZE;
}
break;
case 'R': /* rotate image or cropped segment */
crop_data->crop_mode |= CROP_ROTATE;
switch (strtoul(optarg, NULL, 0))
{
case 90: crop_data->rotation = (uint16)90;
break;
case 180: crop_data->rotation = (uint16)180;
break;
case 270: crop_data->rotation = (uint16)270;
break;
default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */
sep = strpbrk(optarg, ",:");
if (sep)
{
*sep = '\0';
page->cols = atoi(optarg);
page->rows = atoi(sep +1);
}
else
{
page->cols = atoi(optarg);
page->rows = atoi(optarg);
}
if ((page->cols * page->rows) > MAX_SECTIONS)
{
TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS);
exit (-1);
}
page->mode |= PAGE_MODE_ROWSCOLS;
break;
case 'U': /* units for measurements and offsets */
if (streq(optarg, "in"))
{
crop_data->res_unit = RESUNIT_INCH;
page->res_unit = RESUNIT_INCH;
}
else if (streq(optarg, "cm"))
{
crop_data->res_unit = RESUNIT_CENTIMETER;
page->res_unit = RESUNIT_CENTIMETER;
}
else if (streq(optarg, "px"))
{
crop_data->res_unit = RESUNIT_NONE;
page->res_unit = RESUNIT_NONE;
}
else
{
TIFFError ("Illegal unit of measure","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'V': /* set vertical resolution to new value */
page->vres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'X': /* selection width */
crop_data->crop_mode |= CROP_WIDTH;
crop_data->width = atof(optarg);
break;
case 'Y': /* selection length */
crop_data->crop_mode |= CROP_LENGTH;
crop_data->length = atof(optarg);
break;
case 'Z': /* zones of an image X:Y read as zone X of Y */
crop_data->crop_mode |= CROP_ZONES;
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ",")), i++)
{
crop_data->zones++;
opt_offset = strchr(opt_ptr, ':');
if (!opt_offset) {
TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h");
exit(-1);
}
*opt_offset = '\0';
crop_data->zonelist[i].position = atoi(opt_ptr);
crop_data->zonelist[i].total = atoi(opt_offset + 1);
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS);
exit (-1);
}
break;
case '?': TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
/*NOTREACHED*/
}
}
} /* end process_command_opts */
/* Start a new output file if one has not been previously opened or
* autoindex is set to non-zero. Update page and file counters
* so TIFFTAG PAGENUM will be correct in image.
*/
static int
update_output_file (TIFF **tiffout, char *mode, int autoindex,
char *outname, unsigned int *page)
{
static int findex = 0; /* file sequence indicator */
char *sep;
char filenum[16];
char export_ext[16];
char exportname[PATH_MAX];
if (autoindex && (*tiffout != NULL))
{
/* Close any export file that was previously opened */
TIFFClose (*tiffout);
*tiffout = NULL;
}
strcpy (export_ext, ".tiff");
memset (exportname, '\0', PATH_MAX);
/* Leave room for page number portion of the new filename */
strncpy (exportname, outname, PATH_MAX - 16);
if (*tiffout == NULL) /* This is a new export file */
{
if (autoindex)
{ /* create a new filename for each export */
findex++;
if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF")))
{
strncpy (export_ext, sep, 5);
*sep = '\0';
}
else
strncpy (export_ext, ".tiff", 5);
export_ext[5] = '\0';
/* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */
if (findex > MAX_EXPORT_PAGES)
{
TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES);
return 1;
}
snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext);
filenum[14] = '\0';
strncat (exportname, filenum, 15);
}
exportname[PATH_MAX - 1] = '\0';
*tiffout = TIFFOpen(exportname, mode);
if (*tiffout == NULL)
{
TIFFError("update_output_file", "Unable to open output file %s", exportname);
return 1;
}
*page = 0;
return 0;
}
else
(*page)++;
return 0;
} /* end update_output_file */
int
main(int argc, char* argv[])
{
#if !HAVE_DECL_OPTARG
extern int optind;
#endif
uint16 defconfig = (uint16) -1;
uint16 deffillorder = 0;
uint32 deftilewidth = (uint32) 0;
uint32 deftilelength = (uint32) 0;
uint32 defrowsperstrip = (uint32) 0;
uint32 dirnum = 0;
TIFF *in = NULL;
TIFF *out = NULL;
char mode[10];
char *mp = mode;
/** RJN additions **/
struct image_data image; /* Image parameters for one image */
struct crop_mask crop; /* Cropping parameters for all images */
struct pagedef page; /* Page definition for output pages */
struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */
struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */
struct dump_opts dump; /* Data dump options */
unsigned char *read_buff = NULL; /* Input image data buffer */
unsigned char *crop_buff = NULL; /* Crop area buffer */
unsigned char *sect_buff = NULL; /* Image section buffer */
unsigned char *sect_src = NULL; /* Image section buffer pointer */
unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */
unsigned int image_count = 0;
unsigned int dump_images = 0;
unsigned int next_image = 0;
unsigned int next_page = 0;
unsigned int total_pages = 0;
unsigned int total_images = 0;
unsigned int end_of_input = FALSE;
int seg, length;
char temp_filename[PATH_MAX + 1];
little_endian = *((unsigned char *)&little_endian) & '1';
initImageData(&image);
initCropMasks(&crop);
initPageSetup(&page, sections, seg_buffs);
initDumpOptions(&dump);
process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig,
&deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip,
&crop, &page, &dump, imagelist, &image_count);
if (argc - optind < 2)
usage();
if ((argc - optind) == 2)
pageNum = -1;
else
total_images = 0;
/* read multiple input files and write to output file(s) */
while (optind < argc - 1)
{
in = TIFFOpen (argv[optind], "r");
if (in == NULL)
return (-3);
/* If only one input file is specified, we can use directory count */
total_images = TIFFNumberOfDirectories(in);
if (image_count == 0)
{
dirnum = 0;
total_pages = total_images; /* Only valid with single input file */
}
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
/* Total pages only valid for enumerated list of pages not derived
* using odd, even, or last keywords.
*/
if (image_count > total_images)
image_count = total_images;
total_pages = image_count;
}
/* MAX_IMAGES is used for special case "last" in selection list */
if (dirnum == (MAX_IMAGES - 1))
dirnum = total_images - 1;
if (dirnum > (total_images))
{
TIFFError (TIFFFileName(in),
"Invalid image number %d, File contains only %d images",
(int)dirnum + 1, total_images);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum))
{
TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
end_of_input = FALSE;
while (end_of_input == FALSE)
{
config = defconfig;
compression = defcompression;
predictor = defpredictor;
fillorder = deffillorder;
rowsperstrip = defrowsperstrip;
tilewidth = deftilewidth;
tilelength = deftilelength;
g3opts = defg3opts;
if (dump.format != DUMP_NONE)
{
/* manage input and/or output dump files here */
dump_images++;
length = strlen(dump.infilename);
if (length > 0)
{
if (dump.infile != NULL)
fclose (dump.infile);
/* dump.infilename is guaranteed to be NUL termimated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s",
dump.infilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (-1);
}
dump_info(dump.infile, dump.format, "Reading image","%d from %s",
dump_images, TIFFFileName(in));
}
length = strlen(dump.outfilename);
if (length > 0)
{
if (dump.outfile != NULL)
fclose (dump.outfile);
/* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s",
dump.outfilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (-1);
}
dump_info(dump.outfile, dump.format, "Writing image","%d from %s",
dump_images, TIFFFileName(in));
}
}
if (dump.debug)
TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages);
if (loadImage(in, &image, &dump, &read_buff))
{
TIFFError("main", "Unable to load source image");
exit (-1);
}
/* Correct the image orientation if it was not ORIENTATION_TOPLEFT.
*/
if (image.adjustments != 0)
{
if (correct_orientation(&image, &read_buff))
TIFFError("main", "Unable to correct image orientation");
}
if (getCropOffsets(&image, &crop, &dump))
{
TIFFError("main", "Unable to define crop regions");
exit (-1);
}
if (crop.selections > 0)
{
if (processCropSelections(&image, &crop, &read_buff, seg_buffs))
{
TIFFError("main", "Unable to process image selections");
exit (-1);
}
}
else /* Single image segment without zones or regions */
{
if (createCroppedImage(&image, &crop, &read_buff, &crop_buff))
{
TIFFError("main", "Unable to create output image");
exit (-1);
}
}
if (page.mode == PAGE_MODE_NONE)
{ /* Whole image or sections not based on output page size */
if (crop.selections > 0)
{
writeSelections(in, &out, &crop, &image, &dump, seg_buffs,
mp, argv[argc - 1], &next_page, total_pages);
}
else /* One file all images and sections */
{
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1],
&next_page))
exit (1);
if (writeCroppedImage(in, out, &image, &dump,crop.combined_width,
crop.combined_length, crop_buff, next_page, total_pages))
{
TIFFError("main", "Unable to write new image");
exit (-1);
}
}
}
else
{
/* If we used a crop buffer, our data is there, otherwise it is
* in the read_buffer
*/
if (crop_buff != NULL)
sect_src = crop_buff;
else
sect_src = read_buff;
/* Break input image into pages or rows and columns */
if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump))
{
TIFFError("main", "Unable to compute output section data");
exit (-1);
}
/* If there are multiple files on the command line, the final one is assumed
* to be the output filename into which the images are written.
*/
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page))
exit (1);
if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, §_buff))
{
TIFFError("main", "Unable to write image sections");
exit (-1);
}
}
/* No image list specified, just read the next image */
if (image_count == 0)
dirnum++;
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
}
if (dirnum == MAX_IMAGES - 1)
dirnum = TIFFNumberOfDirectories(in) - 1;
if (!TIFFSetDirectory(in, (tdir_t)dirnum))
end_of_input = TRUE;
}
TIFFClose(in);
optind++;
}
/* If we did not use the read buffer as the crop buffer */
if (read_buff)
_TIFFfree(read_buff);
if (crop_buff)
_TIFFfree(crop_buff);
if (sect_buff)
_TIFFfree(sect_buff);
/* Clean up any segment buffers used for zones or regions */
for (seg = 0; seg < crop.selections; seg++)
_TIFFfree (seg_buffs[seg].buffer);
if (dump.format != DUMP_NONE)
{
if (dump.infile != NULL)
fclose (dump.infile);
if (dump.outfile != NULL)
{
dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out));
fclose (dump.outfile);
}
}
TIFFClose(out);
return (0);
} /* end main */
/* Debugging functions */
static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count)
{
int j, k;
uint32 i;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (i = 0; i < count; i++)
{
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s", dump_array);
}
fprintf (dumpfile,"\n");
}
else
{
if ((fwrite (data, 1, count, dumpfile)) != count)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data)
{
int j, k;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 1, 1, dumpfile)) != 1)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data)
{
int j, k;
char dump_array[20];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 15; k >= 0; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[17] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 2, 1, dumpfile)) != 2)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data)
{
int j, k;
char dump_array[40];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 31; k >= 0; j++, k--)
{
bitset = data & (((uint32)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[35] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 4, 1, dumpfile)) != 4)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data)
{
int j, k;
char dump_array[80];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 63; k >= 0; j++, k--)
{
bitset = data & (((uint64)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[71] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 8, 1, dumpfile)) != 8)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...)
{
if (format == DUMP_TEXT)
{
va_list ap;
va_start(ap, msg);
fprintf(dumpfile, "%s ", prefix);
vfprintf(dumpfile, msg, ap);
fprintf(dumpfile, "\n");
va_end(ap);
}
}
static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width,
uint32 row, unsigned char *buff)
{
int j, k;
uint32 i;
unsigned char * dump_ptr;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
for (i = 0; i < rows; i++)
{
dump_ptr = buff + (i * width);
if (format == DUMP_TEXT)
dump_info (dumpfile, format, "",
"Row %4d, %d bytes at offset %d",
row + i + 1, width, row * width);
for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10)
dump_data (dumpfile, format, "", dump_ptr, 10);
if (k > 0)
dump_data (dumpfile, format, "", dump_ptr, k);
}
return (0);
}
/* Extract one or more samples from an interleaved buffer. If count == 1,
* only the sample plane indicated by sample will be extracted. If count > 1,
* count samples beginning at sample will be extracted. Portions of a
* scanline can be extracted by specifying a start and end value.
*/
static int
extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int i, bytes_per_sample, sindex;
uint32 col, dst_rowsize, bit_offset;
uint32 src_byte /*, src_bit */;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesBytes","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid end column value %d ignored", end);
end = cols;
}
dst_rowsize = (bps * (end - start) * count) / 8;
bytes_per_sample = (bps + 7) / 8;
/* Optimize case for copying all samples */
if (count == spp)
{
src = in + (start * spp * bytes_per_sample);
_TIFFmemcpy (dst, src, dst_rowsize);
}
else
{
for (col = start; col < end; col++)
{
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
bit_offset = col * bps * spp;
if (sindex == 0)
{
src_byte = bit_offset / 8;
/* src_bit = bit_offset % 8; */
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
/* src_bit = (bit_offset + (sindex * bps)) % 8; */
}
src = in + src_byte;
for (i = 0; i < bytes_per_sample; i++)
*dst++ = *src++;
}
}
}
return (0);
} /* end extractContigSamplesBytes */
static int
extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = (buff2 | (buff1 >> ready_bits));
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples8bits */
static int
extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
{
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples16bits */
static int
extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples24bits */
static int
extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = 0;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples32bits */
static int
extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
if ((col == start) && (sindex == sample))
buff2 = *src & ((uint8)-1) << (shift);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ |= buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = buff2 | (buff1 >> ready_bits);
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted8bits */
static int
extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint16)-1) << (8 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
buff2 = buff2 | (buff1 >> ready_bits);
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted16bits */
static int
extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint32)-1) << (16 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted24bits */
static int
extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = shift;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
if ((col == start) && (sindex == sample))
buff2 = buff3 & ((uint64)-1) << (32 - shift);
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted32bits */
static int
extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row, first_col = 0;
uint32 dst_rowsize, dst_offset;
tsample_t count = 1;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src_rowsize = ((bps * spp * cols) + 7) / 8;
dst_rowsize = ((bps * cols) + 7) / 8;
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToBuffer */
static int
extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
uint32 imagewidth, uint32 tilewidth, tsample_t sample,
uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row;
uint32 dst_rowsize, dst_offset;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
src_rowsize = ((bps * spp * imagewidth) + 7) / 8;
dst_rowsize = ((bps * tilewidth * count) + 7) / 8;
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToTileBuffer */
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += stripsize;
}
return 1;
} /* end readContigStripsIntoBuffer */
static int
combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * spp * cols) + 7) / 8;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
row_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
col_offset = row_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
src += bytes_per_sample;
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamplesBytes */
static int
combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
/* int bytes_per_sample = 0; */
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples8bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples8bits */
static int
combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples16bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples16bits */
static int
combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples24bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples24bits */
static int
combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples32bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateSamples32bits */
static int
combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = imagewidth * bytes_per_sample * spp;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
#ifdef DEVELMODE
TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d",
row, src_offset, dst - out);
#endif
for (col = 0; col < cols; col++)
{
col_offset = src_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamplesBytes */
static int
combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples8bits */
static int
combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples16bits */
static int
combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples24bits */
static int
combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateTileSamples32bits */
static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length,
uint32 width, uint16 spp,
struct dump_opts *dump)
{
int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
uint32 j;
int32 bytes_read = 0;
uint16 bps, planar;
uint32 nstrips;
uint32 strips_per_sample;
uint32 src_rowsize, dst_rowsize, rows_processed, rps;
uint32 rows_this_strip = 0;
tsample_t s;
tstrip_t strip;
tsize_t scanlinesize = TIFFScanlineSize(in);
tsize_t stripsize = TIFFStripSize(in);
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *buff = NULL;
unsigned char *dst = NULL;
if (obuf == NULL)
{
TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument");
return (0);
}
memset (srcbuffs, '\0', sizeof(srcbuffs));
TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
if (rps > length)
rps = length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
src_rowsize = ((bps * width) + 7) / 8;
dst_rowsize = ((bps * width * spp) + 7) / 8;
dst = obuf;
if ((dump->infile != NULL) && (dump->level == 3))
{
dump_info (dump->infile, dump->format, "",
"Image width %d, length %d, Scanline size, %4d bytes",
width, length, scanlinesize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d, Shift width %d",
bps, spp, shift_width);
}
/* Libtiff seems to assume/require that data for separate planes are
* written one complete plane after another and not interleaved in any way.
* Multiple scanlines and possibly strips of the same plane must be
* written before data for any other plane.
*/
nstrips = TIFFNumberOfStrips(in);
strips_per_sample = nstrips /spp;
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
srcbuffs[s] = NULL;
buff = _TIFFmalloc(stripsize);
if (!buff)
{
TIFFError ("readSeparateStripsIntoBuffer",
"Unable to allocate strip read buffer for sample %d", s);
for (i = 0; i < s; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[s] = buff;
}
rows_processed = 0;
for (j = 0; (j < strips_per_sample) && (result == 1); j++)
{
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
strip = (s * strips_per_sample) + j;
bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize);
rows_this_strip = bytes_read / src_rowsize;
if (bytes_read < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu for sample %d",
(unsigned long) strip, s + 1);
result = 0;
break;
}
#ifdef DEVELMODE
TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d",
strip, bytes_read, rows_this_strip, shift_width);
#endif
}
if (rps > rows_this_strip)
rps = rows_this_strip;
dst = obuf + (dst_rowsize * rows_processed);
if ((bps % 8) == 0)
{
if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
}
else
{
switch (shift_width)
{
case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps);
result = 0;
break;
}
}
if ((rows_processed + rps) > length)
{
rows_processed = length;
rps = length - rows_processed;
}
else
rows_processed += rps;
}
/* free any buffers allocated for each plane or scanline and
* any temporary buffers
*/
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
if (buff != NULL)
_TIFFfree(buff);
}
return (result);
} /* end readSeparateStripsIntoBuffer */
static int
get_page_geometry (char *name, struct pagedef *page)
{
char *ptr;
int n;
for (ptr = name; *ptr; ptr++)
*ptr = (char)tolower((int)*ptr);
for (n = 0; n < MAX_PAPERNAMES; n++)
{
if (strcmp(name, PaperTable[n].name) == 0)
{
page->width = PaperTable[n].width;
page->length = PaperTable[n].length;
strncpy (page->name, PaperTable[n].name, 15);
page->name[15] = '\0';
return (0);
}
}
return (1);
}
static void
initPageSetup (struct pagedef *page, struct pageseg *pagelist,
struct buffinfo seg_buffs[])
{
int i;
strcpy (page->name, "");
page->mode = PAGE_MODE_NONE;
page->res_unit = RESUNIT_NONE;
page->hres = 0.0;
page->vres = 0.0;
page->width = 0.0;
page->length = 0.0;
page->hmargin = 0.0;
page->vmargin = 0.0;
page->rows = 0;
page->cols = 0;
page->orient = ORIENTATION_NONE;
for (i = 0; i < MAX_SECTIONS; i++)
{
pagelist[i].x1 = (uint32)0;
pagelist[i].x2 = (uint32)0;
pagelist[i].y1 = (uint32)0;
pagelist[i].y2 = (uint32)0;
pagelist[i].buffsize = (uint32)0;
pagelist[i].position = 0;
pagelist[i].total = 0;
}
for (i = 0; i < MAX_OUTBUFFS; i++)
{
seg_buffs[i].size = 0;
seg_buffs[i].buffer = NULL;
}
}
static void
initImageData (struct image_data *image)
{
image->xres = 0.0;
image->yres = 0.0;
image->width = 0;
image->length = 0;
image->res_unit = RESUNIT_NONE;
image->bps = 0;
image->spp = 0;
image->planar = 0;
image->photometric = 0;
image->orientation = 0;
image->compression = COMPRESSION_NONE;
image->adjustments = 0;
}
static void
initCropMasks (struct crop_mask *cps)
{
int i;
cps->crop_mode = CROP_NONE;
cps->res_unit = RESUNIT_NONE;
cps->edge_ref = EDGE_TOP;
cps->width = 0;
cps->length = 0;
for (i = 0; i < 4; i++)
cps->margins[i] = 0.0;
cps->bufftotal = (uint32)0;
cps->combined_width = (uint32)0;
cps->combined_length = (uint32)0;
cps->rotation = (uint16)0;
cps->photometric = INVERT_DATA_AND_TAG;
cps->mirror = (uint16)0;
cps->invert = (uint16)0;
cps->zones = (uint32)0;
cps->regions = (uint32)0;
for (i = 0; i < MAX_REGIONS; i++)
{
cps->corners[i].X1 = 0.0;
cps->corners[i].X2 = 0.0;
cps->corners[i].Y1 = 0.0;
cps->corners[i].Y2 = 0.0;
cps->regionlist[i].x1 = 0;
cps->regionlist[i].x2 = 0;
cps->regionlist[i].y1 = 0;
cps->regionlist[i].y2 = 0;
cps->regionlist[i].width = 0;
cps->regionlist[i].length = 0;
cps->regionlist[i].buffsize = 0;
cps->regionlist[i].buffptr = NULL;
cps->zonelist[i].position = 0;
cps->zonelist[i].total = 0;
}
cps->exp_mode = ONE_FILE_COMPOSITE;
cps->img_mode = COMPOSITE_IMAGES;
}
static void initDumpOptions(struct dump_opts *dump)
{
dump->debug = 0;
dump->format = DUMP_NONE;
dump->level = 1;
sprintf (dump->mode, "w");
memset (dump->infilename, '\0', PATH_MAX + 1);
memset (dump->outfilename, '\0',PATH_MAX + 1);
dump->infile = NULL;
dump->outfile = NULL;
}
/* Compute pixel offsets into the image for margins and fixed regions */
static int
computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image,
struct offset *off)
{
double scale;
float xres, yres;
/* Values for these offsets are in pixels from start of image, not bytes,
* and are indexed from zero to width - 1 or length - 1 */
uint32 tmargin, bmargin, lmargin, rmargin;
uint32 startx, endx; /* offsets of first and last columns to extract */
uint32 starty, endy; /* offsets of first and last row to extract */
uint32 width, length, crop_width, crop_length;
uint32 i, max_width, max_length, zwidth, zlength, buffsize;
uint32 x1, x2, y1, y2;
if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER)
{
xres = 1.0;
yres = 1.0;
}
else
{
if (((image->xres == 0) || (image->yres == 0)) &&
(crop->res_unit != RESUNIT_NONE) &&
((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))
{
TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution");
TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again");
return (-1);
}
xres = image->xres;
yres = image->yres;
}
/* Translate user units to image units */
scale = 1.0;
switch (crop->res_unit) {
case RESUNIT_CENTIMETER:
if (image->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (image->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
if (crop->crop_mode & CROP_REGIONS)
{
max_width = max_length = 0;
for (i = 0; i < crop->regions; i++)
{
if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER))
{
x1 = (uint32) (crop->corners[i].X1 * scale * xres);
x2 = (uint32) (crop->corners[i].X2 * scale * xres);
y1 = (uint32) (crop->corners[i].Y1 * scale * yres);
y2 = (uint32) (crop->corners[i].Y2 * scale * yres);
}
else
{
x1 = (uint32) (crop->corners[i].X1);
x2 = (uint32) (crop->corners[i].X2);
y1 = (uint32) (crop->corners[i].Y1);
y2 = (uint32) (crop->corners[i].Y2);
}
if (x1 < 1)
crop->regionlist[i].x1 = 0;
else
crop->regionlist[i].x1 = (uint32) (x1 - 1);
if (x2 > image->width - 1)
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = (uint32) (x2 - 1);
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
if (y1 < 1)
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = (uint32) (y1 - 1);
if (y2 > image->length - 1)
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = (uint32) (y2 - 1);
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
if (zwidth > max_width)
max_width = zwidth;
if (zlength > max_length)
max_length = zlength;
buffsize = (uint32)
(((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (crop->img_mode == COMPOSITE_IMAGES)
{
switch (crop->edge_ref)
{
case EDGE_LEFT:
case EDGE_RIGHT:
crop->combined_length = zlength;
crop->combined_width += zwidth;
break;
case EDGE_BOTTOM:
case EDGE_TOP: /* width from left, length from top */
default:
crop->combined_width = zwidth;
crop->combined_length += zlength;
break;
}
}
}
return (0);
}
/* Convert crop margins into offsets into image
* Margins are expressed as pixel rows and columns, not bytes
*/
if (crop->crop_mode & CROP_MARGINS)
{
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{ /* User has specified pixels as reference unit */
tmargin = (uint32)(crop->margins[0]);
lmargin = (uint32)(crop->margins[1]);
bmargin = (uint32)(crop->margins[2]);
rmargin = (uint32)(crop->margins[3]);
}
else
{ /* inches or centimeters specified */
tmargin = (uint32)(crop->margins[0] * scale * yres);
lmargin = (uint32)(crop->margins[1] * scale * xres);
bmargin = (uint32)(crop->margins[2] * scale * yres);
rmargin = (uint32)(crop->margins[3] * scale * xres);
}
if ((lmargin + rmargin) > image->width)
{
TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width");
lmargin = (uint32) 0;
rmargin = (uint32) 0;
return (-1);
}
if ((tmargin + bmargin) > image->length)
{
TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length");
tmargin = (uint32) 0;
bmargin = (uint32) 0;
return (-1);
}
}
else
{ /* no margins requested */
tmargin = (uint32) 0;
lmargin = (uint32) 0;
bmargin = (uint32) 0;
rmargin = (uint32) 0;
}
/* Width, height, and margins are expressed as pixel offsets into image */
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{
if (crop->crop_mode & CROP_WIDTH)
width = (uint32)crop->width;
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = (uint32)crop->length;
else
length = image->length - tmargin - bmargin;
}
else
{
if (crop->crop_mode & CROP_WIDTH)
width = (uint32)(crop->width * scale * image->xres);
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = (uint32)(crop->length * scale * image->yres);
else
length = image->length - tmargin - bmargin;
}
off->tmargin = tmargin;
off->bmargin = bmargin;
off->lmargin = lmargin;
off->rmargin = rmargin;
/* Calculate regions defined by margins, width, and length.
* Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,
* since they are used to compute offsets into buffers */
switch (crop->edge_ref) {
case EDGE_BOTTOM:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
endy = image->length - bmargin - 1;
if ((endy - length) <= tmargin)
starty = tmargin;
else
starty = endy - length + 1;
break;
case EDGE_RIGHT:
endx = image->width - rmargin - 1;
if ((endx - width) <= lmargin)
startx = lmargin;
else
startx = endx - width + 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
case EDGE_TOP: /* width from left, length from top */
case EDGE_LEFT:
default:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
}
off->startx = startx;
off->starty = starty;
off->endx = endx;
off->endy = endy;
crop_width = endx - startx + 1;
crop_length = endy - starty + 1;
if (crop_width <= 0)
{
TIFFError("computeInputPixelOffsets",
"Invalid left/right margins and /or image crop width requested");
return (-1);
}
if (crop_width > image->width)
crop_width = image->width;
if (crop_length <= 0)
{
TIFFError("computeInputPixelOffsets",
"Invalid top/bottom margins and /or image crop length requested");
return (-1);
}
if (crop_length > image->length)
crop_length = image->length;
off->crop_width = crop_width;
off->crop_length = crop_length;
return (0);
} /* end computeInputPixelOffsets */
/*
* Translate crop options into pixel offsets for one or more regions of the image.
* Options are applied in this order: margins, specific width and length, zones,
* but all are optional. Margins are relative to each edge. Width, length and
* zones are relative to the specified reference edge. Zones are expressed as
* X:Y where X is the ordinal value in a set of Y equal sized portions. eg.
* 2:3 would indicate the middle third of the region qualified by margins and
* any explicit width and length specified. Regions are specified by coordinates
* of the top left and lower right corners with range 1 to width or height.
*/
static int
getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump)
{
struct offset offsets;
int i;
int32 test;
uint32 seg, total, need_buff = 0;
uint32 buffsize;
uint32 zwidth, zlength;
memset(&offsets, '\0', sizeof(struct offset));
crop->bufftotal = 0;
crop->combined_width = (uint32)0;
crop->combined_length = (uint32)0;
crop->selections = 0;
/* Compute pixel offsets if margins or fixed width or length specified */
if ((crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_REGIONS) ||
(crop->crop_mode & CROP_LENGTH) ||
(crop->crop_mode & CROP_WIDTH))
{
if (computeInputPixelOffsets(crop, image, &offsets))
{
TIFFError ("getCropOffsets", "Unable to compute crop margins");
return (-1);
}
need_buff = TRUE;
crop->selections = crop->regions;
/* Regions are only calculated from top and left edges with no margins */
if (crop->crop_mode & CROP_REGIONS)
return (0);
}
else
{ /* cropped area is the full image */
offsets.tmargin = 0;
offsets.lmargin = 0;
offsets.bmargin = 0;
offsets.rmargin = 0;
offsets.crop_width = image->width;
offsets.crop_length = image->length;
offsets.startx = 0;
offsets.endx = image->width - 1;
offsets.starty = 0;
offsets.endy = image->length - 1;
need_buff = FALSE;
}
if (dump->outfile != NULL)
{
dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d",
offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin);
dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d",
offsets.crop_width, offsets.crop_length);
}
if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */
{
if (need_buff == FALSE) /* No margins or fixed width or length areas */
{
crop->selections = 0;
crop->combined_width = image->width;
crop->combined_length = image->length;
return (0);
}
else
{
/* Use one region for margins and fixed width or length areas
* even though it was not formally declared as a region.
*/
crop->selections = 1;
crop->zones = 1;
crop->zonelist[0].total = 1;
crop->zonelist[0].position = 1;
}
}
else
crop->selections = crop->zones;
for (i = 0; i < crop->zones; i++)
{
seg = crop->zonelist[i].position;
total = crop->zonelist[i].total;
switch (crop->edge_ref)
{
case EDGE_LEFT: /* zones from left to right, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * 1.0 * (seg - 1) / total);
test = (int32)offsets.startx +
(int32)(offsets.crop_width * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_BOTTOM: /* width from left, zones from bottom to top */
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = test + 1;
test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
case EDGE_RIGHT: /* zones from right to left, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * (total - seg) * 1.0 / total);
test = offsets.startx +
(offsets.crop_width * (total - seg + 1) * 1.0 / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_TOP: /* width from left, zones from top to bottom */
default:
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total);
test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test - 1;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
} /* end switch statement */
buffsize = (uint32)
((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].width = (uint32) zwidth;
crop->regionlist[i].length = (uint32) zlength;
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (dump->outfile != NULL)
dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d",
i + 1, (uint32)zwidth, (uint32)zlength,
crop->regionlist[i].x1, crop->regionlist[i].x2,
crop->regionlist[i].y1, crop->regionlist[i].y2);
}
return (0);
} /* end getCropOffsets */
static int
computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts* dump)
{
double scale;
double pwidth, plength; /* Output page width and length in user units*/
uint32 iwidth, ilength; /* Input image width and length in pixels*/
uint32 owidth, olength; /* Output image width and length in pixels*/
uint32 orows, ocols; /* rows and cols for output */
uint32 hmargin, vmargin; /* Horizontal and vertical margins */
uint32 x1, x2, y1, y2, line_bytes;
/* unsigned int orientation; */
uint32 i, j, k;
scale = 1.0;
if (page->res_unit == RESUNIT_NONE)
page->res_unit = image->res_unit;
switch (image->res_unit) {
case RESUNIT_CENTIMETER:
if (page->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (page->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
/* get width, height, resolutions of input image selection */
if (crop->combined_width > 0)
iwidth = crop->combined_width;
else
iwidth = image->width;
if (crop->combined_length > 0)
ilength = crop->combined_length;
else
ilength = image->length;
if (page->hres <= 1.0)
page->hres = image->xres;
if (page->vres <= 1.0)
page->vres = image->yres;
if ((page->hres < 1.0) || (page->vres < 1.0))
{
TIFFError("computeOutputPixelOffsets",
"Invalid horizontal or vertical resolution specified or read from input image");
return (1);
}
/* If no page sizes are being specified, we just use the input image size to
* calculate maximum margins that can be taken from image.
*/
if (page->width <= 0)
pwidth = iwidth;
else
pwidth = page->width;
if (page->length <= 0)
plength = ilength;
else
plength = page->length;
if (dump->debug)
{
TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, "
"Hmargin: %3.2f, Vmargin: %3.2f",
page->name, page->vres, page->hres,
page->hmargin, page->vmargin);
TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f",
page->res_unit, scale, pwidth, plength);
}
/* compute margins at specified unit and resolution */
if (page->mode & PAGE_MODE_MARGINS)
{
if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER)
{ /* inches or centimeters specified */
hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8));
vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8));
}
else
{ /* Otherwise user has specified pixels as reference unit */
hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8));
vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8));
}
if ((hmargin * 2.0) > (pwidth * page->hres))
{
TIFFError("computeOutputPixelOffsets",
"Combined left and right margins exceed page width");
hmargin = (uint32) 0;
return (-1);
}
if ((vmargin * 2.0) > (plength * page->vres))
{
TIFFError("computeOutputPixelOffsets",
"Combined top and bottom margins exceed page length");
vmargin = (uint32) 0;
return (-1);
}
}
else
{
hmargin = 0;
vmargin = 0;
}
if (page->mode & PAGE_MODE_ROWSCOLS )
{
/* Maybe someday but not for now */
if (page->mode & PAGE_MODE_MARGINS)
TIFFError("computeOutputPixelOffsets",
"Output margins cannot be specified with rows and columns");
owidth = TIFFhowmany(iwidth, page->cols);
olength = TIFFhowmany(ilength, page->rows);
}
else
{
if (page->mode & PAGE_MODE_PAPERSIZE )
{
owidth = (uint32)((pwidth * page->hres) - (hmargin * 2));
olength = (uint32)((plength * page->vres) - (vmargin * 2));
}
else
{
owidth = (uint32)(iwidth - (hmargin * 2 * page->hres));
olength = (uint32)(ilength - (vmargin * 2 * page->vres));
}
}
if (owidth > iwidth)
owidth = iwidth;
if (olength > ilength)
olength = ilength;
/* Compute the number of pages required for Portrait or Landscape */
switch (page->orient)
{
case ORIENTATION_NONE:
case ORIENTATION_PORTRAIT:
ocols = TIFFhowmany(iwidth, owidth);
orows = TIFFhowmany(ilength, olength);
/* orientation = ORIENTATION_PORTRAIT; */
break;
case ORIENTATION_LANDSCAPE:
ocols = TIFFhowmany(iwidth, olength);
orows = TIFFhowmany(ilength, owidth);
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
break;
case ORIENTATION_AUTO:
default:
x1 = TIFFhowmany(iwidth, owidth);
x2 = TIFFhowmany(ilength, olength);
y1 = TIFFhowmany(iwidth, olength);
y2 = TIFFhowmany(ilength, owidth);
if ( (x1 * x2) < (y1 * y2))
{ /* Portrait */
ocols = x1;
orows = x2;
/* orientation = ORIENTATION_PORTRAIT; */
}
else
{ /* Landscape */
ocols = y1;
orows = y2;
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
}
}
if (ocols < 1)
ocols = 1;
if (orows < 1)
orows = 1;
/* If user did not specify rows and cols, set them from calcuation */
if (page->rows < 1)
page->rows = orows;
if (page->cols < 1)
page->cols = ocols;
line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp;
if ((page->rows * page->cols) > MAX_SECTIONS)
{
TIFFError("computeOutputPixelOffsets",
"Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections");
return (-1);
}
/* build the list of offsets for each output section */
for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++)
{
y1 = (uint32)(olength * i);
y2 = (uint32)(olength * (i + 1) - 1);
if (y2 >= ilength)
y2 = ilength - 1;
for (j = 0; j < ocols; j++, k++)
{
x1 = (uint32)(owidth * j);
x2 = (uint32)(owidth * (j + 1) - 1);
if (x2 >= iwidth)
x2 = iwidth - 1;
sections[k].x1 = x1;
sections[k].x2 = x2;
sections[k].y1 = y1;
sections[k].y2 = y2;
sections[k].buffsize = line_bytes * olength;
sections[k].position = k + 1;
sections[k].total = orows * ocols;
}
}
return (0);
} /* end computeOutputPixelOffsets */
static int
loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
{
uint32 i;
float xres = 0.0, yres = 0.0;
uint32 nstrips = 0, ntiles = 0;
uint16 planar = 0;
uint16 bps = 0, spp = 0, res_unit = 0;
uint16 orientation = 0;
uint16 input_compression = 0, input_photometric = 0;
uint16 subsampling_horiz, subsampling_vert;
uint32 width = 0, length = 0;
uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0;
uint32 tw = 0, tl = 0; /* Tile width and length */
uint32 tile_rowsize = 0;
unsigned char *read_buff = NULL;
unsigned char *new_buff = NULL;
int readunit = 0;
static uint32 prev_readsize = 0;
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
TIFFError("loadImage","Image lacks Photometric interpreation tag");
if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
TIFFError("loadimage","Image lacks image width tag");
if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
TIFFError("loadimage","Image lacks image length tag");
TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = RESUNIT_INCH;
if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
char compressionid[16];
switch (input_compression)
{
case COMPRESSION_NONE: /* 1 dump mode */
strcpy (compressionid, "None/dump");
break;
case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
strcpy (compressionid, "Huffman RLE");
break;
case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
strcpy (compressionid, "Group3 Fax");
break;
case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
strcpy (compressionid, "Group4 Fax");
break;
case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
strcpy (compressionid, "LZW");
break;
case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
strcpy (compressionid, "Old Jpeg");
break;
case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
strcpy (compressionid, "New Jpeg");
break;
case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
strcpy (compressionid, "Next RLE");
break;
case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
strcpy (compressionid, "CITTRLEW");
break;
case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
strcpy (compressionid, "Mac Packbits");
break;
case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
strcpy (compressionid, "Thunderscan");
break;
case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
strcpy (compressionid, "IT8 padded");
break;
case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
strcpy (compressionid, "IT8 RLE");
break;
case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
strcpy (compressionid, "IT8 mono");
break;
case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
strcpy (compressionid, "IT8 lineart");
break;
case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
strcpy (compressionid, "Pixar 10 bit");
break;
case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
strcpy (compressionid, "Pixar 11bit");
break;
case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
strcpy (compressionid, "Deflate");
break;
case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
strcpy (compressionid, "Adobe deflate");
break;
default:
strcpy (compressionid, "None/unknown");
break;
}
TIFFError("loadImage", "Input compression %s", compressionid);
#endif
scanlinesize = TIFFScanlineSize(in);
image->bps = bps;
image->spp = spp;
image->planar = planar;
image->width = width;
image->length = length;
image->xres = xres;
image->yres = yres;
image->res_unit = res_unit;
image->compression = input_compression;
image->photometric = input_photometric;
#ifdef DEBUG2
char photometricid[12];
switch (input_photometric)
{
case PHOTOMETRIC_MINISWHITE:
strcpy (photometricid, "MinIsWhite");
break;
case PHOTOMETRIC_MINISBLACK:
strcpy (photometricid, "MinIsBlack");
break;
case PHOTOMETRIC_RGB:
strcpy (photometricid, "RGB");
break;
case PHOTOMETRIC_PALETTE:
strcpy (photometricid, "Palette");
break;
case PHOTOMETRIC_MASK:
strcpy (photometricid, "Mask");
break;
case PHOTOMETRIC_SEPARATED:
strcpy (photometricid, "Separated");
break;
case PHOTOMETRIC_YCBCR:
strcpy (photometricid, "YCBCR");
break;
case PHOTOMETRIC_CIELAB:
strcpy (photometricid, "CIELab");
break;
case PHOTOMETRIC_ICCLAB:
strcpy (photometricid, "ICCLab");
break;
case PHOTOMETRIC_ITULAB:
strcpy (photometricid, "ITULab");
break;
case PHOTOMETRIC_LOGL:
strcpy (photometricid, "LogL");
break;
case PHOTOMETRIC_LOGLUV:
strcpy (photometricid, "LOGLuv");
break;
default:
strcpy (photometricid, "Unknown");
break;
}
TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
#endif
image->orientation = orientation;
switch (orientation)
{
case 0:
case ORIENTATION_TOPLEFT:
image->adjustments = 0;
break;
case ORIENTATION_TOPRIGHT:
image->adjustments = MIRROR_HORIZ;
break;
case ORIENTATION_BOTRIGHT:
image->adjustments = ROTATECW_180;
break;
case ORIENTATION_BOTLEFT:
image->adjustments = MIRROR_VERT;
break;
case ORIENTATION_LEFTTOP:
image->adjustments = MIRROR_VERT | ROTATECW_90;
break;
case ORIENTATION_RIGHTTOP:
image->adjustments = ROTATECW_90;
break;
case ORIENTATION_RIGHTBOT:
image->adjustments = MIRROR_VERT | ROTATECW_270;
break;
case ORIENTATION_LEFTBOT:
image->adjustments = ROTATECW_270;
break;
default:
image->adjustments = 0;
image->orientation = ORIENTATION_TOPLEFT;
}
if ((bps == 0) || (spp == 0))
{
TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)",
spp, bps);
return (-1);
}
if (TIFFIsTiled(in))
{
readunit = TILE;
tlsize = TIFFTileSize(in);
ntiles = TIFFNumberOfTiles(in);
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
tile_rowsize = TIFFTileRowSize(in);
if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
{
TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
exit(-1);
}
buffsize = tlsize * ntiles;
if (tlsize != (buffsize / ntiles))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
if (buffsize < (uint32)(ntiles * tl * tile_rowsize))
{
buffsize = ntiles * tl * tile_rowsize;
if (ntiles != (buffsize / tl / tile_rowsize))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
#ifdef DEBUG2
TIFFError("loadImage",
"Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu",
tlsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Tilesize: %u, Number of Tiles: %u, Tile row size: %u",
tlsize, ntiles, tile_rowsize);
}
else
{
uint32 buffsize_check;
readunit = STRIP;
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
stsize = TIFFStripSize(in);
nstrips = TIFFNumberOfStrips(in);
if (nstrips == 0 || stsize == 0)
{
TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
exit(-1);
}
buffsize = stsize * nstrips;
if (stsize != (buffsize / nstrips))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
buffsize_check = ((length * width * spp * bps) + 7);
if (length != ((buffsize_check - 7) / width / spp / bps))
{
TIFFError("loadImage", "Integer overflow detected.");
exit(-1);
}
if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8))
{
buffsize = ((length * width * spp * bps) + 7) / 8;
#ifdef DEBUG2
TIFFError("loadImage",
"Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu",
stsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u",
stsize, nstrips, rowsperstrip, scanlinesize);
}
if (input_compression == COMPRESSION_JPEG)
{ /* Force conversion to RGB */
jpegcolormode = JPEGCOLORMODE_RGB;
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
/* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
else
{ /* Otherwise, can't handle subsampled input */
if (input_photometric == PHOTOMETRIC_YCBCR)
{
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsampling_horiz, &subsampling_vert);
if (subsampling_horiz != 1 || subsampling_vert != 1)
{
TIFFError("loadImage",
"Can't copy/convert subsampled image with subsampling %d horiz %d vert",
subsampling_horiz, subsampling_vert);
return (-1);
}
}
}
read_buff = *read_ptr;
/* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
/* outside buffer */
if (!read_buff)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
{
if (prev_readsize < buffsize)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
new_buff = _TIFFrealloc(read_buff, buffsize+3);
if (!new_buff)
{
free (read_buff);
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
read_buff = new_buff;
}
}
if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff[buffsize] = 0;
read_buff[buffsize+1] = 0;
read_buff[buffsize+2] = 0;
prev_readsize = buffsize;
*read_ptr = read_buff;
/* N.B. The read functions used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
*/
switch (readunit) {
case STRIP:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigStripsIntoBuffer(in, read_buff)))
{
TIFFError("loadImage", "Unable to read contiguous strips into buffer");
return (-1);
}
}
else
{
if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
{
TIFFError("loadImage", "Unable to read separate strips into buffer");
return (-1);
}
}
break;
case TILE:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
return (-1);
}
}
else
{
if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read separate tiles into buffer");
return (-1);
}
}
break;
default: TIFFError("loadImage", "Unsupported image file format");
return (-1);
break;
}
if ((dump->infile != NULL) && (dump->level == 2))
{
dump_info (dump->infile, dump->format, "loadImage",
"Image width %d, length %d, Raw image data, %4d bytes",
width, length, buffsize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d", bps, spp);
for (i = 0; i < length; i++)
dump_buffer(dump->infile, dump->format, 1, scanlinesize,
i, read_buff + (i * scanlinesize));
}
return (0);
} /* end loadImage */
static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr)
{
uint16 mirror, rotation;
unsigned char *work_buff;
work_buff = *work_buff_ptr;
if ((image == NULL) || (work_buff == NULL))
{
TIFFError ("correct_orientatin", "Invalid image or buffer pointer");
return (-1);
}
if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT))
{
mirror = (uint16)(image->adjustments & MIRROR_BOTH);
if (mirrorImage(image->spp, image->bps, mirror,
image->width, image->length, work_buff))
{
TIFFError ("correct_orientation", "Unable to mirror image");
return (-1);
}
}
if (image->adjustments & ROTATE_ANY)
{
if (image->adjustments & ROTATECW_90)
rotation = (uint16) 90;
else
if (image->adjustments & ROTATECW_180)
rotation = (uint16) 180;
else
if (image->adjustments & ROTATECW_270)
rotation = (uint16) 270;
else
{
TIFFError ("correct_orientation", "Invalid rotation value: %d",
image->adjustments & ROTATE_ANY);
return (-1);
}
if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr))
{
TIFFError ("correct_orientation", "Unable to rotate image");
return (-1);
}
image->orientation = ORIENTATION_TOPLEFT;
}
return (0);
} /* end correct_orientation */
/* Extract multiple zones from an image and combine into a single composite image */
static int
extractCompositeRegions(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 i, trailing_bits, prev_trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_rowsize, dst_rowsize, src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint32 prev_length, prev_width, composite_width;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract one or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src = read_buff;
dst = crop_buff;
/* These are setup for adding additional sections */
prev_width = prev_length = 0;
prev_trailing_bits = trailing_bits = 0;
composite_width = crop->combined_width;
crop->combined_width = 0;
crop->combined_length = 0;
for (i = 0; i < crop->selections; i++)
{
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[i].y1;
last_row = crop->regionlist[i].y2;
first_col = crop->regionlist[i].x1;
last_col = crop->regionlist[i].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
/* These should not be needed for composite images */
crop->regionlist[i].width = crop_width;
crop->regionlist[i].length = crop_length;
crop->regionlist[i].buffptr = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * count) + 7) / 8);
switch (crop->edge_ref)
{
default:
case EDGE_TOP:
case EDGE_BOTTOM:
if ((i > 0) && (crop_width != crop->regionlist[i - 1].width))
{
TIFFError ("extractCompositeRegions",
"Only equal width regions can be combined for -E top or bottom");
return (1);
}
crop->combined_width = crop_width;
crop->combined_length += crop_length;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + (prev_length * dst_rowsize);
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_length += crop_length;
break;
case EDGE_LEFT: /* splice the pieces of each row together, side by side */
case EDGE_RIGHT:
if ((i > 0) && (crop_length != crop->regionlist[i - 1].length))
{
TIFFError ("extractCompositeRegions",
"Only equal length regions can be combined for -E left or right");
return (1);
}
crop->combined_width += crop_width;
crop->combined_length = crop_length;
dst_rowsize = (((composite_width * bps * count) + 7) / 8);
trailing_bits = (crop_width * bps * count) % 8;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + prev_width;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_width += (crop_width * bps * count) / 8;
prev_trailing_bits += trailing_bits;
if (prev_trailing_bits > 7)
prev_trailing_bits-= 8;
break;
}
}
if (crop->combined_width != composite_width)
TIFFError("combineSeparateRegions","Combined width does not match composite width");
return (0);
} /* end extractCompositeRegions */
/* Copy a single region of input buffer to an output buffer.
* The read functions used copy separate plane data into a buffer
* as interleaved samples rather than separate planes so the same
* logic works to extract regions regardless of the way the data
* are organized in the input file. This function can be used to
* extract one or more samples from the input image by updating the
* parameters for starting sample and number of samples to copy in the
* fifth and eighth arguments of the call to extractContigSamples.
* They would be passed as new elements of the crop_mask struct.
*/
static int
extractSeparateRegion(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff,
int region)
{
int shift_width, prev_trailing_bits = 0;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, dst_rowsize;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract more or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0; /* Byte aligned data only */
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[region].y1;
last_row = crop->regionlist[region].y2;
first_col = crop->regionlist[region].x1;
last_col = crop->regionlist[region].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
crop->regionlist[region].width = crop_width;
crop->regionlist[region].length = crop_length;
crop->regionlist[region].buffptr = crop_buff;
src = read_buff;
dst = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * spp) + 7) / 8);
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps);
return (1);
}
}
return (0);
} /* end extractSeparateRegion */
static int
extractImageSection(struct image_data *image, struct pageseg *section,
unsigned char *src_buff, unsigned char *sect_buff)
{
unsigned char bytebuff1, bytebuff2;
#ifdef DEVELMODE
/* unsigned char *src, *dst; */
#endif
uint32 img_width, img_rowsize;
#ifdef DEVELMODE
uint32 img_length;
#endif
uint32 j, shift1, shift2, trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset, row_offset, col_offset;
uint32 offset1, offset2, full_bytes;
uint32 sect_width;
#ifdef DEVELMODE
uint32 sect_length;
#endif
uint16 bps, spp;
#ifdef DEVELMODE
int k;
unsigned char bitset;
static char *bitarray = NULL;
#endif
img_width = image->width;
#ifdef DEVELMODE
img_length = image->length;
#endif
bps = image->bps;
spp = image->spp;
#ifdef DEVELMODE
/* src = src_buff; */
/* dst = sect_buff; */
#endif
src_offset = 0;
dst_offset = 0;
#ifdef DEVELMODE
if (bitarray == NULL)
{
if ((bitarray = (char *)malloc(img_width)) == NULL)
{
TIFFError ("", "DEBUG: Unable to allocate debugging bitarray");
return (-1);
}
}
#endif
/* rows, columns, width, length are expressed in pixels */
first_row = section->y1;
last_row = section->y2;
first_col = section->x1;
last_col = section->x2;
sect_width = last_col - first_col + 1;
#ifdef DEVELMODE
sect_length = last_row - first_row + 1;
#endif
img_rowsize = ((img_width * bps + 7) / 8) * spp;
full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */
trailing_bits = (sect_width * bps) % 8;
#ifdef DEVELMODE
TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n",
first_row, last_row, first_col, last_col);
TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n",
img_width, img_length, bps, spp);
TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n",
sect_width, sect_length, full_bytes, trailing_bits);
#endif
if ((bps % 8) == 0)
{
col_offset = first_col * spp * bps / 8;
for (row = first_row; row <= last_row; row++)
{
/* row_offset = row * img_width * spp * bps / 8; */
row_offset = row * img_rowsize;
src_offset = row_offset + col_offset;
#ifdef DEVELMODE
TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset);
#endif
_TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes);
dst_offset += full_bytes;
}
}
else
{ /* bps != 8 */
shift1 = spp * ((first_col * bps) % 8);
shift2 = spp * ((last_col * bps) % 8);
for (row = first_row; row <= last_row; row++)
{
/* pull out the first byte */
row_offset = row * img_rowsize;
offset1 = row_offset + (first_col * bps / 8);
offset2 = row_offset + (last_col * bps / 8);
#ifdef DEVELMODE
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
sprintf(&bitarray[8], " ");
sprintf(&bitarray[9], " ");
for (j = 10, k = 7; j < 18; j++, k--)
{
bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[18] = '\0';
TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n",
row, offset1, shift1, offset2, shift2);
#endif
bytebuff1 = bytebuff2 = 0;
if (shift1 == 0) /* the region is byte and sample alligned */
{
_TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes);
#ifdef DEVELMODE
TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset);
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2));
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n",
offset2, dst_offset);
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
else /* each destination byte will have to be built from two source bytes*/
{
#ifdef DEVELMODE
TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset);
#endif
for (j = 0; j <= full_bytes; j++)
{
bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1);
bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1));
sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1));
}
#ifdef DEVELMODE
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset);
#endif
if (shift2 > shift1)
{
bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2));
bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1);
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Shift2 > Shift1\n");
#endif
}
else
{
if (shift2 < shift1)
{
bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1));
sect_buff[dst_offset] &= bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Shift2 < Shift1\n");
#endif
}
#ifdef DEVELMODE
else
TIFFError ("", " Shift2 == Shift1\n");
#endif
}
}
#ifdef DEVELMODE
sprintf(&bitarray[28], " ");
sprintf(&bitarray[29], " ");
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
}
return (0);
} /* end extractImageSection */
static int
writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop,
struct image_data *image, struct dump_opts *dump,
struct buffinfo seg_buffs[], char *mp, char *filename,
unsigned int *page, unsigned int total_pages)
{
int i, page_count;
int autoindex = 0;
unsigned char *crop_buff = NULL;
/* Where we open a new file depends on the export mode */
switch (crop->exp_mode)
{
case ONE_FILE_COMPOSITE: /* Regions combined into single image */
autoindex = 0;
crop_buff = seg_buffs[0].buffer;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = total_pages;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case ONE_FILE_SEPARATED: /* Regions as separated images */
autoindex = 0;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = crop->selections * total_pages;
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */
autoindex = 1;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[0].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */
autoindex = 1;
page_count = crop->selections;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_SELECTION:
autoindex = 1;
page_count = 1;
for (i = 0; i < crop->selections; i++)
{
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
default: return (1);
}
return (0);
} /* end writeRegions */
static int
writeImageSections(TIFF *in, TIFF *out, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts * dump, unsigned char *src_buff,
unsigned char **sect_buff_ptr)
{
double hres, vres;
uint32 i, k, width, length, sectsize;
unsigned char *sect_buff = *sect_buff_ptr;
hres = page->hres;
vres = page->vres;
k = page->cols * page->rows;
if ((k < 1) || (k > MAX_SECTIONS))
{
TIFFError("writeImageSections",
"%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k);
return (-1);
}
for (i = 0; i < k; i++)
{
width = sections[i].x2 - sections[i].x1 + 1;
length = sections[i].y2 - sections[i].y1 + 1;
sectsize = (uint32)
ceil((width * image->bps + 7) / (double)8) * image->spp * length;
/* allocate a buffer if we don't have one already */
if (createImageSection(sectsize, sect_buff_ptr))
{
TIFFError("writeImageSections", "Unable to allocate section buffer");
exit (-1);
}
sect_buff = *sect_buff_ptr;
if (extractImageSection (image, §ions[i], src_buff, sect_buff))
{
TIFFError("writeImageSections", "Unable to extract image sections");
exit (-1);
}
/* call the write routine here instead of outside the loop */
if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff))
{
TIFFError("writeImageSections", "Unable to write image section");
exit (-1);
}
}
return (0);
} /* end writeImageSections */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
*/
static int
writeSingleSection(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
double hres, double vres,
unsigned char *sect_buff)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
/* Calling this seems to reset the compression mode on the TIFF *in file.
TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode);
*/
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
/* This is the global variable compression which is set
* if the user has specified a command line option for
* a compression option. Should be passed around in one
* of the parameters instead of as a global. If no user
* option specified it will still be (uint16) -1. */
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{ /* OJPEG is no longer supported for writing so upgrade to JPEG */
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else /* Use the compression from the input file */
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */
{
TIFFError ("writeSingleSection",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input photometric: %s",
(input_photometric == PHOTOMETRIC_RGB) ? "RGB" :
((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr"));
#endif
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeSingleSection",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
/* These are references to GLOBAL variables set by defaults
* and /or the compression flag
*/
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeSingleSection",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += (strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
if (pageNum < 0) /* only one input file */
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Update these since they are overwritten from input res by loop above */
TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres);
TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigTiles (out, sect_buff, length, width, spp, dump);
else
writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump);
}
else
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigStrips (out, sect_buff, length);
else
writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump);
}
if (!TIFFWriteDirectory(out))
{
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeSingleSection */
/* Create a buffer to write one section at a time */
static int
createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr)
{
unsigned char *sect_buff = NULL;
unsigned char *new_buff = NULL;
static uint32 prev_sectsize = 0;
sect_buff = *sect_buff_ptr;
if (!sect_buff)
{
sect_buff = (unsigned char *)_TIFFmalloc(sectsize);
*sect_buff_ptr = sect_buff;
_TIFFmemset(sect_buff, 0, sectsize);
}
else
{
if (prev_sectsize < sectsize)
{
new_buff = _TIFFrealloc(sect_buff, sectsize);
if (!new_buff)
{
free (sect_buff);
sect_buff = (unsigned char *)_TIFFmalloc(sectsize);
}
else
sect_buff = new_buff;
_TIFFmemset(sect_buff, 0, sectsize);
}
}
if (!sect_buff)
{
TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
return (-1);
}
prev_sectsize = sectsize;
*sect_buff_ptr = sect_buff;
return (0);
} /* end createImageSection */
/* Process selections defined by regions, zones, margins, or fixed sized areas */
static int
processCropSelections(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, struct buffinfo seg_buffs[])
{
int i;
uint32 width, length, total_width, total_length;
tsize_t cropsize;
unsigned char *crop_buff = NULL;
unsigned char *read_buff = NULL;
unsigned char *next_buff = NULL;
tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
if (crop->img_mode == COMPOSITE_IMAGES)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[0].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize);
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = cropsize;
/* Checks for matching width or length as required */
if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0)
return (1);
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for composite regions");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
/* Mirror and Rotate will not work with multiple regions unless they are the same width */
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror composite regions %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, &crop_buff))
{
TIFFError("processCropSelections",
"Failed to rotate composite regions by %d degrees", crop->rotation);
return (-1);
}
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8)
* image->spp) * crop->combined_length;
}
}
else /* Separated Images */
{
total_width = total_length = 0;
for (i = 0; i < crop->selections; i++)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[i].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize);
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = cropsize;
if (extractSeparateRegion(image, crop, read_buff, crop_buff, i))
{
TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i);
return (-1);
}
width = crop->regionlist[i].width;
length = crop->regionlist[i].length;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
width, length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for region");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
width, length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror crop region %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->regionlist[i].width,
&crop->regionlist[i].length, &crop_buff))
{
TIFFError("processCropSelections",
"Failed to rotate crop region by %d degrees", crop->rotation);
return (-1);
}
total_width += crop->regionlist[i].width;
total_length += crop->regionlist[i].length;
crop->combined_width = total_width;
crop->combined_length = total_length;
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8)
* image->spp) * crop->regionlist[i].length;
}
}
}
return (0);
} /* end processCropSelections */
/* Copy the crop section of the data from the current image into a buffer
* and adjust the IFD values to reflect the new size. If no cropping is
* required, use the origial read buffer as the crop buffer.
*
* There is quite a bit of redundancy between this routine and the more
* specialized processCropSelections, but this provides
* the most optimized path when no Zones or Regions are required.
*/
static int
createCroppedImage(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr)
{
tsize_t cropsize;
unsigned char *read_buff = NULL;
unsigned char *crop_buff = NULL;
unsigned char *new_buff = NULL;
static tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
/* process full image, no crop buffer needed */
crop_buff = read_buff;
*crop_buff_ptr = read_buff;
crop->combined_width = image->width;
crop->combined_length = image->length;
cropsize = crop->bufftotal;
crop_buff = *crop_buff_ptr;
if (!crop_buff)
{
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
*crop_buff_ptr = crop_buff;
_TIFFmemset(crop_buff, 0, cropsize);
prev_cropsize = cropsize;
}
else
{
if (prev_cropsize < cropsize)
{
new_buff = _TIFFrealloc(crop_buff, cropsize);
if (!new_buff)
{
free (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = new_buff;
_TIFFmemset(crop_buff, 0, cropsize);
}
}
if (!crop_buff)
{
TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
return (-1);
}
*crop_buff_ptr = crop_buff;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage",
"Failed to invert colorspace for image or cropped selection");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, crop_buff_ptr))
{
TIFFError("createCroppedImage",
"Failed to rotate image or cropped selection by %d degrees", crop->rotation);
return (-1);
}
}
if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */
*read_buff_ptr = NULL; /* so we don't try to free it later */
return (0);
} /* end createCroppedImage */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
* Use of global variables for config, compression and others
* should be replaced by addition to the crop_mask struct (which
* will be renamed to proc_opts indicating that is controlls
* user supplied processing options, not just cropping) and
* then passed in as an argument.
*/
static int
writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
unsigned char *crop_buff, int pagenum, int total_pages)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeCroppedImage", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */
{
TIFFError ("writeCroppedImage",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
{
if (input_compression == COMPRESSION_SGILOG ||
input_compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
}
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeCroppedImage",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeCroppedImage",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (bps != 1)
{
TIFFError("writeCroppedImage",
"Group 3/4 compression is not usable with bps > 1");
return (-1);
}
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
case COMPRESSION_NONE:
break;
default: break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += (strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write contiguous tile data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate tile data for page %d", pagenum);
}
}
else
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigStrips (out, crop_buff, length))
TIFFError("","Unable to write contiguous strip data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate strip data for page %d", pagenum);
}
}
if (!TIFFWriteDirectory(out))
{
TIFFError("","Failed to write IFD for page number %d", pagenum);
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeCroppedImage */
static int
rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 src_byte = 0, src_bit = 0;
uint32 row, rowsize = 0, bit_offset = 0;
uint8 matchbits = 0, maskbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples8bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length ; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*next) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end rotateContigSamples8bits */
static int
rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint16 matchbits = 0, maskbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples16bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 8) | next[1];
else
buff1 = (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end rotateContigSamples16bits */
static int
rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 matchbits = 0, maskbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint32)-1 >> (32 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
else
buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples24bits */
static int
rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 row, rowsize, bit_offset;
uint32 src_byte, src_bit;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint64)-1 >> (64 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples32bits */
/* Rotate an image by a multiple of 90 degrees clockwise */
static int
rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width,
uint32 *img_length, unsigned char **ibuff_ptr)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, src_offset, dst_offset;
uint32 i, col, width, length;
uint32 colsize, buffsize, col_offset, pix_offset;
unsigned char *ibuff;
unsigned char *src;
unsigned char *dst;
uint16 spp, bps;
float res_temp;
unsigned char *rbuff = NULL;
width = *img_width;
length = *img_length;
spp = image->spp;
bps = image->bps;
rowsize = ((bps * spp * width) + 7) / 8;
colsize = ((bps * spp * length) + 7) / 8;
if ((colsize * width) > (rowsize * length))
buffsize = (colsize + 1) * width;
else
buffsize = (rowsize + 1) * length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (rotation)
{
case 0:
case 360: return (0);
case 90:
case 180:
case 270: break;
default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation);
return (-1);
}
if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize)))
{
TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize);
return (-1);
}
_TIFFmemset(rbuff, '\0', buffsize);
ibuff = *ibuff_ptr;
switch (rotation)
{
case 180: if ((bps % 8) == 0) /* byte alligned data */
{
src = ibuff;
pix_offset = (spp * bps) / 8;
for (row = 0; row < length; row++)
{
dst_offset = (length - row - 1) * rowsize;
for (col = 0; col < width; col++)
{
col_offset = (width - col - 1) * pix_offset;
dst = rbuff + dst_offset + col_offset;
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *src++;
}
}
}
else
{ /* non 8 bit per sample data */
for (row = 0; row < length; row++)
{
src_offset = row * rowsize;
dst_offset = (length - row - 1) * rowsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (reverseSamples8bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (reverseSamples16bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
break;
case 90: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel);
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src -= rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = (length - 1) * rowsize;
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
break;
case 270: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = col * bytes_per_pixel;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src += rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = 0;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
break;
default:
break;
}
return (0);
} /* end rotateImage */
static int
reverseSamples8bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte, src_bit;
uint32 bit_offset = 0;
uint8 match_bits = 0, mask_bits = 0;
uint8 buff1 = 0, buff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples8bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint8)-1 >> ( 8 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (8 - src_bit - bps);
buff1 = ((*src) & match_bits) << (src_bit);
if (ready_bits < 8)
buff2 = (buff2 | (buff1 >> ready_bits));
else /* If we have a full buffer's worth, write it out */
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end reverseSamples8bits */
static int
reverseSamples16bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint16 match_bits = 0, mask_bits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSample16bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint16)-1 >> (16 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (16 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 8)
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end reverseSamples16bits */
static int
reverseSamples24bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint32 match_bits = 0, mask_bits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples24bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint32)-1 >> (32 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (32 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 16)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end reverseSamples24bits */
static int
reverseSamples32bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 bit_offset;
uint32 src_byte = 0, high_bit = 0;
uint32 col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 mask_bits = 0, match_bits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples32bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint64)-1 >> (64 - bps);
dst = obuff;
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (64 - high_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & match_bits) << (high_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end reverseSamples32bits */
static int
reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
/* Mirror an image horizontally or vertically */
static int
mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, row_offset;
unsigned char *line_buff = NULL;
unsigned char *src;
unsigned char *dst;
src = ibuff;
rowsize = ((width * bps * spp) + 7) / 8;
switch (mirror)
{
case MIRROR_BOTH:
case MIRROR_VERT:
line_buff = (unsigned char *)_TIFFmalloc(rowsize);
if (line_buff == NULL)
{
TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize);
return (-1);
}
dst = ibuff + (rowsize * (length - 1));
for (row = 0; row < length / 2; row++)
{
_TIFFmemcpy(line_buff, src, rowsize);
_TIFFmemcpy(src, dst, rowsize);
_TIFFmemcpy(dst, line_buff, rowsize);
src += (rowsize);
dst -= (rowsize);
}
if (line_buff)
_TIFFfree(line_buff);
if (mirror == MIRROR_VERT)
break;
case MIRROR_HORIZ :
if ((bps % 8) == 0) /* byte alligned data */
{
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
dst = ibuff + row_offset + rowsize;
if (reverseSamplesBytes(spp, bps, width, src, dst))
{
return (-1);
}
}
}
else
{ /* non 8 bit per sample data */
if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1)))
{
TIFFError("mirrorImage", "Unable to allocate mirror line buffer");
return (-1);
}
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
_TIFFmemset (line_buff, '\0', rowsize);
switch (shift_width)
{
case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
default: TIFFError("mirrorImage","Unsupported bit depth %d", bps);
_TIFFfree(line_buff);
return (-1);
}
}
if (line_buff)
_TIFFfree(line_buff);
}
break;
default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror);
return (-1);
break;
}
return (0);
}
/* Invert the light and dark values for a bilevel or grayscale image */
static int
invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff)
{
uint32 row, col;
unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4;
unsigned char *src;
uint16 *src_uint16;
uint32 *src_uint32;
if (spp != 1)
{
TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel");
return (-1);
}
if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK)
{
TIFFError("invertImage", "Only black and white and grayscale images can be inverted");
return (-1);
}
src = work_buff;
if (src == NULL)
{
TIFFError ("invertImage", "Invalid crop buffer passed to invertImage");
return (-1);
}
switch (bps)
{
case 32: src_uint32 = (uint32 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint32 = (uint32)0xFFFFFFFF - *src_uint32;
src_uint32++;
}
break;
case 16: src_uint16 = (uint16 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint16 = (uint16)0xFFFF - *src_uint16;
src_uint16++;
}
break;
case 8: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src = (uint8)255 - *src;
src++;
}
break;
case 4: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
bytebuff1 = 16 - (uint8)(*src & 240 >> 4);
bytebuff2 = 16 - (*src & 15);
*src = bytebuff1 << 4 & bytebuff2;
src++;
}
break;
case 2: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
bytebuff1 = 4 - (uint8)(*src & 192 >> 6);
bytebuff2 = 4 - (uint8)(*src & 48 >> 4);
bytebuff3 = 4 - (uint8)(*src & 12 >> 2);
bytebuff4 = 4 - (uint8)(*src & 3);
*src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4;
src++;
}
break;
case 1: for (row = 0; row < length; row++)
for (col = 0; col < width; col += 8 /(spp * bps))
{
*src = ~(*src);
src++;
}
break;
default: TIFFError("invertImage", "Unsupported bit depth %d", bps);
return (-1);
}
return (0);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4798_1 |
crossvul-cpp_data_bad_5353_1 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* Quadrature Mirror-Image Filter Bank (QMFB) Library
*
* $Id$
*/
/******************************************************************************\
*
\******************************************************************************/
#undef WT_LENONE /* This is not needed due to normalization. */
#define WT_DOSCALE
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <assert.h>
#include "jasper/jas_fix.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_math.h"
#include "jpc_qmfb.h"
#include "jpc_tsfb.h"
#include "jpc_math.h"
/******************************************************************************\
*
\******************************************************************************/
#define QMFB_SPLITBUFSIZE 4096
#define QMFB_JOINBUFSIZE 4096
int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
int stride);
int jpc_ft_synthesize(jpc_fix_t *a, int xstart, int ystart, int width, int height,
int stride);
int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
int stride);
int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
int height, int stride);
void jpc_ft_fwdlift_row(jpc_fix_t *a, int numcols, int parity);
void jpc_ft_fwdlift_col(jpc_fix_t *a, int numrows, int stride,
int parity);
void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity);
void jpc_ft_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity);
void jpc_ft_invlift_row(jpc_fix_t *a, int numcols, int parity);
void jpc_ft_invlift_col(jpc_fix_t *a, int numrows, int stride,
int parity);
void jpc_ft_invlift_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity);
void jpc_ft_invlift_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity);
void jpc_ns_fwdlift_row(jpc_fix_t *a, int numcols, int parity);
void jpc_ns_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
void jpc_ns_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
int parity);
void jpc_ns_invlift_row(jpc_fix_t *a, int numcols, int parity);
void jpc_ns_invlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
void jpc_ns_invlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
int parity);
void jpc_qmfb_split_row(jpc_fix_t *a, int numcols, int parity);
void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride, int parity);
void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
int parity);
void jpc_qmfb_join_row(jpc_fix_t *a, int numcols, int parity);
void jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride, int parity);
void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity);
void jpc_qmfb_join_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
int parity);
double jpc_ft_lpenergywts[32] = {
1.2247448713915889,
1.6583123951776999,
2.3184046238739260,
3.2691742076555053,
4.6199296531440819,
6.5323713152269596,
9.2377452606141937,
13.0639951297449581,
18.4752262333915667,
26.1278968190610392,
36.9504194305524791,
52.2557819580462777,
73.9008347315741645,
104.5115624560829133,
147.8016689469569656,
209.0231247296646018,
295.6033378293900000,
418.0462494347059419,
591.2066756503630813,
836.0924988714708661,
/* approximations */
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661,
836.0924988714708661
};
double jpc_ft_hpenergywts[32] = {
0.8477912478906585,
0.9601432184835760,
1.2593401049756179,
1.7444107171191079,
2.4538713036750726,
3.4656517695088755,
4.8995276398597856,
6.9283970402160842,
9.7980274940131444,
13.8564306871112652,
19.5959265076535587,
27.7128159494245487,
39.1918369552045860,
55.4256262207444053,
78.3836719028959124,
110.8512517317256822,
156.7673435548526868,
221.7025033739244293,
313.5346870787551552,
443.4050067351659550,
/* approximations */
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550,
443.4050067351659550
};
double jpc_ns_lpenergywts[32] = {
1.4021081679297411,
2.0303718560817923,
2.9011625562785555,
4.1152851751758002,
5.8245108637728071,
8.2387599345725171,
11.6519546479210838,
16.4785606470644375,
23.3042776444606794,
32.9572515613740435,
46.6086013487782793,
65.9145194076860861,
93.2172084551803977,
131.8290408510004283,
186.4344176300625691,
263.6580819564562148,
372.8688353500955373,
527.3161639447193920,
745.7376707114038936,
1054.6323278917823245,
/* approximations follow */
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245,
1054.6323278917823245
};
double jpc_ns_hpenergywts[32] = {
1.4425227650161456,
1.9669426082455688,
2.8839248082788891,
4.1475208393432981,
5.8946497530677817,
8.3471789178590949,
11.8086046551047463,
16.7012780415647804,
23.6196657032246620,
33.4034255108592362,
47.2396388881632632,
66.8069597416714061,
94.4793162154500692,
133.6139330736999113,
188.9586372358249378,
267.2278678461869390,
377.9172750722391356,
534.4557359047058753,
755.8345502191498326,
1068.9114718353569060,
/* approximations follow */
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060,
1068.9114718353569060
};
jpc_qmfb2d_t jpc_ft_qmfb2d = {
jpc_ft_analyze,
jpc_ft_synthesize,
jpc_ft_lpenergywts,
jpc_ft_hpenergywts
};
jpc_qmfb2d_t jpc_ns_qmfb2d = {
jpc_ns_analyze,
jpc_ns_synthesize,
jpc_ns_lpenergywts,
jpc_ns_hpenergywts
};
/******************************************************************************\
* generic
\******************************************************************************/
void jpc_qmfb_split_row(jpc_fix_t *a, int numcols, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numcols, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
jpc_fix_t *buf = splitbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
register int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numcols >= 2) {
hstartcol = (numcols + 1 - parity) >> 1;
// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numcols - hstartcol);
m = numcols - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[1 - parity];
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
srcptr += 2;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[1 - parity];
srcptr = &a[2 - parity];
n = numcols - m - (!parity);
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
srcptr += 2;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol];
srcptr = buf;
n = m;
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
++srcptr;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
jpc_fix_t *buf = splitbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
register int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
*dstptr = *srcptr;
++dstptr;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
++srcptr;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += JPC_QMFB_COLGRPSIZE;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
// ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol);
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += numcols;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += numcols;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
void jpc_qmfb_join_row(jpc_fix_t *a, int numcols, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numcols, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
jpc_fix_t *buf = joinbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numcols + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
*dstptr = *srcptr;
++srcptr;
++dstptr;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol];
dstptr = &a[1 - parity];
n = numcols - hstartcol;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += 2;
++srcptr;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity];
n = hstartcol;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += 2;
++srcptr;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
void jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE];
jpc_fix_t *buf = joinbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
*dstptr = *srcptr;
srcptr += stride;
++dstptr;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += 2 * stride;
++srcptr;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = joinbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
srcptr += stride;
dstptr += JPC_QMFB_COLGRPSIZE;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
void jpc_qmfb_join_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = joinbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int hstartcol;
/* Allocate memory for the join buffer from the heap. */
if (bufsize > QMFB_JOINBUFSIZE) {
if (!(buf = jas_alloc3(bufsize, numcols, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide. */
abort();
}
}
hstartcol = (numrows + 1 - parity) >> 1;
/* Save the samples from the lowpass channel. */
n = hstartcol;
srcptr = &a[0];
dstptr = buf;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
srcptr += stride;
dstptr += numcols;
}
/* Copy the samples from the highpass channel into place. */
srcptr = &a[hstartcol * stride];
dstptr = &a[(1 - parity) * stride];
n = numrows - hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += stride;
}
/* Copy the samples from the lowpass channel into place. */
srcptr = buf;
dstptr = &a[parity * stride];
n = hstartcol;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += 2 * stride;
srcptr += numcols;
}
/* If the join buffer was allocated on the heap, free this memory. */
if (buf != joinbuf) {
jas_free(buf);
}
}
/******************************************************************************\
* 5/3 transform
\******************************************************************************/
void jpc_ft_fwdlift_row(jpc_fix_t *a, int numcols, int parity)
{
register jpc_fix_t *lptr;
register jpc_fix_t *hptr;
register int n;
int llen;
llen = (numcols + 1 - parity) >> 1;
if (numcols > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (parity) {
hptr[0] -= lptr[0];
++hptr;
}
n = numcols - llen - parity - (parity == (numcols & 1));
while (n-- > 0) {
//hptr[0] -= (lptr[0] + lptr[1]) >> 1;
hptr[0] -= jpc_fix_asr(lptr[0] + lptr[1], 1);
++hptr;
++lptr;
}
if (parity == (numcols & 1)) {
hptr[0] -= lptr[0];
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (!parity) {
//lptr[0] += (hptr[0] + 1) >> 1;
lptr[0] += jpc_fix_asr(hptr[0] + 1, 1);
++lptr;
}
n = llen - (!parity) - (parity != (numcols & 1));
while (n-- > 0) {
//lptr[0] += (hptr[0] + hptr[1] + 2) >> 2;
lptr[0] += jpc_fix_asr(hptr[0] + hptr[1] + 2, 2);
++lptr;
++hptr;
}
if (parity != (numcols & 1)) {
//lptr[0] += (hptr[0] + 1) >> 1;
lptr[0] += jpc_fix_asr(hptr[0] + 1, 1);
}
} else {
if (parity) {
lptr = &a[0];
//lptr[0] <<= 1;
lptr[0] = jpc_fix_asl(lptr[0], 1);
}
}
}
void jpc_ft_fwdlift_col(jpc_fix_t *a, int numrows, int stride, int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
#if 0
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int i;
#endif
register int n;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
hptr[0] -= lptr[0];
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
//hptr[0] -= (lptr[0] + lptr[stride]) >> 1;
hptr[0] -= jpc_fix_asr(lptr[0] + lptr[stride], 1);
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
hptr[0] -= lptr[0];
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
//lptr[0] += (hptr[0] + 1) >> 1;
lptr[0] += jpc_fix_asr(hptr[0] + 1, 1);
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
//lptr[0] += (hptr[0] + hptr[stride] + 2) >> 2;
lptr[0] += jpc_fix_asr(hptr[0] + hptr[stride] + 2, 2);
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
//lptr[0] += (hptr[0] + 1) >> 1;
lptr[0] += jpc_fix_asr(hptr[0] + 1, 1);
}
} else {
if (parity) {
lptr = &a[0];
//lptr[0] <<= 1;
lptr[0] = jpc_fix_asl(lptr[0], 1);
}
}
}
void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
hptr2[0] -= lptr2[0];
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//hptr2[0] -= (lptr2[0] + lptr2[stride]) >> 1;
hptr2[0] -= jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
hptr2[0] -= lptr2[0];
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] += (hptr2[0] + 1) >> 1;
lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] += (hptr2[0] + hptr2[stride] + 2) >> 2;
lptr2[0] += jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] += (hptr2[0] + 1) >> 1;
lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
}
} else {
if (parity) {
lptr2 = &a[0];
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] <<= 1;
lptr2[0] = jpc_fix_asl(lptr2[0], 1);
++lptr2;
}
}
}
}
void jpc_ft_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
hptr2[0] -= lptr2[0];
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//hptr2[0] -= (lptr2[0] + lptr2[stride]) >> 1;
hptr2[0] -= jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
hptr2[0] -= lptr2[0];
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//lptr2[0] += (hptr2[0] + 1) >> 1;
lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//lptr2[0] += (hptr2[0] + hptr2[stride] + 2) >> 2;
lptr2[0] += jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//lptr2[0] += (hptr2[0] + 1) >> 1;
lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
}
} else {
if (parity) {
lptr2 = &a[0];
for (i = 0; i < numcols; ++i) {
//lptr2[0] <<= 1;
lptr2[0] = jpc_fix_asl(lptr2[0], 1);
++lptr2;
}
}
}
}
void jpc_ft_invlift_row(jpc_fix_t *a, int numcols, int parity)
{
register jpc_fix_t *lptr;
register jpc_fix_t *hptr;
register int n;
int llen;
llen = (numcols + 1 - parity) >> 1;
if (numcols > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (!parity) {
//lptr[0] -= (hptr[0] + 1) >> 1;
lptr[0] -= jpc_fix_asr(hptr[0] + 1, 1);
++lptr;
}
n = llen - (!parity) - (parity != (numcols & 1));
while (n-- > 0) {
//lptr[0] -= (hptr[0] + hptr[1] + 2) >> 2;
lptr[0] -= jpc_fix_asr(hptr[0] + hptr[1] + 2, 2);
++lptr;
++hptr;
}
if (parity != (numcols & 1)) {
//lptr[0] -= (hptr[0] + 1) >> 1;
lptr[0] -= jpc_fix_asr(hptr[0] + 1, 1);
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (parity) {
hptr[0] += lptr[0];
++hptr;
}
n = numcols - llen - parity - (parity == (numcols & 1));
while (n-- > 0) {
//hptr[0] += (lptr[0] + lptr[1]) >> 1;
hptr[0] += jpc_fix_asr(lptr[0] + lptr[1], 1);
++hptr;
++lptr;
}
if (parity == (numcols & 1)) {
hptr[0] += lptr[0];
}
} else {
if (parity) {
lptr = &a[0];
//lptr[0] >>= 1;
lptr[0] = jpc_fix_asr(lptr[0], 1);
}
}
}
void jpc_ft_invlift_col(jpc_fix_t *a, int numrows, int stride, int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
#if 0
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int i;
#endif
register int n;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
//lptr[0] -= (hptr[0] + 1) >> 1;
lptr[0] -= jpc_fix_asr(hptr[0] + 1, 1);
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
//lptr[0] -= (hptr[0] + hptr[stride] + 2) >> 2;
lptr[0] -= jpc_fix_asr(hptr[0] + hptr[stride] + 2, 2);
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
//lptr[0] -= (hptr[0] + 1) >> 1;
lptr[0] -= jpc_fix_asr(hptr[0] + 1, 1);
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
hptr[0] += lptr[0];
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
//hptr[0] += (lptr[0] + lptr[stride]) >> 1;
hptr[0] += jpc_fix_asr(lptr[0] + lptr[stride], 1);
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
hptr[0] += lptr[0];
}
} else {
if (parity) {
lptr = &a[0];
//lptr[0] >>= 1;
lptr[0] = jpc_fix_asr(lptr[0], 1);
}
}
}
void jpc_ft_invlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] -= (hptr2[0] + 1) >> 1;
lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] -= (hptr2[0] + hptr2[stride] + 2) >> 2;
lptr2[0] -= jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] -= (hptr2[0] + 1) >> 1;
lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
hptr2[0] += lptr2[0];
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//hptr2[0] += (lptr2[0] + lptr2[stride]) >> 1;
hptr2[0] += jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
hptr2[0] += lptr2[0];
++lptr2;
++hptr2;
}
}
} else {
if (parity) {
lptr2 = &a[0];
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] >>= 1;
lptr2[0] = jpc_fix_asr(lptr2[0], 1);
++lptr2;
}
}
}
}
void jpc_ft_invlift_colres(jpc_fix_t *a, int numrows, int numcols, int stride,
int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//lptr2[0] -= (hptr2[0] + 1) >> 1;
lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//lptr2[0] -= (hptr2[0] + hptr2[stride] + 2) >> 2;
lptr2[0] -= jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2);
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//lptr2[0] -= (hptr2[0] + 1) >> 1;
lptr2[0] -= jpc_fix_asr(hptr2[0] + 1, 1);
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
hptr2[0] += lptr2[0];
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
//hptr2[0] += (lptr2[0] + lptr2[stride]) >> 1;
hptr2[0] += jpc_fix_asr(lptr2[0] + lptr2[stride], 1);
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
hptr2[0] += lptr2[0];
++lptr2;
++hptr2;
}
}
} else {
if (parity) {
lptr2 = &a[0];
for (i = 0; i < numcols; ++i) {
//lptr2[0] >>= 1;
lptr2[0] = jpc_fix_asr(lptr2[0], 1);
++lptr2;
}
}
}
}
int jpc_ft_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
int stride)
{
int numrows = height;
int numcols = width;
int rowparity = ystart & 1;
int colparity = xstart & 1;
int i;
jpc_fix_t *startptr;
int maxcols;
maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
startptr = &a[0];
for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
jpc_ft_fwdlift_colgrp(startptr, numrows, stride, rowparity);
startptr += JPC_QMFB_COLGRPSIZE;
}
if (maxcols < numcols) {
jpc_qmfb_split_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
jpc_ft_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
}
startptr = &a[0];
for (i = 0; i < numrows; ++i) {
jpc_qmfb_split_row(startptr, numcols, colparity);
jpc_ft_fwdlift_row(startptr, numcols, colparity);
startptr += stride;
}
return 0;
}
int jpc_ft_synthesize(jpc_fix_t *a, int xstart, int ystart, int width, int height,
int stride)
{
int numrows = height;
int numcols = width;
int rowparity = ystart & 1;
int colparity = xstart & 1;
int maxcols;
jpc_fix_t *startptr;
int i;
startptr = &a[0];
for (i = 0; i < numrows; ++i) {
jpc_ft_invlift_row(startptr, numcols, colparity);
jpc_qmfb_join_row(startptr, numcols, colparity);
startptr += stride;
}
maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
startptr = &a[0];
for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
jpc_ft_invlift_colgrp(startptr, numrows, stride, rowparity);
jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity);
startptr += JPC_QMFB_COLGRPSIZE;
}
if (maxcols < numcols) {
jpc_ft_invlift_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
}
return 0;
}
/******************************************************************************\
* 9/7 transform
\******************************************************************************/
#define ALPHA (-1.586134342059924)
#define BETA (-0.052980118572961)
#define GAMMA (0.882911075530934)
#define DELTA (0.443506852043971)
#define LGAIN (1.0 / 1.23017410558578)
#define HGAIN (1.0 / 1.62578613134411)
void jpc_ns_fwdlift_row(jpc_fix_t *a, int numcols, int parity)
{
register jpc_fix_t *lptr;
register jpc_fix_t *hptr;
register int n;
int llen;
llen = (numcols + 1 - parity) >> 1;
if (numcols > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (parity) {
jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr[0]));
++hptr;
}
n = numcols - llen - parity - (parity == (numcols & 1));
while (n-- > 0) {
jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr[0], lptr[1])));
++hptr;
++lptr;
}
if (parity == (numcols & 1)) {
jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr[0]));
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (!parity) {
jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr[0]));
++lptr;
}
n = llen - (!parity) - (parity != (numcols & 1));
while (n-- > 0) {
jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr[0], hptr[1])));
++lptr;
++hptr;
}
if (parity != (numcols & 1)) {
jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr[0]));
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (parity) {
jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr[0]));
++hptr;
}
n = numcols - llen - parity - (parity == (numcols & 1));
while (n-- > 0) {
jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr[0], lptr[1])));
++hptr;
++lptr;
}
if (parity == (numcols & 1)) {
jpc_fix_pluseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr[0]));
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (!parity) {
jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr[0]));
++lptr;
}
n = llen - (!parity) - (parity != (numcols & 1));
while (n-- > 0) {
jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr[0], hptr[1])));
++lptr;
++hptr;
}
if (parity != (numcols & 1)) {
jpc_fix_pluseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr[0]));
}
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr[0] = jpc_fix_mul(lptr[0], jpc_dbltofix(LGAIN));
++lptr;
}
hptr = &a[llen];
n = numcols - llen;
while (n-- > 0) {
hptr[0] = jpc_fix_mul(hptr[0], jpc_dbltofix(HGAIN));
++hptr;
}
#endif
} else {
#if defined(WT_LENONE)
if (parity) {
lptr = &a[0];
//lptr[0] <<= 1;
lptr[0] = jpc_fix_asl(lptr[0], 1);
}
#endif
}
}
void jpc_ns_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr2 = lptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
++lptr2;
}
lptr += stride;
}
hptr = &a[llen * stride];
n = numrows - llen;
while (n-- > 0) {
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
++hptr2;
}
hptr += stride;
}
#endif
} else {
#if defined(WT_LENONE)
if (parity) {
lptr2 = &a[0];
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] <<= 1;
lptr2[0] = jpc_fix_asl(lptr2[0], 1);
++lptr2;
}
}
#endif
}
}
void jpc_ns_fwdlift_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr2 = lptr;
for (i = 0; i < numcols; ++i) {
lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
++lptr2;
}
lptr += stride;
}
hptr = &a[llen * stride];
n = numrows - llen;
while (n-- > 0) {
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
++hptr2;
}
hptr += stride;
}
#endif
} else {
#if defined(WT_LENONE)
if (parity) {
lptr2 = &a[0];
for (i = 0; i < numcols; ++i) {
//lptr2[0] <<= 1;
lptr2[0] = jpc_fix_asl(lptr2[0], 1);
++lptr2;
}
}
#endif
}
}
void jpc_ns_fwdlift_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr2[0]));
++hptr2;
++lptr2;
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr2[0]));
++hptr2;
++lptr2;
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr2[0]));
++lptr2;
++hptr2;
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_pluseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr2 = lptr;
lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(LGAIN));
++lptr2;
lptr += stride;
}
hptr = &a[llen * stride];
n = numrows - llen;
while (n-- > 0) {
hptr2 = hptr;
hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(HGAIN));
++hptr2;
hptr += stride;
}
#endif
} else {
#if defined(WT_LENONE)
if (parity) {
lptr2 = &a[0];
//lptr2[0] <<= 1;
lptr2[0] = jpc_fix_asl(lptr2[0], 1);
++lptr2;
}
#endif
}
}
void jpc_ns_invlift_row(jpc_fix_t *a, int numcols, int parity)
{
register jpc_fix_t *lptr;
register jpc_fix_t *hptr;
register int n;
int llen;
llen = (numcols + 1 - parity) >> 1;
if (numcols > 1) {
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr[0] = jpc_fix_mul(lptr[0], jpc_dbltofix(1.0 / LGAIN));
++lptr;
}
hptr = &a[llen];
n = numcols - llen;
while (n-- > 0) {
hptr[0] = jpc_fix_mul(hptr[0], jpc_dbltofix(1.0 / HGAIN));
++hptr;
}
#endif
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (!parity) {
jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr[0]));
++lptr;
}
n = llen - (!parity) - (parity != (numcols & 1));
while (n-- > 0) {
jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr[0], hptr[1])));
++lptr;
++hptr;
}
if (parity != (numcols & 1)) {
jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * DELTA),
hptr[0]));
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (parity) {
jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr[0]));
++hptr;
}
n = numcols - llen - parity - (parity == (numcols & 1));
while (n-- > 0) {
jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr[0], lptr[1])));
++hptr;
++lptr;
}
if (parity == (numcols & 1)) {
jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * GAMMA),
lptr[0]));
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (!parity) {
jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr[0]));
++lptr;
}
n = llen - (!parity) - (parity != (numcols & 1));
while (n-- > 0) {
jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr[0], hptr[1])));
++lptr;
++hptr;
}
if (parity != (numcols & 1)) {
jpc_fix_minuseq(lptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr[0]));
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen];
if (parity) {
jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr[0]));
++hptr;
}
n = numcols - llen - parity - (parity == (numcols & 1));
while (n-- > 0) {
jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr[0], lptr[1])));
++hptr;
++lptr;
}
if (parity == (numcols & 1)) {
jpc_fix_minuseq(hptr[0], jpc_fix_mul(jpc_dbltofix(2.0 * ALPHA),
lptr[0]));
}
} else {
#if defined(WT_LENONE)
if (parity) {
lptr = &a[0];
//lptr[0] >>= 1;
lptr[0] = jpc_fix_asr(lptr[0], 1);
}
#endif
}
}
void jpc_ns_invlift_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr2 = lptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
++lptr2;
}
lptr += stride;
}
hptr = &a[llen * stride];
n = numrows - llen;
while (n-- > 0) {
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
++hptr2;
}
hptr += stride;
}
#endif
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
DELTA), hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
DELTA), hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
GAMMA), lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
GAMMA), lptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
ALPHA), lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
ALPHA), lptr2[0]));
++lptr2;
++hptr2;
}
}
} else {
#if defined(WT_LENONE)
if (parity) {
lptr2 = &a[0];
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
//lptr2[0] >>= 1;
lptr2[0] = jpc_fix_asr(lptr2[0], 1);
++lptr2;
}
}
#endif
}
}
void jpc_ns_invlift_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
register int i;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr2 = lptr;
for (i = 0; i < numcols; ++i) {
lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
++lptr2;
}
lptr += stride;
}
hptr = &a[llen * stride];
n = numrows - llen;
while (n-- > 0) {
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
++hptr2;
}
hptr += stride;
}
#endif
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
DELTA), hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
DELTA), hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
GAMMA), lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
GAMMA), lptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
}
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
ALPHA), lptr2[0]));
++hptr2;
++lptr2;
}
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
}
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
for (i = 0; i < numcols; ++i) {
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
ALPHA), lptr2[0]));
++lptr2;
++hptr2;
}
}
} else {
#if defined(WT_LENONE)
if (parity) {
lptr2 = &a[0];
for (i = 0; i < numcols; ++i) {
//lptr2[0] >>= 1;
lptr2[0] = jpc_fix_asr(lptr2[0], 1);
++lptr2;
}
}
#endif
}
}
void jpc_ns_invlift_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
jpc_fix_t *lptr;
jpc_fix_t *hptr;
register jpc_fix_t *lptr2;
register jpc_fix_t *hptr2;
register int n;
int llen;
llen = (numrows + 1 - parity) >> 1;
if (numrows > 1) {
/* Apply the scaling step. */
#if defined(WT_DOSCALE)
lptr = &a[0];
n = llen;
while (n-- > 0) {
lptr2 = lptr;
lptr2[0] = jpc_fix_mul(lptr2[0], jpc_dbltofix(1.0 / LGAIN));
++lptr2;
lptr += stride;
}
hptr = &a[llen * stride];
n = numrows - llen;
while (n-- > 0) {
hptr2 = hptr;
hptr2[0] = jpc_fix_mul(hptr2[0], jpc_dbltofix(1.0 / HGAIN));
++hptr2;
hptr += stride;
}
#endif
/* Apply the first lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
DELTA), hptr2[0]));
++lptr2;
++hptr2;
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(DELTA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
DELTA), hptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the second lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
GAMMA), lptr2[0]));
++hptr2;
++lptr2;
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(GAMMA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
GAMMA), lptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the third lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (!parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
lptr += stride;
}
n = llen - (!parity) - (parity != (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(BETA),
jpc_fix_add(hptr2[0], hptr2[stride])));
++lptr2;
++hptr2;
lptr += stride;
hptr += stride;
}
if (parity != (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(lptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 * BETA),
hptr2[0]));
++lptr2;
++hptr2;
}
/* Apply the fourth lifting step. */
lptr = &a[0];
hptr = &a[llen * stride];
if (parity) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
ALPHA), lptr2[0]));
++hptr2;
++lptr2;
hptr += stride;
}
n = numrows - llen - parity - (parity == (numrows & 1));
while (n-- > 0) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(ALPHA),
jpc_fix_add(lptr2[0], lptr2[stride])));
++lptr2;
++hptr2;
hptr += stride;
lptr += stride;
}
if (parity == (numrows & 1)) {
lptr2 = lptr;
hptr2 = hptr;
jpc_fix_minuseq(hptr2[0], jpc_fix_mul(jpc_dbltofix(2.0 *
ALPHA), lptr2[0]));
++lptr2;
++hptr2;
}
} else {
#if defined(WT_LENONE)
if (parity) {
lptr2 = &a[0];
//lptr2[0] >>= 1;
lptr2[0] = jpc_fix_asr(lptr2[0], 1);
++lptr2;
}
#endif
}
}
int jpc_ns_analyze(jpc_fix_t *a, int xstart, int ystart, int width, int height,
int stride)
{
int numrows = height;
int numcols = width;
int rowparity = ystart & 1;
int colparity = xstart & 1;
int i;
jpc_fix_t *startptr;
int maxcols;
maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
startptr = &a[0];
for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
jpc_qmfb_split_colgrp(startptr, numrows, stride, rowparity);
jpc_ns_fwdlift_colgrp(startptr, numrows, stride, rowparity);
startptr += JPC_QMFB_COLGRPSIZE;
}
if (maxcols < numcols) {
jpc_qmfb_split_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
jpc_ns_fwdlift_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
}
startptr = &a[0];
for (i = 0; i < numrows; ++i) {
jpc_qmfb_split_row(startptr, numcols, colparity);
jpc_ns_fwdlift_row(startptr, numcols, colparity);
startptr += stride;
}
return 0;
}
int jpc_ns_synthesize(jpc_fix_t *a, int xstart, int ystart, int width,
int height, int stride)
{
int numrows = height;
int numcols = width;
int rowparity = ystart & 1;
int colparity = xstart & 1;
int maxcols;
jpc_fix_t *startptr;
int i;
startptr = &a[0];
for (i = 0; i < numrows; ++i) {
jpc_ns_invlift_row(startptr, numcols, colparity);
jpc_qmfb_join_row(startptr, numcols, colparity);
startptr += stride;
}
maxcols = (numcols / JPC_QMFB_COLGRPSIZE) * JPC_QMFB_COLGRPSIZE;
startptr = &a[0];
for (i = 0; i < maxcols; i += JPC_QMFB_COLGRPSIZE) {
jpc_ns_invlift_colgrp(startptr, numrows, stride, rowparity);
jpc_qmfb_join_colgrp(startptr, numrows, stride, rowparity);
startptr += JPC_QMFB_COLGRPSIZE;
}
if (maxcols < numcols) {
jpc_ns_invlift_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
jpc_qmfb_join_colres(startptr, numrows, numcols - maxcols, stride,
rowparity);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5353_1 |
crossvul-cpp_data_good_4787_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% AAA AAA IIIII %
% A A A A I %
% AAAAA AAAAA I %
% A A A A I %
% A A A A IIIII %
% %
% %
% Read/Write AAI X Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteAAIImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadAAIImage() reads an AAI Dune image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadAAIImage method is:
%
% Image *ReadAAIImage(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 *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
height,
length,
width;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read AAI Dune image.
*/
width=ReadBlobLSBLong(image);
height=ReadBlobLSBLong(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((width == 0UL) || (height == 0UL))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Convert AAI raster image to pixel packets.
*/
image->columns=width;
image->rows=height;
image->depth=8;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,
4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=(size_t) 4*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if ((size_t) count != length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelRed(q,ScaleCharToQuantum(*p++));
if (*p == 254)
*p=255;
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
if (q->opacity != OpaqueOpacity)
image->matte=MagickTrue;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
width=ReadBlobLSBLong(image);
height=ReadBlobLSBLong(image);
if ((width != 0UL) && (height != 0UL))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((width != 0UL) && (height != 0UL));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterAAIImage() adds attributes for the AAI Dune 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 RegisterAAIImage method is:
%
% size_t RegisterAAIImage(void)
%
*/
ModuleExport size_t RegisterAAIImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("AAI");
entry->decoder=(DecodeImageHandler *) ReadAAIImage;
entry->encoder=(EncodeImageHandler *) WriteAAIImage;
entry->description=ConstantString("AAI Dune image");
entry->module=ConstantString("AAI");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterAAIImage() removes format registrations made by the
% AAI module from the list of supported formats.
%
% The format of the UnregisterAAIImage method is:
%
% UnregisterAAIImage(void)
%
*/
ModuleExport void UnregisterAAIImage(void)
{
(void) UnregisterMagickInfo("AAI");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e A A I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteAAIImage() writes an image to a file in AAI Dune image format.
%
% The format of the WriteAAIImage method is:
%
% MagickBooleanType WriteAAIImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteAAIImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
scene;
register const PixelPacket
*restrict p;
register ssize_t
x;
register unsigned char
*restrict q;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Write AAI header.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
/*
Allocate memory for pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,
4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert MIFF to AAI raster pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q=ScaleQuantumToChar((Quantum) (QuantumRange-(image->matte !=
MagickFalse ? GetPixelOpacity(p) : OpaqueOpacity)));
if (*q == 255)
*q=254;
p++;
q++;
}
count=WriteBlob(image,(size_t) (q-pixels),pixels);
if (count != (ssize_t) (q-pixels))
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_1 |
crossvul-cpp_data_good_252_5 | #define TEST_NO_MAIN
#include "acutest.h"
#include "mutt/base64.h"
#include <string.h>
static const char clear[] = "Hello";
static const char encoded[] = "SGVsbG8=";
void test_base64_encode(void)
{
char buffer[16];
size_t len = mutt_b64_encode(buffer, clear, sizeof(clear) - 1, sizeof(buffer));
if (!TEST_CHECK(len == sizeof(encoded) - 1))
{
TEST_MSG("Expected: %zu", sizeof(encoded) - 1);
TEST_MSG("Actual : %zu", len);
}
if (!TEST_CHECK(strcmp(buffer, encoded) == 0))
{
TEST_MSG("Expected: %zu", encoded);
TEST_MSG("Actual : %zu", buffer);
}
}
void test_base64_decode(void)
{
char buffer[16];
int len = mutt_b64_decode(buffer, encoded, sizeof(buffer));
if (!TEST_CHECK(len == sizeof(clear) - 1))
{
TEST_MSG("Expected: %zu", sizeof(clear) - 1);
TEST_MSG("Actual : %zu", len);
}
buffer[len] = '\0';
if (!TEST_CHECK(strcmp(buffer, clear) == 0))
{
TEST_MSG("Expected: %s", clear);
TEST_MSG("Actual : %s", buffer);
}
}
void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1, sizeof(out2));
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_252_5 |
crossvul-cpp_data_good_651_1 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / ISO Media File Format sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/isomedia_dev.h>
#include <gpac/constants.h>
#ifndef GPAC_DISABLE_AV_PARSERS
#include <gpac/internal/media_dev.h>
#endif
#ifndef GPAC_DISABLE_ISOM
Bool gf_isom_is_nalu_based_entry(GF_MediaBox *mdia, GF_SampleEntryBox *_entry)
{
GF_MPEGVisualSampleEntryBox *entry;
if (mdia->handler->handlerType != GF_ISOM_MEDIA_VISUAL) return GF_FALSE;
switch (_entry->type) {
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_SVC2:
case GF_ISOM_BOX_TYPE_MVC1:
case GF_ISOM_BOX_TYPE_MVC2:
case GF_ISOM_BOX_TYPE_HVC1:
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVC2:
case GF_ISOM_BOX_TYPE_HEV2:
case GF_ISOM_BOX_TYPE_LHV1:
case GF_ISOM_BOX_TYPE_LHE1:
case GF_ISOM_BOX_TYPE_MHV1:
case GF_ISOM_BOX_TYPE_MHC1:
case GF_ISOM_BOX_TYPE_HVT1:
case GF_ISOM_BOX_TYPE_LHT1:
return GF_TRUE;
case GF_ISOM_BOX_TYPE_GNRV:
case GF_ISOM_BOX_TYPE_GNRA:
case GF_ISOM_BOX_TYPE_GNRM:
return GF_FALSE;
default:
break;
}
entry = (GF_MPEGVisualSampleEntryBox*)_entry;
if (!entry) return GF_FALSE;
if (entry->avc_config || entry->svc_config || entry->mvc_config || entry->hevc_config || entry->lhvc_config) return GF_TRUE;
return GF_FALSE;
}
static void rewrite_nalus_list(GF_List *nalus, GF_BitStream *bs, Bool rewrite_start_codes, u32 nal_unit_size_field)
{
u32 i, count = gf_list_count(nalus);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(nalus, i);
if (rewrite_start_codes) gf_bs_write_u32(bs, 1);
else gf_bs_write_int(bs, sl->size, 8*nal_unit_size_field);
gf_bs_write_data(bs, sl->data, sl->size);
}
}
static GF_Err process_extractor(GF_ISOFile *file, GF_MediaBox *mdia, u32 sampleNumber, u64 sampleDTS, u32 nal_size, u16 nal_hdr, u32 nal_unit_size_field, Bool is_hevc, Bool rewrite_ps, Bool rewrite_start_codes, GF_BitStream *src_bs, GF_BitStream *dst_bs, u32 extractor_mode)
{
GF_Err e;
u32 di, ref_track_index, ref_track_num, data_offset, data_length, cur_extract_mode, ref_extract_mode, ref_nalu_size, nb_bytes_nalh;
GF_TrackReferenceTypeBox *dpnd;
GF_ISOSample *ref_samp;
GF_BitStream *ref_bs;
GF_TrackBox *ref_trak;
s8 sample_offset;
char*buffer = NULL;
u32 max_size = 0;
u32 last_byte, ref_sample_num, prev_ref_sample_num;
Bool header_written = GF_FALSE;
nb_bytes_nalh = is_hevc ? 2 : 1;
switch (extractor_mode) {
case 0:
last_byte = (u32) gf_bs_get_position(src_bs) + nal_size - (is_hevc ? 2 : 1);
if (!is_hevc) gf_bs_read_int(src_bs, 24); //1 byte for HEVC , 3 bytes for AVC of NALUHeader in extractor
while (gf_bs_get_position(src_bs) < last_byte) {
u32 xmode = 0;
//hevc extractors use constructors
if (is_hevc) xmode = gf_bs_read_u8(src_bs);
if (xmode) {
u8 done=0, len = gf_bs_read_u8(src_bs);
while (done<len) {
u8 c = gf_bs_read_u8(src_bs);
done++;
if (header_written) {
gf_bs_write_u8(dst_bs, c);
} else if (done==nal_unit_size_field) {
if (rewrite_start_codes) {
gf_bs_write_int(dst_bs, 1, 32);
} else {
gf_bs_write_u8(dst_bs, c);
}
header_written = GF_TRUE;
} else if (!rewrite_start_codes) {
gf_bs_write_u8(dst_bs, c);
}
}
continue;
}
ref_track_index = gf_bs_read_u8(src_bs);
sample_offset = (s8) gf_bs_read_int(src_bs, 8);
data_offset = gf_bs_read_int(src_bs, nal_unit_size_field*8);
data_length = gf_bs_read_int(src_bs, nal_unit_size_field*8);
Track_FindRef(mdia->mediaTrack, GF_ISOM_REF_SCAL, &dpnd);
ref_track_num = 0;
if (dpnd && ref_track_index && (ref_track_index<=dpnd->trackIDCount))
ref_track_num = gf_isom_get_track_by_id(file, dpnd->trackIDs[ref_track_index-1]);
if (!ref_track_num) {
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("ISOBMF: Extractor target track is not present in file - skipping.\n"));
return GF_OK;
}
cur_extract_mode = gf_isom_get_nalu_extract_mode(file, ref_track_num);
//we must be in inspect mode only otherwise the reference sample will not be the one stored on file (change in start codes, PS inserted or other NALUs inserted)
//and this will corrupt extraction (wrong data offsets)
ref_extract_mode = GF_ISOM_NALU_EXTRACT_INSPECT;
gf_isom_set_nalu_extract_mode(file, ref_track_num, ref_extract_mode);
ref_trak = gf_isom_get_track_from_file(file, ref_track_num);
if (!ref_trak) return GF_ISOM_INVALID_FILE;
ref_samp = gf_isom_sample_new();
if (!ref_samp) return GF_IO_ERR;
e = stbl_findEntryForTime(ref_trak->Media->information->sampleTable, sampleDTS, 0, &ref_sample_num, &prev_ref_sample_num);
if (e) return e;
if (!ref_sample_num) ref_sample_num = prev_ref_sample_num;
if (!ref_sample_num) return GF_ISOM_INVALID_FILE;
if ((sample_offset<0) && (ref_sample_num > (u32) -sample_offset)) return GF_ISOM_INVALID_FILE;
ref_sample_num = (u32) ( (s32) ref_sample_num + sample_offset);
e = Media_GetSample(ref_trak->Media, ref_sample_num, &ref_samp, &di, GF_FALSE, NULL);
if (e) return e;
#if 0
if (!header_written && rewrite_start_codes) {
gf_bs_write_int(dst_bs, 1, 32);
if (is_hevc) {
gf_bs_write_int(dst_bs, 0, 1);
gf_bs_write_int(dst_bs, GF_HEVC_NALU_ACCESS_UNIT, 6);
gf_bs_write_int(dst_bs, 0, 9);
/*pic-type - by default we signal all slice types possible*/
gf_bs_write_int(dst_bs, 2, 3);
gf_bs_write_int(dst_bs, 0, 5);
} else {
gf_bs_write_int(dst_bs, (ref_samp->data[0] & 0x60) | GF_AVC_NALU_ACCESS_UNIT, 8);
gf_bs_write_int(dst_bs, 0xF0 , 8); /*7 "all supported NALUs" (=111) + rbsp trailing (10000)*/;
}
}
#endif
ref_bs = gf_bs_new(ref_samp->data + data_offset, ref_samp->dataLength - data_offset, GF_BITSTREAM_READ);
if (ref_samp->dataLength - data_offset >= data_length) {
while (data_length && gf_bs_available(ref_bs)) {
if (!header_written) {
ref_nalu_size = gf_bs_read_int(ref_bs, 8*nal_unit_size_field);
if (!data_length)
data_length = ref_nalu_size + nal_unit_size_field;
assert(data_length>nal_unit_size_field);
data_length -= nal_unit_size_field;
if (data_length > gf_bs_available(ref_bs)) {
data_length = (u32)gf_bs_available(ref_bs);
}
} else {
ref_nalu_size = data_length;
}
if (ref_nalu_size > max_size) {
buffer = (char*) gf_realloc(buffer, sizeof(char) * ref_nalu_size );
max_size = ref_nalu_size;
}
gf_bs_read_data(ref_bs, buffer, ref_nalu_size);
if (!header_written) {
if (rewrite_start_codes)
gf_bs_write_u32(dst_bs, 1);
else
gf_bs_write_int(dst_bs, ref_nalu_size, 8*nal_unit_size_field);
}
assert(data_length >= ref_nalu_size);
gf_bs_write_data(dst_bs, buffer, ref_nalu_size);
data_length -= ref_nalu_size;
header_written = GF_FALSE;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("ISOBMF: Extractor size is larger than refered sample size - skipping.\n"));
}
gf_isom_sample_del(&ref_samp);
ref_samp = NULL;
gf_bs_del(ref_bs);
ref_bs = NULL;
if (buffer) gf_free(buffer);
buffer = NULL;
gf_isom_set_nalu_extract_mode(file, ref_track_num, cur_extract_mode);
if (!is_hevc) break;
}
break;
case 1:
//skip to end of this NALU
gf_bs_skip_bytes(src_bs, nal_size - nb_bytes_nalh);
break;
case 2:
buffer = (char*) gf_malloc( sizeof(char) * (nal_size - nb_bytes_nalh));
gf_bs_read_data(src_bs, buffer, nal_size - nb_bytes_nalh);
if (rewrite_start_codes)
gf_bs_write_u32(dst_bs, 1);
else
gf_bs_write_int(dst_bs, nal_size, 8*nal_unit_size_field);
gf_bs_write_u8(dst_bs, nal_hdr);
gf_bs_write_data(dst_bs, buffer, nal_size - nb_bytes_nalh);
gf_free(buffer);
break;
}
return GF_OK;
}
#ifndef GPAC_DISABLE_HEVC
/* returns the SAP type as defined in the 14496-12 specification */
static SAPType sap_type_from_nal_type(u8 nal_type) {
switch (nal_type) {
case GF_HEVC_NALU_SLICE_CRA:
return SAP_TYPE_3;
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
return SAP_TYPE_1;
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_W_LP:
return SAP_TYPE_2;
default:
return RAP_NO;
}
}
#endif
static SAPType is_sample_idr(GF_ISOSample *sample, GF_MPEGVisualSampleEntryBox *entry)
{
Bool is_hevc = GF_FALSE;
u32 nalu_size_field = 0;
GF_BitStream *bs;
if (entry->avc_config && entry->avc_config->config) nalu_size_field = entry->avc_config->config->nal_unit_size;
else if (entry->svc_config && entry->svc_config->config) nalu_size_field = entry->svc_config->config->nal_unit_size;
else if (entry->mvc_config && entry->mvc_config->config) nalu_size_field = entry->mvc_config->config->nal_unit_size;
else if (entry->hevc_config && entry->hevc_config->config) {
nalu_size_field = entry->hevc_config->config->nal_unit_size;
is_hevc = GF_TRUE;
}
else if (entry->lhvc_config && entry->lhvc_config->config) {
nalu_size_field = entry->lhvc_config->config->nal_unit_size;
is_hevc = GF_TRUE;
}
if (!nalu_size_field) return RAP_NO;
bs = gf_bs_new(sample->data, sample->dataLength, GF_BITSTREAM_READ);
if (!bs) return RAP_NO;
while (gf_bs_available(bs)) {
u8 nal_type;
u32 size = gf_bs_read_int(bs, 8*nalu_size_field);
if (is_hevc) {
#ifndef GPAC_DISABLE_HEVC
u16 nal_hdr = gf_bs_read_u16(bs);
nal_type = (nal_hdr&0x7E00) >> 9;
switch (nal_type) {
case GF_HEVC_NALU_SLICE_CRA:
gf_bs_del(bs);
return SAP_TYPE_3;
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
gf_bs_del(bs);
return SAP_TYPE_1;
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_W_LP:
gf_bs_del(bs);
return SAP_TYPE_2;
case GF_HEVC_NALU_ACCESS_UNIT:
case GF_HEVC_NALU_FILLER_DATA:
case GF_HEVC_NALU_SEI_PREFIX:
case GF_HEVC_NALU_VID_PARAM:
case GF_HEVC_NALU_SEQ_PARAM:
case GF_HEVC_NALU_PIC_PARAM:
break;
default:
gf_bs_del(bs);
return RAP_NO;
}
gf_bs_skip_bytes(bs, size - 2);
#endif
} else {
u8 nal_hdr = gf_bs_read_u8(bs);
nal_type = nal_hdr & 0x1F;
switch (nal_type) {
/* case GF_AVC_NALU_SEQ_PARAM:
case GF_AVC_NALU_PIC_PARAM:
case GF_AVC_NALU_SEQ_PARAM_EXT:
case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
*/ case GF_AVC_NALU_IDR_SLICE:
gf_bs_del(bs);
return SAP_TYPE_1;
case GF_AVC_NALU_ACCESS_UNIT:
case GF_AVC_NALU_FILLER_DATA:
case GF_AVC_NALU_SEI:
break;
default:
gf_bs_del(bs);
return RAP_NO;
}
gf_bs_skip_bytes(bs, size - 1);
}
}
gf_bs_del(bs);
return RAP_NO;
}
static void nalu_merge_ps(GF_BitStream *ps_bs, Bool rewrite_start_codes, u32 nal_unit_size_field, GF_MPEGVisualSampleEntryBox *entry, Bool is_hevc)
{
u32 i, count;
if (is_hevc) {
if (entry->hevc_config) {
count = gf_list_count(entry->hevc_config->config->param_array);
for (i=0; i<count; i++) {
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(entry->hevc_config->config->param_array, i);
rewrite_nalus_list(ar->nalus, ps_bs, rewrite_start_codes, nal_unit_size_field);
}
}
if (entry->lhvc_config) {
count = gf_list_count(entry->lhvc_config->config->param_array);
for (i=0; i<count; i++) {
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(entry->lhvc_config->config->param_array, i);
rewrite_nalus_list(ar->nalus, ps_bs, rewrite_start_codes, nal_unit_size_field);
}
}
} else {
if (entry->avc_config) {
rewrite_nalus_list(entry->avc_config->config->sequenceParameterSets, ps_bs, rewrite_start_codes, nal_unit_size_field);
rewrite_nalus_list(entry->avc_config->config->sequenceParameterSetExtensions, ps_bs, rewrite_start_codes, nal_unit_size_field);
rewrite_nalus_list(entry->avc_config->config->pictureParameterSets, ps_bs, rewrite_start_codes, nal_unit_size_field);
}
/*add svc config */
if (entry->svc_config) {
rewrite_nalus_list(entry->svc_config->config->sequenceParameterSets, ps_bs, rewrite_start_codes, nal_unit_size_field);
rewrite_nalus_list(entry->svc_config->config->pictureParameterSets, ps_bs, rewrite_start_codes, nal_unit_size_field);
}
/*add mvc config */
if (entry->mvc_config) {
rewrite_nalus_list(entry->mvc_config->config->sequenceParameterSets, ps_bs, rewrite_start_codes, nal_unit_size_field);
rewrite_nalus_list(entry->mvc_config->config->pictureParameterSets, ps_bs, rewrite_start_codes, nal_unit_size_field);
}
}
}
GF_Err gf_isom_nalu_sample_rewrite(GF_MediaBox *mdia, GF_ISOSample *sample, u32 sampleNumber, GF_MPEGVisualSampleEntryBox *entry)
{
Bool is_hevc = GF_FALSE;
//if only one sync given in the sample sync table, insert sps/pps/vps before cra/bla in hevc
// Bool check_cra_bla = (mdia->information->sampleTable->SyncSample && mdia->information->sampleTable->SyncSample->nb_entries>1) ? 0 : 1;
Bool check_cra_bla = GF_TRUE;
Bool insert_nalu_delim = GF_TRUE;
Bool force_sei_inspect = GF_FALSE;
GF_Err e = GF_OK;
GF_ISOSample *ref_samp;
GF_BitStream *src_bs, *ref_bs, *dst_bs, *ps_bs, *sei_suffix_bs;
u32 nal_size, max_size, nal_unit_size_field, extractor_mode;
Bool rewrite_ps, rewrite_start_codes, insert_vdrd_code;
s8 nal_type;
u32 nal_hdr, sabt_ref, i, track_num;
u32 temporal_id = 0;
char *buffer;
GF_ISOFile *file = mdia->mediaTrack->moov->mov;
GF_TrackReferenceTypeBox *scal = NULL;
src_bs = ref_bs = dst_bs = ps_bs = sei_suffix_bs = NULL;
ref_samp = NULL;
buffer = NULL;
Track_FindRef(mdia->mediaTrack, GF_ISOM_REF_SCAL, &scal);
rewrite_ps = (mdia->mediaTrack->extractor_mode & GF_ISOM_NALU_EXTRACT_INBAND_PS_FLAG) ? GF_TRUE : GF_FALSE;
rewrite_start_codes = (mdia->mediaTrack->extractor_mode & GF_ISOM_NALU_EXTRACT_ANNEXB_FLAG) ? GF_TRUE : GF_FALSE;
insert_vdrd_code = (mdia->mediaTrack->extractor_mode & GF_ISOM_NALU_EXTRACT_VDRD_FLAG) ? GF_TRUE : GF_FALSE;
if (!entry->svc_config && !entry->mvc_config && !entry->lhvc_config) insert_vdrd_code = GF_FALSE;
extractor_mode = mdia->mediaTrack->extractor_mode&0x0000FFFF;
if (mdia->mediaTrack->extractor_mode & GF_ISOM_NALU_EXTRACT_TILE_ONLY) {
insert_nalu_delim = GF_FALSE;
}
track_num = 1 + gf_list_find(mdia->mediaTrack->moov->trackList, mdia->mediaTrack);
if ( (extractor_mode != GF_ISOM_NALU_EXTRACT_INSPECT) && !(mdia->mediaTrack->extractor_mode & GF_ISOM_NALU_EXTRACT_TILE_ONLY) ) {
u32 ref_track, di;
//aggregate all sabt samples with the same DTS
if (entry->lhvc_config && !entry->hevc_config && !(mdia->mediaTrack->extractor_mode & GF_ISOM_NALU_EXTRACT_LAYER_ONLY)) {
GF_ISOSample *base_samp;
if (gf_isom_get_reference_count(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_SCAL) <= 0) {
//FIXME - for now we only support two layers (base + enh) in implicit
if ( gf_isom_get_reference_count(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_BASE) >= 1) {
gf_isom_get_reference(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_BASE, 1, &ref_track);
switch (gf_isom_get_media_subtype(mdia->mediaTrack->moov->mov , ref_track, 1)) {
case GF_ISOM_SUBTYPE_HVC1:
case GF_ISOM_SUBTYPE_HVC2:
case GF_ISOM_SUBTYPE_HEV1:
case GF_ISOM_SUBTYPE_HEV2:
base_samp = gf_isom_get_sample(mdia->mediaTrack->moov->mov, ref_track, sampleNumber + mdia->mediaTrack->sample_count_at_seg_start, &di);
if (base_samp && base_samp->data) {
sample->data = gf_realloc(sample->data, sample->dataLength+base_samp->dataLength);
memmove(sample->data + base_samp->dataLength, sample->data , sample->dataLength);
memcpy(sample->data, base_samp->data, base_samp->dataLength);
sample->dataLength += base_samp->dataLength;
}
if (base_samp) gf_isom_sample_del(&base_samp);
Track_FindRef(mdia->mediaTrack, GF_ISOM_REF_BASE, &scal);
break;
}
}
}
}
sabt_ref = gf_isom_get_reference_count(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_SABT);
if ((s32) sabt_ref > 0) {
force_sei_inspect = GF_TRUE;
for (i=0; i<sabt_ref; i++) {
GF_ISOSample *tile_samp;
gf_isom_get_reference(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_SABT, i+1, &ref_track);
tile_samp = gf_isom_get_sample(mdia->mediaTrack->moov->mov, ref_track, sampleNumber + mdia->mediaTrack->sample_count_at_seg_start, &di);
if (tile_samp && tile_samp ->data) {
sample->data = gf_realloc(sample->data, sample->dataLength+tile_samp->dataLength);
memcpy(sample->data + sample->dataLength, tile_samp->data, tile_samp->dataLength);
sample->dataLength += tile_samp->dataLength;
}
if (tile_samp) gf_isom_sample_del(&tile_samp);
}
}
}
if ( gf_isom_get_reference_count(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_TBAS) >= 1) {
u32 ref_track;
u32 idx = gf_list_find(mdia->information->sampleTable->SampleDescription->other_boxes, entry);
GF_TrackBox *tbas;
gf_isom_get_reference(mdia->mediaTrack->moov->mov, track_num, GF_ISOM_REF_TBAS, 1, &ref_track);
tbas = (GF_TrackBox *)gf_list_get(mdia->mediaTrack->moov->trackList, ref_track-1);
entry = gf_list_get(tbas->Media->information->sampleTable->SampleDescription->other_boxes, idx);
}
if (sample->IsRAP < SAP_TYPE_2) {
if (mdia->information->sampleTable->no_sync_found || (!sample->IsRAP && check_cra_bla) ) {
sample->IsRAP = is_sample_idr(sample, entry);
}
}
if (!sample->IsRAP)
rewrite_ps = GF_FALSE;
if (extractor_mode != GF_ISOM_NALU_EXTRACT_LAYER_ONLY)
insert_vdrd_code = GF_FALSE;
//this is a compatible HEVC, don't insert VDRD, insert NALU delim
if (entry->lhvc_config && entry->hevc_config)
insert_vdrd_code = GF_FALSE;
if (extractor_mode == GF_ISOM_NALU_EXTRACT_INSPECT) {
if (!rewrite_ps && !rewrite_start_codes)
return GF_OK;
}
if (!entry) return GF_BAD_PARAM;
nal_unit_size_field = 0;
/*if svc rewrite*/
if (entry->svc_config && entry->svc_config->config)
nal_unit_size_field = entry->svc_config->config->nal_unit_size;
/*if mvc rewrite*/
if (entry->mvc_config && entry->mvc_config->config)
nal_unit_size_field = entry->mvc_config->config->nal_unit_size;
/*if lhvc rewrite*/
else if (entry->lhvc_config && entry->lhvc_config->config) {
is_hevc = GF_TRUE;
nal_unit_size_field = entry->lhvc_config->config->nal_unit_size;
}
/*otherwise do nothing*/
else if (!rewrite_ps && !rewrite_start_codes && !scal && !force_sei_inspect) {
return GF_OK;
}
if (!nal_unit_size_field) {
if (entry->avc_config) nal_unit_size_field = entry->avc_config->config->nal_unit_size;
else if (entry->hevc_config || entry->lhvc_config ) {
nal_unit_size_field = entry->lhvc_config ? entry->lhvc_config->config->nal_unit_size : entry->hevc_config->config->nal_unit_size;
is_hevc = GF_TRUE;
}
}
if (!nal_unit_size_field) return GF_ISOM_INVALID_FILE;
dst_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
ps_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
src_bs = gf_bs_new(sample->data, sample->dataLength, GF_BITSTREAM_READ);
if (!src_bs && sample->data) return GF_ISOM_INVALID_FILE;
max_size = 4096;
/*rewrite start code with NALU delim*/
if (rewrite_start_codes) {
//we are SVC, don't write NALU delim, only insert VDRD NALU
if (insert_vdrd_code) {
if (is_hevc) {
//spec is not clear here, we don't insert an NALU AU delimiter before the layer starts since it breaks openHEVC
// insert_nalu_delim=0;
} else {
gf_bs_write_int(dst_bs, 1, 32);
gf_bs_write_int(dst_bs, GF_AVC_NALU_VDRD , 8);
insert_nalu_delim=0;
}
}
//AVC/HEVC base, insert NALU delim
if (insert_nalu_delim) {
gf_bs_write_int(dst_bs, 1, 32);
if (is_hevc) {
#ifndef GPAC_DISABLE_HEVC
gf_bs_write_int(dst_bs, 0, 1);
gf_bs_write_int(dst_bs, GF_HEVC_NALU_ACCESS_UNIT, 6);
gf_bs_write_int(dst_bs, insert_vdrd_code ? 1 : 0, 6); //we should pick the layerID of the following nalus ...
gf_bs_write_int(dst_bs, 1, 3); //nuh_temporal_id_plus1 - cannot be 0, we use 1 by default, and overwrite it if needed at the end
/*pic-type - by default we signal all slice types possible*/
gf_bs_write_int(dst_bs, 2, 3);
gf_bs_write_int(dst_bs, 0, 5);
#endif
} else {
gf_bs_write_int(dst_bs, (sample->data[0] & 0x60) | GF_AVC_NALU_ACCESS_UNIT, 8);
gf_bs_write_int(dst_bs, 0xF0 , 8); /*7 "all supported NALUs" (=111) + rbsp trailing (10000)*/;
}
}
}
if (rewrite_ps) {
//in inspect mode or single-layer mode just use the xPS from this layer
if (extractor_mode == GF_ISOM_NALU_EXTRACT_DEFAULT) {
u32 i;
if (scal) {
for (i=0; i<scal->trackIDCount; i++) {
GF_TrackBox *a_track = GetTrackbyID(mdia->mediaTrack->moov, scal->trackIDs[i]);
GF_MPEGVisualSampleEntryBox *an_entry = NULL;
if (a_track && a_track->Media && a_track->Media->information && a_track->Media->information->sampleTable && a_track->Media->information->sampleTable->SampleDescription)
an_entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(a_track->Media->information->sampleTable->SampleDescription->other_boxes, 0);
if (an_entry)
nalu_merge_ps(ps_bs, rewrite_start_codes, nal_unit_size_field, an_entry, is_hevc);
}
}
}
nalu_merge_ps(ps_bs, rewrite_start_codes, nal_unit_size_field, entry, is_hevc);
if (is_hevc) {
/*little optimization if we are not asked to start codes: copy over the sample*/
if (!rewrite_start_codes && !entry->lhvc_config && !scal) {
if (ps_bs) {
u8 nal_type = (sample->data[nal_unit_size_field] & 0x7E) >> 1;
//temp fix - if we detect xPS in the beginning of the sample do NOT copy the ps bitstream
//this is not correct since we are not sure whether they are the same xPS or not, but it crashes openHEVC ...
switch (nal_type) {
#ifndef GPAC_DISABLE_HEVC
case GF_HEVC_NALU_VID_PARAM:
case GF_HEVC_NALU_SEQ_PARAM:
case GF_HEVC_NALU_PIC_PARAM:
break;
#endif
default:
gf_bs_transfer(dst_bs, ps_bs);
break;
}
gf_bs_del(ps_bs);
ps_bs = NULL;
}
gf_bs_write_data(dst_bs, sample->data, sample->dataLength);
gf_free(sample->data);
sample->data = NULL;
gf_bs_get_content(dst_bs, &sample->data, &sample->dataLength);
gf_bs_del(src_bs);
gf_bs_del(dst_bs);
return GF_OK;
}
}
}
/*little optimization if we are not asked to rewrite extractors or start codes: copy over the sample*/
if (!scal && !rewrite_start_codes && !rewrite_ps && !force_sei_inspect) {
if (ps_bs)
{
gf_bs_transfer(dst_bs, ps_bs);
gf_bs_del(ps_bs);
ps_bs = NULL;
}
gf_bs_write_data(dst_bs, sample->data, sample->dataLength);
gf_free(sample->data);
sample->data = NULL;
gf_bs_get_content(dst_bs, &sample->data, &sample->dataLength);
gf_bs_del(src_bs);
gf_bs_del(dst_bs);
return GF_OK;
}
buffer = (char *)gf_malloc(sizeof(char)*max_size);
while (gf_bs_available(src_bs)) {
nal_size = gf_bs_read_int(src_bs, 8*nal_unit_size_field);
if (gf_bs_get_position(src_bs) + nal_size > sample->dataLength) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("Sample %u (size %u) rewrite: corrupted NAL Unit (size %u)\n", sampleNumber, sample->dataLength, nal_size));
goto exit;
}
if (nal_size>max_size) {
buffer = (char*) gf_realloc(buffer, sizeof(char)*nal_size);
max_size = nal_size;
}
if (is_hevc) {
nal_hdr = gf_bs_read_u16(src_bs);
nal_type = (nal_hdr&0x7E00) >> 9;
} else {
nal_hdr = gf_bs_read_u8(src_bs);
nal_type = nal_hdr & 0x1F;
}
if (is_hevc) {
GF_BitStream *write_to_bs = dst_bs;
if (ps_bs) {
gf_bs_transfer(dst_bs, ps_bs);
gf_bs_del(ps_bs);
ps_bs = NULL;
}
#ifndef GPAC_DISABLE_HEVC
/*we already wrote this stuff*/
if (nal_type==GF_HEVC_NALU_ACCESS_UNIT) {
gf_bs_skip_bytes(src_bs, nal_size-2);
continue;
}
switch (nal_type) {
//extractor
case 49:
e = process_extractor(file, mdia, sampleNumber, sample->DTS, nal_size, nal_hdr, nal_unit_size_field, GF_TRUE, rewrite_ps, rewrite_start_codes, src_bs, dst_bs, extractor_mode);
if (e) goto exit;
break;
case GF_HEVC_NALU_SLICE_TSA_N:
case GF_HEVC_NALU_SLICE_STSA_N:
case GF_HEVC_NALU_SLICE_TSA_R:
case GF_HEVC_NALU_SLICE_STSA_R:
if (temporal_id < (nal_hdr & 0x7))
temporal_id = (nal_hdr & 0x7);
/*rewrite nal*/
gf_bs_read_data(src_bs, buffer, nal_size-2);
if (rewrite_start_codes)
gf_bs_write_u32(dst_bs, 1);
else
gf_bs_write_int(dst_bs, nal_size, 8*nal_unit_size_field);
gf_bs_write_u16(dst_bs, nal_hdr);
gf_bs_write_data(dst_bs, buffer, nal_size-2);
break;
case GF_HEVC_NALU_SLICE_BLA_W_LP:
case GF_HEVC_NALU_SLICE_BLA_W_DLP:
case GF_HEVC_NALU_SLICE_BLA_N_LP:
case GF_HEVC_NALU_SLICE_IDR_W_DLP:
case GF_HEVC_NALU_SLICE_IDR_N_LP:
case GF_HEVC_NALU_SLICE_CRA:
//insert xPS before CRA/BLA
if (check_cra_bla && !sample->IsRAP) {
if (ref_samp) gf_isom_sample_del(&ref_samp);
if (src_bs) gf_bs_del(src_bs);
if (ref_bs) gf_bs_del(ref_bs);
if (dst_bs) gf_bs_del(dst_bs);
if (buffer) gf_free(buffer);
sample->IsRAP = sap_type_from_nal_type(nal_type);
return gf_isom_nalu_sample_rewrite(mdia, sample, sampleNumber, entry);
}
default:
/*rewrite nal*/
if (nal_size<2) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid nal size %d in sample %d\n", nal_type, sampleNumber));
e = GF_NON_COMPLIANT_BITSTREAM;
goto exit;
}
gf_bs_read_data(src_bs, buffer, nal_size-2);
if (nal_type==GF_HEVC_NALU_SEI_SUFFIX) {
if (!sei_suffix_bs) sei_suffix_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
write_to_bs = sei_suffix_bs;
}
if (rewrite_start_codes)
gf_bs_write_u32(write_to_bs, 1);
else
gf_bs_write_int(write_to_bs, nal_size, 8*nal_unit_size_field);
gf_bs_write_u16(write_to_bs, nal_hdr);
gf_bs_write_data(write_to_bs, buffer, nal_size-2);
}
#endif
//done with HEVC
continue;
}
switch(nal_type) {
case GF_AVC_NALU_ACCESS_UNIT:
/*we already wrote this stuff*/
gf_bs_skip_bytes(src_bs, nal_size-1);
continue;
//extractor
case 31:
e = process_extractor(file, mdia, sampleNumber, sample->DTS, nal_size, nal_hdr, nal_unit_size_field, GF_FALSE, rewrite_ps, rewrite_start_codes, src_bs, dst_bs, extractor_mode);
if (e) goto exit;
break;
// case GF_AVC_NALU_SEI:
case GF_AVC_NALU_SEQ_PARAM:
case GF_AVC_NALU_PIC_PARAM:
case GF_AVC_NALU_SEQ_PARAM_EXT:
case GF_AVC_NALU_SVC_SUBSEQ_PARAM:
// we will rewrite the sps/pps if and only if there is no sps/pps in bistream
if (ps_bs) {
gf_bs_del(ps_bs);
ps_bs = NULL;
}
default:
if (ps_bs) {
gf_bs_transfer(dst_bs, ps_bs);
gf_bs_del(ps_bs);
ps_bs = NULL;
}
gf_bs_read_data(src_bs, buffer, nal_size-1);
if (rewrite_start_codes)
gf_bs_write_u32(dst_bs, 1);
else
gf_bs_write_int(dst_bs, nal_size, 8*nal_unit_size_field);
gf_bs_write_u8(dst_bs, nal_hdr);
gf_bs_write_data(dst_bs, buffer, nal_size-1);
}
}
if (sei_suffix_bs) {
gf_bs_transfer(dst_bs, sei_suffix_bs);
gf_bs_del(sei_suffix_bs);
}
/*done*/
gf_free(sample->data);
sample->data = NULL;
gf_bs_get_content(dst_bs, &sample->data, &sample->dataLength);
/*rewrite temporal ID of AU Ddelim NALU (first one)*/
if (rewrite_start_codes && is_hevc && temporal_id) {
sample->data[6] = (sample->data[6] & 0xF8) | (temporal_id+1);
}
exit:
if (ref_samp) gf_isom_sample_del(&ref_samp);
if (src_bs) gf_bs_del(src_bs);
if (ref_bs) gf_bs_del(ref_bs);
if (dst_bs) gf_bs_del(dst_bs);
if (ps_bs) gf_bs_del(ps_bs);
if (buffer) gf_free(buffer);
return e;
}
GF_HEVCConfig *HEVC_DuplicateConfig(GF_HEVCConfig *cfg)
{
char *data;
u32 data_size;
GF_HEVCConfig *new_cfg;
GF_BitStream *bs;
if (!cfg) return NULL;
bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);
gf_odf_hevc_cfg_write_bs(cfg, bs);
gf_bs_get_content(bs, &data, &data_size);
gf_bs_del(bs);
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
new_cfg = gf_odf_hevc_cfg_read_bs(bs, cfg->is_lhvc);
new_cfg->is_lhvc = cfg->is_lhvc;
gf_bs_del(bs);
gf_free(data);
return new_cfg;
}
static GF_AVCConfig *AVC_DuplicateConfig(GF_AVCConfig *cfg)
{
u32 i, count;
GF_AVCConfigSlot *p1, *p2;
GF_AVCConfig *cfg_new = gf_odf_avc_cfg_new();
cfg_new->AVCLevelIndication = cfg->AVCLevelIndication;
cfg_new->AVCProfileIndication = cfg->AVCProfileIndication;
cfg_new->configurationVersion = cfg->configurationVersion;
cfg_new->nal_unit_size = cfg->nal_unit_size;
cfg_new->profile_compatibility = cfg->profile_compatibility;
cfg_new->complete_representation = cfg->complete_representation;
cfg_new->chroma_bit_depth = cfg->chroma_bit_depth;
cfg_new->luma_bit_depth = cfg->luma_bit_depth;
cfg_new->chroma_format = cfg->chroma_format;
count = gf_list_count(cfg->sequenceParameterSets);
for (i=0; i<count; i++) {
p1 = (GF_AVCConfigSlot*)gf_list_get(cfg->sequenceParameterSets, i);
p2 = (GF_AVCConfigSlot*)gf_malloc(sizeof(GF_AVCConfigSlot));
p2->size = p1->size;
p2->id = p1->id;
p2->data = (char *)gf_malloc(sizeof(char)*p1->size);
memcpy(p2->data, p1->data, sizeof(char)*p1->size);
gf_list_add(cfg_new->sequenceParameterSets, p2);
}
count = gf_list_count(cfg->pictureParameterSets);
for (i=0; i<count; i++) {
p1 = (GF_AVCConfigSlot*)gf_list_get(cfg->pictureParameterSets, i);
p2 = (GF_AVCConfigSlot*)gf_malloc(sizeof(GF_AVCConfigSlot));
p2->size = p1->size;
p2->id = p1->id;
p2->data = (char*)gf_malloc(sizeof(char)*p1->size);
memcpy(p2->data, p1->data, sizeof(char)*p1->size);
gf_list_add(cfg_new->pictureParameterSets, p2);
}
if (cfg->sequenceParameterSetExtensions) {
cfg_new->sequenceParameterSetExtensions = gf_list_new();
count = gf_list_count(cfg->sequenceParameterSetExtensions);
for (i=0; i<count; i++) {
p1 = (GF_AVCConfigSlot*)gf_list_get(cfg->sequenceParameterSetExtensions, i);
p2 = (GF_AVCConfigSlot*)gf_malloc(sizeof(GF_AVCConfigSlot));
p2->size = p1->size;
p2->id = p1->id;
p2->data = (char*)gf_malloc(sizeof(char)*p1->size);
memcpy(p2->data, p1->data, sizeof(char)*p1->size);
gf_list_add(cfg_new->sequenceParameterSetExtensions, p2);
}
}
return cfg_new;
}
static void merge_avc_config(GF_AVCConfig *dst_cfg, GF_AVCConfig *src_cfg)
{
GF_AVCConfig *cfg = AVC_DuplicateConfig(src_cfg);
if (!cfg || !dst_cfg) return;
while (gf_list_count(cfg->sequenceParameterSets)) {
GF_AVCConfigSlot *p = (GF_AVCConfigSlot*)gf_list_get(cfg->sequenceParameterSets, 0);
gf_list_rem(cfg->sequenceParameterSets, 0);
gf_list_insert(dst_cfg->sequenceParameterSets, p, 0);
}
while (gf_list_count(cfg->pictureParameterSets)) {
GF_AVCConfigSlot *p = (GF_AVCConfigSlot*)gf_list_get(cfg->pictureParameterSets, 0);
gf_list_rem(cfg->pictureParameterSets, 0);
gf_list_insert(dst_cfg->pictureParameterSets, p, 0);
}
gf_odf_avc_cfg_del(cfg);
}
void merge_hevc_config(GF_HEVCConfig *dst_cfg, GF_HEVCConfig *src_cfg, Bool force_insert)
{
GF_HEVCConfig *cfg = HEVC_DuplicateConfig(src_cfg);
//merge all xPS
u32 i, j, count = cfg->param_array ? gf_list_count(cfg->param_array) : 0;
for (i=0; i<count; i++) {
GF_HEVCParamArray *ar_h = NULL;
u32 count2 = dst_cfg->param_array ? gf_list_count(dst_cfg->param_array) : 0;
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(cfg->param_array, i);
for (j=0; j<count2; j++) {
ar_h = (GF_HEVCParamArray*)gf_list_get(dst_cfg->param_array, j);
if (ar_h->type==ar->type) {
break;
}
ar_h = NULL;
}
if (!ar_h) {
gf_list_add(dst_cfg->param_array, ar);
gf_list_rem(cfg->param_array, i);
count--;
i--;
} else {
while (gf_list_count(ar->nalus)) {
GF_AVCConfigSlot *p = (GF_AVCConfigSlot*)gf_list_get(ar->nalus, 0);
gf_list_rem(ar->nalus, 0);
if (force_insert)
gf_list_insert(ar_h->nalus, p, 0);
else
gf_list_add(ar_h->nalus, p);
}
}
}
gf_odf_hevc_cfg_del(cfg);
#define CHECK_CODE(__code) if (dst_cfg->__code < src_cfg->__code) dst_cfg->__code = src_cfg->__code;
CHECK_CODE(configurationVersion)
CHECK_CODE(profile_idc)
CHECK_CODE(profile_space)
CHECK_CODE(tier_flag)
CHECK_CODE(general_profile_compatibility_flags)
CHECK_CODE(progressive_source_flag)
CHECK_CODE(interlaced_source_flag)
CHECK_CODE(constraint_indicator_flags)
CHECK_CODE(level_idc)
CHECK_CODE(min_spatial_segmentation_idc)
}
void merge_all_config(GF_AVCConfig *avc_cfg, GF_HEVCConfig *hevc_cfg, GF_MediaBox *mdia)
{
u32 i;
GF_TrackReferenceTypeBox *scal = NULL;
Track_FindRef(mdia->mediaTrack, GF_ISOM_REF_SCAL, &scal);
if (!scal) return;
for (i=0; i<scal->trackIDCount; i++) {
GF_TrackBox *a_track = GetTrackbyID(mdia->mediaTrack->moov, scal->trackIDs[i]);
GF_MPEGVisualSampleEntryBox *an_entry = NULL;
if (a_track && a_track->Media && a_track->Media->information && a_track->Media->information->sampleTable && a_track->Media->information->sampleTable->SampleDescription)
an_entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(a_track->Media->information->sampleTable->SampleDescription->other_boxes, 0);
if (!an_entry) continue;
if (avc_cfg && an_entry->svc_config && an_entry->svc_config->config)
merge_avc_config(avc_cfg, an_entry->svc_config->config);
if (avc_cfg && an_entry->mvc_config && an_entry->mvc_config->config)
merge_avc_config(avc_cfg, an_entry->mvc_config->config);
if (avc_cfg && an_entry->avc_config && an_entry->avc_config->config)
merge_avc_config(avc_cfg, an_entry->avc_config->config);
if (hevc_cfg && an_entry->lhvc_config && an_entry->lhvc_config->config)
merge_hevc_config(hevc_cfg, an_entry->lhvc_config->config, GF_TRUE);
if (hevc_cfg && an_entry->hevc_config && an_entry->hevc_config->config)
merge_hevc_config(hevc_cfg, an_entry->hevc_config->config, GF_TRUE);
}
if (hevc_cfg) hevc_cfg->is_lhvc = GF_FALSE;
}
void AVC_RewriteESDescriptorEx(GF_MPEGVisualSampleEntryBox *avc, GF_MediaBox *mdia)
{
GF_AVCConfig *avcc, *svcc, *mvcc;
GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)avc, GF_FALSE);
if (avc->emul_esd) gf_odf_desc_del((GF_Descriptor *)avc->emul_esd);
avc->emul_esd = gf_odf_desc_esd_new(2);
avc->emul_esd->decoderConfig->streamType = GF_STREAM_VISUAL;
/*AVC OTI is 0x21, AVC parameter set stream OTI (not supported in gpac) is 0x22, SVC OTI is 0x24*/
/*if we have only SVC stream, set objectTypeIndication to AVC OTI; else set it to AVC OTI*/
if (avc->svc_config && !avc->avc_config)
avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_SVC;
else if (avc->mvc_config && !avc->avc_config)
avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MVC;
else
avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_AVC;
if (btrt) {
avc->emul_esd->decoderConfig->bufferSizeDB = btrt->bufferSizeDB;
avc->emul_esd->decoderConfig->avgBitrate = btrt->avgBitrate;
avc->emul_esd->decoderConfig->maxBitrate = btrt->maxBitrate;
}
if (avc->descr) {
u32 i=0;
GF_Descriptor *desc,*clone;
i=0;
while ((desc = (GF_Descriptor *)gf_list_enum(avc->descr->descriptors, &i))) {
clone = NULL;
gf_odf_desc_copy(desc, &clone);
if (gf_odf_desc_add_desc((GF_Descriptor *)avc->emul_esd, clone) != GF_OK)
gf_odf_desc_del(clone);
}
}
if (avc->avc_config) {
avcc = avc->avc_config->config ? AVC_DuplicateConfig(avc->avc_config->config) : NULL;
/*merge SVC config*/
if (avc->svc_config) {
merge_avc_config(avcc, avc->svc_config->config);
}
/*merge MVC config*/
if (avc->mvc_config) {
merge_avc_config(avcc, avc->mvc_config->config);
}
if (avcc) {
if (mdia) merge_all_config(avcc, NULL, mdia);
gf_odf_avc_cfg_write(avcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_odf_avc_cfg_del(avcc);
}
} else if (avc->svc_config) {
svcc = AVC_DuplicateConfig(avc->svc_config->config);
if (mdia) merge_all_config(svcc, NULL, mdia);
gf_odf_avc_cfg_write(svcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_odf_avc_cfg_del(svcc);
}
else if (avc->mvc_config) {
mvcc = AVC_DuplicateConfig(avc->mvc_config->config);
if (mdia) merge_all_config(mvcc, NULL, mdia);
gf_odf_avc_cfg_write(mvcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_odf_avc_cfg_del(mvcc);
}
}
void AVC_RewriteESDescriptor(GF_MPEGVisualSampleEntryBox *avc)
{
AVC_RewriteESDescriptorEx(avc, NULL);
}
void HEVC_RewriteESDescriptorEx(GF_MPEGVisualSampleEntryBox *hevc, GF_MediaBox *mdia)
{
GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)hevc, GF_FALSE);
if (hevc->emul_esd) gf_odf_desc_del((GF_Descriptor *)hevc->emul_esd);
hevc->emul_esd = gf_odf_desc_esd_new(2);
hevc->emul_esd->decoderConfig->streamType = GF_STREAM_VISUAL;
hevc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_HEVC;
if (hevc->lhvc_config /*&& !hevc->hevc_config*/)
hevc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_LHVC;
if (btrt) {
hevc->emul_esd->decoderConfig->bufferSizeDB = btrt->bufferSizeDB;
hevc->emul_esd->decoderConfig->avgBitrate = btrt->avgBitrate;
hevc->emul_esd->decoderConfig->maxBitrate = btrt->maxBitrate;
}
if (hevc->descr) {
u32 i=0;
GF_Descriptor *desc,*clone;
i=0;
while ((desc = (GF_Descriptor *)gf_list_enum(hevc->descr->descriptors, &i))) {
clone = NULL;
gf_odf_desc_copy(desc, &clone);
if (gf_odf_desc_add_desc((GF_Descriptor *)hevc->emul_esd, clone) != GF_OK)
gf_odf_desc_del(clone);
}
}
if (hevc->hevc_config || hevc->lhvc_config) {
GF_HEVCConfig *hcfg = HEVC_DuplicateConfig(hevc->hevc_config ? hevc->hevc_config->config : hevc->lhvc_config->config);
if (hevc->hevc_config && hevc->lhvc_config) {
//merge LHVC config to HEVC conf, so we add entry rather than insert
merge_hevc_config(hcfg, hevc->lhvc_config->config, GF_FALSE);
}
if (mdia) merge_all_config(NULL, hcfg, mdia);
if (hcfg) {
if (mdia && ((mdia->mediaTrack->extractor_mode&0x0000FFFF) != GF_ISOM_NALU_EXTRACT_INSPECT)) {
hcfg->is_lhvc=GF_FALSE;
}
gf_odf_hevc_cfg_write(hcfg, &hevc->emul_esd->decoderConfig->decoderSpecificInfo->data, &hevc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength);
gf_odf_hevc_cfg_del(hcfg);
}
}
}
void HEVC_RewriteESDescriptor(GF_MPEGVisualSampleEntryBox *hevc)
{
HEVC_RewriteESDescriptorEx(hevc, NULL);
}
GF_Err AVC_HEVC_UpdateESD(GF_MPEGVisualSampleEntryBox *avc, GF_ESD *esd)
{
GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)avc, GF_TRUE);
if (avc->descr) gf_isom_box_del((GF_Box *) avc->descr);
avc->descr = NULL;
btrt->avgBitrate = esd->decoderConfig->avgBitrate;
btrt->maxBitrate = esd->decoderConfig->maxBitrate;
btrt->bufferSizeDB = esd->decoderConfig->bufferSizeDB;
if (gf_list_count(esd->IPIDataSet)
|| gf_list_count(esd->IPMPDescriptorPointers)
|| esd->langDesc
|| gf_list_count(esd->extensionDescriptors)
|| esd->ipiPtr || esd->qos || esd->RegDescriptor) {
avc->descr = (GF_MPEG4ExtensionDescriptorsBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_M4DS);
if (esd->RegDescriptor) {
gf_list_add(avc->descr->descriptors, esd->RegDescriptor);
esd->RegDescriptor = NULL;
}
if (esd->qos) {
gf_list_add(avc->descr->descriptors, esd->qos);
esd->qos = NULL;
}
if (esd->ipiPtr) {
gf_list_add(avc->descr->descriptors, esd->ipiPtr);
esd->ipiPtr= NULL;
}
while (gf_list_count(esd->IPIDataSet)) {
GF_Descriptor *desc = (GF_Descriptor *)gf_list_get(esd->IPIDataSet, 0);
gf_list_rem(esd->IPIDataSet, 0);
gf_list_add(avc->descr->descriptors, desc);
}
while (gf_list_count(esd->IPMPDescriptorPointers)) {
GF_Descriptor *desc = (GF_Descriptor *)gf_list_get(esd->IPMPDescriptorPointers, 0);
gf_list_rem(esd->IPMPDescriptorPointers, 0);
gf_list_add(avc->descr->descriptors, desc);
}
if (esd->langDesc) {
gf_list_add(avc->descr->descriptors, esd->langDesc);
esd->langDesc = NULL;
}
while (gf_list_count(esd->extensionDescriptors)) {
GF_Descriptor *desc = (GF_Descriptor *)gf_list_get(esd->extensionDescriptors, 0);
gf_list_rem(esd->extensionDescriptors, 0);
gf_list_add(avc->descr->descriptors, desc);
}
}
if (!avc->lhvc_config && (esd->decoderConfig->objectTypeIndication==GPAC_OTI_VIDEO_HEVC)) {
if (!avc->hevc_config) avc->hevc_config = (GF_HEVCConfigurationBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_HVCC);
if (esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) {
if (avc->hevc_config->config) gf_odf_hevc_cfg_del(avc->hevc_config->config);
avc->hevc_config->config = gf_odf_hevc_cfg_read(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, GF_FALSE);
}
}
else if (!avc->svc_config && !avc->mvc_config && (esd->decoderConfig->objectTypeIndication==GPAC_OTI_VIDEO_AVC)) {
if (!avc->avc_config) avc->avc_config = (GF_AVCConfigurationBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_AVCC);
if (esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) {
if (avc->avc_config->config) gf_odf_avc_cfg_del(avc->avc_config->config);
avc->avc_config->config = gf_odf_avc_cfg_read(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength);
}
}
gf_odf_desc_del((GF_Descriptor *)esd);
if (avc->hevc_config) {
HEVC_RewriteESDescriptor(avc);
} else {
AVC_RewriteESDescriptor(avc);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_EXPORT
GF_Err gf_isom_avc_config_new(GF_ISOFile *the_file, u32 trackNumber, GF_AVCConfig *cfg, char *URLname, char *URNname, u32 *outDescriptionIndex)
{
GF_TrackBox *trak;
GF_Err e;
u32 dataRefIndex;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !cfg) return GF_BAD_PARAM;
//get or create the data ref
e = Media_FindDataRef(trak->Media->information->dataInformation->dref, URLname, URNname, &dataRefIndex);
if (e) return e;
if (!dataRefIndex) {
e = Media_CreateDataRef(trak->Media->information->dataInformation->dref, URLname, URNname, &dataRefIndex);
if (e) return e;
}
if (!the_file->keep_utc)
trak->Media->mediaHeader->modificationTime = gf_isom_get_mp4time();
//create a new entry
entry = (GF_MPEGVisualSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_AVC1);
if (!entry) return GF_OUT_OF_MEM;
entry->avc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_AVCC);
entry->avc_config->config = AVC_DuplicateConfig(cfg);
entry->dataReferenceIndex = dataRefIndex;
e = gf_list_add(trak->Media->information->sampleTable->SampleDescription->other_boxes, entry);
*outDescriptionIndex = gf_list_count(trak->Media->information->sampleTable->SampleDescription->other_boxes);
AVC_RewriteESDescriptor(entry);
return e;
}
static GF_Err gf_isom_avc_config_update_ex(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_AVCConfig *cfg, u32 op_type)
{
GF_TrackBox *trak;
GF_Err e;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return GF_BAD_PARAM;
entry = (GF_MPEGVisualSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return GF_BAD_PARAM;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
break;
default:
return GF_BAD_PARAM;
}
switch (op_type) {
/*AVCC replacement*/
case 0:
if (!cfg) return GF_BAD_PARAM;
if (!entry->avc_config) entry->avc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_AVCC);
if (entry->avc_config->config) gf_odf_avc_cfg_del(entry->avc_config->config);
entry->avc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_AVC1;
break;
/*SVCC replacement*/
case 1:
if (!cfg) return GF_BAD_PARAM;
if (!entry->svc_config) entry->svc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_SVCC);
if (entry->svc_config->config) gf_odf_avc_cfg_del(entry->svc_config->config);
entry->svc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_AVC1;
break;
/*SVCC replacement and AVC removal*/
case 2:
if (!cfg) return GF_BAD_PARAM;
if (entry->avc_config) {
gf_isom_box_del((GF_Box*)entry->avc_config);
entry->avc_config = NULL;
}
if (!entry->svc_config) entry->svc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_SVCC);
if (entry->svc_config->config) gf_odf_avc_cfg_del(entry->svc_config->config);
entry->svc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_SVC1;
break;
/*AVCC removal and switch to avc3*/
case 3:
if (!entry->avc_config || !entry->avc_config->config)
return GF_BAD_PARAM;
if (entry->svc_config) {
gf_isom_box_del((GF_Box*)entry->svc_config);
entry->svc_config = NULL;
}
if (entry->mvc_config) {
gf_isom_box_del((GF_Box*)entry->mvc_config);
entry->mvc_config = NULL;
}
while (gf_list_count(entry->avc_config->config->sequenceParameterSets)) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(entry->avc_config->config->sequenceParameterSets, 0);
gf_list_rem(entry->avc_config->config->sequenceParameterSets, 0);
if (sl->data) gf_free(sl->data);
gf_free(sl);
}
while (gf_list_count(entry->avc_config->config->pictureParameterSets)) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(entry->avc_config->config->pictureParameterSets, 0);
gf_list_rem(entry->avc_config->config->pictureParameterSets, 0);
if (sl->data) gf_free(sl->data);
gf_free(sl);
}
if (entry->type == GF_ISOM_BOX_TYPE_AVC1)
entry->type = GF_ISOM_BOX_TYPE_AVC3;
else if (entry->type == GF_ISOM_BOX_TYPE_AVC2)
entry->type = GF_ISOM_BOX_TYPE_AVC4;
break;
/*MVCC replacement*/
case 4:
if (!cfg) return GF_BAD_PARAM;
if (!entry->mvc_config) entry->mvc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_MVCC);
if (entry->mvc_config->config) gf_odf_avc_cfg_del(entry->mvc_config->config);
entry->mvc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_AVC1;
break;
/*MVCC replacement and AVC removal*/
case 5:
if (!cfg) return GF_BAD_PARAM;
if (entry->avc_config) {
gf_isom_box_del((GF_Box*)entry->avc_config);
entry->avc_config = NULL;
}
if (!entry->mvc_config) entry->mvc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_MVCC);
if (entry->mvc_config->config) gf_odf_avc_cfg_del(entry->mvc_config->config);
entry->mvc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_MVC1;
break;
}
AVC_RewriteESDescriptor(entry);
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_avc_set_inband_config(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
return gf_isom_avc_config_update_ex(the_file, trackNumber, DescriptionIndex, NULL, 3);
}
GF_EXPORT
GF_Err gf_isom_avc_config_update(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_AVCConfig *cfg)
{
return gf_isom_avc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, 0);
}
GF_Err gf_isom_svc_config_update(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_AVCConfig *cfg, Bool is_add)
{
return gf_isom_avc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, is_add ? 1 : 2);
}
GF_Err gf_isom_mvc_config_update(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_AVCConfig *cfg, Bool is_add)
{
return gf_isom_avc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, is_add ? 4 : 5);
}
static GF_Err gf_isom_svc_mvc_config_del(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, Bool is_mvc)
{
GF_TrackBox *trak;
GF_Err e;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return GF_BAD_PARAM;
entry = (GF_MPEGVisualSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return GF_BAD_PARAM;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
break;
default:
return GF_BAD_PARAM;
}
if (is_mvc && entry->mvc_config) {
gf_isom_box_del((GF_Box*)entry->mvc_config);
entry->mvc_config = NULL;
}
else if (!is_mvc && entry->svc_config) {
gf_isom_box_del((GF_Box*)entry->svc_config);
entry->svc_config = NULL;
}
AVC_RewriteESDescriptor(entry);
return GF_OK;
}
GF_Err gf_isom_svc_config_del(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
return gf_isom_svc_mvc_config_del(the_file, trackNumber, DescriptionIndex, GF_FALSE);
}
GF_Err gf_isom_mvc_config_del(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
return gf_isom_svc_mvc_config_del(the_file, trackNumber, DescriptionIndex, GF_TRUE);
}
GF_EXPORT
GF_Err gf_isom_set_ipod_compatible(GF_ISOFile *the_file, u32 trackNumber)
{
GF_TrackBox *trak;
GF_Err e;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media) return GF_BAD_PARAM;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, 0);
if (!entry) return GF_OK;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
case GF_ISOM_BOX_TYPE_HVC1:
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVT1:
break;
default:
return GF_OK;
}
if (!entry->ipod_ext) entry->ipod_ext = (GF_UnknownUUIDBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_UUID);
memcpy(entry->ipod_ext->uuid, GF_ISOM_IPOD_EXT, sizeof(u8)*16);
entry->ipod_ext->dataSize = 0;
return GF_OK;
}
static GF_Err gf_isom_svc_mvc_config_new(GF_ISOFile *the_file, u32 trackNumber, GF_AVCConfig *cfg, Bool is_mvc, char *URLname, char *URNname, u32 *outDescriptionIndex)
{
GF_TrackBox *trak;
GF_Err e;
u32 dataRefIndex;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !cfg) return GF_BAD_PARAM;
//get or create the data ref
e = Media_FindDataRef(trak->Media->information->dataInformation->dref, URLname, URNname, &dataRefIndex);
if (e) return e;
if (!dataRefIndex) {
e = Media_CreateDataRef(trak->Media->information->dataInformation->dref, URLname, URNname, &dataRefIndex);
if (e) return e;
}
if (!the_file->keep_utc)
trak->Media->mediaHeader->modificationTime = gf_isom_get_mp4time();
//create a new entry
if (is_mvc) {
entry = (GF_MPEGVisualSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_MVC1);
if (!entry) return GF_OUT_OF_MEM;
entry->mvc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_MVCC);
entry->mvc_config->config = AVC_DuplicateConfig(cfg);
} else {
entry = (GF_MPEGVisualSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_SVC1);
if (!entry) return GF_OUT_OF_MEM;
entry->svc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_SVCC);
entry->svc_config->config = AVC_DuplicateConfig(cfg);
}
entry->dataReferenceIndex = dataRefIndex;
e = gf_list_add(trak->Media->information->sampleTable->SampleDescription->other_boxes, entry);
*outDescriptionIndex = gf_list_count(trak->Media->information->sampleTable->SampleDescription->other_boxes);
AVC_RewriteESDescriptor(entry);
return e;
}
GF_EXPORT
GF_Err gf_isom_svc_config_new(GF_ISOFile *the_file, u32 trackNumber, GF_AVCConfig *cfg, char *URLname, char *URNname, u32 *outDescriptionIndex)
{
return gf_isom_svc_mvc_config_new(the_file, trackNumber, cfg, GF_FALSE, URLname, URNname,outDescriptionIndex);
}
GF_EXPORT
GF_Err gf_isom_mvc_config_new(GF_ISOFile *the_file, u32 trackNumber, GF_AVCConfig *cfg, char *URLname, char *URNname, u32 *outDescriptionIndex)
{
return gf_isom_svc_mvc_config_new(the_file, trackNumber, cfg, GF_TRUE, URLname, URNname,outDescriptionIndex);
}
GF_EXPORT
GF_Err gf_isom_hevc_config_new(GF_ISOFile *the_file, u32 trackNumber, GF_HEVCConfig *cfg, char *URLname, char *URNname, u32 *outDescriptionIndex)
{
GF_TrackBox *trak;
GF_Err e;
u32 dataRefIndex;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !cfg) return GF_BAD_PARAM;
//get or create the data ref
e = Media_FindDataRef(trak->Media->information->dataInformation->dref, URLname, URNname, &dataRefIndex);
if (e) return e;
if (!dataRefIndex) {
e = Media_CreateDataRef(trak->Media->information->dataInformation->dref, URLname, URNname, &dataRefIndex);
if (e) return e;
}
if (!the_file->keep_utc)
trak->Media->mediaHeader->modificationTime = gf_isom_get_mp4time();
//create a new entry
entry = (GF_MPEGVisualSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_HVC1);
if (!entry) return GF_OUT_OF_MEM;
entry->hevc_config = (GF_HEVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_HVCC);
entry->hevc_config->config = HEVC_DuplicateConfig(cfg);
entry->dataReferenceIndex = dataRefIndex;
e = gf_list_add(trak->Media->information->sampleTable->SampleDescription->other_boxes, entry);
*outDescriptionIndex = gf_list_count(trak->Media->information->sampleTable->SampleDescription->other_boxes);
HEVC_RewriteESDescriptor(entry);
return e;
}
typedef enum
{
GF_ISOM_HVCC_UPDATE = 0,
GF_ISOM_HVCC_SET_INBAND,
GF_ISOM_HVCC_SET_TILE,
GF_ISOM_HVCC_SET_TILE_BASE_TRACK,
GF_ISOM_HVCC_SET_LHVC,
GF_ISOM_HVCC_SET_LHVC_WITH_BASE,
GF_ISOM_HVCC_SET_LHVC_WITH_BASE_BACKWARD,
GF_ISOM_LHCC_SET_INBAND
} HevcConfigUpdateType;
static Bool hevc_cleanup_config(GF_HEVCConfig *cfg, HevcConfigUpdateType operand_type)
{
u32 i;
Bool array_incomplete = (operand_type==GF_ISOM_HVCC_SET_INBAND) ? 1 : 0;
if (!cfg) return 0;
for (i=0; i<gf_list_count(cfg->param_array); i++) {
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(cfg->param_array, i);
/*we want to force hev1*/
if (operand_type==GF_ISOM_HVCC_SET_INBAND) {
ar->array_completeness = 0;
while (gf_list_count(ar->nalus)) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(ar->nalus, 0);
gf_list_rem(ar->nalus, 0);
if (sl->data) gf_free(sl->data);
gf_free(sl);
}
gf_list_del(ar->nalus);
gf_free(ar);
gf_list_rem(cfg->param_array, i);
i--;
}
if (!ar->array_completeness)
array_incomplete = 1;
}
return array_incomplete;
}
static
GF_Err gf_isom_hevc_config_update_ex(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_HEVCConfig *cfg, u32 operand_type)
{
u32 array_incomplete;
GF_TrackBox *trak;
GF_Err e;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return GF_BAD_PARAM;
entry = (GF_MPEGVisualSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return GF_BAD_PARAM;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_HVC1:
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVC2:
case GF_ISOM_BOX_TYPE_HEV2:
case GF_ISOM_BOX_TYPE_LHV1:
case GF_ISOM_BOX_TYPE_LHE1:
case GF_ISOM_BOX_TYPE_HVT1:
break;
default:
return GF_BAD_PARAM;
}
if (operand_type == GF_ISOM_HVCC_SET_TILE_BASE_TRACK) {
if (entry->type==GF_ISOM_BOX_TYPE_HVC1)
entry->type = GF_ISOM_BOX_TYPE_HVC2;
else if (entry->type==GF_ISOM_BOX_TYPE_HEV1)
entry->type = GF_ISOM_BOX_TYPE_HEV2;
} else if (operand_type == GF_ISOM_HVCC_SET_TILE) {
if (!entry->hevc_config) entry->hevc_config = (GF_HEVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_HVCC);
if (entry->hevc_config->config) gf_odf_hevc_cfg_del(entry->hevc_config->config);
entry->hevc_config->config = NULL;
entry->type = GF_ISOM_BOX_TYPE_HVT1;
} else if (operand_type < GF_ISOM_HVCC_SET_LHVC) {
if ((operand_type != GF_ISOM_HVCC_SET_INBAND) && !entry->hevc_config)
entry->hevc_config = (GF_HEVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_HVCC);
if (cfg) {
if (entry->hevc_config->config) gf_odf_hevc_cfg_del(entry->hevc_config->config);
entry->hevc_config->config = HEVC_DuplicateConfig(cfg);
} else if (operand_type != GF_ISOM_HVCC_SET_TILE) {
operand_type=GF_ISOM_HVCC_SET_INBAND;
}
array_incomplete = (operand_type==GF_ISOM_HVCC_SET_INBAND) ? 1 : 0;
if (entry->hevc_config && hevc_cleanup_config(entry->hevc_config->config, operand_type))
array_incomplete=1;
if (entry->lhvc_config && hevc_cleanup_config(entry->lhvc_config->config, operand_type))
array_incomplete=1;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVC1:
entry->type = array_incomplete ? GF_ISOM_BOX_TYPE_HEV1 : GF_ISOM_BOX_TYPE_HVC1;
break;
case GF_ISOM_BOX_TYPE_HEV2:
case GF_ISOM_BOX_TYPE_HVC2:
entry->type = array_incomplete ? GF_ISOM_BOX_TYPE_HEV2 : GF_ISOM_BOX_TYPE_HVC2;
break;
case GF_ISOM_BOX_TYPE_LHE1:
case GF_ISOM_BOX_TYPE_LHV1:
entry->type = array_incomplete ? GF_ISOM_BOX_TYPE_LHE1 : GF_ISOM_BOX_TYPE_LHV1;
break;
}
} else {
/*SVCC replacement/removal with HEVC base, backward compatible signaling*/
if ((operand_type==GF_ISOM_HVCC_SET_LHVC_WITH_BASE_BACKWARD) || (operand_type==GF_ISOM_HVCC_SET_LHVC_WITH_BASE)) {
if (!entry->hevc_config) return GF_BAD_PARAM;
if (!cfg) {
if (entry->lhvc_config) {
gf_isom_box_del((GF_Box*)entry->lhvc_config);
entry->lhvc_config = NULL;
}
if (entry->type==GF_ISOM_BOX_TYPE_LHE1) entry->type = (operand_type==GF_ISOM_HVCC_SET_LHVC_WITH_BASE) ? GF_ISOM_BOX_TYPE_HEV2 : GF_ISOM_BOX_TYPE_HEV1;
else if (entry->type==GF_ISOM_BOX_TYPE_HEV1) entry->type = (operand_type==GF_ISOM_HVCC_SET_LHVC_WITH_BASE) ? GF_ISOM_BOX_TYPE_HEV2 : GF_ISOM_BOX_TYPE_HEV1;
else entry->type = (operand_type==GF_ISOM_HVCC_SET_LHVC_WITH_BASE) ? GF_ISOM_BOX_TYPE_HVC2 : GF_ISOM_BOX_TYPE_HVC1;
} else {
if (!entry->lhvc_config) entry->lhvc_config = (GF_HEVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_LHVC);
if (entry->lhvc_config->config) gf_odf_hevc_cfg_del(entry->lhvc_config->config);
entry->lhvc_config->config = HEVC_DuplicateConfig(cfg);
if (operand_type==GF_ISOM_HVCC_SET_LHVC_WITH_BASE_BACKWARD) {
if (entry->type==GF_ISOM_BOX_TYPE_HEV2) entry->type = GF_ISOM_BOX_TYPE_HEV1;
else entry->type = GF_ISOM_BOX_TYPE_HVC1;
} else {
if (entry->type==GF_ISOM_BOX_TYPE_HEV1) entry->type = GF_ISOM_BOX_TYPE_HEV2;
else entry->type = GF_ISOM_BOX_TYPE_HVC2;
}
}
}
/*LHEVC track without base*/
else if (operand_type==GF_ISOM_HVCC_SET_LHVC) {
if (entry->hevc_config) {
gf_isom_box_del((GF_Box*)entry->hevc_config);
entry->hevc_config=NULL;
}
if (!cfg) return GF_BAD_PARAM;
if (!entry->lhvc_config) entry->lhvc_config = (GF_HEVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_LHVC);
if (entry->lhvc_config->config) gf_odf_hevc_cfg_del(entry->lhvc_config->config);
entry->lhvc_config->config = HEVC_DuplicateConfig(cfg);
if ((entry->type==GF_ISOM_BOX_TYPE_HEV1) || (entry->type==GF_ISOM_BOX_TYPE_HEV2)) entry->type = GF_ISOM_BOX_TYPE_LHE1;
else entry->type = GF_ISOM_BOX_TYPE_LHV1;
}
/*LHEVC inband, no config change*/
else if (operand_type==GF_ISOM_LHCC_SET_INBAND) {
entry->type = GF_ISOM_BOX_TYPE_LHE1;
}
}
HEVC_RewriteESDescriptor(entry);
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_hevc_config_update(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_HEVCConfig *cfg)
{
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_UPDATE);
}
GF_EXPORT
GF_Err gf_isom_hevc_set_inband_config(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, NULL, GF_ISOM_HVCC_SET_INBAND);
}
GF_EXPORT
GF_Err gf_isom_lhvc_force_inband_config(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, NULL, GF_ISOM_LHCC_SET_INBAND);
}
GF_EXPORT
GF_Err gf_isom_hevc_set_tile_config(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_HEVCConfig *cfg, Bool is_base_track)
{
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, is_base_track ? GF_ISOM_HVCC_SET_TILE_BASE_TRACK : GF_ISOM_HVCC_SET_TILE);
}
GF_Err gf_isom_lhvc_config_update(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_HEVCConfig *cfg, GF_ISOMLHEVCTrackType track_type)
{
if (cfg) cfg->is_lhvc = GF_TRUE;
switch (track_type) {
case GF_ISOM_LEHVC_ONLY:
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_SET_LHVC);
case GF_ISOM_LEHVC_WITH_BASE:
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_SET_LHVC_WITH_BASE);
case GF_ISOM_LEHVC_WITH_BASE_BACKWARD:
return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_SET_LHVC_WITH_BASE_BACKWARD);
default:
return GF_BAD_PARAM;
}
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_EXPORT
GF_Box *gf_isom_clone_config_box(GF_Box *box)
{
GF_Box *clone;
switch (box->type)
{
case GF_ISOM_BOX_TYPE_AVCC:
case GF_ISOM_BOX_TYPE_SVCC:
case GF_ISOM_BOX_TYPE_MVCC:
clone = gf_isom_box_new(box->type);
((GF_AVCConfigurationBox *)clone)->config = AVC_DuplicateConfig(((GF_AVCConfigurationBox *)box)->config);
break;
case GF_ISOM_BOX_TYPE_HVCC:
clone = gf_isom_box_new(box->type);
((GF_HEVCConfigurationBox *)clone)->config = HEVC_DuplicateConfig(((GF_HEVCConfigurationBox *)box)->config);
break;
default:
clone = NULL;
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("Cloning of config not supported for type %s\n", gf_4cc_to_str(box->type)));
break;
}
return clone;
}
GF_EXPORT
GF_AVCConfig *gf_isom_avc_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return NULL;
if (gf_isom_get_avc_svc_type(the_file, trackNumber, DescriptionIndex)==GF_ISOM_AVCTYPE_NONE)
return NULL;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return NULL;
if (!entry->avc_config) return NULL;
return AVC_DuplicateConfig(entry->avc_config->config);
}
GF_EXPORT
GF_HEVCConfig *gf_isom_hevc_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
if (gf_isom_get_reference_count(the_file, trackNumber, GF_ISOM_REF_TBAS)) {
u32 ref_track;
GF_Err e = gf_isom_get_reference(the_file, trackNumber, GF_ISOM_REF_TBAS, 1, &ref_track);
if (e == GF_OK) {
trackNumber = ref_track;
}
}
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return NULL;
if (gf_isom_get_hevc_lhvc_type(the_file, trackNumber, DescriptionIndex)==GF_ISOM_HEVCTYPE_NONE)
return NULL;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return NULL;
if (!entry->hevc_config) return NULL;
return HEVC_DuplicateConfig(entry->hevc_config->config);
}
GF_EXPORT
GF_AVCConfig *gf_isom_svc_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return NULL;
if (gf_isom_get_avc_svc_type(the_file, trackNumber, DescriptionIndex)==GF_ISOM_AVCTYPE_NONE)
return NULL;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return NULL;
if (!entry->svc_config) return NULL;
return AVC_DuplicateConfig(entry->svc_config->config);
}
GF_EXPORT
GF_AVCConfig *gf_isom_mvc_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return NULL;
if (gf_isom_get_avc_svc_type(the_file, trackNumber, DescriptionIndex)==GF_ISOM_AVCTYPE_NONE)
return NULL;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return NULL;
if (!entry->mvc_config) return NULL;
return AVC_DuplicateConfig(entry->mvc_config->config);
}
GF_EXPORT
u32 gf_isom_get_avc_svc_type(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
u32 type;
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return GF_ISOM_AVCTYPE_NONE;
if (trak->Media->handler->handlerType != GF_ISOM_MEDIA_VISUAL) return GF_ISOM_AVCTYPE_NONE;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return GF_ISOM_AVCTYPE_NONE;
type = entry->type;
if (type == GF_ISOM_BOX_TYPE_ENCV) {
GF_ProtectionSchemeInfoBox *sinf = (GF_ProtectionSchemeInfoBox *) gf_list_get(entry->protections, 0);
if (sinf && sinf->original_format) type = sinf->original_format->data_format;
}
else if (type == GF_ISOM_BOX_TYPE_RESV) {
if (entry->rinf && entry->rinf->original_format) type = entry->rinf->original_format->data_format;
}
switch (type) {
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
break;
default:
return GF_ISOM_AVCTYPE_NONE;
}
if (entry->avc_config && !entry->svc_config && !entry->mvc_config) return GF_ISOM_AVCTYPE_AVC_ONLY;
if (entry->avc_config && entry->svc_config) return GF_ISOM_AVCTYPE_AVC_SVC;
if (entry->avc_config && entry->mvc_config) return GF_ISOM_AVCTYPE_AVC_MVC;
if (!entry->avc_config && entry->svc_config) return GF_ISOM_AVCTYPE_SVC_ONLY;
if (!entry->avc_config && entry->mvc_config) return GF_ISOM_AVCTYPE_MVC_ONLY;
return GF_ISOM_AVCTYPE_NONE;
}
GF_EXPORT
u32 gf_isom_get_hevc_lhvc_type(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
u32 type;
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return GF_ISOM_HEVCTYPE_NONE;
if (trak->Media->handler->handlerType != GF_ISOM_MEDIA_VISUAL) return GF_ISOM_HEVCTYPE_NONE;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return GF_ISOM_AVCTYPE_NONE;
type = entry->type;
if (type == GF_ISOM_BOX_TYPE_ENCV) {
GF_ProtectionSchemeInfoBox *sinf = (GF_ProtectionSchemeInfoBox *) gf_list_get(entry->protections, 0);
if (sinf && sinf->original_format) type = sinf->original_format->data_format;
}
else if (type == GF_ISOM_BOX_TYPE_RESV) {
if (entry->rinf && entry->rinf->original_format) type = entry->rinf->original_format->data_format;
}
switch (type) {
case GF_ISOM_BOX_TYPE_HVC1:
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVC2:
case GF_ISOM_BOX_TYPE_HEV2:
case GF_ISOM_BOX_TYPE_LHV1:
case GF_ISOM_BOX_TYPE_LHE1:
case GF_ISOM_BOX_TYPE_HVT1:
break;
default:
return GF_ISOM_HEVCTYPE_NONE;
}
if (entry->hevc_config && !entry->lhvc_config) return GF_ISOM_HEVCTYPE_HEVC_ONLY;
if (entry->hevc_config && entry->lhvc_config) return GF_ISOM_HEVCTYPE_HEVC_LHVC;
if (!entry->hevc_config && entry->lhvc_config) return GF_ISOM_HEVCTYPE_LHVC_ONLY;
return GF_ISOM_HEVCTYPE_NONE;
}
GF_EXPORT
GF_HEVCConfig *gf_isom_lhvc_config_get(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex)
{
GF_HEVCConfig *lhvc;
GF_OperatingPointsInformation *oinf=NULL;
GF_TrackBox *trak;
GF_MPEGVisualSampleEntryBox *entry;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return NULL;
if (gf_isom_get_hevc_lhvc_type(the_file, trackNumber, DescriptionIndex)==GF_ISOM_HEVCTYPE_NONE)
return NULL;
entry = (GF_MPEGVisualSampleEntryBox*)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return NULL;
if (!entry->lhvc_config) return NULL;
lhvc = HEVC_DuplicateConfig(entry->lhvc_config->config);
if (!lhvc) return NULL;
gf_isom_get_oinf_info(the_file, trackNumber, &oinf);
if (oinf) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_last(oinf->profile_tier_levels);
if (ptl) {
lhvc->profile_space = ptl->general_profile_space;
lhvc->tier_flag = ptl->general_tier_flag;
lhvc->profile_idc = ptl->general_profile_idc;
lhvc->general_profile_compatibility_flags = ptl->general_profile_compatibility_flags;
lhvc->constraint_indicator_flags = ptl->general_constraint_indicator_flags;
}
}
return lhvc;
}
void btrt_del(GF_Box *s)
{
GF_BitRateBox *ptr = (GF_BitRateBox *)s;
if (ptr) gf_free(ptr);
}
GF_Err btrt_Read(GF_Box *s, GF_BitStream *bs)
{
GF_BitRateBox *ptr = (GF_BitRateBox *)s;
ptr->bufferSizeDB = gf_bs_read_u32(bs);
ptr->maxBitrate = gf_bs_read_u32(bs);
ptr->avgBitrate = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *btrt_New()
{
GF_BitRateBox *tmp = (GF_BitRateBox *) gf_malloc(sizeof(GF_BitRateBox));
if (tmp == NULL) return NULL;
memset(tmp, 0, sizeof(GF_BitRateBox));
tmp->type = GF_ISOM_BOX_TYPE_BTRT;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err btrt_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_BitRateBox *ptr = (GF_BitRateBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->bufferSizeDB);
gf_bs_write_u32(bs, ptr->maxBitrate);
gf_bs_write_u32(bs, ptr->avgBitrate);
return GF_OK;
}
GF_Err btrt_Size(GF_Box *s)
{
GF_BitRateBox *ptr = (GF_BitRateBox *)s;
ptr->size += 12;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void m4ds_del(GF_Box *s)
{
GF_MPEG4ExtensionDescriptorsBox *ptr = (GF_MPEG4ExtensionDescriptorsBox *)s;
gf_odf_desc_list_del(ptr->descriptors);
gf_list_del(ptr->descriptors);
gf_free(ptr);
}
GF_Err m4ds_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
char *enc_od;
GF_MPEG4ExtensionDescriptorsBox *ptr = (GF_MPEG4ExtensionDescriptorsBox *)s;
u32 od_size = (u32) ptr->size;
if (!od_size) return GF_OK;
enc_od = (char *)gf_malloc(sizeof(char) * od_size);
gf_bs_read_data(bs, enc_od, od_size);
e = gf_odf_desc_list_read((char *)enc_od, od_size, ptr->descriptors);
gf_free(enc_od);
return e;
}
GF_Box *m4ds_New()
{
GF_MPEG4ExtensionDescriptorsBox *tmp = (GF_MPEG4ExtensionDescriptorsBox *) gf_malloc(sizeof(GF_MPEG4ExtensionDescriptorsBox));
if (tmp == NULL) return NULL;
memset(tmp, 0, sizeof(GF_MPEG4ExtensionDescriptorsBox));
tmp->type = GF_ISOM_BOX_TYPE_M4DS;
tmp->descriptors = gf_list_new();
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err m4ds_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
char *enc_ods;
u32 enc_od_size;
GF_MPEG4ExtensionDescriptorsBox *ptr = (GF_MPEG4ExtensionDescriptorsBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
enc_ods = NULL;
enc_od_size = 0;
e = gf_odf_desc_list_write(ptr->descriptors, &enc_ods, &enc_od_size);
if (e) return e;
if (enc_od_size) {
gf_bs_write_data(bs, enc_ods, enc_od_size);
gf_free(enc_ods);
}
return GF_OK;
}
GF_Err m4ds_Size(GF_Box *s)
{
GF_Err e;
u32 descSize = 0;
GF_MPEG4ExtensionDescriptorsBox *ptr = (GF_MPEG4ExtensionDescriptorsBox *)s;
e = gf_odf_desc_list_size(ptr->descriptors, &descSize);
ptr->size += descSize;
return e;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void avcc_del(GF_Box *s)
{
GF_AVCConfigurationBox *ptr = (GF_AVCConfigurationBox *)s;
if (ptr->config) gf_odf_avc_cfg_del(ptr->config);
gf_free(ptr);
}
GF_Err avcc_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, count;
GF_AVCConfigurationBox *ptr = (GF_AVCConfigurationBox *)s;
if (ptr->config) gf_odf_avc_cfg_del(ptr->config);
ptr->config = gf_odf_avc_cfg_new();
ptr->config->configurationVersion = gf_bs_read_u8(bs);
ptr->config->AVCProfileIndication = gf_bs_read_u8(bs);
ptr->config->profile_compatibility = gf_bs_read_u8(bs);
ptr->config->AVCLevelIndication = gf_bs_read_u8(bs);
if (ptr->type==GF_ISOM_BOX_TYPE_AVCC) {
gf_bs_read_int(bs, 6);
} else {
ptr->config->complete_representation = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 5);
}
ptr->config->nal_unit_size = 1 + gf_bs_read_int(bs, 2);
gf_bs_read_int(bs, 3);
count = gf_bs_read_int(bs, 5);
ptr->size -= 7; //including 2nd count
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot *) gf_malloc(sizeof(GF_AVCConfigSlot));
sl->size = gf_bs_read_u16(bs);
sl->data = (char *)gf_malloc(sizeof(char) * sl->size);
gf_bs_read_data(bs, sl->data, sl->size);
gf_list_add(ptr->config->sequenceParameterSets, sl);
ptr->size -= 2+sl->size;
}
count = gf_bs_read_u8(bs);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot *)gf_malloc(sizeof(GF_AVCConfigSlot));
sl->size = gf_bs_read_u16(bs);
if (gf_bs_available(bs) < sl->size) {
gf_free(sl);
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("AVCC: Not enough bits to parse. Aborting.\n"));
return GF_ISOM_INVALID_FILE;
}
sl->data = (char *)gf_malloc(sizeof(char) * sl->size);
gf_bs_read_data(bs, sl->data, sl->size);
gf_list_add(ptr->config->pictureParameterSets, sl);
ptr->size -= 2+sl->size;
}
if (ptr->type==GF_ISOM_BOX_TYPE_AVCC) {
if (gf_avc_is_rext_profile(ptr->config->AVCProfileIndication)) {
if (!ptr->size) {
#ifndef GPAC_DISABLE_AV_PARSERS
AVCState avc;
s32 idx, vui_flag_pos;
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(ptr->config->sequenceParameterSets, 0);
idx = gf_media_avc_read_sps(sl->data+1, sl->size-1, &avc, 0, (u32 *) &vui_flag_pos);
if (idx>=0) {
ptr->config->chroma_format = avc.sps[idx].chroma_format;
ptr->config->luma_bit_depth = 8 + avc.sps[idx].luma_bit_depth_m8;
ptr->config->chroma_bit_depth = 8 + avc.sps[idx].chroma_bit_depth_m8;
}
#else
/*set default values ...*/
ptr->config->chroma_format = 1;
ptr->config->luma_bit_depth = 8;
ptr->config->chroma_bit_depth = 8;
#endif
return GF_OK;
}
gf_bs_read_int(bs, 6);
ptr->config->chroma_format = gf_bs_read_int(bs, 2);
gf_bs_read_int(bs, 5);
ptr->config->luma_bit_depth = 8 + gf_bs_read_int(bs, 3);
gf_bs_read_int(bs, 5);
ptr->config->chroma_bit_depth = 8 + gf_bs_read_int(bs, 3);
count = gf_bs_read_int(bs, 8);
ptr->size -= 4;
if (count*2 > ptr->size) {
//ffmpeg just ignores this part while allocating bytes (filled with garbage?)
GF_LOG(GF_LOG_WARNING, GF_LOG_CODING, ("AVCC: invalid numOfSequenceParameterSetExt value. Skipping.\n"));
return GF_OK;
}
if (count) {
ptr->config->sequenceParameterSetExtensions = gf_list_new();
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot *)gf_malloc(sizeof(GF_AVCConfigSlot));
sl->size = gf_bs_read_u16(bs);
if (gf_bs_available(bs) < sl->size) {
gf_free(sl);
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("AVCC: Not enough bits to parse. Aborting.\n"));
return GF_ISOM_INVALID_FILE;
}
sl->data = (char *)gf_malloc(sizeof(char) * sl->size);
gf_bs_read_data(bs, sl->data, sl->size);
gf_list_add(ptr->config->sequenceParameterSetExtensions, sl);
ptr->size -= sl->size + 2;
}
}
}
}
return GF_OK;
}
GF_Box *avcc_New()
{
GF_AVCConfigurationBox *tmp = (GF_AVCConfigurationBox *) gf_malloc(sizeof(GF_AVCConfigurationBox));
if (tmp == NULL) return NULL;
memset(tmp, 0, sizeof(GF_AVCConfigurationBox));
tmp->type = GF_ISOM_BOX_TYPE_AVCC;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err avcc_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i, count;
GF_Err e;
GF_AVCConfigurationBox *ptr = (GF_AVCConfigurationBox *) s;
if (!s) return GF_BAD_PARAM;
if (!ptr->config) return GF_OK;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u8(bs, ptr->config->configurationVersion);
gf_bs_write_u8(bs, ptr->config->AVCProfileIndication);
gf_bs_write_u8(bs, ptr->config->profile_compatibility);
gf_bs_write_u8(bs, ptr->config->AVCLevelIndication);
if (ptr->type==GF_ISOM_BOX_TYPE_AVCC) {
gf_bs_write_int(bs, 0x3F, 6);
} else {
gf_bs_write_int(bs, ptr->config->complete_representation, 1);
gf_bs_write_int(bs, 0x1F, 5);
}
gf_bs_write_int(bs, ptr->config->nal_unit_size - 1, 2);
gf_bs_write_int(bs, 0x7, 3);
count = gf_list_count(ptr->config->sequenceParameterSets);
gf_bs_write_int(bs, count, 5);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot *) gf_list_get(ptr->config->sequenceParameterSets, i);
gf_bs_write_u16(bs, sl->size);
gf_bs_write_data(bs, sl->data, sl->size);
}
count = gf_list_count(ptr->config->pictureParameterSets);
gf_bs_write_u8(bs, count);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot *) gf_list_get(ptr->config->pictureParameterSets, i);
gf_bs_write_u16(bs, sl->size);
gf_bs_write_data(bs, sl->data, sl->size);
}
if (ptr->type==GF_ISOM_BOX_TYPE_AVCC) {
if (gf_avc_is_rext_profile(ptr->config->AVCProfileIndication)) {
gf_bs_write_int(bs, 0xFF, 6);
gf_bs_write_int(bs, ptr->config->chroma_format, 2);
gf_bs_write_int(bs, 0xFF, 5);
gf_bs_write_int(bs, ptr->config->luma_bit_depth - 8, 3);
gf_bs_write_int(bs, 0xFF, 5);
gf_bs_write_int(bs, ptr->config->chroma_bit_depth - 8, 3);
count = ptr->config->sequenceParameterSetExtensions ? gf_list_count(ptr->config->sequenceParameterSetExtensions) : 0;
gf_bs_write_u8(bs, count);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot *) gf_list_get(ptr->config->sequenceParameterSetExtensions, i);
gf_bs_write_u16(bs, sl->size);
gf_bs_write_data(bs, sl->data, sl->size);
}
}
}
return GF_OK;
}
GF_Err avcc_Size(GF_Box *s)
{
u32 i, count;
GF_AVCConfigurationBox *ptr = (GF_AVCConfigurationBox *)s;
if (!ptr->config) {
ptr->size = 0;
return GF_OK;
}
ptr->size += 7;
count = gf_list_count(ptr->config->sequenceParameterSets);
for (i=0; i<count; i++)
ptr->size += 2 + ((GF_AVCConfigSlot *)gf_list_get(ptr->config->sequenceParameterSets, i))->size;
count = gf_list_count(ptr->config->pictureParameterSets);
for (i=0; i<count; i++)
ptr->size += 2 + ((GF_AVCConfigSlot *)gf_list_get(ptr->config->pictureParameterSets, i))->size;
if (ptr->type==GF_ISOM_BOX_TYPE_AVCC) {
if (gf_avc_is_rext_profile(ptr->config->AVCProfileIndication)) {
ptr->size += 4;
count = ptr->config->sequenceParameterSetExtensions ?gf_list_count(ptr->config->sequenceParameterSetExtensions) : 0;
for (i=0; i<count; i++)
ptr->size += 2 + ((GF_AVCConfigSlot *)gf_list_get(ptr->config->sequenceParameterSetExtensions, i))->size;
}
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void hvcc_del(GF_Box *s)
{
GF_HEVCConfigurationBox *ptr = (GF_HEVCConfigurationBox*)s;
if (ptr->config) gf_odf_hevc_cfg_del(ptr->config);
gf_free(ptr);
}
GF_Err hvcc_Read(GF_Box *s, GF_BitStream *bs)
{
u64 pos;
GF_HEVCConfigurationBox *ptr = (GF_HEVCConfigurationBox *)s;
if (ptr->config) gf_odf_hevc_cfg_del(ptr->config);
pos = gf_bs_get_position(bs);
ptr->config = gf_odf_hevc_cfg_read_bs(bs, (s->type == GF_ISOM_BOX_TYPE_HVCC) ? GF_FALSE : GF_TRUE);
pos = gf_bs_get_position(bs) - pos ;
if (pos < ptr->size)
ptr->size -= (u32) pos;
return ptr->config ? GF_OK : GF_ISOM_INVALID_FILE;
}
GF_Box *hvcc_New()
{
GF_HEVCConfigurationBox *tmp = (GF_HEVCConfigurationBox *) gf_malloc(sizeof(GF_HEVCConfigurationBox));
if (tmp == NULL) return NULL;
memset(tmp, 0, sizeof(GF_HEVCConfigurationBox));
tmp->type = GF_ISOM_BOX_TYPE_HVCC;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err hvcc_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_HEVCConfigurationBox *ptr = (GF_HEVCConfigurationBox *) s;
if (!s) return GF_BAD_PARAM;
if (!ptr->config) return GF_OK;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
return gf_odf_hevc_cfg_write_bs(ptr->config, bs);
}
GF_Err hvcc_Size(GF_Box *s)
{
u32 i, count, j, subcount;
GF_HEVCConfigurationBox *ptr = (GF_HEVCConfigurationBox *)s;
if (!ptr->config) {
ptr->size = 0;
return GF_OK;
}
if (!ptr->config->is_lhvc)
ptr->size += 23;
else
ptr->size += 6;
count = gf_list_count(ptr->config->param_array);
for (i=0; i<count; i++) {
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(ptr->config->param_array, i);
ptr->size += 3;
subcount = gf_list_count(ar->nalus);
for (j=0; j<subcount; j++) {
ptr->size += 2 + ((GF_AVCConfigSlot *)gf_list_get(ar->nalus, j))->size;
}
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_OperatingPointsInformation *gf_isom_oinf_new_entry()
{
GF_OperatingPointsInformation* ptr;
GF_SAFEALLOC(ptr, GF_OperatingPointsInformation);
if (ptr) {
ptr->profile_tier_levels = gf_list_new();
ptr->operating_points = gf_list_new();
ptr->dependency_layers = gf_list_new();
}
return ptr;
}
void gf_isom_oinf_del_entry(void *entry)
{
GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;
if (!ptr) return;
if (ptr->profile_tier_levels) {
while (gf_list_count(ptr->profile_tier_levels)) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, 0);
gf_free(ptl);
gf_list_rem(ptr->profile_tier_levels, 0);
}
gf_list_del(ptr->profile_tier_levels);
}
if (ptr->operating_points) {
while (gf_list_count(ptr->operating_points)) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, 0);
gf_free(op);
gf_list_rem(ptr->operating_points, 0);
}
gf_list_del(ptr->operating_points);
}
if (ptr->dependency_layers) {
while (gf_list_count(ptr->dependency_layers)) {
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, 0);
gf_free(dep);
gf_list_rem(ptr->dependency_layers, 0);
}
gf_list_del(ptr->dependency_layers);
}
gf_free(ptr);
return;
}
GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs)
{
GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;
u32 i, j, count;
if (!ptr) return GF_BAD_PARAM;
ptr->scalability_mask = gf_bs_read_u16(bs);
gf_bs_read_int(bs, 2);//reserved
count = gf_bs_read_int(bs, 6);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl;
GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel);
if (!ptl) return GF_OUT_OF_MEM;
ptl->general_profile_space = gf_bs_read_int(bs, 2);
ptl->general_tier_flag= gf_bs_read_int(bs, 1);
ptl->general_profile_idc = gf_bs_read_int(bs, 5);
ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs);
ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48);
ptl->general_level_idc = gf_bs_read_u8(bs);
gf_list_add(ptr->profile_tier_levels, ptl);
}
count = gf_bs_read_u16(bs);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op;
GF_SAFEALLOC(op, LHEVC_OperatingPoint);
if (!op) return GF_OUT_OF_MEM;
op->output_layer_set_idx = gf_bs_read_u16(bs);
op->max_temporal_id = gf_bs_read_u8(bs);
op->layer_count = gf_bs_read_u8(bs);
if (op->layer_count > ARRAY_LENGTH(op->layers_info))
return GF_NON_COMPLIANT_BITSTREAM;
for (j = 0; j < op->layer_count; j++) {
op->layers_info[j].ptl_idx = gf_bs_read_u8(bs);
op->layers_info[j].layer_id = gf_bs_read_int(bs, 6);
op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
}
op->minPicWidth = gf_bs_read_u16(bs);
op->minPicHeight = gf_bs_read_u16(bs);
op->maxPicWidth = gf_bs_read_u16(bs);
op->maxPicHeight = gf_bs_read_u16(bs);
op->maxChromaFormat = gf_bs_read_int(bs, 2);
op->maxBitDepth = gf_bs_read_int(bs, 3) + 8;
gf_bs_read_int(bs, 1);//reserved
op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE;
if (op->frame_rate_info_flag) {
op->avgFrameRate = gf_bs_read_u16(bs);
gf_bs_read_int(bs, 6); //reserved
op->constantFrameRate = gf_bs_read_int(bs, 2);
}
if (op->bit_rate_info_flag) {
op->maxBitRate = gf_bs_read_u32(bs);
op->avgBitRate = gf_bs_read_u32(bs);
}
gf_list_add(ptr->operating_points, op);
}
count = gf_bs_read_u8(bs);
for (i = 0; i < count; i++) {
LHEVC_DependentLayer *dep;
GF_SAFEALLOC(dep, LHEVC_DependentLayer);
if (!dep) return GF_OUT_OF_MEM;
dep->dependent_layerID = gf_bs_read_u8(bs);
dep->num_layers_dependent_on = gf_bs_read_u8(bs);
for (j = 0; j < dep->num_layers_dependent_on; j++)
dep->dependent_on_layerID[j] = gf_bs_read_u8(bs);
for (j = 0; j < 16; j++) {
if (ptr->scalability_mask & (1 << j))
dep->dimension_identifier[j] = gf_bs_read_u8(bs);
}
gf_list_add(ptr->dependency_layers, dep);
}
return GF_OK;
}
GF_Err gf_isom_oinf_write_entry(void *entry, GF_BitStream *bs)
{
GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;
u32 i, j, count;
if (!ptr) return GF_OK;
gf_bs_write_u16(bs, ptr->scalability_mask);
gf_bs_write_int(bs, 0xFF, 2);//reserved
count=gf_list_count(ptr->profile_tier_levels);
gf_bs_write_int(bs, count, 6);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
gf_bs_write_int(bs, ptl->general_profile_space, 2);
gf_bs_write_int(bs, ptl->general_tier_flag, 1);
gf_bs_write_int(bs, ptl->general_profile_idc, 5);
gf_bs_write_u32(bs, ptl->general_profile_compatibility_flags);
gf_bs_write_long_int(bs, ptl->general_constraint_indicator_flags, 48);
gf_bs_write_u8(bs, ptl->general_level_idc);
}
count=gf_list_count(ptr->operating_points);
gf_bs_write_u16(bs, count);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);;
gf_bs_write_u16(bs, op->output_layer_set_idx);
gf_bs_write_u8(bs, op->max_temporal_id);
gf_bs_write_u8(bs, op->layer_count);
for (j = 0; j < op->layer_count; j++) {
gf_bs_write_u8(bs, op->layers_info[j].ptl_idx);
gf_bs_write_int(bs, op->layers_info[j].layer_id, 6);
op->layers_info[j].is_outputlayer ? gf_bs_write_int(bs, 0x1, 1) : gf_bs_write_int(bs, 0x0, 1);
op->layers_info[j].is_alternate_outputlayer ? gf_bs_write_int(bs, 0x1, 1) : gf_bs_write_int(bs, 0x0, 1);
}
gf_bs_write_u16(bs, op->minPicWidth);
gf_bs_write_u16(bs, op->minPicHeight);
gf_bs_write_u16(bs, op->maxPicWidth);
gf_bs_write_u16(bs, op->maxPicHeight);
gf_bs_write_int(bs, op->maxChromaFormat, 2);
gf_bs_write_int(bs, op->maxBitDepth - 8, 3);
gf_bs_write_int(bs, 0x1, 1);//resereved
op->frame_rate_info_flag ? gf_bs_write_int(bs, 0x1, 1) : gf_bs_write_int(bs, 0x0, 1);
op->bit_rate_info_flag ? gf_bs_write_int(bs, 0x1, 1) : gf_bs_write_int(bs, 0x0, 1);
if (op->frame_rate_info_flag) {
gf_bs_write_u16(bs, op->avgFrameRate);
gf_bs_write_int(bs, 0xFF, 6); //reserved
gf_bs_write_int(bs, op->constantFrameRate, 2);
}
if (op->bit_rate_info_flag) {
gf_bs_write_u32(bs, op->maxBitRate);
gf_bs_write_u32(bs, op->avgBitRate);
}
}
count=gf_list_count(ptr->dependency_layers);
gf_bs_write_u8(bs, count);
for (i = 0; i < count; i++) {
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
gf_bs_write_u8(bs, dep->dependent_layerID);
gf_bs_write_u8(bs, dep->num_layers_dependent_on);
for (j = 0; j < dep->num_layers_dependent_on; j++)
gf_bs_write_u8(bs, dep->dependent_on_layerID[j]);
for (j = 0; j < 16; j++) {
if (ptr->scalability_mask & (1 << j))
gf_bs_write_u8(bs, dep->dimension_identifier[j]);
}
}
return GF_OK;
}
u32 gf_isom_oinf_size_entry(void *entry)
{
GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry;
u32 size = 0, i ,j, count;
if (!ptr) return 0;
size += 3; //scalability_mask + reserved + num_profile_tier_level
count=gf_list_count(ptr->profile_tier_levels);
size += count * 12; //general_profile_space + general_tier_flag + general_profile_idc + general_profile_compatibility_flags + general_constraint_indicator_flags + general_level_idc
size += 2;//num_operating_points
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);;
size += 2/*output_layer_set_idx*/ + 1/*max_temporal_id*/ + 1/*layer_count*/;
size += op->layer_count * 2;
size += 9;
if (op->frame_rate_info_flag) {
size += 3;
}
if (op->bit_rate_info_flag) {
size += 8;
}
}
size += 1;//max_layer_count
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
size += 1/*dependent_layerID*/ + 1/*num_layers_dependent_on*/;
size += dep->num_layers_dependent_on * 1;//dependent_on_layerID
for (j = 0; j < 16; j++) {
if (ptr->scalability_mask & (1 << j))
size += 1;//dimension_identifier
}
}
return size;
}
GF_LHVCLayerInformation *gf_isom_linf_new_entry()
{
GF_LHVCLayerInformation* ptr;
GF_SAFEALLOC(ptr, GF_LHVCLayerInformation);
if (ptr) ptr->num_layers_in_track = gf_list_new();
return ptr;
}
void gf_isom_linf_del_entry(void *entry)
{
GF_LHVCLayerInformation* ptr = (GF_LHVCLayerInformation *)entry;
if (!ptr) return;
while (gf_list_count(ptr->num_layers_in_track)) {
LHVCLayerInfoItem *li = (LHVCLayerInfoItem *)gf_list_get(ptr->num_layers_in_track, 0);
gf_free(li);
gf_list_rem(ptr->num_layers_in_track, 0);
}
gf_list_del(ptr->num_layers_in_track);
gf_free(ptr);
return;
}
GF_Err gf_isom_linf_read_entry(void *entry, GF_BitStream *bs)
{
GF_LHVCLayerInformation* ptr = (GF_LHVCLayerInformation *)entry;
u32 i, count;
if (!ptr) return GF_BAD_PARAM;
gf_bs_read_int(bs, 2);
count = gf_bs_read_int(bs, 6);
for (i = 0; i < count; i++) {
LHVCLayerInfoItem *li;
GF_SAFEALLOC(li, LHVCLayerInfoItem);
if (!li) return GF_OUT_OF_MEM;
gf_bs_read_int(bs, 4);
li->layer_id = gf_bs_read_int(bs, 6);
li->min_TemporalId = gf_bs_read_int(bs, 3);
li->max_TemporalId = gf_bs_read_int(bs, 3);
gf_bs_read_int(bs, 1);
li->sub_layer_presence_flags = gf_bs_read_int(bs, 7);
gf_list_add(ptr->num_layers_in_track, li);
}
return GF_OK;
}
GF_Err gf_isom_linf_write_entry(void *entry, GF_BitStream *bs)
{
GF_LHVCLayerInformation* ptr = (GF_LHVCLayerInformation *)entry;
u32 i, count;
if (!ptr) return GF_OK;
gf_bs_write_int(bs, 0, 2);
count=gf_list_count(ptr->num_layers_in_track);
gf_bs_write_int(bs, count, 6);
for (i = 0; i < count; i++) {
LHVCLayerInfoItem *li = (LHVCLayerInfoItem *)gf_list_get(ptr->num_layers_in_track, i);
gf_bs_write_int(bs, 0, 4);
gf_bs_write_int(bs, li->layer_id, 6);
gf_bs_write_int(bs, li->min_TemporalId, 3);
gf_bs_write_int(bs, li->max_TemporalId, 3);
gf_bs_write_int(bs, 0, 1);
gf_bs_write_int(bs, li->sub_layer_presence_flags, 7);
}
return GF_OK;
}
u32 gf_isom_linf_size_entry(void *entry)
{
GF_LHVCLayerInformation* ptr = (GF_LHVCLayerInformation *)entry;
u32 size = 0, count;
if (!ptr) return 0;
size += 1;
count=gf_list_count(ptr->num_layers_in_track);
size += count * 3;
return size;
}
#endif /*GPAC_DISABLE_ISOM*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_651_1 |
crossvul-cpp_data_good_731_0 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2014, STMicroelectronics International N.V.
*/
#include <assert.h>
#include <compiler.h>
#include <crypto/crypto.h>
#include <kernel/tee_ta_manager.h>
#include <mm/tee_mmu.h>
#include <string_ext.h>
#include <string.h>
#include <sys/queue.h>
#include <tee_api_types.h>
#include <tee/tee_cryp_utl.h>
#include <tee/tee_obj.h>
#include <tee/tee_svc_cryp.h>
#include <tee/tee_svc.h>
#include <trace.h>
#include <utee_defines.h>
#include <util.h>
#include <tee_api_defines_extensions.h>
#if defined(CFG_CRYPTO_HKDF)
#include <tee/tee_cryp_hkdf.h>
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
#include <tee/tee_cryp_concat_kdf.h>
#endif
#if defined(CFG_CRYPTO_PBKDF2)
#include <tee/tee_cryp_pbkdf2.h>
#endif
typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo);
struct tee_cryp_state {
TAILQ_ENTRY(tee_cryp_state) link;
uint32_t algo;
uint32_t mode;
vaddr_t key1;
vaddr_t key2;
void *ctx;
tee_cryp_ctx_finalize_func_t ctx_finalize;
};
struct tee_cryp_obj_secret {
uint32_t key_size;
uint32_t alloc_size;
/*
* Pseudo code visualize layout of structure
* Next follows data, such as:
* uint8_t data[alloc_size]
* key_size must never exceed alloc_size
*/
};
#define TEE_TYPE_ATTR_OPTIONAL 0x0
#define TEE_TYPE_ATTR_REQUIRED 0x1
#define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2
#define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4
#define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8
#define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10
/* Handle storing of generic secret keys of varying lengths */
#define ATTR_OPS_INDEX_SECRET 0
/* Convert to/from big-endian byte array and provider-specific bignum */
#define ATTR_OPS_INDEX_BIGNUM 1
/* Convert to/from value attribute depending on direction */
#define ATTR_OPS_INDEX_VALUE 2
struct tee_cryp_obj_type_attrs {
uint32_t attr_id;
uint16_t flags;
uint16_t ops_index;
uint16_t raw_offs;
uint16_t raw_size;
};
#define RAW_DATA(_x, _y) \
.raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_secret_value_attrs[] = {
{
.attr_id = TEE_ATTR_SECRET_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = {
{
.attr_id = TEE_ATTR_RSA_MODULUS,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_public_key, n)
},
{
.attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_public_key, e)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_RSA_MODULUS,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, n)
},
{
.attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, e)
},
{
.attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, d)
},
{
.attr_id = TEE_ATTR_RSA_PRIME1,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, p)
},
{
.attr_id = TEE_ATTR_RSA_PRIME2,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, q)
},
{
.attr_id = TEE_ATTR_RSA_EXPONENT1,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, dp)
},
{
.attr_id = TEE_ATTR_RSA_EXPONENT2,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, dq)
},
{
.attr_id = TEE_ATTR_RSA_COEFFICIENT,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, qp)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = {
{
.attr_id = TEE_ATTR_DSA_PRIME,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, p)
},
{
.attr_id = TEE_ATTR_DSA_SUBPRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, q)
},
{
.attr_id = TEE_ATTR_DSA_BASE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, g)
},
{
.attr_id = TEE_ATTR_DSA_PUBLIC_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, y)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_DSA_PRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, p)
},
{
.attr_id = TEE_ATTR_DSA_SUBPRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR |
TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, q)
},
{
.attr_id = TEE_ATTR_DSA_BASE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, g)
},
{
.attr_id = TEE_ATTR_DSA_PRIVATE_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, x)
},
{
.attr_id = TEE_ATTR_DSA_PUBLIC_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, y)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_DH_PRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR |
TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, p)
},
{
.attr_id = TEE_ATTR_DH_BASE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, g)
},
{
.attr_id = TEE_ATTR_DH_PUBLIC_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, y)
},
{
.attr_id = TEE_ATTR_DH_PRIVATE_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, x)
},
{
.attr_id = TEE_ATTR_DH_SUBPRIME,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, q)
},
{
.attr_id = TEE_ATTR_DH_X_BITS,
.flags = TEE_TYPE_ATTR_GEN_KEY_OPT,
.ops_index = ATTR_OPS_INDEX_VALUE,
RAW_DATA(struct dh_keypair, xbits)
},
};
#if defined(CFG_CRYPTO_HKDF)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_hkdf_ikm_attrs[] = {
{
.attr_id = TEE_ATTR_HKDF_IKM,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_concat_kdf_z_attrs[] = {
{
.attr_id = TEE_ATTR_CONCAT_KDF_Z,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
#endif
#if defined(CFG_CRYPTO_PBKDF2)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_pbkdf2_passwd_attrs[] = {
{
.attr_id = TEE_ATTR_PBKDF2_PASSWORD,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
#endif
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = {
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_public_key, x)
},
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_public_key, y)
},
{
.attr_id = TEE_ATTR_ECC_CURVE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_VALUE,
RAW_DATA(struct ecc_public_key, curve)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_ECC_PRIVATE_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_keypair, d)
},
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_keypair, x)
},
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_keypair, y)
},
{
.attr_id = TEE_ATTR_ECC_CURVE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_VALUE,
RAW_DATA(struct ecc_keypair, curve)
},
};
struct tee_cryp_obj_type_props {
TEE_ObjectType obj_type;
uint16_t min_size; /* may not be smaller than this */
uint16_t max_size; /* may not be larger than this */
uint16_t alloc_size; /* this many bytes are allocated to hold data */
uint8_t quanta; /* may only be an multiple of this */
uint8_t num_type_attrs;
const struct tee_cryp_obj_type_attrs *type_attrs;
};
#define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \
{ (obj_type), (min_size), (max_size), (alloc_size), (quanta), \
ARRAY_SIZE(type_attrs), (type_attrs) }
static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = {
PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */
256 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_DES, 56, 56, 56,
/*
* Valid size 56 without parity, note that we still allocate
* for 64 bits since the key is supplied with parity.
*/
64 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_DES3, 56, 112, 168,
/*
* Valid sizes 112, 168 without parity, note that we still
* allocate for with space for the parity since the key is
* supplied with parity.
*/
192 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512,
512 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512,
512 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512,
512 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024,
1024 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024,
1024 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024,
1024 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
#if defined(CFG_CRYPTO_HKDF)
PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_hkdf_ikm_attrs),
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_concat_kdf_z_attrs),
#endif
#if defined(CFG_CRYPTO_PBKDF2)
PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_pbkdf2_passwd_attrs),
#endif
PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS,
sizeof(struct rsa_public_key),
tee_cryp_obj_rsa_pub_key_attrs),
PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS,
sizeof(struct rsa_keypair),
tee_cryp_obj_rsa_keypair_attrs),
PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072,
sizeof(struct dsa_public_key),
tee_cryp_obj_dsa_pub_key_attrs),
PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072,
sizeof(struct dsa_keypair),
tee_cryp_obj_dsa_keypair_attrs),
PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048,
sizeof(struct dh_keypair),
tee_cryp_obj_dh_keypair_attrs),
PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521,
sizeof(struct ecc_public_key),
tee_cryp_obj_ecc_pub_key_attrs),
PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521,
sizeof(struct ecc_keypair),
tee_cryp_obj_ecc_keypair_attrs),
PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521,
sizeof(struct ecc_public_key),
tee_cryp_obj_ecc_pub_key_attrs),
PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521,
sizeof(struct ecc_keypair),
tee_cryp_obj_ecc_keypair_attrs),
};
struct attr_ops {
TEE_Result (*from_user)(void *attr, const void *buffer, size_t size);
TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess,
void *buffer, uint64_t *size);
TEE_Result (*to_binary)(void *attr, void *data, size_t data_len,
size_t *offs);
bool (*from_binary)(void *attr, const void *data, size_t data_len,
size_t *offs);
TEE_Result (*from_obj)(void *attr, void *src_attr);
void (*free)(void *attr);
void (*clear)(void *attr);
};
static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data,
size_t data_len, size_t *offs)
{
uint32_t field;
size_t next_offs;
if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs))
return TEE_ERROR_OVERFLOW;
if (data && next_offs <= data_len) {
field = TEE_U32_TO_BIG_ENDIAN(v);
memcpy(data + *offs, &field, sizeof(field));
}
(*offs) = next_offs;
return TEE_SUCCESS;
}
static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data,
size_t data_len, size_t *offs)
{
uint32_t field;
if (!data || (*offs + sizeof(field)) > data_len)
return false;
memcpy(&field, data + *offs, sizeof(field));
*v = TEE_U32_FROM_BIG_ENDIAN(field);
(*offs) += sizeof(field);
return true;
}
static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer,
size_t size)
{
struct tee_cryp_obj_secret *key = attr;
/* Data size has to fit in allocated buffer */
if (size > key->alloc_size)
return TEE_ERROR_SECURITY;
memcpy(key + 1, buffer, size);
key->key_size = size;
return TEE_SUCCESS;
}
static TEE_Result op_attr_secret_value_to_user(void *attr,
struct tee_ta_session *sess __unused,
void *buffer, uint64_t *size)
{
TEE_Result res;
struct tee_cryp_obj_secret *key = attr;
uint64_t s;
uint64_t key_size;
res = tee_svc_copy_from_user(&s, size, sizeof(s));
if (res != TEE_SUCCESS)
return res;
key_size = key->key_size;
res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size));
if (res != TEE_SUCCESS)
return res;
if (s < key->key_size || !buffer)
return TEE_ERROR_SHORT_BUFFER;
return tee_svc_copy_to_user(buffer, key + 1, key->key_size);
}
static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data,
size_t data_len, size_t *offs)
{
TEE_Result res;
struct tee_cryp_obj_secret *key = attr;
size_t next_offs;
res = op_u32_to_binary_helper(key->key_size, data, data_len, offs);
if (res != TEE_SUCCESS)
return res;
if (ADD_OVERFLOW(*offs, key->key_size, &next_offs))
return TEE_ERROR_OVERFLOW;
if (data && next_offs <= data_len)
memcpy((uint8_t *)data + *offs, key + 1, key->key_size);
(*offs) = next_offs;
return TEE_SUCCESS;
}
static bool op_attr_secret_value_from_binary(void *attr, const void *data,
size_t data_len, size_t *offs)
{
struct tee_cryp_obj_secret *key = attr;
uint32_t s;
if (!op_u32_from_binary_helper(&s, data, data_len, offs))
return false;
if ((*offs + s) > data_len)
return false;
/* Data size has to fit in allocated buffer */
if (s > key->alloc_size)
return false;
key->key_size = s;
memcpy(key + 1, (const uint8_t *)data + *offs, s);
(*offs) += s;
return true;
}
static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr)
{
struct tee_cryp_obj_secret *key = attr;
struct tee_cryp_obj_secret *src_key = src_attr;
if (src_key->key_size > key->alloc_size)
return TEE_ERROR_BAD_STATE;
memcpy(key + 1, src_key + 1, src_key->key_size);
key->key_size = src_key->key_size;
return TEE_SUCCESS;
}
static void op_attr_secret_value_clear(void *attr)
{
struct tee_cryp_obj_secret *key = attr;
key->key_size = 0;
memset(key + 1, 0, key->alloc_size);
}
static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer,
size_t size)
{
struct bignum **bn = attr;
return crypto_bignum_bin2bn(buffer, size, *bn);
}
static TEE_Result op_attr_bignum_to_user(void *attr,
struct tee_ta_session *sess,
void *buffer, uint64_t *size)
{
TEE_Result res;
struct bignum **bn = attr;
uint64_t req_size;
uint64_t s;
res = tee_svc_copy_from_user(&s, size, sizeof(s));
if (res != TEE_SUCCESS)
return res;
req_size = crypto_bignum_num_bytes(*bn);
res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size));
if (res != TEE_SUCCESS)
return res;
if (!req_size)
return TEE_SUCCESS;
if (s < req_size || !buffer)
return TEE_ERROR_SHORT_BUFFER;
/* Check we can access data using supplied user mode pointer */
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)buffer, req_size);
if (res != TEE_SUCCESS)
return res;
/*
* Write the bignum (wich raw data points to) into an array of
* bytes (stored in buffer)
*/
crypto_bignum_bn2bin(*bn, buffer);
return TEE_SUCCESS;
}
static TEE_Result op_attr_bignum_to_binary(void *attr, void *data,
size_t data_len, size_t *offs)
{
TEE_Result res;
struct bignum **bn = attr;
uint32_t n = crypto_bignum_num_bytes(*bn);
size_t next_offs;
res = op_u32_to_binary_helper(n, data, data_len, offs);
if (res != TEE_SUCCESS)
return res;
if (ADD_OVERFLOW(*offs, n, &next_offs))
return TEE_ERROR_OVERFLOW;
if (data && next_offs <= data_len)
crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs);
(*offs) = next_offs;
return TEE_SUCCESS;
}
static bool op_attr_bignum_from_binary(void *attr, const void *data,
size_t data_len, size_t *offs)
{
struct bignum **bn = attr;
uint32_t n;
if (!op_u32_from_binary_helper(&n, data, data_len, offs))
return false;
if ((*offs + n) > data_len)
return false;
if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn))
return false;
(*offs) += n;
return true;
}
static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr)
{
struct bignum **bn = attr;
struct bignum **src_bn = src_attr;
crypto_bignum_copy(*bn, *src_bn);
return TEE_SUCCESS;
}
static void op_attr_bignum_clear(void *attr)
{
struct bignum **bn = attr;
crypto_bignum_clear(*bn);
}
static void op_attr_bignum_free(void *attr)
{
struct bignum **bn = attr;
crypto_bignum_free(*bn);
*bn = NULL;
}
static TEE_Result op_attr_value_from_user(void *attr, const void *buffer,
size_t size)
{
uint32_t *v = attr;
if (size != sizeof(uint32_t) * 2)
return TEE_ERROR_GENERIC; /* "can't happen */
/* Note that only the first value is copied */
memcpy(v, buffer, sizeof(uint32_t));
return TEE_SUCCESS;
}
static TEE_Result op_attr_value_to_user(void *attr,
struct tee_ta_session *sess __unused,
void *buffer, uint64_t *size)
{
TEE_Result res;
uint32_t *v = attr;
uint64_t s;
uint32_t value[2] = { *v };
uint64_t req_size = sizeof(value);
res = tee_svc_copy_from_user(&s, size, sizeof(s));
if (res != TEE_SUCCESS)
return res;
if (s < req_size || !buffer)
return TEE_ERROR_SHORT_BUFFER;
return tee_svc_copy_to_user(buffer, value, req_size);
}
static TEE_Result op_attr_value_to_binary(void *attr, void *data,
size_t data_len, size_t *offs)
{
uint32_t *v = attr;
return op_u32_to_binary_helper(*v, data, data_len, offs);
}
static bool op_attr_value_from_binary(void *attr, const void *data,
size_t data_len, size_t *offs)
{
uint32_t *v = attr;
return op_u32_from_binary_helper(v, data, data_len, offs);
}
static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr)
{
uint32_t *v = attr;
uint32_t *src_v = src_attr;
*v = *src_v;
return TEE_SUCCESS;
}
static void op_attr_value_clear(void *attr)
{
uint32_t *v = attr;
*v = 0;
}
static const struct attr_ops attr_ops[] = {
[ATTR_OPS_INDEX_SECRET] = {
.from_user = op_attr_secret_value_from_user,
.to_user = op_attr_secret_value_to_user,
.to_binary = op_attr_secret_value_to_binary,
.from_binary = op_attr_secret_value_from_binary,
.from_obj = op_attr_secret_value_from_obj,
.free = op_attr_secret_value_clear, /* not a typo */
.clear = op_attr_secret_value_clear,
},
[ATTR_OPS_INDEX_BIGNUM] = {
.from_user = op_attr_bignum_from_user,
.to_user = op_attr_bignum_to_user,
.to_binary = op_attr_bignum_to_binary,
.from_binary = op_attr_bignum_from_binary,
.from_obj = op_attr_bignum_from_obj,
.free = op_attr_bignum_free,
.clear = op_attr_bignum_clear,
},
[ATTR_OPS_INDEX_VALUE] = {
.from_user = op_attr_value_from_user,
.to_user = op_attr_value_to_user,
.to_binary = op_attr_value_to_binary,
.from_binary = op_attr_value_from_binary,
.from_obj = op_attr_value_from_obj,
.free = op_attr_value_clear, /* not a typo */
.clear = op_attr_value_clear,
},
};
TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
goto exit;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
goto exit;
res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info));
exit:
return res;
}
TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj,
unsigned long usage)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
goto exit;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
goto exit;
o->info.objectUsage &= usage;
exit:
return res;
}
static int tee_svc_cryp_obj_find_type_attr_idx(
uint32_t attr_id,
const struct tee_cryp_obj_type_props *type_props)
{
size_t n;
for (n = 0; n < type_props->num_type_attrs; n++) {
if (attr_id == type_props->type_attrs[n].attr_id)
return n;
}
return -1;
}
static const struct tee_cryp_obj_type_props *tee_svc_find_type_props(
TEE_ObjectType obj_type)
{
size_t n;
for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) {
if (tee_cryp_obj_props[n].obj_type == obj_type)
return tee_cryp_obj_props + n;
}
return NULL;
}
/* Set an attribute on an object */
static void set_attribute(struct tee_obj *o,
const struct tee_cryp_obj_type_props *props,
uint32_t attr)
{
int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props);
if (idx < 0)
return;
o->have_attrs |= BIT(idx);
}
/* Get an attribute on an object */
static uint32_t get_attribute(const struct tee_obj *o,
const struct tee_cryp_obj_type_props *props,
uint32_t attr)
{
int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props);
if (idx < 0)
return 0;
return o->have_attrs & BIT(idx);
}
TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id,
void *buffer, uint64_t *size)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
int idx;
const struct attr_ops *ops;
void *attr;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return TEE_ERROR_ITEM_NOT_FOUND;
/* Check that the object is initialized */
if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED))
return TEE_ERROR_BAD_PARAMETERS;
/* Check that getting the attribute is allowed */
if (!(attr_id & TEE_ATTR_BIT_PROTECTED) &&
!(o->info.objectUsage & TEE_USAGE_EXTRACTABLE))
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props) {
/* Unknown object type, "can't happen" */
return TEE_ERROR_BAD_STATE;
}
idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props);
if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0))
return TEE_ERROR_ITEM_NOT_FOUND;
ops = attr_ops + type_props->type_attrs[idx].ops_index;
attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs;
return ops->to_user(attr, sess, buffer, size);
}
void tee_obj_attr_free(struct tee_obj *o)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
if (!o->attr)
return;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs);
}
}
void tee_obj_attr_clear(struct tee_obj *o)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
if (!o->attr)
return;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
attr_ops[ta->ops_index].clear((uint8_t *)o->attr +
ta->raw_offs);
}
}
TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data,
size_t *data_len)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
size_t offs = 0;
size_t len = data ? *data_len : 0;
TEE_Result res;
if (o->info.objectType == TEE_TYPE_DATA) {
*data_len = 0;
return TEE_SUCCESS; /* pure data object */
}
if (!o->attr)
return TEE_ERROR_BAD_STATE;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return TEE_ERROR_BAD_STATE;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
void *attr = (uint8_t *)o->attr + ta->raw_offs;
res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs);
if (res != TEE_SUCCESS)
return res;
}
*data_len = offs;
if (data && offs > len)
return TEE_ERROR_SHORT_BUFFER;
return TEE_SUCCESS;
}
TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data,
size_t data_len)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
size_t offs = 0;
if (o->info.objectType == TEE_TYPE_DATA)
return TEE_SUCCESS; /* pure data object */
if (!o->attr)
return TEE_ERROR_BAD_STATE;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return TEE_ERROR_BAD_STATE;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
void *attr = (uint8_t *)o->attr + ta->raw_offs;
if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len,
&offs))
return TEE_ERROR_CORRUPT_OBJECT;
}
return TEE_SUCCESS;
}
TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src)
{
TEE_Result res;
const struct tee_cryp_obj_type_props *tp;
const struct tee_cryp_obj_type_attrs *ta;
size_t n;
uint32_t have_attrs = 0;
void *attr;
void *src_attr;
if (o->info.objectType == TEE_TYPE_DATA)
return TEE_SUCCESS; /* pure data object */
if (!o->attr)
return TEE_ERROR_BAD_STATE;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return TEE_ERROR_BAD_STATE;
if (o->info.objectType == src->info.objectType) {
have_attrs = src->have_attrs;
for (n = 0; n < tp->num_type_attrs; n++) {
ta = tp->type_attrs + n;
attr = (uint8_t *)o->attr + ta->raw_offs;
src_attr = (uint8_t *)src->attr + ta->raw_offs;
res = attr_ops[ta->ops_index].from_obj(attr, src_attr);
if (res != TEE_SUCCESS)
return res;
}
} else {
const struct tee_cryp_obj_type_props *tp_src;
int idx;
if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else {
return TEE_ERROR_BAD_PARAMETERS;
}
tp_src = tee_svc_find_type_props(src->info.objectType);
if (!tp_src)
return TEE_ERROR_BAD_STATE;
have_attrs = BIT32(tp->num_type_attrs) - 1;
for (n = 0; n < tp->num_type_attrs; n++) {
ta = tp->type_attrs + n;
idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id,
tp_src);
if (idx < 0)
return TEE_ERROR_BAD_STATE;
attr = (uint8_t *)o->attr + ta->raw_offs;
src_attr = (uint8_t *)src->attr +
tp_src->type_attrs[idx].raw_offs;
res = attr_ops[ta->ops_index].from_obj(attr, src_attr);
if (res != TEE_SUCCESS)
return res;
}
}
o->have_attrs = have_attrs;
return TEE_SUCCESS;
}
TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type,
size_t max_key_size)
{
TEE_Result res = TEE_SUCCESS;
const struct tee_cryp_obj_type_props *type_props;
/* Can only set type for newly allocated objs */
if (o->attr)
return TEE_ERROR_BAD_STATE;
/*
* Verify that maxKeySize is supported and find out how
* much should be allocated.
*/
if (obj_type == TEE_TYPE_DATA) {
if (max_key_size)
return TEE_ERROR_NOT_SUPPORTED;
} else {
/* Find description of object */
type_props = tee_svc_find_type_props(obj_type);
if (!type_props)
return TEE_ERROR_NOT_SUPPORTED;
/* Check that maxKeySize follows restrictions */
if (max_key_size % type_props->quanta != 0)
return TEE_ERROR_NOT_SUPPORTED;
if (max_key_size < type_props->min_size)
return TEE_ERROR_NOT_SUPPORTED;
if (max_key_size > type_props->max_size)
return TEE_ERROR_NOT_SUPPORTED;
o->attr = calloc(1, type_props->alloc_size);
if (!o->attr)
return TEE_ERROR_OUT_OF_MEMORY;
}
/* If we have a key structure, pre-allocate the bignums inside */
switch (obj_type) {
case TEE_TYPE_RSA_PUBLIC_KEY:
res = crypto_acipher_alloc_rsa_public_key(o->attr,
max_key_size);
break;
case TEE_TYPE_RSA_KEYPAIR:
res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size);
break;
case TEE_TYPE_DSA_PUBLIC_KEY:
res = crypto_acipher_alloc_dsa_public_key(o->attr,
max_key_size);
break;
case TEE_TYPE_DSA_KEYPAIR:
res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size);
break;
case TEE_TYPE_DH_KEYPAIR:
res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size);
break;
case TEE_TYPE_ECDSA_PUBLIC_KEY:
case TEE_TYPE_ECDH_PUBLIC_KEY:
res = crypto_acipher_alloc_ecc_public_key(o->attr,
max_key_size);
break;
case TEE_TYPE_ECDSA_KEYPAIR:
case TEE_TYPE_ECDH_KEYPAIR:
res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size);
break;
default:
if (obj_type != TEE_TYPE_DATA) {
struct tee_cryp_obj_secret *key = o->attr;
key->alloc_size = type_props->alloc_size -
sizeof(*key);
}
break;
}
if (res != TEE_SUCCESS)
return res;
o->info.objectType = obj_type;
o->info.maxKeySize = max_key_size;
o->info.objectUsage = TEE_USAGE_DEFAULT;
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type,
unsigned long max_key_size, uint32_t *obj)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
if (obj_type == TEE_TYPE_DATA)
return TEE_ERROR_NOT_SUPPORTED;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
o = tee_obj_alloc();
if (!o)
return TEE_ERROR_OUT_OF_MEMORY;
res = tee_obj_set_type(o, obj_type, max_key_size);
if (res != TEE_SUCCESS) {
tee_obj_free(o);
return res;
}
tee_obj_add(to_user_ta_ctx(sess->ctx), o);
res = tee_svc_copy_kaddr_to_uref(obj, o);
if (res != TEE_SUCCESS)
tee_obj_close(to_user_ta_ctx(sess->ctx), o);
return res;
}
TEE_Result syscall_cryp_obj_close(unsigned long obj)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/*
* If it's busy it's used by an operation, a client should never have
* this handle.
*/
if (o->busy)
return TEE_ERROR_ITEM_NOT_FOUND;
tee_obj_close(to_user_ta_ctx(sess->ctx), o);
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_obj_reset(unsigned long obj)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) {
tee_obj_attr_clear(o);
o->info.keySize = 0;
o->info.objectUsage = TEE_USAGE_DEFAULT;
} else {
return TEE_ERROR_BAD_PARAMETERS;
}
/* the object is no more initialized */
o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED;
return TEE_SUCCESS;
}
static TEE_Result copy_in_attrs(struct user_ta_ctx *utc,
const struct utee_attribute *usr_attrs,
uint32_t attr_count, TEE_Attribute *attrs)
{
TEE_Result res;
uint32_t n;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)usr_attrs,
attr_count * sizeof(struct utee_attribute));
if (res != TEE_SUCCESS)
return res;
for (n = 0; n < attr_count; n++) {
attrs[n].attributeID = usr_attrs[n].attribute_id;
if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) {
attrs[n].content.value.a = usr_attrs[n].a;
attrs[n].content.value.b = usr_attrs[n].b;
} else {
uintptr_t buf = usr_attrs[n].a;
size_t len = usr_attrs[n].b;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER, buf, len);
if (res != TEE_SUCCESS)
return res;
attrs[n].content.ref.buffer = (void *)buf;
attrs[n].content.ref.length = len;
}
}
return TEE_SUCCESS;
}
enum attr_usage {
ATTR_USAGE_POPULATE,
ATTR_USAGE_GENERATE_KEY
};
static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage,
const struct tee_cryp_obj_type_props
*type_props,
const TEE_Attribute *attrs,
uint32_t attr_count)
{
uint32_t required_flag;
uint32_t opt_flag;
bool all_opt_needed;
uint32_t req_attrs = 0;
uint32_t opt_grp_attrs = 0;
uint32_t attrs_found = 0;
size_t n;
uint32_t bit;
uint32_t flags;
int idx;
if (usage == ATTR_USAGE_POPULATE) {
required_flag = TEE_TYPE_ATTR_REQUIRED;
opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP;
all_opt_needed = true;
} else {
required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ;
opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT;
all_opt_needed = false;
}
/*
* First find out which attributes are required and which belong to
* the optional group
*/
for (n = 0; n < type_props->num_type_attrs; n++) {
bit = 1 << n;
flags = type_props->type_attrs[n].flags;
if (flags & required_flag)
req_attrs |= bit;
else if (flags & opt_flag)
opt_grp_attrs |= bit;
}
/*
* Verify that all required attributes are in place and
* that the same attribute isn't repeated.
*/
for (n = 0; n < attr_count; n++) {
idx = tee_svc_cryp_obj_find_type_attr_idx(
attrs[n].attributeID,
type_props);
/* attribute not defined in current object type */
if (idx < 0)
return TEE_ERROR_ITEM_NOT_FOUND;
bit = 1 << idx;
/* attribute not repeated */
if ((attrs_found & bit) != 0)
return TEE_ERROR_ITEM_NOT_FOUND;
attrs_found |= bit;
}
/* Required attribute missing */
if ((attrs_found & req_attrs) != req_attrs)
return TEE_ERROR_ITEM_NOT_FOUND;
/*
* If the flag says that "if one of the optional attributes are included
* all of them has to be included" this must be checked.
*/
if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 &&
(attrs_found & opt_grp_attrs) != opt_grp_attrs)
return TEE_ERROR_ITEM_NOT_FOUND;
return TEE_SUCCESS;
}
static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size)
{
switch (curve) {
case TEE_ECC_CURVE_NIST_P192:
*key_size = 192;
break;
case TEE_ECC_CURVE_NIST_P224:
*key_size = 224;
break;
case TEE_ECC_CURVE_NIST_P256:
*key_size = 256;
break;
case TEE_ECC_CURVE_NIST_P384:
*key_size = 384;
break;
case TEE_ECC_CURVE_NIST_P521:
*key_size = 521;
break;
default:
return TEE_ERROR_NOT_SUPPORTED;
}
return TEE_SUCCESS;
}
static TEE_Result tee_svc_cryp_obj_populate_type(
struct tee_obj *o,
const struct tee_cryp_obj_type_props *type_props,
const TEE_Attribute *attrs,
uint32_t attr_count)
{
TEE_Result res;
uint32_t have_attrs = 0;
size_t obj_size = 0;
size_t n;
int idx;
const struct attr_ops *ops;
void *attr;
for (n = 0; n < attr_count; n++) {
idx = tee_svc_cryp_obj_find_type_attr_idx(
attrs[n].attributeID,
type_props);
/* attribute not defined in current object type */
if (idx < 0)
return TEE_ERROR_ITEM_NOT_FOUND;
have_attrs |= BIT32(idx);
ops = attr_ops + type_props->type_attrs[idx].ops_index;
attr = (uint8_t *)o->attr +
type_props->type_attrs[idx].raw_offs;
if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE)
res = ops->from_user(attr, &attrs[n].content.value,
sizeof(attrs[n].content.value));
else
res = ops->from_user(attr, attrs[n].content.ref.buffer,
attrs[n].content.ref.length);
if (res != TEE_SUCCESS)
return res;
/*
* First attr_idx signifies the attribute that gives the size
* of the object
*/
if (type_props->type_attrs[idx].flags &
TEE_TYPE_ATTR_SIZE_INDICATOR) {
/*
* For ECDSA/ECDH we need to translate curve into
* object size
*/
if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) {
res = get_ec_key_size(attrs[n].content.value.a,
&obj_size);
if (res != TEE_SUCCESS)
return res;
} else {
obj_size += (attrs[n].content.ref.length * 8);
}
}
}
/*
* We have to do it like this because the parity bits aren't counted
* when telling the size of the key in bits.
*/
if (o->info.objectType == TEE_TYPE_DES ||
o->info.objectType == TEE_TYPE_DES3)
obj_size -= obj_size / 8; /* Exclude parity in size of key */
o->have_attrs = have_attrs;
o->info.keySize = obj_size;
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_obj_populate(unsigned long obj,
struct utee_attribute *usr_attrs,
unsigned long attr_count)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *attrs = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_IMPLEMENTED;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size))
return TEE_ERROR_OVERFLOW;
attrs = malloc(alloc_size);
if (!attrs)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,
attrs);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
attrs, attr_count);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
if (res == TEE_SUCCESS)
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
out:
free(attrs);
return res;
}
TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *dst_o;
struct tee_obj *src_o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(dst), &dst_o);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(src), &src_o);
if (res != TEE_SUCCESS)
return res;
if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_obj_attr_copy_from(dst_o, src_o);
if (res != TEE_SUCCESS)
return res;
dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
dst_o->info.keySize = src_o->info.keySize;
dst_o->info.objectUsage = src_o->info.objectUsage;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_rsa(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size,
const TEE_Attribute *params, uint32_t param_count)
{
TEE_Result res;
struct rsa_keypair *key = o->attr;
uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537);
/* Copy the present attributes into the obj before starting */
res = tee_svc_cryp_obj_populate_type(o, type_props, params,
param_count);
if (res != TEE_SUCCESS)
return res;
if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT))
crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e);
res = crypto_acipher_gen_rsa_key(key, key_size);
if (res != TEE_SUCCESS)
return res;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_dsa(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size)
{
TEE_Result res;
res = crypto_acipher_gen_dsa_key(o->attr, key_size);
if (res != TEE_SUCCESS)
return res;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_dh(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size __unused,
const TEE_Attribute *params, uint32_t param_count)
{
TEE_Result res;
struct dh_keypair *tee_dh_key;
struct bignum *dh_q = NULL;
uint32_t dh_xbits = 0;
/* Copy the present attributes into the obj before starting */
res = tee_svc_cryp_obj_populate_type(o, type_props, params,
param_count);
if (res != TEE_SUCCESS)
return res;
tee_dh_key = (struct dh_keypair *)o->attr;
if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME))
dh_q = tee_dh_key->q;
if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS))
dh_xbits = tee_dh_key->xbits;
res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits);
if (res != TEE_SUCCESS)
return res;
/* Set bits for the generated public and private key */
set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE);
set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE);
set_attribute(o, type_props, TEE_ATTR_DH_X_BITS);
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_ecc(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size __unused,
const TEE_Attribute *params, uint32_t param_count)
{
TEE_Result res;
struct ecc_keypair *tee_ecc_key;
/* Copy the present attributes into the obj before starting */
res = tee_svc_cryp_obj_populate_type(o, type_props, params,
param_count);
if (res != TEE_SUCCESS)
return res;
tee_ecc_key = (struct ecc_keypair *)o->attr;
res = crypto_acipher_gen_ecc_key(tee_ecc_key);
if (res != TEE_SUCCESS)
return res;
/* Set bits for the generated public and private key */
set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE);
set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X);
set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y);
set_attribute(o, type_props, TEE_ATTR_ECC_CURVE);
return TEE_SUCCESS;
}
TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size,
const struct utee_attribute *usr_params,
unsigned long param_count)
{
TEE_Result res;
struct tee_ta_session *sess;
const struct tee_cryp_obj_type_props *type_props;
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
size_t byte_size;
TEE_Attribute *params = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_STATE;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_STATE;
/* Find description of object */
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_SUPPORTED;
/* Check that maxKeySize follows restrictions */
if (key_size % type_props->quanta != 0)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size < type_props->min_size)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size > type_props->max_size)
return TEE_ERROR_NOT_SUPPORTED;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size))
return TEE_ERROR_OVERFLOW;
params = malloc(alloc_size);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count,
params);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
switch (o->info.objectType) {
case TEE_TYPE_AES:
case TEE_TYPE_DES:
case TEE_TYPE_DES3:
case TEE_TYPE_HMAC_MD5:
case TEE_TYPE_HMAC_SHA1:
case TEE_TYPE_HMAC_SHA224:
case TEE_TYPE_HMAC_SHA256:
case TEE_TYPE_HMAC_SHA384:
case TEE_TYPE_HMAC_SHA512:
case TEE_TYPE_GENERIC_SECRET:
byte_size = key_size / 8;
/*
* We have to do it like this because the parity bits aren't
* counted when telling the size of the key in bits.
*/
if (o->info.objectType == TEE_TYPE_DES ||
o->info.objectType == TEE_TYPE_DES3) {
byte_size = (key_size + key_size / 7) / 8;
}
key = (struct tee_cryp_obj_secret *)o->attr;
if (byte_size > key->alloc_size) {
res = TEE_ERROR_EXCESS_DATA;
goto out;
}
res = crypto_rng_read((void *)(key + 1), byte_size);
if (res != TEE_SUCCESS)
goto out;
key->key_size = byte_size;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
break;
case TEE_TYPE_RSA_KEYPAIR:
res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DSA_KEYPAIR:
res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DH_KEYPAIR:
res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_ECDSA_KEYPAIR:
case TEE_TYPE_ECDH_KEYPAIR:
res = tee_svc_obj_generate_key_ecc(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
default:
res = TEE_ERROR_BAD_FORMAT;
}
out:
free(params);
if (res == TEE_SUCCESS) {
o->info.keySize = key_size;
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
}
return res;
}
static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess,
uint32_t state_id,
struct tee_cryp_state **state)
{
struct tee_cryp_state *s;
struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
TAILQ_FOREACH(s, &utc->cryp_states, link) {
if (state_id == (vaddr_t)s) {
*state = s;
return TEE_SUCCESS;
}
}
return TEE_ERROR_BAD_PARAMETERS;
}
static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs)
{
struct tee_obj *o;
if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS)
tee_obj_close(utc, o);
if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS)
tee_obj_close(utc, o);
TAILQ_REMOVE(&utc->cryp_states, cs, link);
if (cs->ctx_finalize != NULL)
cs->ctx_finalize(cs->ctx, cs->algo);
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_CIPHER:
crypto_cipher_free_ctx(cs->ctx, cs->algo);
break;
case TEE_OPERATION_AE:
crypto_authenc_free_ctx(cs->ctx, cs->algo);
break;
case TEE_OPERATION_DIGEST:
crypto_hash_free_ctx(cs->ctx, cs->algo);
break;
case TEE_OPERATION_MAC:
crypto_mac_free_ctx(cs->ctx, cs->algo);
break;
default:
assert(!cs->ctx);
}
free(cs);
}
static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o,
uint32_t algo,
TEE_OperationMode mode)
{
uint32_t req_key_type;
uint32_t req_key_type2 = 0;
switch (TEE_ALG_GET_MAIN_ALG(algo)) {
case TEE_MAIN_ALGO_MD5:
req_key_type = TEE_TYPE_HMAC_MD5;
break;
case TEE_MAIN_ALGO_SHA1:
req_key_type = TEE_TYPE_HMAC_SHA1;
break;
case TEE_MAIN_ALGO_SHA224:
req_key_type = TEE_TYPE_HMAC_SHA224;
break;
case TEE_MAIN_ALGO_SHA256:
req_key_type = TEE_TYPE_HMAC_SHA256;
break;
case TEE_MAIN_ALGO_SHA384:
req_key_type = TEE_TYPE_HMAC_SHA384;
break;
case TEE_MAIN_ALGO_SHA512:
req_key_type = TEE_TYPE_HMAC_SHA512;
break;
case TEE_MAIN_ALGO_AES:
req_key_type = TEE_TYPE_AES;
break;
case TEE_MAIN_ALGO_DES:
req_key_type = TEE_TYPE_DES;
break;
case TEE_MAIN_ALGO_DES3:
req_key_type = TEE_TYPE_DES3;
break;
case TEE_MAIN_ALGO_RSA:
req_key_type = TEE_TYPE_RSA_KEYPAIR;
if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY;
break;
case TEE_MAIN_ALGO_DSA:
req_key_type = TEE_TYPE_DSA_KEYPAIR;
if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY;
break;
case TEE_MAIN_ALGO_DH:
req_key_type = TEE_TYPE_DH_KEYPAIR;
break;
case TEE_MAIN_ALGO_ECDSA:
req_key_type = TEE_TYPE_ECDSA_KEYPAIR;
if (mode == TEE_MODE_VERIFY)
req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY;
break;
case TEE_MAIN_ALGO_ECDH:
req_key_type = TEE_TYPE_ECDH_KEYPAIR;
break;
#if defined(CFG_CRYPTO_HKDF)
case TEE_MAIN_ALGO_HKDF:
req_key_type = TEE_TYPE_HKDF_IKM;
break;
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
case TEE_MAIN_ALGO_CONCAT_KDF:
req_key_type = TEE_TYPE_CONCAT_KDF_Z;
break;
#endif
#if defined(CFG_CRYPTO_PBKDF2)
case TEE_MAIN_ALGO_PBKDF2:
req_key_type = TEE_TYPE_PBKDF2_PASSWORD;
break;
#endif
default:
return TEE_ERROR_BAD_PARAMETERS;
}
if (req_key_type != o->info.objectType &&
req_key_type2 != o->info.objectType)
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode,
unsigned long key1, unsigned long key2,
uint32_t *state)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o1 = NULL;
struct tee_obj *o2 = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
if (key1 != 0) {
res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1);
if (res != TEE_SUCCESS)
return res;
if (o1->busy)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_svc_cryp_check_key_type(o1, algo, mode);
if (res != TEE_SUCCESS)
return res;
}
if (key2 != 0) {
res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2);
if (res != TEE_SUCCESS)
return res;
if (o2->busy)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_svc_cryp_check_key_type(o2, algo, mode);
if (res != TEE_SUCCESS)
return res;
}
cs = calloc(1, sizeof(struct tee_cryp_state));
if (!cs)
return TEE_ERROR_OUT_OF_MEMORY;
TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link);
cs->algo = algo;
cs->mode = mode;
switch (TEE_ALG_GET_CLASS(algo)) {
case TEE_OPERATION_EXTENSION:
#ifdef CFG_CRYPTO_RSASSA_NA1
if (algo == TEE_ALG_RSASSA_PKCS1_V1_5)
goto rsassa_na1;
#endif
res = TEE_ERROR_NOT_SUPPORTED;
break;
case TEE_OPERATION_CIPHER:
if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) ||
(algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_cipher_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_AE:
if (key1 == 0 || key2 != 0) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_authenc_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_MAC:
if (key1 == 0 || key2 != 0) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_mac_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_DIGEST:
if (key1 != 0 || key2 != 0) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_hash_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_ASYMMETRIC_CIPHER:
case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
rsassa_na1: __maybe_unused
if (key1 == 0 || key2 != 0)
res = TEE_ERROR_BAD_PARAMETERS;
break;
case TEE_OPERATION_KEY_DERIVATION:
if (key1 == 0 || key2 != 0)
res = TEE_ERROR_BAD_PARAMETERS;
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
break;
}
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_copy_kaddr_to_uref(state, cs);
if (res != TEE_SUCCESS)
goto out;
/* Register keys */
if (o1 != NULL) {
o1->busy = true;
cs->key1 = (vaddr_t)o1;
}
if (o2 != NULL) {
o2->busy = true;
cs->key2 = (vaddr_t)o2;
}
out:
if (res != TEE_SUCCESS)
cryp_state_free(utc, cs);
return res;
}
TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src)
{
TEE_Result res;
struct tee_cryp_state *cs_dst;
struct tee_cryp_state *cs_src;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src);
if (res != TEE_SUCCESS)
return res;
if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
return TEE_ERROR_BAD_PARAMETERS;
switch (TEE_ALG_GET_CLASS(cs_src->algo)) {
case TEE_OPERATION_CIPHER:
crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx,
cs_src->algo);
break;
case TEE_OPERATION_AE:
crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx,
cs_src->algo);
break;
case TEE_OPERATION_DIGEST:
crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo);
break;
case TEE_OPERATION_MAC:
crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo);
break;
default:
return TEE_ERROR_BAD_STATE;
}
return TEE_SUCCESS;
}
void tee_svc_cryp_free_states(struct user_ta_ctx *utc)
{
struct tee_cryp_state_head *states = &utc->cryp_states;
while (!TAILQ_EMPTY(states))
cryp_state_free(utc, TAILQ_FIRST(states));
}
TEE_Result syscall_cryp_state_free(unsigned long state)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
cryp_state_free(to_user_ta_ctx(sess->ctx), cs);
return TEE_SUCCESS;
}
TEE_Result syscall_hash_init(unsigned long state,
const void *iv __maybe_unused,
size_t iv_len __maybe_unused)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_DIGEST:
res = crypto_hash_init(cs->ctx, cs->algo);
if (res != TEE_SUCCESS)
return res;
break;
case TEE_OPERATION_MAC:
{
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
cs->key1, &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags &
TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
key = (struct tee_cryp_obj_secret *)o->attr;
res = crypto_mac_init(cs->ctx, cs->algo,
(void *)(key + 1), key->key_size);
if (res != TEE_SUCCESS)
return res;
break;
}
default:
return TEE_ERROR_BAD_PARAMETERS;
}
return TEE_SUCCESS;
}
TEE_Result syscall_hash_update(unsigned long state, const void *chunk,
size_t chunk_size)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
/* No data, but size provided isn't valid parameters. */
if (!chunk && chunk_size)
return TEE_ERROR_BAD_PARAMETERS;
/* Zero length hash is valid, but nothing we need to do. */
if (!chunk_size)
return TEE_SUCCESS;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_DIGEST:
res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
break;
case TEE_OPERATION_MAC:
res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
break;
default:
return TEE_ERROR_BAD_PARAMETERS;
}
return TEE_SUCCESS;
}
TEE_Result syscall_hash_final(unsigned long state, const void *chunk,
size_t chunk_size, void *hash, uint64_t *hash_len)
{
TEE_Result res, res2;
size_t hash_size;
uint64_t hlen;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
/* No data, but size provided isn't valid parameters. */
if (!chunk && chunk_size)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)hash, hlen);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_DIGEST:
res = tee_hash_get_digest_size(cs->algo, &hash_size);
if (res != TEE_SUCCESS)
return res;
if (*hash_len < hash_size) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
if (chunk_size) {
res = crypto_hash_update(cs->ctx, cs->algo, chunk,
chunk_size);
if (res != TEE_SUCCESS)
return res;
}
res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size);
if (res != TEE_SUCCESS)
return res;
break;
case TEE_OPERATION_MAC:
res = tee_mac_get_digest_size(cs->algo, &hash_size);
if (res != TEE_SUCCESS)
return res;
if (*hash_len < hash_size) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
if (chunk_size) {
res = crypto_mac_update(cs->ctx, cs->algo, chunk,
chunk_size);
if (res != TEE_SUCCESS)
return res;
}
res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size);
if (res != TEE_SUCCESS)
return res;
break;
default:
return TEE_ERROR_BAD_PARAMETERS;
}
out:
hlen = hash_size;
res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len));
if (res2 != TEE_SUCCESS)
return res2;
return res;
}
TEE_Result syscall_cipher_init(unsigned long state, const void *iv,
size_t iv_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
struct tee_cryp_obj_secret *key1;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) iv, iv_len);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
key1 = o->attr;
if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) {
struct tee_cryp_obj_secret *key2 = o->attr;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode,
(uint8_t *)(key1 + 1), key1->key_size,
(uint8_t *)(key2 + 1), key2->key_size,
iv, iv_len);
} else {
res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode,
(uint8_t *)(key1 + 1), key1->key_size,
NULL, 0, iv, iv_len);
}
if (res != TEE_SUCCESS)
return res;
cs->ctx_finalize = crypto_cipher_final;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_cipher_update_helper(unsigned long state,
bool last_block, const void *src, size_t src_len,
void *dst, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)src, src_len);
if (res != TEE_SUCCESS)
return res;
if (!dst_len) {
dlen = 0;
} else {
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst, dlen);
if (res != TEE_SUCCESS)
return res;
}
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
if (src_len > 0) {
/* Permit src_len == 0 to finalize the operation */
res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
last_block, src, src_len, dst);
}
if (last_block && cs->ctx_finalize != NULL) {
cs->ctx_finalize(cs->ctx, cs->algo);
cs->ctx_finalize = NULL;
}
out:
if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
dst_len != NULL) {
TEE_Result res2;
dlen = src_len;
res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
res = res2;
}
return res;
}
TEE_Result syscall_cipher_update(unsigned long state, const void *src,
size_t src_len, void *dst, uint64_t *dst_len)
{
return tee_svc_cipher_update_helper(state, false /* last_block */,
src, src_len, dst, dst_len);
}
TEE_Result syscall_cipher_final(unsigned long state, const void *src,
size_t src_len, void *dst, uint64_t *dst_len)
{
return tee_svc_cipher_update_helper(state, true /* last_block */,
src, src_len, dst, dst_len);
}
#if defined(CFG_CRYPTO_HKDF)
static TEE_Result get_hkdf_params(const TEE_Attribute *params,
uint32_t param_count,
void **salt, size_t *salt_len, void **info,
size_t *info_len, size_t *okm_len)
{
size_t n;
enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
uint8_t found = 0;
*salt = *info = NULL;
*salt_len = *info_len = *okm_len = 0;
for (n = 0; n < param_count; n++) {
switch (params[n].attributeID) {
case TEE_ATTR_HKDF_SALT:
if (!(found & SALT)) {
*salt = params[n].content.ref.buffer;
*salt_len = params[n].content.ref.length;
found |= SALT;
}
break;
case TEE_ATTR_HKDF_OKM_LENGTH:
if (!(found & LENGTH)) {
*okm_len = params[n].content.value.a;
found |= LENGTH;
}
break;
case TEE_ATTR_HKDF_INFO:
if (!(found & INFO)) {
*info = params[n].content.ref.buffer;
*info_len = params[n].content.ref.length;
found |= INFO;
}
break;
default:
/* Unexpected attribute */
return TEE_ERROR_BAD_PARAMETERS;
}
}
if (!(found & LENGTH))
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
uint32_t param_count,
void **other_info,
size_t *other_info_len,
size_t *derived_key_len)
{
size_t n;
enum { LENGTH = 0x1, INFO = 0x2 };
uint8_t found = 0;
*other_info = NULL;
*other_info_len = *derived_key_len = 0;
for (n = 0; n < param_count; n++) {
switch (params[n].attributeID) {
case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
if (!(found & INFO)) {
*other_info = params[n].content.ref.buffer;
*other_info_len = params[n].content.ref.length;
found |= INFO;
}
break;
case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
if (!(found & LENGTH)) {
*derived_key_len = params[n].content.value.a;
found |= LENGTH;
}
break;
default:
/* Unexpected attribute */
return TEE_ERROR_BAD_PARAMETERS;
}
}
if (!(found & LENGTH))
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
#endif
#if defined(CFG_CRYPTO_PBKDF2)
static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
uint32_t param_count, void **salt,
size_t *salt_len, size_t *derived_key_len,
size_t *iteration_count)
{
size_t n;
enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
uint8_t found = 0;
*salt = NULL;
*salt_len = *derived_key_len = *iteration_count = 0;
for (n = 0; n < param_count; n++) {
switch (params[n].attributeID) {
case TEE_ATTR_PBKDF2_SALT:
if (!(found & SALT)) {
*salt = params[n].content.ref.buffer;
*salt_len = params[n].content.ref.length;
found |= SALT;
}
break;
case TEE_ATTR_PBKDF2_DKM_LENGTH:
if (!(found & LENGTH)) {
*derived_key_len = params[n].content.value.a;
found |= LENGTH;
}
break;
case TEE_ATTR_PBKDF2_ITERATION_COUNT:
if (!(found & COUNT)) {
*iteration_count = params[n].content.value.a;
found |= COUNT;
}
break;
default:
/* Unexpected attribute */
return TEE_ERROR_BAD_PARAMETERS;
}
}
if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
#endif
TEE_Result syscall_cryp_derive_key(unsigned long state,
const struct utee_attribute *usr_params,
unsigned long param_count, unsigned long derived_key)
{
TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
struct tee_ta_session *sess;
struct tee_obj *ko;
struct tee_obj *so;
struct tee_cryp_state *cs;
struct tee_cryp_obj_secret *sk;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size))
return TEE_ERROR_OVERFLOW;
params = malloc(alloc_size);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, param_count, params);
if (res != TEE_SUCCESS)
goto out;
/* Get key set in operation */
res = tee_obj_get(utc, cs->key1, &ko);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so);
if (res != TEE_SUCCESS)
goto out;
/* Find information needed about the object to initialize */
sk = so->attr;
/* Find description of object */
type_props = tee_svc_find_type_props(so->info.objectType);
if (!type_props) {
res = TEE_ERROR_NOT_SUPPORTED;
goto out;
}
if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
size_t alloc_size;
struct bignum *pub;
struct bignum *ss;
if (param_count != 1 ||
params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
alloc_size = params[0].content.ref.length * 8;
pub = crypto_bignum_allocate(alloc_size);
ss = crypto_bignum_allocate(alloc_size);
if (pub && ss) {
crypto_bignum_bin2bn(params[0].content.ref.buffer,
params[0].content.ref.length, pub);
res = crypto_acipher_dh_shared_secret(ko->attr,
pub, ss);
if (res == TEE_SUCCESS) {
sk->key_size = crypto_bignum_num_bytes(ss);
crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1));
so->info.handleFlags |=
TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props,
TEE_ATTR_SECRET_VALUE);
}
} else {
res = TEE_ERROR_OUT_OF_MEMORY;
}
crypto_bignum_free(pub);
crypto_bignum_free(ss);
} else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) {
size_t alloc_size;
struct ecc_public_key key_public;
uint8_t *pt_secret;
unsigned long pt_secret_len;
if (param_count != 2 ||
params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X ||
params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (cs->algo) {
case TEE_ALG_ECDH_P192:
alloc_size = 192;
break;
case TEE_ALG_ECDH_P224:
alloc_size = 224;
break;
case TEE_ALG_ECDH_P256:
alloc_size = 256;
break;
case TEE_ALG_ECDH_P384:
alloc_size = 384;
break;
case TEE_ALG_ECDH_P521:
alloc_size = 521;
break;
default:
res = TEE_ERROR_NOT_IMPLEMENTED;
goto out;
}
/* Create the public key */
res = crypto_acipher_alloc_ecc_public_key(&key_public,
alloc_size);
if (res != TEE_SUCCESS)
goto out;
key_public.curve = ((struct ecc_keypair *)ko->attr)->curve;
crypto_bignum_bin2bn(params[0].content.ref.buffer,
params[0].content.ref.length,
key_public.x);
crypto_bignum_bin2bn(params[1].content.ref.buffer,
params[1].content.ref.length,
key_public.y);
pt_secret = (uint8_t *)(sk + 1);
pt_secret_len = sk->alloc_size;
res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public,
pt_secret,
&pt_secret_len);
if (res == TEE_SUCCESS) {
sk->key_size = pt_secret_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
/* free the public key */
crypto_acipher_free_ecc_public_key(&key_public);
}
#if defined(CFG_CRYPTO_HKDF)
else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
void *salt, *info;
size_t salt_len, info_len, okm_len;
uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
struct tee_cryp_obj_secret *ik = ko->attr;
const uint8_t *ikm = (const uint8_t *)(ik + 1);
res = get_hkdf_params(params, param_count, &salt, &salt_len,
&info, &info_len, &okm_len);
if (res != TEE_SUCCESS)
goto out;
/* Requested size must fit into the output object's buffer */
if (okm_len > ik->alloc_size) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
info, info_len, (uint8_t *)(sk + 1),
okm_len);
if (res == TEE_SUCCESS) {
sk->key_size = okm_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
}
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
void *info;
size_t info_len, derived_key_len;
uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
struct tee_cryp_obj_secret *ss = ko->attr;
const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
res = get_concat_kdf_params(params, param_count, &info,
&info_len, &derived_key_len);
if (res != TEE_SUCCESS)
goto out;
/* Requested size must fit into the output object's buffer */
if (derived_key_len > ss->alloc_size) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
info, info_len, (uint8_t *)(sk + 1),
derived_key_len);
if (res == TEE_SUCCESS) {
sk->key_size = derived_key_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
}
#endif
#if defined(CFG_CRYPTO_PBKDF2)
else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
void *salt;
size_t salt_len, iteration_count, derived_key_len;
uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
struct tee_cryp_obj_secret *ss = ko->attr;
const uint8_t *password = (const uint8_t *)(ss + 1);
res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
&derived_key_len, &iteration_count);
if (res != TEE_SUCCESS)
goto out;
/* Requested size must fit into the output object's buffer */
if (derived_key_len > ss->alloc_size) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
salt_len, iteration_count,
(uint8_t *)(sk + 1), derived_key_len);
if (res == TEE_SUCCESS) {
sk->key_size = derived_key_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
}
#endif
else
res = TEE_ERROR_NOT_SUPPORTED;
out:
free(params);
return res;
}
TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen)
{
TEE_Result res;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)buf, blen);
if (res != TEE_SUCCESS)
return res;
res = crypto_rng_read(buf, blen);
if (res != TEE_SUCCESS)
return res;
return res;
}
TEE_Result syscall_authenc_init(unsigned long state, const void *nonce,
size_t nonce_len, size_t tag_len,
size_t aad_len, size_t payload_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
key = o->attr;
res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode,
(uint8_t *)(key + 1), key->key_size,
nonce, nonce_len, tag_len, aad_len,
payload_len);
if (res != TEE_SUCCESS)
return res;
cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final;
return TEE_SUCCESS;
}
TEE_Result syscall_authenc_update_aad(unsigned long state,
const void *aad_data, size_t aad_data_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) aad_data,
aad_data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode,
aad_data, aad_data_len);
if (res != TEE_SUCCESS)
return res;
return TEE_SUCCESS;
}
TEE_Result syscall_authenc_update_payload(unsigned long state,
const void *src_data, size_t src_len, void *dst_data,
uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
size_t tmp_dlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
tmp_dlen = dlen;
res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode,
src_data, src_len, dst_data,
&tmp_dlen);
dlen = tmp_dlen;
out:
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen,
sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
res = res2;
}
return res;
}
TEE_Result syscall_authenc_enc_final(unsigned long state,
const void *src_data, size_t src_len, void *dst_data,
uint64_t *dst_len, void *tag, uint64_t *tag_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
uint64_t tlen = 0;
size_t tmp_dlen;
size_t tmp_tlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_ENCRYPT)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)src_data, src_len);
if (res != TEE_SUCCESS)
return res;
if (!dst_len) {
dlen = 0;
} else {
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
}
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)tag, tlen);
if (res != TEE_SUCCESS)
return res;
tmp_dlen = dlen;
tmp_tlen = tlen;
res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data,
src_len, dst_data, &tmp_dlen, tag,
&tmp_tlen);
dlen = tmp_dlen;
tlen = tmp_tlen;
out:
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
if (dst_len != NULL) {
res2 = tee_svc_copy_to_user(dst_len, &dlen,
sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
TEE_Result syscall_authenc_dec_final(unsigned long state,
const void *src_data, size_t src_len, void *dst_data,
uint64_t *dst_len, const void *tag, size_t tag_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
size_t tmp_dlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_DECRYPT)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)src_data, src_len);
if (res != TEE_SUCCESS)
return res;
if (!dst_len) {
dlen = 0;
} else {
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
}
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)tag, tag_len);
if (res != TEE_SUCCESS)
return res;
tmp_dlen = dlen;
res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len,
dst_data, &tmp_dlen, tag, tag_len);
dlen = tmp_dlen;
out:
if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
dst_len != NULL) {
TEE_Result res2;
res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params,
size_t default_len)
{
size_t n;
assert(default_len < INT_MAX);
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
if (params[n].content.value.a < INT_MAX)
return params[n].content.value.a;
break;
}
}
/*
* If salt length isn't provided use the default value which is
* the length of the digest.
*/
return default_len;
}
TEE_Result syscall_asymm_operate(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *src_data, size_t src_len,
void *dst_data, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen64;
size_t dlen;
struct tee_obj *o;
void *label = NULL;
size_t label_len = 0;
size_t n;
int salt_len;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64));
if (res != TEE_SUCCESS)
return res;
dlen = dlen64;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_GENERIC;
goto out;
}
switch (cs->algo) {
case TEE_ALG_RSA_NOPAD:
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else {
/*
* We will panic because "the mode is not compatible
* with the function"
*/
res = TEE_ERROR_GENERIC;
}
break;
case TEE_ALG_RSAES_PKCS1_V1_5:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
label = params[n].content.ref.buffer;
label_len = params[n].content.ref.length;
break;
}
}
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
label, label_len,
src_data, src_len,
dst_data, &dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsaes_decrypt(
cs->algo, o->attr, label, label_len,
src_data, src_len, dst_data, &dlen);
} else {
res = TEE_ERROR_BAD_PARAMETERS;
}
break;
#if defined(CFG_CRYPTO_RSASSA_NA1)
case TEE_ALG_RSASSA_PKCS1_V1_5:
#endif
case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
if (cs->mode != TEE_MODE_SIGN) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params, src_len);
res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
src_data, src_len, dst_data,
&dlen);
break;
case TEE_ALG_DSA_SHA1:
case TEE_ALG_DSA_SHA224:
case TEE_ALG_DSA_SHA256:
res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
case TEE_ALG_ECDSA_P192:
case TEE_ALG_ECDSA_P224:
case TEE_ALG_ECDSA_P256:
case TEE_ALG_ECDSA_P384:
case TEE_ALG_ECDSA_P521:
res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
default:
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
out:
free(params);
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
dlen64 = dlen;
res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
TEE_Result syscall_asymm_verify(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *data, size_t data_len,
const void *sig, size_t sig_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
size_t hash_size;
int salt_len = 0;
TEE_Attribute *params = NULL;
uint32_t hash_algo;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_VERIFY)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)data, data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)sig, sig_len);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
case TEE_MAIN_ALGO_RSA:
if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
if (data_len != hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params,
hash_size);
}
res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
data, data_len, sig,
sig_len);
break;
case TEE_MAIN_ALGO_DSA:
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
/*
* Depending on the DSA algorithm (NIST), the digital signature
* output size may be truncated to the size of a key pair
* (Q prime size). Q prime size must be less or equal than the
* hash output length of the hash algorithm involved.
*/
if (data_len > hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
case TEE_MAIN_ALGO_ECDSA:
res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
}
out:
free(params);
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_731_0 |
crossvul-cpp_data_good_3406_1 | /* radare - LGPL - Copyright 2009-2017 - pancake */
#include <string.h>
#include "r_bin.h"
#include "r_config.h"
#include "r_cons.h"
#include "r_core.h"
#define PAIR_WIDTH 9
// TODO: reuse implementation in core/bin.c
static void pair(const char *a, const char *b) {
char ws[16];
int al = strlen (a);
if (!b) {
return;
}
memset (ws, ' ', sizeof (ws));
al = PAIR_WIDTH - al;
if (al < 0) {
al = 0;
}
ws[al] = 0;
r_cons_printf ("%s%s%s\n", a, ws, b);
}
static bool demangle_internal(RCore *core, const char *lang, const char *s) {
char *res = NULL;
int type = r_bin_demangle_type (lang);
switch (type) {
case R_BIN_NM_CXX: res = r_bin_demangle_cxx (core->bin->cur, s, 0); break;
case R_BIN_NM_JAVA: res = r_bin_demangle_java (s); break;
case R_BIN_NM_OBJC: res = r_bin_demangle_objc (NULL, s); break;
case R_BIN_NM_SWIFT: res = r_bin_demangle_swift (s, core->bin->demanglercmd); break;
case R_BIN_NM_DLANG: res = r_bin_demangle_plugin (core->bin, "dlang", s); break;
default:
r_bin_demangle_list (core->bin);
return true;
}
if (res) {
if (*res) {
printf ("%s\n", res);
}
free (res);
return false;
}
return true;
}
static int demangle(RCore *core, const char *s) {
char *p, *q;
const char *ss = strchr (s, ' ');
if (!*s) {
return 0;
}
if (!ss) {
const char *lang = r_config_get (core->config, "bin.lang");
demangle_internal (core, lang, s);
return 1;
}
p = strdup (s);
q = p + (ss - s);
*q = 0;
demangle_internal (core, p, q + 1);
free (p);
return 1;
}
#define STR(x) (x)? (x): ""
static void r_core_file_info(RCore *core, int mode) {
const char *fn = NULL;
int dbg = r_config_get_i (core->config, "cfg.debug");
bool io_cache = r_config_get_i (core->config, "io.cache");
RBinInfo *info = r_bin_get_info (core->bin);
RBinFile *binfile = r_core_bin_cur (core);
RCoreFile *cf = core->file;
RBinPlugin *plugin = r_bin_file_cur_plugin (binfile);
if (mode == R_CORE_BIN_JSON) {
r_cons_printf ("{");
}
if (mode == R_CORE_BIN_RADARE) {
return;
}
if (mode == R_CORE_BIN_SIMPLE) {
return;
}
if (info) {
fn = info->file;
if (mode == R_CORE_BIN_JSON) {
r_cons_printf ("\"type\":\"%s\"", STR (info->type));
}
} else {
fn = (cf && cf->desc)? cf->desc->name: NULL;
}
if (cf && mode == R_CORE_BIN_JSON) {
const char *uri = fn;
if (!uri) {
if (cf->desc && cf->desc->uri && *cf->desc->uri) {
uri = cf->desc->uri;
} else {
uri = "";
}
}
{
char *escapedFile = r_str_utf16_encode (uri, -1);
r_cons_printf (",\"file\":\"%s\"", escapedFile);
free (escapedFile);
}
if (dbg) {
dbg = R_IO_WRITE | R_IO_EXEC;
}
if (cf->desc) {
ut64 fsz = r_io_desc_size (core->io, cf->desc);
r_cons_printf (",\"fd\":%d", cf->desc->fd);
if (fsz != UT64_MAX) {
r_cons_printf (",\"size\":%"PFMT64d, fsz);
char *humansz = r_num_units (NULL, fsz);
if (humansz) {
r_cons_printf (",\"humansz\":\"%s\"", humansz);
free (humansz);
}
}
r_cons_printf (",\"iorw\":%s", r_str_bool ( io_cache ||\
cf->desc->flags & R_IO_WRITE ));
r_cons_printf (",\"mode\":\"%s\"", r_str_rwx_i (
cf->desc->flags & 7 ));
r_cons_printf (",\"obsz\":%"PFMT64d, (ut64) core->io->desc->obsz);
if (cf->desc->referer && *cf->desc->referer) {
r_cons_printf (",\"referer\":\"%s\"", cf->desc->referer);
}
}
r_cons_printf (",\"block\":%d", core->blocksize);
if (binfile) {
if (binfile->curxtr) {
r_cons_printf (",\"packet\":\"%s\"",
binfile->curxtr->name);
}
if (plugin) {
r_cons_printf (",\"format\":\"%s\"",
plugin->name);
}
}
r_cons_printf ("}");
} else if (cf && mode != R_CORE_BIN_SIMPLE) {
//r_cons_printf ("# Core file info\n");
if (dbg) {
dbg = R_IO_WRITE | R_IO_EXEC;
}
if (cf->desc) {
pair ("blksz", sdb_fmt (0, "0x%"PFMT64x, (ut64) core->io->desc->obsz));
}
pair ("block", sdb_fmt (0, "0x%x", core->blocksize));
if (cf->desc) {
pair ("fd", sdb_fmt (0, "%d", cf->desc->fd));
}
if (fn || (cf->desc && cf->desc->uri)) {
pair ("file", fn? fn: cf->desc->uri);
}
if (plugin) {
pair ("format", plugin->name);
}
if (cf->desc) {
pair ("iorw", r_str_bool (io_cache || cf->desc->flags & R_IO_WRITE ));
pair ("mode", r_str_rwx_i (cf->desc->flags & 7));
}
if (binfile && binfile->curxtr) {
pair ("packet", binfile->curxtr->name);
}
if (cf->desc && cf->desc->referer && *cf->desc->referer) {
pair ("referer", cf->desc->referer);
}
if (cf->desc) {
ut64 fsz = r_io_desc_size (core->io, cf->desc);
if (fsz != UT64_MAX) {
pair ("size", sdb_fmt (0,"0x%"PFMT64x, fsz));
char *humansz = r_num_units (NULL, fsz);
if (humansz) {
pair ("humansz", humansz);
free (humansz);
}
}
}
if (info) {
pair ("type", info->type);
}
}
}
static int bin_is_executable(RBinObject *obj){
RListIter *it;
RBinSection *sec;
if (obj) {
if (obj->info && obj->info->arch) {
return true;
}
r_list_foreach (obj->sections, it, sec){
if (R_BIN_SCN_EXECUTABLE & sec->srwx) {
return true;
}
}
}
return false;
}
static void cmd_info_bin(RCore *core, int va, int mode) {
RBinObject *obj = r_bin_cur_object (core->bin);
int array = 0;
if (core->file) {
if ((mode & R_CORE_BIN_JSON) && !(mode & R_CORE_BIN_ARRAY)) {
mode = R_CORE_BIN_JSON;
r_cons_printf ("{\"core\":");
}
if ((mode & R_CORE_BIN_JSON) && (mode & R_CORE_BIN_ARRAY)) {
mode = R_CORE_BIN_JSON;
array = 1;
r_cons_printf (",\"core\":");
}
r_core_file_info (core, mode);
if (bin_is_executable (obj)) {
if ((mode & R_CORE_BIN_JSON)) {
r_cons_printf (",\"bin\":");
}
r_core_bin_info (core, R_CORE_BIN_ACC_INFO, mode, va, NULL, NULL);
}
if (mode == R_CORE_BIN_JSON && array == 0) {
r_cons_printf ("}\n");
}
} else {
eprintf ("No file selected\n");
}
}
static void playMsg(RCore *core, const char *n, int len) {
if (r_config_get_i (core->config, "scr.tts")) {
if (len > 0) {
char *s = r_str_newf ("%d %s", len, n);
r_sys_tts (s, true);
free (s);
} else if (len == 0) {
char *s = r_str_newf ("there are no %s", n);
r_sys_tts (s, true);
free (s);
}
}
}
static int cmd_info(void *data, const char *input) {
RCore *core = (RCore *) data;
bool newline = r_config_get_i (core->config, "scr.interactive");
RBinObject *o = r_bin_cur_object (core->bin);
RCoreFile *cf = core->file;
int i, va = core->io->va || core->io->debug;
int mode = 0; //R_CORE_BIN_SIMPLE;
int is_array = 0;
Sdb *db;
for (i = 0; input[i] && input[i] != ' '; i++)
;
if (i > 0) {
switch (input[i - 1]) {
case '*': mode = R_CORE_BIN_RADARE; break;
case 'j': mode = R_CORE_BIN_JSON; break;
case 'q': mode = R_CORE_BIN_SIMPLE; break;
}
}
if (mode == R_CORE_BIN_JSON) {
if (strlen (input + 1) > 1) {
is_array = 1;
}
}
if (is_array) {
r_cons_printf ("{");
}
if (!*input) {
cmd_info_bin (core, va, mode);
}
/* i* is an alias for iI* */
if (!strcmp (input, "*")) {
input = "I*";
}
RBinObject *obj = r_bin_cur_object (core->bin);
while (*input) {
switch (*input) {
case 'b': // "ib"
{
ut64 baddr = r_config_get_i (core->config, "bin.baddr");
if (input[1] == ' ') {
baddr = r_num_math (core->num, input + 1);
}
// XXX: this will reload the bin using the buffer.
// An assumption is made that assumes there is an underlying
// plugin that will be used to load the bin (e.g. malloc://)
// TODO: Might be nice to reload a bin at a specified offset?
r_core_bin_reload (core, NULL, baddr);
r_core_block_read (core);
newline = false;
}
break;
case 'k':
db = o? o->kv: NULL;
//:eprintf ("db = %p\n", db);
switch (input[1]) {
case 'v':
if (db) {
char *o = sdb_querys (db, NULL, 0, input + 3);
if (o && *o) {
r_cons_print (o);
}
free (o);
}
break;
case '*':
r_core_bin_export_info_rad (core);
break;
case '.':
case ' ':
if (db) {
char *o = sdb_querys (db, NULL, 0, input + 2);
if (o && *o) {
r_cons_print (o);
}
free (o);
}
break;
case '\0':
if (db) {
char *o = sdb_querys (db, NULL, 0, "*");
if (o && *o) {
r_cons_print (o);
}
free (o);
}
break;
case '?':
default:
eprintf ("Usage: ik [sdb-query]\n");
eprintf ("Usage: ik* # load all header information\n");
}
goto done;
break;
case 'o':
{
if (!cf) {
eprintf ("Core file not open\n");
return 0;
}
const char *fn = input[1] == ' '? input + 2: cf->desc->name;
ut64 baddr = r_config_get_i (core->config, "bin.baddr");
r_core_bin_load (core, fn, baddr);
}
break;
#define RBININFO(n,x,y,z)\
if (is_array) {\
if (is_array == 1) { is_array++;\
} else { r_cons_printf (",");}\
r_cons_printf ("\"%s\":",n);\
}\
if (z) { playMsg (core, n, z);}\
r_core_bin_info (core, x, mode, va, NULL, y);
case 'A':
newline = false;
if (input[1] == 'j') {
r_cons_printf ("{");
r_bin_list_archs (core->bin, 'j');
r_cons_printf ("}\n");
} else {
r_bin_list_archs (core->bin, 1);
}
break;
case 'E': RBININFO ("exports", R_CORE_BIN_ACC_EXPORTS, NULL, 0); break;
case 'Z': RBININFO ("size", R_CORE_BIN_ACC_SIZE, NULL, 0); break;
case 'S':
//we comes from ia or iS
if ((input[1] == 'm' && input[2] == 'z') || !input[1]) {
RBININFO ("sections", R_CORE_BIN_ACC_SECTIONS, NULL, 0);
} else { //iS entropy,sha1
RBinObject *obj = r_bin_cur_object (core->bin);
if (mode == R_CORE_BIN_RADARE || mode == R_CORE_BIN_JSON || mode == R_CORE_BIN_SIMPLE) {
RBININFO ("sections", R_CORE_BIN_ACC_SECTIONS, input + 2,
obj? r_list_length (obj->sections): 0);
} else {
RBININFO ("sections", R_CORE_BIN_ACC_SECTIONS, input + 1,
obj? r_list_length (obj->sections): 0);
}
//we move input until get '\0'
while (*(++input)) ;
//input-- because we are inside a while that does input++
// oob read if not input--
input--;
}
break;
case 'H':
if (input[1] == 'H') { // "iHH"
RBININFO ("header", R_CORE_BIN_ACC_HEADER, NULL, -1);
break;
}
case 'h': RBININFO ("fields", R_CORE_BIN_ACC_FIELDS, NULL, 0); break;
case 'l':
{
RBinObject *obj = r_bin_cur_object (core->bin);
RBININFO ("libs", R_CORE_BIN_ACC_LIBS, NULL, obj? r_list_length (obj->libs): 0);
}
break;
case 'L':
{
char *ptr = strchr (input, ' ');
int json = input[1] == 'j'? 'j': 0;
if (ptr && ptr[1]) {
const char *plugin_name = ptr + 1;
if (is_array) {
r_cons_printf ("\"plugin\": ");
}
r_bin_list_plugin (core->bin, plugin_name, json);
} else {
r_bin_list (core->bin, json);
}
newline = false;
goto done;
}
break;
case 's':
if (input[1] == '.') {
ut64 addr = core->offset + (core->print->cur_enabled? core->print->cur: 0);
RFlagItem *f = r_flag_get_at (core->flags, addr, false);
if (f) {
if (f->offset == addr || !f->offset) {
r_cons_printf ("%s", f->name);
} else {
r_cons_printf ("%s+%d", f->name, (int) (addr - f->offset));
}
}
input++;
break;
} else {
RBinObject *obj = r_bin_cur_object (core->bin);
RBININFO ("symbols", R_CORE_BIN_ACC_SYMBOLS, NULL, obj? r_list_length (obj->symbols): 0);
break;
}
case 'R':
if (input[1] == '*') {
mode = R_CORE_BIN_RADARE;
} else if (input[1] == 'j') {
mode = R_CORE_BIN_JSON;
}
RBININFO ("resources", R_CORE_BIN_ACC_RESOURCES, NULL, 0);
break;
case 'r': RBININFO ("relocs", R_CORE_BIN_ACC_RELOCS, NULL, 0); break;
case 'd': RBININFO ("dwarf", R_CORE_BIN_ACC_DWARF, NULL, -1); break;
case 'i': {
RBinObject *obj = r_bin_cur_object (core->bin);
RBININFO ("imports", R_CORE_BIN_ACC_IMPORTS, NULL,
obj? r_list_length (obj->imports): 0);
}
break;
case 'I': RBININFO ("info", R_CORE_BIN_ACC_INFO, NULL, 0); break;
case 'e': RBININFO ("entries", R_CORE_BIN_ACC_ENTRIES, NULL, 0); break;
case 'M': RBININFO ("main", R_CORE_BIN_ACC_MAIN, NULL, 0); break;
case 'm': RBININFO ("memory", R_CORE_BIN_ACC_MEM, NULL, 0); break;
case 'V': RBININFO ("versioninfo", R_CORE_BIN_ACC_VERSIONINFO, NULL, 0); break;
case 'C': RBININFO ("signature", R_CORE_BIN_ACC_SIGNATURE, NULL, 0); break;
case 'z':
if (input[1] == 'z') { //izz
switch (input[2]) {
case '*':
mode = R_CORE_BIN_RADARE;
break;
case 'j':
mode = R_CORE_BIN_JSON;
break;
case 'q': //izzq
if (input[3] == 'q') { //izzqq
mode = R_CORE_BIN_SIMPLEST;
input++;
} else {
mode = R_CORE_BIN_SIMPLE;
}
break;
default:
mode = R_CORE_BIN_PRINT;
break;
}
input++;
RBININFO ("strings", R_CORE_BIN_ACC_RAW_STRINGS, NULL, 0);
} else {
RBinObject *obj = r_bin_cur_object (core->bin);
if (input[1] == 'q') {
mode = (input[2] == 'q')
? R_CORE_BIN_SIMPLEST
: R_CORE_BIN_SIMPLE;
input++;
}
if (obj) {
RBININFO ("strings", R_CORE_BIN_ACC_STRINGS, NULL,
obj? r_list_length (obj->strings): 0);
}
}
break;
case 'c': // for r2 `ic`
if (input[1] == '?') {
eprintf ("Usage: ic[ljq*] [class-index or name]\n");
} else if (input[1] == ' ' || input[1] == 'q' || input[1] == 'j' || input[1] == 'l') {
RBinClass *cls;
RBinSymbol *sym;
RListIter *iter, *iter2;
RBinObject *obj = r_bin_cur_object (core->bin);
if (obj) {
if (input[2]) {
int idx = -1;
const char * cls_name = NULL;
if (r_num_is_valid_input (core->num, input + 2)) {
idx = r_num_math (core->num, input + 2);
} else {
const char * first_char = input + ((input[1] == ' ') ? 1 : 2);
int not_space = strspn (first_char, " ");
if (first_char[not_space]) {
cls_name = first_char + not_space;
}
}
int count = 0;
r_list_foreach (obj->classes, iter, cls) {
if ((idx >= 0 && idx != count++) ||
(cls_name && strcmp (cls_name, cls->name) != 0)){
continue;
}
switch (input[1]) {
case '*':
r_list_foreach (cls->methods, iter2, sym) {
r_cons_printf ("f sym.%s @ 0x%"PFMT64x "\n",
sym->name, sym->vaddr);
}
input++;
break;
case 'l':
r_list_foreach (cls->methods, iter2, sym) {
const char *comma = iter2->p? " ": "";
r_cons_printf ("%s0x%"PFMT64d, comma, sym->vaddr);
}
r_cons_newline ();
input++;
break;
case 'j':
input++;
r_cons_printf ("\"class\":\"%s\"", cls->name);
r_cons_printf (",\"methods\":[");
r_list_foreach (cls->methods, iter2, sym) {
const char *comma = iter2->p? ",": "";
if (sym->method_flags) {
char *flags = r_core_bin_method_flags_str (sym, R_CORE_BIN_JSON);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"vaddr\":%"PFMT64d "}",
comma, sym->name, flags, sym->vaddr);
R_FREE (flags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"vaddr\":%"PFMT64d "}",
comma, sym->name, sym->vaddr);
}
}
r_cons_printf ("]");
break;
default:
r_cons_printf ("class %s\n", cls->name);
r_list_foreach (cls->methods, iter2, sym) {
char *flags = r_core_bin_method_flags_str (sym, 0);
r_cons_printf ("0x%08"PFMT64x " method %s %s %s\n",
sym->vaddr, cls->name, flags, sym->name);
R_FREE (flags);
}
break;
}
goto done;
}
goto done;
} else {
playMsg (core, "classes", r_list_length (obj->classes));
if (input[1] == 'l' && obj) { // "icl"
r_list_foreach (obj->classes, iter, cls) {
r_list_foreach (cls->methods, iter2, sym) {
const char *comma = iter2->p? " ": "";
r_cons_printf ("%s0x%"PFMT64d, comma, sym->vaddr);
}
if (!r_list_empty (cls->methods)) {
r_cons_newline ();
}
}
} else {
RBININFO ("classes", R_CORE_BIN_ACC_CLASSES, NULL, r_list_length (obj->classes));
}
}
}
} else {
RBinObject *obj = r_bin_cur_object (core->bin);
int len = obj? r_list_length (obj->classes): 0;
RBININFO ("classes", R_CORE_BIN_ACC_CLASSES, NULL, len);
}
break;
case 'D':
if (input[1] != ' ' || !demangle (core, input + 2)) {
eprintf ("|Usage: iD lang symbolname\n");
}
return 0;
case 'a':
switch (mode) {
case R_CORE_BIN_RADARE: cmd_info (core, "iIiecsSmz*"); break;
case R_CORE_BIN_JSON: cmd_info (core, "iIiecsSmzj"); break;
case R_CORE_BIN_SIMPLE: cmd_info (core, "iIiecsSmzq"); break;
default: cmd_info (core, "IiEecsSmz"); break;
}
break;
case '?': {
const char *help_message[] = {
"Usage: i", "", "Get info from opened file (see rabin2's manpage)",
"Output mode:", "", "",
"'*'", "", "Output in radare commands",
"'j'", "", "Output in json",
"'q'", "", "Simple quiet output",
"Actions:", "", "",
"i|ij", "", "Show info of current file (in JSON)",
"iA", "", "List archs",
"ia", "", "Show all info (imports, exports, sections..)",
"ib", "", "Reload the current buffer for setting of the bin (use once only)",
"ic", "", "List classes, methods and fields",
"iC", "", "Show signature info (entitlements, ...)",
"id", "", "Debug information (source lines)",
"iD", " lang sym", "demangle symbolname for given language",
"ie", "", "Entrypoint",
"iE", "", "Exports (global symbols)",
"ih", "", "Headers (alias for iH)",
"iHH", "", "Verbose Headers in raw text",
"ii", "", "Imports",
"iI", "", "Binary info",
"ik", " [query]", "Key-value database from RBinObject",
"il", "", "Libraries",
"iL ", "[plugin]", "List all RBin plugins loaded or plugin details",
"im", "", "Show info about predefined memory allocation",
"iM", "", "Show main address",
"io", " [file]", "Load info from file (or last opened) use bin.baddr",
"ir", "", "Relocs",
"iR", "", "Resources",
"is", "", "Symbols",
"iS ", "[entropy,sha1]", "Sections (choose which hash algorithm to use)",
"iV", "", "Display file version info",
"iz|izj", "", "Strings in data sections (in JSON/Base64)",
"izz", "", "Search for Strings in the whole binary",
"iZ", "", "Guess size of binary program",
NULL
};
r_core_cmd_help (core, help_message);
}
goto done;
case '*':
mode = R_CORE_BIN_RADARE;
goto done;
case 'q':
mode = R_CORE_BIN_SIMPLE;
cmd_info_bin (core, va, mode);
goto done;
case 'j':
mode = R_CORE_BIN_JSON;
if (is_array > 1) {
mode |= R_CORE_BIN_ARRAY;
}
cmd_info_bin (core, va, mode);
goto done;
default:
cmd_info_bin (core, va, mode);
break;
}
input++;
if ((*input == 'j' || *input == 'q') && !input[1]) {
break;
}
}
done:
if (is_array) {
r_cons_printf ("}\n");
}
if (newline) {
r_cons_newline ();
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3406_1 |
crossvul-cpp_data_bad_342_6 | /*
* pkcs15-sc-hsm.c : Initialize PKCS#15 emulation
*
* Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#include "asn1.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strnlen.h"
#include "card-sc-hsm.h"
extern struct sc_aid sc_hsm_aid;
void sc_hsm_set_serialnr(sc_card_t *card, char *serial);
static struct ec_curve curves[] = {
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24},
{ (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24},
{ (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32},
{ (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32},
{ (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24},
{ (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24},
{ (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24},
{ (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49},
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28},
{ (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28},
{ (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28},
{ (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57},
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32},
{ (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32},
{ (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32},
{ (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65},
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40},
{ (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40},
{ (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40},
{ (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81},
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24},
{ (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32},
{ (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0}
}
};
#define C_ASN1_CVC_PUBKEY_SIZE 10
static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = {
{ "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL },
{ "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_BODY_SIZE 5
static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = {
{ "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL },
{ "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL },
{ "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVCERT_SIZE 3
static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = {
{ "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_SIZE 2
static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_AUTHREQ_SIZE 4
static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_REQ_SIZE 2
static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = {
{ "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2],
u8 *efbin, size_t *len, int optional)
{
sc_path_t path;
int r;
sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
/* look this up with our AID */
path.aid = sc_hsm_aid;
/* we don't have a pre-known size of the file */
path.count = -1;
if (!p15card->opts.use_file_cache || !efbin
|| SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) {
/* avoid re-selection of SC-HSM */
path.aid.len = 0;
r = sc_select_file(p15card->card, &path, NULL);
if (r < 0) {
sc_log(p15card->card->ctx, "Could not select EF");
} else {
r = sc_read_binary(p15card->card, 0, efbin, *len, 0);
}
if (r < 0) {
sc_log(p15card->card->ctx, "Could not read EF");
if (!optional) {
return r;
}
/* optional files are saved as empty files to avoid card
* transactions. Parsing the file's data will reveal that they were
* missing. */
*len = 0;
} else {
*len = r;
}
if (p15card->opts.use_file_cache) {
/* save this with our AID */
path.aid = sc_hsm_aid;
sc_pkcs15_cache_file(p15card, &path, efbin, *len);
}
}
return SC_SUCCESS;
}
/*
* Decode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card,
const u8 ** buf, size_t *buflen,
sc_cvc_t *cvc)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE];
struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE];
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
unsigned int cla,tag;
size_t taglen;
size_t lenchr = sizeof(cvc->chr);
size_t lencar = sizeof(cvc->car);
size_t lenoutercar = sizeof(cvc->outer_car);
const u8 *tbuf;
int r;
memset(cvc, 0, sizeof(*cvc));
sc_copy_asn1_entry(c_asn1_req, asn1_req);
sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq);
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0);
sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0);
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0);
sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0);
sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0);
/* sc_asn1_print_tags(*buf, *buflen); */
tbuf = *buf;
r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen);
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
/* Determine if we deal with an authenticated request, plain request or certificate */
if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) {
r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen);
} else {
r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen);
}
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Encode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card,
sc_cvc_t *cvc,
u8 ** buf, size_t *buflen)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
size_t lenchr;
size_t lencar;
int r;
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL;
asn1_cvcert[1].flags = SC_ASN1_OPTIONAL;
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1);
if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1);
if (cvc->coefficientB && (cvc->coefficientBlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1);
if (cvc->publicPoint && (cvc->publicPointlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1);
}
if (cvc->modulusSize > 0) {
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1);
}
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1);
lencar = strnlen(cvc->car, sizeof cvc->car);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1);
lenchr = strnlen(cvc->chr, sizeof cvc->chr);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1);
if (cvc->signature && (cvc->signatureLen > 0)) {
sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1);
}
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1);
r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen);
LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) {
*curve = &curves[i];
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) {
*oid = &curves[i].oid;
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
pubkey->algorithm = SC_ALGORITHM_RSA;
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id)
return SC_ERROR_OUT_OF_MEMORY;
pubkey->alg_id->algorithm = SC_ALGORITHM_RSA;
pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen;
pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len);
pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen;
pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len);
if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len);
memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len);
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
struct sc_ec_parameters *ecp;
const struct sc_lv_data *oid;
int r;
pubkey->algorithm = SC_ALGORITHM_EC;
r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid);
if (r != SC_SUCCESS)
return r;
ecp = calloc(1, sizeof(struct sc_ec_parameters));
if (!ecp)
return SC_ERROR_OUT_OF_MEMORY;
ecp->der.len = oid->len + 2;
ecp->der.value = calloc(ecp->der.len, 1);
if (!ecp->der.value) {
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
*(ecp->der.value + 0) = 0x06;
*(ecp->der.value + 1) = (u8)oid->len;
memcpy(ecp->der.value + 2, oid->value, oid->len);
ecp->type = 1; // Named curve
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id) {
free(ecp->der.value);
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
pubkey->alg_id->algorithm = SC_ALGORITHM_EC;
pubkey->alg_id->params = ecp;
pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen);
if (!pubkey->u.ec.ecpointQ.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen);
pubkey->u.ec.ecpointQ.len = cvc->publicPointlen;
pubkey->u.ec.params.der.value = malloc(ecp->der.len);
if (!pubkey->u.ec.params.der.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len);
pubkey->u.ec.params.der.len = ecp->der.len;
/* FIXME: check return value? */
sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params);
return SC_SUCCESS;
}
int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
if (cvc->publicPoint && cvc->publicPointlen) {
return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey);
} else {
return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey);
}
}
void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc)
{
if (cvc->signature) {
free(cvc->signature);
cvc->signature = NULL;
}
if (cvc->primeOrModulus) {
free(cvc->primeOrModulus);
cvc->primeOrModulus = NULL;
}
if (cvc->coefficientAorExponent) {
free(cvc->coefficientAorExponent);
cvc->coefficientAorExponent = NULL;
}
if (cvc->coefficientB) {
free(cvc->coefficientB);
cvc->coefficientB = NULL;
}
if (cvc->basePointG) {
free(cvc->basePointG);
cvc->basePointG = NULL;
}
if (cvc->order) {
free(cvc->order);
cvc->order = NULL;
}
if (cvc->publicPoint) {
free(cvc->publicPoint);
cvc->publicPoint = NULL;
}
if (cvc->cofactor) {
free(cvc->cofactor);
cvc->cofactor = NULL;
}
}
static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label)
{
struct sc_context *ctx = p15card->card->ctx;
sc_card_t *card = p15card->card;
sc_pkcs15_pubkey_info_t pubkey_info;
sc_pkcs15_object_t pubkey_obj;
struct sc_pkcs15_pubkey pubkey;
sc_cvc_t cvc;
u8 *cvcpo;
int r;
cvcpo = efbin;
memset(&cvc, 0, sizeof(cvc));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc);
LOG_TEST_RET(ctx, r, "Could decode certificate signing request");
memset(&pubkey, 0, sizeof(pubkey));
r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey);
LOG_TEST_RET(card->ctx, r, "Could not extract public key");
memset(&pubkey_info, 0, sizeof(pubkey_info));
memset(&pubkey_obj, 0, sizeof(pubkey_obj));
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
pubkey_info.id = key_info->id;
strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label));
if (pubkey.algorithm == SC_ALGORITHM_RSA) {
pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP;
r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
} else {
/* TODO fix if support of non multiple of 8 curves are added */
pubkey_info.field_length = cvc.primeOrModuluslen << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info);
}
LOG_TEST_RET(ctx, r, "Could not add public key");
sc_pkcs15emu_sc_hsm_free_cvc(&cvc);
sc_pkcs15_erase_pubkey(&pubkey);
return SC_SUCCESS;
}
/*
* Add a key and the key description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t cert_info;
sc_pkcs15_object_t cert_obj;
struct sc_pkcs15_object prkd;
sc_pkcs15_prkey_info_t *key_info;
u8 fid[2];
/* enough to hold a complete certificate */
u8 efbin[4096];
u8 *ptr;
size_t len;
int r;
fid[0] = PRKD_PREFIX;
fid[1] = keyid;
/* Try to select a related EF containing the PKCS#15 description of the key */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
ptr = efbin;
memset(&prkd, 0, sizeof(prkd));
r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
/* All keys require user PIN authentication */
prkd.auth_id.len = 1;
prkd.auth_id.value[0] = 1;
/*
* Set private key flag as all keys are private anyway
*/
prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE;
key_info = (sc_pkcs15_prkey_info_t *)prkd.data;
key_info->key_reference = keyid;
key_info->path.aid.len = 0;
if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) {
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info);
} else {
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info);
}
LOG_TEST_RET(card->ctx, r, "Could not add private key to framework");
/* Check if we also have a certificate for the private key */
fid[0] = EE_CERTIFICATE_PREFIX;
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 0);
LOG_TEST_RET(card->ctx, r, "Could not read EF");
if (efbin[0] == 0x67) { /* Decode CSR and create public key object */
sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label);
free(key_info);
return SC_SUCCESS; /* Ignore any errors */
}
if (efbin[0] != 0x30) {
free(key_info);
return SC_SUCCESS;
}
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id = key_info->id;
sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
cert_info.path.count = -1;
if (p15card->opts.use_file_cache) {
/* look this up with our AID, which should already be cached from the
* call to `read_file`. This may have the side effect that OpenSC's
* caching layer re-selects our applet *if the cached file cannot be
* found/used* and we may loose the authentication status. We assume
* that caching works perfectly without this side effect. */
cert_info.path.aid = sc_hsm_aid;
}
strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
free(key_info);
LOG_TEST_RET(card->ctx, r, "Could not add certificate");
return SC_SUCCESS;
}
/*
* Add a data object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_data_info_t *data_info;
sc_pkcs15_object_t data_obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = DCOD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&data_obj, 0, sizeof(data_obj));
r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD");
data_info = (sc_pkcs15_data_info_t *)data_obj.data;
r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
/*
* Add a unrelated certificate object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t *cert_info;
sc_pkcs15_object_t obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = CD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&obj, 0, sizeof(obj));
r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD");
cert_info = (sc_pkcs15_cert_info_t *)obj.data;
r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
int r;
u8 efbin[512];
size_t len;
LOG_FUNC_CALLED(card->ctx);
/* Read token info */
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects
*
*/
static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) {
return sc_pkcs15emu_sc_hsm_init(p15card);
} else {
if (p15card->card->type != SC_CARD_TYPE_SC_HSM
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) {
return SC_ERROR_WRONG_CARD;
}
return sc_pkcs15emu_sc_hsm_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_342_6 |
crossvul-cpp_data_good_4779_3 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS IIIII X X EEEEE L %
% SS I X X E L %
% SSS I X EEE L %
% SS I X X E L %
% SSSSS IIIII X X EEEEE LLLLL %
% %
% %
% Read/Write DEC SIXEL Format %
% %
% Software Design %
% Hayaki Saito %
% September 2014 %
% Based on kmiya's sixel (2014-03-28) %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/quantize.h"
#include "magick/quantum-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/splay-tree.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/module.h"
#include "magick/threshold.h"
#include "magick/utility.h"
/*
Definitions
*/
#define SIXEL_PALETTE_MAX 256
#define SIXEL_OUTPUT_PACKET_SIZE 1024
/*
Macros
*/
#define SIXEL_RGB(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define SIXEL_PALVAL(n,a,m) (((n) * (a) + ((m) / 2)) / (m))
#define SIXEL_XRGB(r,g,b) SIXEL_RGB(SIXEL_PALVAL(r, 255, 100), SIXEL_PALVAL(g, 255, 100), SIXEL_PALVAL(b, 255, 100))
/*
Structure declarations.
*/
typedef struct sixel_node {
struct sixel_node *next;
int color;
int left;
int right;
unsigned char *map;
} sixel_node_t;
typedef struct sixel_output {
/* compatiblity flags */
/* 0: 7bit terminal,
* 1: 8bit terminal */
unsigned char has_8bit_control;
int save_pixel;
int save_count;
int active_palette;
sixel_node_t *node_top;
sixel_node_t *node_free;
Image *image;
int pos;
unsigned char buffer[1];
} sixel_output_t;
static int const sixel_default_color_table[] = {
SIXEL_XRGB(0, 0, 0), /* 0 Black */
SIXEL_XRGB(20, 20, 80), /* 1 Blue */
SIXEL_XRGB(80, 13, 13), /* 2 Red */
SIXEL_XRGB(20, 80, 20), /* 3 Green */
SIXEL_XRGB(80, 20, 80), /* 4 Magenta */
SIXEL_XRGB(20, 80, 80), /* 5 Cyan */
SIXEL_XRGB(80, 80, 20), /* 6 Yellow */
SIXEL_XRGB(53, 53, 53), /* 7 Gray 50% */
SIXEL_XRGB(26, 26, 26), /* 8 Gray 25% */
SIXEL_XRGB(33, 33, 60), /* 9 Blue* */
SIXEL_XRGB(60, 26, 26), /* 10 Red* */
SIXEL_XRGB(33, 60, 33), /* 11 Green* */
SIXEL_XRGB(60, 33, 60), /* 12 Magenta* */
SIXEL_XRGB(33, 60, 60), /* 13 Cyan* */
SIXEL_XRGB(60, 60, 33), /* 14 Yellow* */
SIXEL_XRGB(80, 80, 80), /* 15 Gray 75% */
};
/*
Forward declarations.
*/
static MagickBooleanType
WriteSIXELImage(const ImageInfo *,Image *);
static int hue_to_rgb(int n1, int n2, int hue)
{
const int HLSMAX = 100;
if (hue < 0) {
hue += HLSMAX;
}
if (hue > HLSMAX) {
hue -= HLSMAX;
}
if (hue < (HLSMAX / 6)) {
return (n1 + (((n2 - n1) * hue + (HLSMAX / 12)) / (HLSMAX / 6)));
}
if (hue < (HLSMAX / 2)) {
return (n2);
}
if (hue < ((HLSMAX * 2) / 3)) {
return (n1 + (((n2 - n1) * (((HLSMAX * 2) / 3) - hue) + (HLSMAX / 12))/(HLSMAX / 6)));
}
return (n1);
}
static int hls_to_rgb(int hue, int lum, int sat)
{
int R, G, B;
int Magic1, Magic2;
const int RGBMAX = 255;
const int HLSMAX = 100;
if (sat == 0) {
R = G = B = (lum * RGBMAX) / HLSMAX;
} else {
if (lum <= (HLSMAX / 2)) {
Magic2 = (lum * (HLSMAX + sat) + (HLSMAX / 2)) / HLSMAX;
} else {
Magic2 = lum + sat - ((lum * sat) + (HLSMAX / 2)) / HLSMAX;
}
Magic1 = 2 * lum - Magic2;
R = (hue_to_rgb(Magic1, Magic2, hue + (HLSMAX / 3)) * RGBMAX + (HLSMAX / 2)) / HLSMAX;
G = (hue_to_rgb(Magic1, Magic2, hue) * RGBMAX + (HLSMAX / 2)) / HLSMAX;
B = (hue_to_rgb(Magic1, Magic2, hue - (HLSMAX / 3)) * RGBMAX + (HLSMAX/2)) / HLSMAX;
}
return SIXEL_RGB(R, G, B);
}
static unsigned char *get_params(unsigned char *p, int *param, int *len)
{
int n;
*len = 0;
while (*p != '\0') {
while (*p == ' ' || *p == '\t') {
p++;
}
if (isdigit(*p)) {
for (n = 0; isdigit(*p); p++) {
n = n * 10 + (*p - '0');
}
if (*len < 10) {
param[(*len)++] = n;
}
while (*p == ' ' || *p == '\t') {
p++;
}
if (*p == ';') {
p++;
}
} else if (*p == ';') {
if (*len < 10) {
param[(*len)++] = 0;
}
p++;
} else
break;
}
return p;
}
/* convert sixel data into indexed pixel bytes and palette data */
MagickBooleanType sixel_decode(unsigned char /* in */ *p, /* sixel bytes */
unsigned char /* out */ **pixels, /* decoded pixels */
size_t /* out */ *pwidth, /* image width */
size_t /* out */ *pheight, /* image height */
unsigned char /* out */ **palette, /* ARGB palette */
size_t /* out */ *ncolors /* palette size (<= 256) */)
{
int n, i, r, g, b, sixel_vertical_mask, c;
int posision_x, posision_y;
int max_x, max_y;
int attributed_pan, attributed_pad;
int attributed_ph, attributed_pv;
int repeat_count, color_index, max_color_index = 2, background_color_index;
int param[10];
int sixel_palet[SIXEL_PALETTE_MAX];
unsigned char *imbuf, *dmbuf;
int imsx, imsy;
int dmsx, dmsy;
int y;
posision_x = posision_y = 0;
max_x = max_y = 0;
attributed_pan = 2;
attributed_pad = 1;
attributed_ph = attributed_pv = 0;
repeat_count = 1;
color_index = 0;
background_color_index = 0;
imsx = 2048;
imsy = 2048;
imbuf = (unsigned char *) AcquireQuantumMemory(imsx , imsy);
if (imbuf == NULL) {
return(MagickFalse);
}
for (n = 0; n < 16; n++) {
sixel_palet[n] = sixel_default_color_table[n];
}
/* colors 16-231 are a 6x6x6 color cube */
for (r = 0; r < 6; r++) {
for (g = 0; g < 6; g++) {
for (b = 0; b < 6; b++) {
sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51);
}
}
}
/* colors 232-255 are a grayscale ramp, intentionally leaving out */
for (i = 0; i < 24; i++) {
sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11);
}
for (; n < SIXEL_PALETTE_MAX; n++) {
sixel_palet[n] = SIXEL_RGB(255, 255, 255);
}
(void) ResetMagickMemory(imbuf, background_color_index, (size_t) imsx * imsy);
while (*p != '\0') {
if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) {
if (*p == '\033') {
p++;
}
p = get_params(++p, param, &n);
if (*p == 'q') {
p++;
if (n > 0) { /* Pn1 */
switch(param[0]) {
case 0:
case 1:
attributed_pad = 2;
break;
case 2:
attributed_pad = 5;
break;
case 3:
attributed_pad = 4;
break;
case 4:
attributed_pad = 4;
break;
case 5:
attributed_pad = 3;
break;
case 6:
attributed_pad = 3;
break;
case 7:
attributed_pad = 2;
break;
case 8:
attributed_pad = 2;
break;
case 9:
attributed_pad = 1;
break;
}
}
if (n > 2) { /* Pn3 */
if (param[2] == 0) {
param[2] = 10;
}
attributed_pan = attributed_pan * param[2] / 10;
attributed_pad = attributed_pad * param[2] / 10;
if (attributed_pan <= 0) attributed_pan = 1;
if (attributed_pad <= 0) attributed_pad = 1;
}
}
} else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) {
break;
} else if (*p == '"') {
/* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */
p = get_params(++p, param, &n);
if (n > 0) attributed_pad = param[0];
if (n > 1) attributed_pan = param[1];
if (n > 2 && param[2] > 0) attributed_ph = param[2];
if (n > 3 && param[3] > 0) attributed_pv = param[3];
if (attributed_pan <= 0) attributed_pan = 1;
if (attributed_pad <= 0) attributed_pad = 1;
if (imsx < attributed_ph || imsy < attributed_pv) {
dmsx = imsx > attributed_ph ? imsx : attributed_ph;
dmsy = imsy > attributed_pv ? imsy : attributed_pv;
dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy);
if (dmbuf == (unsigned char *) NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
(void) ResetMagickMemory(dmbuf, background_color_index, (size_t) dmsx * dmsy);
for (y = 0; y < imsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + (size_t) imsx * y, imsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
} else if (*p == '!') {
/* DECGRI Graphics Repeat Introducer ! Pn Ch */
p = get_params(++p, param, &n);
if (n > 0) {
repeat_count = param[0];
}
} else if (*p == '#') {
/* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */
p = get_params(++p, param, &n);
if (n > 0) {
if ((color_index = param[0]) < 0) {
color_index = 0;
} else if (color_index >= SIXEL_PALETTE_MAX) {
color_index = SIXEL_PALETTE_MAX - 1;
}
}
if (n > 4) {
if (param[1] == 1) { /* HLS */
if (param[2] > 360) param[2] = 360;
if (param[3] > 100) param[3] = 100;
if (param[4] > 100) param[4] = 100;
sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]);
} else if (param[1] == 2) { /* RGB */
if (param[2] > 100) param[2] = 100;
if (param[3] > 100) param[3] = 100;
if (param[4] > 100) param[4] = 100;
sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]);
}
}
} else if (*p == '$') {
/* DECGCR Graphics Carriage Return */
p++;
posision_x = 0;
repeat_count = 1;
} else if (*p == '-') {
/* DECGNL Graphics Next Line */
p++;
posision_x = 0;
posision_y += 6;
repeat_count = 1;
} else if (*p >= '?' && *p <= '\177') {
if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) {
int nx = imsx * 2;
int ny = imsy * 2;
while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) {
nx *= 2;
ny *= 2;
}
dmsx = nx;
dmsy = ny;
dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy);
if (dmbuf == (unsigned char *) NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
(void) ResetMagickMemory(dmbuf, background_color_index, (size_t) dmsx * dmsy);
for (y = 0; y < imsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + (size_t) imsx * y, imsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
if (color_index > max_color_index) {
max_color_index = color_index;
}
if ((b = *(p++) - '?') == 0) {
posision_x += repeat_count;
} else {
sixel_vertical_mask = 0x01;
if (repeat_count <= 1) {
for (i = 0; i < 6; i++) {
if ((b & sixel_vertical_mask) != 0) {
imbuf[imsx * (posision_y + i) + posision_x] = color_index;
if (max_x < posision_x) {
max_x = posision_x;
}
if (max_y < (posision_y + i)) {
max_y = posision_y + i;
}
}
sixel_vertical_mask <<= 1;
}
posision_x += 1;
} else { /* repeat_count > 1 */
for (i = 0; i < 6; i++) {
if ((b & sixel_vertical_mask) != 0) {
c = sixel_vertical_mask << 1;
for (n = 1; (i + n) < 6; n++) {
if ((b & c) == 0) {
break;
}
c <<= 1;
}
for (y = posision_y + i; y < posision_y + i + n; ++y) {
(void) ResetMagickMemory(imbuf + (size_t) imsx * y + posision_x, color_index, repeat_count);
}
if (max_x < (posision_x + repeat_count - 1)) {
max_x = posision_x + repeat_count - 1;
}
if (max_y < (posision_y + i + n - 1)) {
max_y = posision_y + i + n - 1;
}
i += (n - 1);
sixel_vertical_mask <<= (n - 1);
}
sixel_vertical_mask <<= 1;
}
posision_x += repeat_count;
}
}
repeat_count = 1;
} else {
p++;
}
}
if (++max_x < attributed_ph) {
max_x = attributed_ph;
}
if (++max_y < attributed_pv) {
max_y = attributed_pv;
}
if (imsx > max_x || imsy > max_y) {
dmsx = max_x;
dmsy = max_y;
if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy)) == NULL) {
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
return (MagickFalse);
}
for (y = 0; y < dmsy; ++y) {
(void) CopyMagickMemory(dmbuf + dmsx * y, imbuf + imsx * y, dmsx);
}
imbuf = (unsigned char *) RelinquishMagickMemory(imbuf);
imsx = dmsx;
imsy = dmsy;
imbuf = dmbuf;
}
*pixels = imbuf;
*pwidth = imsx;
*pheight = imsy;
*ncolors = max_color_index + 1;
*palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4);
for (n = 0; n < (ssize_t) *ncolors; ++n) {
(*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff;
(*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff;
(*palette)[n * 4 + 2] = sixel_palet[n] & 0xff;
(*palette)[n * 4 + 3] = 0xff;
}
return(MagickTrue);
}
sixel_output_t *sixel_output_create(Image *image)
{
sixel_output_t *output;
output = (sixel_output_t *) AcquireQuantumMemory(sizeof(sixel_output_t) + SIXEL_OUTPUT_PACKET_SIZE * 2, 1);
output->has_8bit_control = 0;
output->save_pixel = 0;
output->save_count = 0;
output->active_palette = (-1);
output->node_top = NULL;
output->node_free = NULL;
output->image = image;
output->pos = 0;
return output;
}
static void sixel_advance(sixel_output_t *context, int nwrite)
{
if ((context->pos += nwrite) >= SIXEL_OUTPUT_PACKET_SIZE) {
WriteBlob(context->image,SIXEL_OUTPUT_PACKET_SIZE,context->buffer);
CopyMagickMemory(context->buffer,
context->buffer + SIXEL_OUTPUT_PACKET_SIZE,
(context->pos -= SIXEL_OUTPUT_PACKET_SIZE));
}
}
static int sixel_put_flash(sixel_output_t *const context)
{
int n;
int nwrite;
#if defined(USE_VT240) /* VT240 Max 255 ? */
while (context->save_count > 255) {
nwrite = spritf((char *)context->buffer + context->pos, "!255%c", context->save_pixel);
if (nwrite <= 0) {
return (-1);
}
sixel_advance(context, nwrite);
context->save_count -= 255;
}
#endif /* defined(USE_VT240) */
if (context->save_count > 3) {
/* DECGRI Graphics Repeat Introducer ! Pn Ch */
nwrite = sprintf((char *)context->buffer + context->pos, "!%d%c", context->save_count, context->save_pixel);
if (nwrite <= 0) {
return (-1);
}
sixel_advance(context, nwrite);
} else {
for (n = 0; n < context->save_count; n++) {
context->buffer[context->pos] = (char)context->save_pixel;
sixel_advance(context, 1);
}
}
context->save_pixel = 0;
context->save_count = 0;
return 0;
}
static void sixel_put_pixel(sixel_output_t *const context, int pix)
{
if (pix < 0 || pix > '?') {
pix = 0;
}
pix += '?';
if (pix == context->save_pixel) {
context->save_count++;
} else {
sixel_put_flash(context);
context->save_pixel = pix;
context->save_count = 1;
}
}
static void sixel_node_del(sixel_output_t *const context, sixel_node_t *np)
{
sixel_node_t *tp;
if ((tp = context->node_top) == np) {
context->node_top = np->next;
}
else {
while (tp->next != NULL) {
if (tp->next == np) {
tp->next = np->next;
break;
}
tp = tp->next;
}
}
np->next = context->node_free;
context->node_free = np;
}
static int sixel_put_node(sixel_output_t *const context, int x,
sixel_node_t *np, int ncolors, int keycolor)
{
int nwrite;
if (ncolors != 2 || keycolor == -1) {
/* designate palette index */
if (context->active_palette != np->color) {
nwrite = sprintf((char *)context->buffer + context->pos,
"#%d", np->color);
sixel_advance(context, nwrite);
context->active_palette = np->color;
}
}
for (; x < np->left; x++) {
sixel_put_pixel(context, 0);
}
for (; x < np->right; x++) {
sixel_put_pixel(context, np->map[x]);
}
sixel_put_flash(context);
return x;
}
static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height,
unsigned char *palette, size_t ncolors, int keycolor,
sixel_output_t *context)
{
#define RelinquishNodesAndMap \
while ((np = context->node_free) != NULL) { \
context->node_free = np->next; \
np=(sixel_node_t *) RelinquishMagickMemory(np); \
} \
map = (unsigned char *) RelinquishMagickMemory(map)
int x, y, i, n, c;
int left, right;
int pix;
size_t len;
unsigned char *map;
sixel_node_t *np, *tp, top;
int nwrite;
context->pos = 0;
if (ncolors < 1) {
return (MagickFalse);
}
len = ncolors * width;
context->active_palette = (-1);
if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) {
return (MagickFalse);
}
(void) ResetMagickMemory(map, 0, len);
if (context->has_8bit_control) {
nwrite = sprintf((char *)context->buffer, "\x90" "0;0;0" "q");
} else {
nwrite = sprintf((char *)context->buffer, "\x1bP" "0;0;0" "q");
}
if (nwrite <= 0) {
return (MagickFalse);
}
sixel_advance(context, nwrite);
nwrite = sprintf((char *)context->buffer + context->pos, "\"1;1;%d;%d", (int) width, (int) height);
if (nwrite <= 0) {
RelinquishNodesAndMap;
return (MagickFalse);
}
sixel_advance(context, nwrite);
if (ncolors != 2 || keycolor == -1) {
for (n = 0; n < (ssize_t) ncolors; n++) {
/* DECGCI Graphics Color Introducer # Pc ; Pu; Px; Py; Pz */
nwrite = sprintf((char *)context->buffer + context->pos, "#%d;2;%d;%d;%d",
n,
(palette[n * 3 + 0] * 100 + 127) / 255,
(palette[n * 3 + 1] * 100 + 127) / 255,
(palette[n * 3 + 2] * 100 + 127) / 255);
if (nwrite <= 0) {
RelinquishNodesAndMap;
return (MagickFalse);
}
sixel_advance(context, nwrite);
if (nwrite <= 0) {
RelinquishNodesAndMap;
return (MagickFalse);
}
}
}
for (y = i = 0; y < (ssize_t) height; y++) {
for (x = 0; x < (ssize_t) width; x++) {
pix = pixels[y * width + x];
if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) {
map[pix * width + x] |= (1 << i);
}
}
if (++i < 6 && (y + 1) < (ssize_t) height) {
continue;
}
for (c = 0; c < (ssize_t) ncolors; c++) {
for (left = 0; left < (ssize_t) width; left++) {
if (*(map + c * width + left) == 0) {
continue;
}
for (right = left + 1; right < (ssize_t) width; right++) {
if (*(map + c * width + right) != 0) {
continue;
}
for (n = 1; (right + n) < (ssize_t) width; n++) {
if (*(map + c * width + right + n) != 0) {
break;
}
}
if (n >= 10 || right + n >= (ssize_t) width) {
break;
}
right = right + n - 1;
}
if ((np = context->node_free) != NULL) {
context->node_free = np->next;
} else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) {
RelinquishNodesAndMap;
return (MagickFalse);
}
np->color = c;
np->left = left;
np->right = right;
np->map = map + c * width;
top.next = context->node_top;
tp = ⊤
while (tp->next != NULL) {
if (np->left < tp->next->left) {
break;
}
if (np->left == tp->next->left && np->right > tp->next->right) {
break;
}
tp = tp->next;
}
np->next = tp->next;
tp->next = np;
context->node_top = top.next;
left = right - 1;
}
}
for (x = 0; (np = context->node_top) != NULL;) {
if (x > np->left) {
/* DECGCR Graphics Carriage Return */
context->buffer[context->pos] = '$';
sixel_advance(context, 1);
x = 0;
}
x = sixel_put_node(context, x, np, (int) ncolors, keycolor);
sixel_node_del(context, np);
np = context->node_top;
while (np != NULL) {
if (np->left < x) {
np = np->next;
continue;
}
x = sixel_put_node(context, x, np, (int) ncolors, keycolor);
sixel_node_del(context, np);
np = context->node_top;
}
}
/* DECGNL Graphics Next Line */
context->buffer[context->pos] = '-';
sixel_advance(context, 1);
if (nwrite <= 0) {
RelinquishNodesAndMap;
return (MagickFalse);
}
i = 0;
(void) ResetMagickMemory(map, 0, len);
}
if (context->has_8bit_control) {
context->buffer[context->pos] = 0x9c;
sixel_advance(context, 1);
} else {
context->buffer[context->pos] = 0x1b;
context->buffer[context->pos + 1] = '\\';
sixel_advance(context, 2);
}
if (nwrite <= 0) {
RelinquishNodesAndMap;
return (MagickFalse);
}
/* flush buffer */
if (context->pos > 0) {
(void) WriteBlob(context->image,context->pos,context->buffer);
}
RelinquishNodesAndMap;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S I X E L %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSIXEL() returns MagickTrue if the image format type, identified by the
% magick string, is SIXEL.
%
% The format of the IsSIXEL method is:
%
% MagickBooleanType IsSIXEL(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes. or
% blob.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsSIXEL(const unsigned char *magick,const size_t length)
{
const unsigned char
*end = magick + length;
if (length < 3)
return(MagickFalse);
if (*magick == 0x90 || (*magick == 0x1b && *++magick == 'P')) {
while (++magick != end) {
if (*magick == 'q')
return(MagickTrue);
if (!(*magick >= '0' && *magick <= '9') && *magick != ';')
return(MagickFalse);
}
}
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S I X E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSIXELImage() reads an X11 pixmap image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadSIXELImage method is:
%
% Image *ReadSIXELImage(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 *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
*sixel_buffer;
Image
*image;
MagickBooleanType
status;
register char
*p;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*r;
size_t
length;
ssize_t
i,
j,
y;
unsigned char
*sixel_pixels,
*sixel_palette;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SIXEL file.
*/
length=MaxTextExtent;
sixel_buffer=(char *) AcquireQuantumMemory((size_t) length,sizeof(*sixel_buffer));
p=sixel_buffer;
if (sixel_buffer != (char *) NULL)
while (ReadBlobString(image,p) != (char *) NULL)
{
if ((*p == '#') && ((p == sixel_buffer) || (*(p-1) == '\n')))
continue;
if ((*p == '}') && (*(p+1) == ';'))
break;
p+=strlen(p);
if ((size_t) (p-sixel_buffer+MaxTextExtent) < length)
continue;
length<<=1;
sixel_buffer=(char *) ResizeQuantumMemory(sixel_buffer,length+MaxTextExtent,
sizeof(*sixel_buffer));
if (sixel_buffer == (char *) NULL)
break;
p=sixel_buffer+strlen(sixel_buffer);
}
if (sixel_buffer == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Decode SIXEL
*/
if (sixel_decode((unsigned char *)sixel_buffer, &sixel_pixels, &image->columns, &image->rows, &sixel_palette, &image->colors) == MagickFalse)
{
sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer);
image->depth=24;
image->storage_class=PseudoClass;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);
sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i = 0; i < (ssize_t) image->colors; ++i) {
image->colormap[i].red = ScaleCharToQuantum(sixel_palette[i * 4 + 0]);
image->colormap[i].green = ScaleCharToQuantum(sixel_palette[i * 4 + 1]);
image->colormap[i].blue = ScaleCharToQuantum(sixel_palette[i * 4 + 2]);
}
j=0;
if (image_info->ping == MagickFalse)
{
/*
Read image pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
r=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
j=(ssize_t) sixel_pixels[y * image->columns + x];
SetPixelIndex(indexes+x,j);
r++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (y < (ssize_t) image->rows)
{
sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);
sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);
ThrowReaderException(CorruptImageError,"NotEnoughPixelData");
}
}
/*
Relinquish resources.
*/
sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels);
sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S I X E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSIXELImage() adds attributes for the SIXEL 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 RegisterSIXELImage method is:
%
% size_t RegisterSIXELImage(void)
%
*/
ModuleExport size_t RegisterSIXELImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("SIXEL");
entry->decoder=(DecodeImageHandler *) ReadSIXELImage;
entry->encoder=(EncodeImageHandler *) WriteSIXELImage;
entry->magick=(IsImageFormatHandler *) IsSIXEL;
entry->adjoin=MagickFalse;
entry->description=ConstantString("DEC SIXEL Graphics Format");
entry->module=ConstantString("SIXEL");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("SIX");
entry->decoder=(DecodeImageHandler *) ReadSIXELImage;
entry->encoder=(EncodeImageHandler *) WriteSIXELImage;
entry->magick=(IsImageFormatHandler *) IsSIXEL;
entry->adjoin=MagickFalse;
entry->description=ConstantString("DEC SIXEL Graphics Format");
entry->module=ConstantString("SIX");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S I X E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSIXELImage() removes format registrations made by the
% SIXEL module from the list of supported formats.
%
% The format of the UnregisterSIXELImage method is:
%
% UnregisterSIXELImage(void)
%
*/
ModuleExport void UnregisterSIXELImage(void)
{
(void) UnregisterMagickInfo("SIXEL");
(void) UnregisterMagickInfo("SIX");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S I X E L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSIXELImage() writes an image to a file in the X pixmap format.
%
% The format of the WriteSIXELImage method is:
%
% MagickBooleanType WriteSIXELImage(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 WriteSIXELImage(const ImageInfo *image_info,Image *image)
{
ExceptionInfo
*exception;
MagickBooleanType
status;
register const IndexPacket
*indexes;
register ssize_t
i,
x;
ssize_t
opacity,
y;
sixel_output_t
*output;
unsigned char
sixel_palette[256 * 3],
*sixel_pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=(&image->exception);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
opacity=(-1);
if (image->matte == MagickFalse)
{
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) SetImageType(image,PaletteType);
}
else
{
MagickRealType
alpha,
beta;
/*
Identify transparent colormap index.
*/
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) SetImageType(image,PaletteBilevelMatteType);
for (i=0; i < (ssize_t) image->colors; i++)
if (image->colormap[i].opacity != OpaqueOpacity)
{
if (opacity < 0)
{
opacity=i;
continue;
}
alpha=(MagickRealType) image->colormap[i].opacity;
beta=(MagickRealType) image->colormap[opacity].opacity;
if (alpha > beta)
opacity=i;
}
if (opacity == -1)
{
(void) SetImageType(image,PaletteBilevelMatteType);
for (i=0; i < (ssize_t) image->colors; i++)
if (image->colormap[i].opacity != OpaqueOpacity)
{
if (opacity < 0)
{
opacity=i;
continue;
}
alpha=(MagickRealType) image->colormap[i].opacity;
beta=(MagickRealType) image->colormap[opacity].opacity;
if (alpha > beta)
opacity=i;
}
}
if (opacity >= 0)
{
image->colormap[opacity].red=image->transparent_color.red;
image->colormap[opacity].green=image->transparent_color.green;
image->colormap[opacity].blue=image->transparent_color.blue;
}
}
/*
SIXEL header.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
sixel_palette[i * 3 + 0] = ScaleQuantumToChar(image->colormap[i].red);
sixel_palette[i * 3 + 1] = ScaleQuantumToChar(image->colormap[i].green);
sixel_palette[i * 3 + 2] = ScaleQuantumToChar(image->colormap[i].blue);
}
/*
Define SIXEL pixels.
*/
output = sixel_output_create(image);
sixel_pixels =(unsigned char *) AcquireQuantumMemory(image->columns , image->rows);
for (y=0; y < (ssize_t) image->rows; y++)
{
(void) GetVirtualPixels(image,0,y,image->columns,1,exception);
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
sixel_pixels[y * image->columns + x] = (unsigned char) ((ssize_t) GetPixelIndex(indexes + x));
}
status = sixel_encode_impl(sixel_pixels, image->columns, image->rows,
sixel_palette, image->colors, -1,
output);
sixel_pixels =(unsigned char *) RelinquishMagickMemory(sixel_pixels);
output = (sixel_output_t *) RelinquishMagickMemory(output);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4779_3 |
crossvul-cpp_data_bad_252_1 | /**
* @file
* IMAP GSS authentication method
*
* @authors
* Copyright (C) 1999-2001,2005,2009 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page imap_auth_gss IMAP GSS authentication method
*
* IMAP GSS authentication method
*
* An overview of the authentication method is in RFC 1731.
*
* An overview of the C API used is in RFC 2744.
* Of note is section 3.2, which describes gss_buffer_desc.
* The length should not include a terminating '\0' byte, and the client
* should not expect the value field to be '\0'terminated.
*/
#include "config.h"
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "mutt.h"
#include "auth.h"
#include "globals.h"
#include "mutt_account.h"
#include "mutt_logging.h"
#include "mutt_socket.h"
#include "options.h"
#include "protos.h"
#ifdef HAVE_HEIMDAL
#include <gssapi/gssapi.h>
#define gss_nt_service_name GSS_C_NT_HOSTBASED_SERVICE
#else
#include <gssapi/gssapi.h>
#include <gssapi/gssapi_generic.h>
#endif
#define GSS_BUFSIZE 8192
#define GSS_AUTH_P_NONE 1
#define GSS_AUTH_P_INTEGRITY 2
#define GSS_AUTH_P_PRIVACY 4
/**
* print_gss_error - Print detailed error message to the debug log
* @param err_maj Error's major number
* @param err_min Error's minor number
*/
static void print_gss_error(OM_uint32 err_maj, OM_uint32 err_min)
{
OM_uint32 maj_stat, min_stat;
OM_uint32 msg_ctx = 0;
gss_buffer_desc status_string;
char buf_maj[512];
char buf_min[512];
do
{
maj_stat = gss_display_status(&min_stat, err_maj, GSS_C_GSS_CODE,
GSS_C_NO_OID, &msg_ctx, &status_string);
if (GSS_ERROR(maj_stat))
break;
size_t status_len = status_string.length;
if (status_len >= sizeof(buf_maj))
status_len = sizeof(buf_maj) - 1;
strncpy(buf_maj, (char *) status_string.value, status_len);
buf_maj[status_len] = '\0';
gss_release_buffer(&min_stat, &status_string);
maj_stat = gss_display_status(&min_stat, err_min, GSS_C_MECH_CODE,
GSS_C_NULL_OID, &msg_ctx, &status_string);
if (!GSS_ERROR(maj_stat))
{
status_len = status_string.length;
if (status_len >= sizeof(buf_min))
status_len = sizeof(buf_min) - 1;
strncpy(buf_min, (char *) status_string.value, status_len);
buf_min[status_len] = '\0';
gss_release_buffer(&min_stat, &status_string);
}
} while (!GSS_ERROR(maj_stat) && msg_ctx != 0);
mutt_debug(2, "((%s:%d )(%s:%d))\n", buf_maj, err_maj, buf_min, err_min);
}
/**
* imap_auth_gss - GSS Authentication support
* @param idata Server data
* @param method Name of this authentication method
* @retval enum Result, e.g. #IMAP_AUTH_SUCCESS
*/
enum ImapAuthRes imap_auth_gss(struct ImapData *idata, const char *method)
{
gss_buffer_desc request_buf, send_token;
gss_buffer_t sec_token;
gss_name_t target_name;
gss_ctx_id_t context;
gss_OID mech_name;
char server_conf_flags;
gss_qop_t quality;
int cflags;
OM_uint32 maj_stat, min_stat;
char buf1[GSS_BUFSIZE], buf2[GSS_BUFSIZE];
unsigned long buf_size;
int rc;
if (!mutt_bit_isset(idata->capabilities, AGSSAPI))
return IMAP_AUTH_UNAVAIL;
if (mutt_account_getuser(&idata->conn->account) < 0)
return IMAP_AUTH_FAILURE;
/* get an IMAP service ticket for the server */
snprintf(buf1, sizeof(buf1), "imap@%s", idata->conn->account.host);
request_buf.value = buf1;
request_buf.length = strlen(buf1);
maj_stat = gss_import_name(&min_stat, &request_buf, gss_nt_service_name, &target_name);
if (maj_stat != GSS_S_COMPLETE)
{
mutt_debug(2, "Couldn't get service name for [%s]\n", buf1);
return IMAP_AUTH_UNAVAIL;
}
else if (DebugLevel >= 2)
{
gss_display_name(&min_stat, target_name, &request_buf, &mech_name);
mutt_debug(2, "Using service name [%s]\n", (char *) request_buf.value);
gss_release_buffer(&min_stat, &request_buf);
}
/* Acquire initial credentials - without a TGT GSSAPI is UNAVAIL */
sec_token = GSS_C_NO_BUFFER;
context = GSS_C_NO_CONTEXT;
/* build token */
maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name,
GSS_C_NO_OID, GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,
0, GSS_C_NO_CHANNEL_BINDINGS, sec_token, NULL,
&send_token, (unsigned int *) &cflags, NULL);
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(1, "Error acquiring credentials - no TGT?\n");
gss_release_name(&min_stat, &target_name);
return IMAP_AUTH_UNAVAIL;
}
/* now begin login */
mutt_message(_("Authenticating (GSSAPI)..."));
imap_cmd_start(idata, "AUTHENTICATE GSSAPI");
/* expect a null continuation response ("+") */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(2, "Invalid response from server: %s\n", buf1);
gss_release_name(&min_stat, &target_name);
goto bail;
}
/* now start the security context initialisation loop... */
mutt_debug(2, "Sending credentials\n");
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
gss_release_buffer(&min_stat, &send_token);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
while (maj_stat == GSS_S_CONTINUE_NEEDED)
{
/* Read server data */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(1, "#1 Error receiving server response.\n");
gss_release_name(&min_stat, &target_name);
goto bail;
}
request_buf.length = mutt_b64_decode(buf2, idata->buf + 2);
request_buf.value = buf2;
sec_token = &request_buf;
/* Write client data */
maj_stat = gss_init_sec_context(
&min_stat, GSS_C_NO_CREDENTIAL, &context, target_name, GSS_C_NO_OID,
GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 0, GSS_C_NO_CHANNEL_BINDINGS,
sec_token, NULL, &send_token, (unsigned int *) &cflags, NULL);
if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(1, "Error exchanging credentials\n");
gss_release_name(&min_stat, &target_name);
goto err_abort_cmd;
}
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
gss_release_buffer(&min_stat, &send_token);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
}
gss_release_name(&min_stat, &target_name);
/* get security flags and buffer size */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc != IMAP_CMD_RESPOND)
{
mutt_debug(1, "#2 Error receiving server response.\n");
goto bail;
}
request_buf.length = mutt_b64_decode(buf2, idata->buf + 2);
request_buf.value = buf2;
maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token, &cflags, &quality);
if (maj_stat != GSS_S_COMPLETE)
{
print_gss_error(maj_stat, min_stat);
mutt_debug(2, "Couldn't unwrap security level data\n");
gss_release_buffer(&min_stat, &send_token);
goto err_abort_cmd;
}
mutt_debug(2, "Credential exchange complete\n");
/* first octet is security levels supported. We want NONE */
server_conf_flags = ((char *) send_token.value)[0];
if (!(((char *) send_token.value)[0] & GSS_AUTH_P_NONE))
{
mutt_debug(2, "Server requires integrity or privacy\n");
gss_release_buffer(&min_stat, &send_token);
goto err_abort_cmd;
}
/* we don't care about buffer size if we don't wrap content. But here it is */
((char *) send_token.value)[0] = '\0';
buf_size = ntohl(*((long *) send_token.value));
gss_release_buffer(&min_stat, &send_token);
mutt_debug(2, "Unwrapped security level flags: %c%c%c\n",
(server_conf_flags & GSS_AUTH_P_NONE) ? 'N' : '-',
(server_conf_flags & GSS_AUTH_P_INTEGRITY) ? 'I' : '-',
(server_conf_flags & GSS_AUTH_P_PRIVACY) ? 'P' : '-');
mutt_debug(2, "Maximum GSS token size is %ld\n", buf_size);
/* agree to terms (hack!) */
buf_size = htonl(buf_size); /* not relevant without integrity/privacy */
memcpy(buf1, &buf_size, 4);
buf1[0] = GSS_AUTH_P_NONE;
/* server decides if principal can log in as user */
strncpy(buf1 + 4, idata->conn->account.user, sizeof(buf1) - 4);
request_buf.value = buf1;
request_buf.length = 4 + strlen(idata->conn->account.user);
maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
&cflags, &send_token);
if (maj_stat != GSS_S_COMPLETE)
{
mutt_debug(2, "Error creating login request\n");
goto err_abort_cmd;
}
mutt_b64_encode(buf1, send_token.value, send_token.length, sizeof(buf1) - 2);
mutt_debug(2, "Requesting authorisation as %s\n", idata->conn->account.user);
mutt_str_strcat(buf1, sizeof(buf1), "\r\n");
mutt_socket_send(idata->conn, buf1);
/* Joy of victory or agony of defeat? */
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
mutt_debug(1, "Unexpected server continuation request.\n");
goto err_abort_cmd;
}
if (imap_code(idata->buf))
{
/* flush the security context */
mutt_debug(2, "Releasing GSS credentials\n");
maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
if (maj_stat != GSS_S_COMPLETE)
mutt_debug(1, "Error releasing credentials\n");
/* send_token may contain a notification to the server to flush
* credentials. RFC1731 doesn't specify what to do, and since this
* support is only for authentication, we'll assume the server knows
* enough to flush its own credentials */
gss_release_buffer(&min_stat, &send_token);
return IMAP_AUTH_SUCCESS;
}
else
goto bail;
err_abort_cmd:
mutt_socket_send(idata->conn, "*\r\n");
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
bail:
mutt_error(_("GSSAPI authentication failed."));
return IMAP_AUTH_FAILURE;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_252_1 |
crossvul-cpp_data_bad_3011_0 | /*
* f2fs extent cache support
*
* Copyright (c) 2015 Motorola Mobility
* Copyright (c) 2015 Samsung Electronics
* Authors: Jaegeuk Kim <jaegeuk@kernel.org>
* Chao Yu <chao2.yu@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include "f2fs.h"
#include "node.h"
#include <trace/events/f2fs.h>
static struct rb_entry *__lookup_rb_tree_fast(struct rb_entry *cached_re,
unsigned int ofs)
{
if (cached_re) {
if (cached_re->ofs <= ofs &&
cached_re->ofs + cached_re->len > ofs) {
return cached_re;
}
}
return NULL;
}
static struct rb_entry *__lookup_rb_tree_slow(struct rb_root *root,
unsigned int ofs)
{
struct rb_node *node = root->rb_node;
struct rb_entry *re;
while (node) {
re = rb_entry(node, struct rb_entry, rb_node);
if (ofs < re->ofs)
node = node->rb_left;
else if (ofs >= re->ofs + re->len)
node = node->rb_right;
else
return re;
}
return NULL;
}
struct rb_entry *__lookup_rb_tree(struct rb_root *root,
struct rb_entry *cached_re, unsigned int ofs)
{
struct rb_entry *re;
re = __lookup_rb_tree_fast(cached_re, ofs);
if (!re)
return __lookup_rb_tree_slow(root, ofs);
return re;
}
struct rb_node **__lookup_rb_tree_for_insert(struct f2fs_sb_info *sbi,
struct rb_root *root, struct rb_node **parent,
unsigned int ofs)
{
struct rb_node **p = &root->rb_node;
struct rb_entry *re;
while (*p) {
*parent = *p;
re = rb_entry(*parent, struct rb_entry, rb_node);
if (ofs < re->ofs)
p = &(*p)->rb_left;
else if (ofs >= re->ofs + re->len)
p = &(*p)->rb_right;
else
f2fs_bug_on(sbi, 1);
}
return p;
}
/*
* lookup rb entry in position of @ofs in rb-tree,
* if hit, return the entry, otherwise, return NULL
* @prev_ex: extent before ofs
* @next_ex: extent after ofs
* @insert_p: insert point for new extent at ofs
* in order to simpfy the insertion after.
* tree must stay unchanged between lookup and insertion.
*/
struct rb_entry *__lookup_rb_tree_ret(struct rb_root *root,
struct rb_entry *cached_re,
unsigned int ofs,
struct rb_entry **prev_entry,
struct rb_entry **next_entry,
struct rb_node ***insert_p,
struct rb_node **insert_parent,
bool force)
{
struct rb_node **pnode = &root->rb_node;
struct rb_node *parent = NULL, *tmp_node;
struct rb_entry *re = cached_re;
*insert_p = NULL;
*insert_parent = NULL;
*prev_entry = NULL;
*next_entry = NULL;
if (RB_EMPTY_ROOT(root))
return NULL;
if (re) {
if (re->ofs <= ofs && re->ofs + re->len > ofs)
goto lookup_neighbors;
}
while (*pnode) {
parent = *pnode;
re = rb_entry(*pnode, struct rb_entry, rb_node);
if (ofs < re->ofs)
pnode = &(*pnode)->rb_left;
else if (ofs >= re->ofs + re->len)
pnode = &(*pnode)->rb_right;
else
goto lookup_neighbors;
}
*insert_p = pnode;
*insert_parent = parent;
re = rb_entry(parent, struct rb_entry, rb_node);
tmp_node = parent;
if (parent && ofs > re->ofs)
tmp_node = rb_next(parent);
*next_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
tmp_node = parent;
if (parent && ofs < re->ofs)
tmp_node = rb_prev(parent);
*prev_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
return NULL;
lookup_neighbors:
if (ofs == re->ofs || force) {
/* lookup prev node for merging backward later */
tmp_node = rb_prev(&re->rb_node);
*prev_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
}
if (ofs == re->ofs + re->len - 1 || force) {
/* lookup next node for merging frontward later */
tmp_node = rb_next(&re->rb_node);
*next_entry = rb_entry_safe(tmp_node, struct rb_entry, rb_node);
}
return re;
}
bool __check_rb_tree_consistence(struct f2fs_sb_info *sbi,
struct rb_root *root)
{
#ifdef CONFIG_F2FS_CHECK_FS
struct rb_node *cur = rb_first(root), *next;
struct rb_entry *cur_re, *next_re;
if (!cur)
return true;
while (cur) {
next = rb_next(cur);
if (!next)
return true;
cur_re = rb_entry(cur, struct rb_entry, rb_node);
next_re = rb_entry(next, struct rb_entry, rb_node);
if (cur_re->ofs + cur_re->len > next_re->ofs) {
f2fs_msg(sbi->sb, KERN_INFO, "inconsistent rbtree, "
"cur(%u, %u) next(%u, %u)",
cur_re->ofs, cur_re->len,
next_re->ofs, next_re->len);
return false;
}
cur = next;
}
#endif
return true;
}
static struct kmem_cache *extent_tree_slab;
static struct kmem_cache *extent_node_slab;
static struct extent_node *__attach_extent_node(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_info *ei,
struct rb_node *parent, struct rb_node **p)
{
struct extent_node *en;
en = kmem_cache_alloc(extent_node_slab, GFP_ATOMIC);
if (!en)
return NULL;
en->ei = *ei;
INIT_LIST_HEAD(&en->list);
en->et = et;
rb_link_node(&en->rb_node, parent, p);
rb_insert_color(&en->rb_node, &et->root);
atomic_inc(&et->node_cnt);
atomic_inc(&sbi->total_ext_node);
return en;
}
static void __detach_extent_node(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_node *en)
{
rb_erase(&en->rb_node, &et->root);
atomic_dec(&et->node_cnt);
atomic_dec(&sbi->total_ext_node);
if (et->cached_en == en)
et->cached_en = NULL;
kmem_cache_free(extent_node_slab, en);
}
/*
* Flow to release an extent_node:
* 1. list_del_init
* 2. __detach_extent_node
* 3. kmem_cache_free.
*/
static void __release_extent_node(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_node *en)
{
spin_lock(&sbi->extent_lock);
f2fs_bug_on(sbi, list_empty(&en->list));
list_del_init(&en->list);
spin_unlock(&sbi->extent_lock);
__detach_extent_node(sbi, et, en);
}
static struct extent_tree *__grab_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
nid_t ino = inode->i_ino;
mutex_lock(&sbi->extent_tree_lock);
et = radix_tree_lookup(&sbi->extent_tree_root, ino);
if (!et) {
et = f2fs_kmem_cache_alloc(extent_tree_slab, GFP_NOFS);
f2fs_radix_tree_insert(&sbi->extent_tree_root, ino, et);
memset(et, 0, sizeof(struct extent_tree));
et->ino = ino;
et->root = RB_ROOT;
et->cached_en = NULL;
rwlock_init(&et->lock);
INIT_LIST_HEAD(&et->list);
atomic_set(&et->node_cnt, 0);
atomic_inc(&sbi->total_ext_tree);
} else {
atomic_dec(&sbi->total_zombie_tree);
list_del_init(&et->list);
}
mutex_unlock(&sbi->extent_tree_lock);
/* never died until evict_inode */
F2FS_I(inode)->extent_tree = et;
return et;
}
static struct extent_node *__init_extent_tree(struct f2fs_sb_info *sbi,
struct extent_tree *et, struct extent_info *ei)
{
struct rb_node **p = &et->root.rb_node;
struct extent_node *en;
en = __attach_extent_node(sbi, et, ei, NULL, p);
if (!en)
return NULL;
et->largest = en->ei;
et->cached_en = en;
return en;
}
static unsigned int __free_extent_tree(struct f2fs_sb_info *sbi,
struct extent_tree *et)
{
struct rb_node *node, *next;
struct extent_node *en;
unsigned int count = atomic_read(&et->node_cnt);
node = rb_first(&et->root);
while (node) {
next = rb_next(node);
en = rb_entry(node, struct extent_node, rb_node);
__release_extent_node(sbi, et, en);
node = next;
}
return count - atomic_read(&et->node_cnt);
}
static void __drop_largest_extent(struct inode *inode,
pgoff_t fofs, unsigned int len)
{
struct extent_info *largest = &F2FS_I(inode)->extent_tree->largest;
if (fofs < largest->fofs + largest->len && fofs + len > largest->fofs) {
largest->len = 0;
f2fs_mark_inode_dirty_sync(inode, true);
}
}
/* return true, if inode page is changed */
bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
struct extent_node *en;
struct extent_info ei;
if (!f2fs_may_extent_tree(inode)) {
/* drop largest extent */
if (i_ext && i_ext->len) {
i_ext->len = 0;
return true;
}
return false;
}
et = __grab_extent_tree(inode);
if (!i_ext || !i_ext->len)
return false;
get_extent_info(&ei, i_ext);
write_lock(&et->lock);
if (atomic_read(&et->node_cnt))
goto out;
en = __init_extent_tree(sbi, et, &ei);
if (en) {
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
spin_unlock(&sbi->extent_lock);
}
out:
write_unlock(&et->lock);
return false;
}
static bool f2fs_lookup_extent_tree(struct inode *inode, pgoff_t pgofs,
struct extent_info *ei)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
struct extent_node *en;
bool ret = false;
f2fs_bug_on(sbi, !et);
trace_f2fs_lookup_extent_tree_start(inode, pgofs);
read_lock(&et->lock);
if (et->largest.fofs <= pgofs &&
et->largest.fofs + et->largest.len > pgofs) {
*ei = et->largest;
ret = true;
stat_inc_largest_node_hit(sbi);
goto out;
}
en = (struct extent_node *)__lookup_rb_tree(&et->root,
(struct rb_entry *)et->cached_en, pgofs);
if (!en)
goto out;
if (en == et->cached_en)
stat_inc_cached_node_hit(sbi);
else
stat_inc_rbtree_node_hit(sbi);
*ei = en->ei;
spin_lock(&sbi->extent_lock);
if (!list_empty(&en->list)) {
list_move_tail(&en->list, &sbi->extent_list);
et->cached_en = en;
}
spin_unlock(&sbi->extent_lock);
ret = true;
out:
stat_inc_total_hit(sbi);
read_unlock(&et->lock);
trace_f2fs_lookup_extent_tree_end(inode, pgofs, ei);
return ret;
}
static struct extent_node *__try_merge_extent_node(struct inode *inode,
struct extent_tree *et, struct extent_info *ei,
struct extent_node *prev_ex,
struct extent_node *next_ex)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_node *en = NULL;
if (prev_ex && __is_back_mergeable(ei, &prev_ex->ei)) {
prev_ex->ei.len += ei->len;
ei = &prev_ex->ei;
en = prev_ex;
}
if (next_ex && __is_front_mergeable(ei, &next_ex->ei)) {
next_ex->ei.fofs = ei->fofs;
next_ex->ei.blk = ei->blk;
next_ex->ei.len += ei->len;
if (en)
__release_extent_node(sbi, et, prev_ex);
en = next_ex;
}
if (!en)
return NULL;
__try_update_largest_extent(inode, et, en);
spin_lock(&sbi->extent_lock);
if (!list_empty(&en->list)) {
list_move_tail(&en->list, &sbi->extent_list);
et->cached_en = en;
}
spin_unlock(&sbi->extent_lock);
return en;
}
static struct extent_node *__insert_extent_tree(struct inode *inode,
struct extent_tree *et, struct extent_info *ei,
struct rb_node **insert_p,
struct rb_node *insert_parent)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct rb_node **p = &et->root.rb_node;
struct rb_node *parent = NULL;
struct extent_node *en = NULL;
if (insert_p && insert_parent) {
parent = insert_parent;
p = insert_p;
goto do_insert;
}
p = __lookup_rb_tree_for_insert(sbi, &et->root, &parent, ei->fofs);
do_insert:
en = __attach_extent_node(sbi, et, ei, parent, p);
if (!en)
return NULL;
__try_update_largest_extent(inode, et, en);
/* update in global extent list */
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
et->cached_en = en;
spin_unlock(&sbi->extent_lock);
return en;
}
static void f2fs_update_extent_tree_range(struct inode *inode,
pgoff_t fofs, block_t blkaddr, unsigned int len)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
struct extent_node *en = NULL, *en1 = NULL;
struct extent_node *prev_en = NULL, *next_en = NULL;
struct extent_info ei, dei, prev;
struct rb_node **insert_p = NULL, *insert_parent = NULL;
unsigned int end = fofs + len;
unsigned int pos = (unsigned int)fofs;
if (!et)
return;
trace_f2fs_update_extent_tree_range(inode, fofs, blkaddr, len);
write_lock(&et->lock);
if (is_inode_flag_set(inode, FI_NO_EXTENT)) {
write_unlock(&et->lock);
return;
}
prev = et->largest;
dei.len = 0;
/*
* drop largest extent before lookup, in case it's already
* been shrunk from extent tree
*/
__drop_largest_extent(inode, fofs, len);
/* 1. lookup first extent node in range [fofs, fofs + len - 1] */
en = (struct extent_node *)__lookup_rb_tree_ret(&et->root,
(struct rb_entry *)et->cached_en, fofs,
(struct rb_entry **)&prev_en,
(struct rb_entry **)&next_en,
&insert_p, &insert_parent, false);
if (!en)
en = next_en;
/* 2. invlidate all extent nodes in range [fofs, fofs + len - 1] */
while (en && en->ei.fofs < end) {
unsigned int org_end;
int parts = 0; /* # of parts current extent split into */
next_en = en1 = NULL;
dei = en->ei;
org_end = dei.fofs + dei.len;
f2fs_bug_on(sbi, pos >= org_end);
if (pos > dei.fofs && pos - dei.fofs >= F2FS_MIN_EXTENT_LEN) {
en->ei.len = pos - en->ei.fofs;
prev_en = en;
parts = 1;
}
if (end < org_end && org_end - end >= F2FS_MIN_EXTENT_LEN) {
if (parts) {
set_extent_info(&ei, end,
end - dei.fofs + dei.blk,
org_end - end);
en1 = __insert_extent_tree(inode, et, &ei,
NULL, NULL);
next_en = en1;
} else {
en->ei.fofs = end;
en->ei.blk += end - dei.fofs;
en->ei.len -= end - dei.fofs;
next_en = en;
}
parts++;
}
if (!next_en) {
struct rb_node *node = rb_next(&en->rb_node);
next_en = rb_entry_safe(node, struct extent_node,
rb_node);
}
if (parts)
__try_update_largest_extent(inode, et, en);
else
__release_extent_node(sbi, et, en);
/*
* if original extent is split into zero or two parts, extent
* tree has been altered by deletion or insertion, therefore
* invalidate pointers regard to tree.
*/
if (parts != 1) {
insert_p = NULL;
insert_parent = NULL;
}
en = next_en;
}
/* 3. update extent in extent cache */
if (blkaddr) {
set_extent_info(&ei, fofs, blkaddr, len);
if (!__try_merge_extent_node(inode, et, &ei, prev_en, next_en))
__insert_extent_tree(inode, et, &ei,
insert_p, insert_parent);
/* give up extent_cache, if split and small updates happen */
if (dei.len >= 1 &&
prev.len < F2FS_MIN_EXTENT_LEN &&
et->largest.len < F2FS_MIN_EXTENT_LEN) {
__drop_largest_extent(inode, 0, UINT_MAX);
set_inode_flag(inode, FI_NO_EXTENT);
}
}
if (is_inode_flag_set(inode, FI_NO_EXTENT))
__free_extent_tree(sbi, et);
write_unlock(&et->lock);
}
unsigned int f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink)
{
struct extent_tree *et, *next;
struct extent_node *en;
unsigned int node_cnt = 0, tree_cnt = 0;
int remained;
if (!test_opt(sbi, EXTENT_CACHE))
return 0;
if (!atomic_read(&sbi->total_zombie_tree))
goto free_node;
if (!mutex_trylock(&sbi->extent_tree_lock))
goto out;
/* 1. remove unreferenced extent tree */
list_for_each_entry_safe(et, next, &sbi->zombie_list, list) {
if (atomic_read(&et->node_cnt)) {
write_lock(&et->lock);
node_cnt += __free_extent_tree(sbi, et);
write_unlock(&et->lock);
}
f2fs_bug_on(sbi, atomic_read(&et->node_cnt));
list_del_init(&et->list);
radix_tree_delete(&sbi->extent_tree_root, et->ino);
kmem_cache_free(extent_tree_slab, et);
atomic_dec(&sbi->total_ext_tree);
atomic_dec(&sbi->total_zombie_tree);
tree_cnt++;
if (node_cnt + tree_cnt >= nr_shrink)
goto unlock_out;
cond_resched();
}
mutex_unlock(&sbi->extent_tree_lock);
free_node:
/* 2. remove LRU extent entries */
if (!mutex_trylock(&sbi->extent_tree_lock))
goto out;
remained = nr_shrink - (node_cnt + tree_cnt);
spin_lock(&sbi->extent_lock);
for (; remained > 0; remained--) {
if (list_empty(&sbi->extent_list))
break;
en = list_first_entry(&sbi->extent_list,
struct extent_node, list);
et = en->et;
if (!write_trylock(&et->lock)) {
/* refresh this extent node's position in extent list */
list_move_tail(&en->list, &sbi->extent_list);
continue;
}
list_del_init(&en->list);
spin_unlock(&sbi->extent_lock);
__detach_extent_node(sbi, et, en);
write_unlock(&et->lock);
node_cnt++;
spin_lock(&sbi->extent_lock);
}
spin_unlock(&sbi->extent_lock);
unlock_out:
mutex_unlock(&sbi->extent_tree_lock);
out:
trace_f2fs_shrink_extent_tree(sbi, node_cnt, tree_cnt);
return node_cnt + tree_cnt;
}
unsigned int f2fs_destroy_extent_node(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
unsigned int node_cnt = 0;
if (!et || !atomic_read(&et->node_cnt))
return 0;
write_lock(&et->lock);
node_cnt = __free_extent_tree(sbi, et);
write_unlock(&et->lock);
return node_cnt;
}
void f2fs_drop_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
set_inode_flag(inode, FI_NO_EXTENT);
write_lock(&et->lock);
__free_extent_tree(sbi, et);
__drop_largest_extent(inode, 0, UINT_MAX);
write_unlock(&et->lock);
}
void f2fs_destroy_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
unsigned int node_cnt = 0;
if (!et)
return;
if (inode->i_nlink && !is_bad_inode(inode) &&
atomic_read(&et->node_cnt)) {
mutex_lock(&sbi->extent_tree_lock);
list_add_tail(&et->list, &sbi->zombie_list);
atomic_inc(&sbi->total_zombie_tree);
mutex_unlock(&sbi->extent_tree_lock);
return;
}
/* free all extent info belong to this extent tree */
node_cnt = f2fs_destroy_extent_node(inode);
/* delete extent tree entry in radix tree */
mutex_lock(&sbi->extent_tree_lock);
f2fs_bug_on(sbi, atomic_read(&et->node_cnt));
radix_tree_delete(&sbi->extent_tree_root, inode->i_ino);
kmem_cache_free(extent_tree_slab, et);
atomic_dec(&sbi->total_ext_tree);
mutex_unlock(&sbi->extent_tree_lock);
F2FS_I(inode)->extent_tree = NULL;
trace_f2fs_destroy_extent_tree(inode, node_cnt);
}
bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs,
struct extent_info *ei)
{
if (!f2fs_may_extent_tree(inode))
return false;
return f2fs_lookup_extent_tree(inode, pgofs, ei);
}
void f2fs_update_extent_cache(struct dnode_of_data *dn)
{
pgoff_t fofs;
block_t blkaddr;
if (!f2fs_may_extent_tree(dn->inode))
return;
if (dn->data_blkaddr == NEW_ADDR)
blkaddr = NULL_ADDR;
else
blkaddr = dn->data_blkaddr;
fofs = start_bidx_of_node(ofs_of_node(dn->node_page), dn->inode) +
dn->ofs_in_node;
f2fs_update_extent_tree_range(dn->inode, fofs, blkaddr, 1);
}
void f2fs_update_extent_cache_range(struct dnode_of_data *dn,
pgoff_t fofs, block_t blkaddr, unsigned int len)
{
if (!f2fs_may_extent_tree(dn->inode))
return;
f2fs_update_extent_tree_range(dn->inode, fofs, blkaddr, len);
}
void init_extent_cache_info(struct f2fs_sb_info *sbi)
{
INIT_RADIX_TREE(&sbi->extent_tree_root, GFP_NOIO);
mutex_init(&sbi->extent_tree_lock);
INIT_LIST_HEAD(&sbi->extent_list);
spin_lock_init(&sbi->extent_lock);
atomic_set(&sbi->total_ext_tree, 0);
INIT_LIST_HEAD(&sbi->zombie_list);
atomic_set(&sbi->total_zombie_tree, 0);
atomic_set(&sbi->total_ext_node, 0);
}
int __init create_extent_cache(void)
{
extent_tree_slab = f2fs_kmem_cache_create("f2fs_extent_tree",
sizeof(struct extent_tree));
if (!extent_tree_slab)
return -ENOMEM;
extent_node_slab = f2fs_kmem_cache_create("f2fs_extent_node",
sizeof(struct extent_node));
if (!extent_node_slab) {
kmem_cache_destroy(extent_tree_slab);
return -ENOMEM;
}
return 0;
}
void destroy_extent_cache(void)
{
kmem_cache_destroy(extent_node_slab);
kmem_cache_destroy(extent_tree_slab);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3011_0 |
crossvul-cpp_data_good_2038_0 | /*-
* Copyright (c) 2008 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Parse Composite Document Files, the format used in Microsoft Office
* document files before they switched to zipped XML.
* Info from: http://sc.openoffice.org/compdocfileformat.pdf
*
* N.B. This is the "Composite Document File" format, and not the
* "Compound Document Format", nor the "Channel Definition Format".
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $")
#endif
#include <assert.h>
#ifdef CDF_DEBUG
#include <err.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifndef EFTYPE
#define EFTYPE EINVAL
#endif
#include "cdf.h"
#ifdef CDF_DEBUG
#define DPRINTF(a) printf a, fflush(stdout)
#else
#define DPRINTF(a)
#endif
static union {
char s[4];
uint32_t u;
} cdf_bo;
#define NEED_SWAP (cdf_bo.u == (uint32_t)0x01020304)
#define CDF_TOLE8(x) ((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x)))
#define CDF_TOLE4(x) ((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x)))
#define CDF_TOLE2(x) ((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x)))
#define CDF_GETUINT32(x, y) cdf_getuint32(x, y)
/*
* swap a short
*/
static uint16_t
_cdf_tole2(uint16_t sv)
{
uint16_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[1];
d[1] = s[0];
return rv;
}
/*
* swap an int
*/
static uint32_t
_cdf_tole4(uint32_t sv)
{
uint32_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[3];
d[1] = s[2];
d[2] = s[1];
d[3] = s[0];
return rv;
}
/*
* swap a quad
*/
static uint64_t
_cdf_tole8(uint64_t sv)
{
uint64_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[7];
d[1] = s[6];
d[2] = s[5];
d[3] = s[4];
d[4] = s[3];
d[5] = s[2];
d[6] = s[1];
d[7] = s[0];
return rv;
}
/*
* grab a uint32_t from a possibly unaligned address, and return it in
* the native host order.
*/
static uint32_t
cdf_getuint32(const uint8_t *p, size_t offs)
{
uint32_t rv;
(void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv));
return CDF_TOLE4(rv);
}
#define CDF_UNPACK(a) \
(void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a)
#define CDF_UNPACKA(a) \
(void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a)
uint16_t
cdf_tole2(uint16_t sv)
{
return CDF_TOLE2(sv);
}
uint32_t
cdf_tole4(uint32_t sv)
{
return CDF_TOLE4(sv);
}
uint64_t
cdf_tole8(uint64_t sv)
{
return CDF_TOLE8(sv);
}
void
cdf_swap_header(cdf_header_t *h)
{
size_t i;
h->h_magic = CDF_TOLE8(h->h_magic);
h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]);
h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]);
h->h_revision = CDF_TOLE2(h->h_revision);
h->h_version = CDF_TOLE2(h->h_version);
h->h_byte_order = CDF_TOLE2(h->h_byte_order);
h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2);
h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2);
h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat);
h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory);
h->h_min_size_standard_stream =
CDF_TOLE4(h->h_min_size_standard_stream);
h->h_secid_first_sector_in_short_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat);
h->h_num_sectors_in_short_sat =
CDF_TOLE4(h->h_num_sectors_in_short_sat);
h->h_secid_first_sector_in_master_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat);
h->h_num_sectors_in_master_sat =
CDF_TOLE4(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]);
}
void
cdf_unpack_header(cdf_header_t *h, char *buf)
{
size_t i;
size_t len = 0;
CDF_UNPACK(h->h_magic);
CDF_UNPACKA(h->h_uuid);
CDF_UNPACK(h->h_revision);
CDF_UNPACK(h->h_version);
CDF_UNPACK(h->h_byte_order);
CDF_UNPACK(h->h_sec_size_p2);
CDF_UNPACK(h->h_short_sec_size_p2);
CDF_UNPACKA(h->h_unused0);
CDF_UNPACK(h->h_num_sectors_in_sat);
CDF_UNPACK(h->h_secid_first_directory);
CDF_UNPACKA(h->h_unused1);
CDF_UNPACK(h->h_min_size_standard_stream);
CDF_UNPACK(h->h_secid_first_sector_in_short_sat);
CDF_UNPACK(h->h_num_sectors_in_short_sat);
CDF_UNPACK(h->h_secid_first_sector_in_master_sat);
CDF_UNPACK(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
CDF_UNPACK(h->h_master_sat[i]);
}
void
cdf_swap_dir(cdf_directory_t *d)
{
d->d_namelen = CDF_TOLE2(d->d_namelen);
d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child);
d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child);
d->d_storage = CDF_TOLE4((uint32_t)d->d_storage);
d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]);
d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]);
d->d_flags = CDF_TOLE4(d->d_flags);
d->d_created = CDF_TOLE8((uint64_t)d->d_created);
d->d_modified = CDF_TOLE8((uint64_t)d->d_modified);
d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector);
d->d_size = CDF_TOLE4(d->d_size);
}
void
cdf_swap_class(cdf_classid_t *d)
{
d->cl_dword = CDF_TOLE4(d->cl_dword);
d->cl_word[0] = CDF_TOLE2(d->cl_word[0]);
d->cl_word[1] = CDF_TOLE2(d->cl_word[1]);
}
void
cdf_unpack_dir(cdf_directory_t *d, char *buf)
{
size_t len = 0;
CDF_UNPACKA(d->d_name);
CDF_UNPACK(d->d_namelen);
CDF_UNPACK(d->d_type);
CDF_UNPACK(d->d_color);
CDF_UNPACK(d->d_left_child);
CDF_UNPACK(d->d_right_child);
CDF_UNPACK(d->d_storage);
CDF_UNPACKA(d->d_storage_uuid);
CDF_UNPACK(d->d_flags);
CDF_UNPACK(d->d_created);
CDF_UNPACK(d->d_modified);
CDF_UNPACK(d->d_stream_first_sector);
CDF_UNPACK(d->d_size);
CDF_UNPACK(d->d_unused0);
}
static int
cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
(void)&line;
if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len));
errno = EFTYPE;
return -1;
}
static ssize_t
cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len)
{
size_t siz = (size_t)off + len;
if ((off_t)(off + len) != (off_t)siz) {
errno = EINVAL;
return -1;
}
if (info->i_buf != NULL && info->i_len >= siz) {
(void)memcpy(buf, &info->i_buf[off], len);
return (ssize_t)len;
}
if (info->i_fd == -1)
return -1;
if (pread(info->i_fd, buf, len, off) != (ssize_t)len)
return -1;
return (ssize_t)len;
}
int
cdf_read_header(const cdf_info_t *info, cdf_header_t *h)
{
char buf[512];
(void)memcpy(cdf_bo.s, "\01\02\03\04", 4);
if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1)
return -1;
cdf_unpack_header(h, buf);
cdf_swap_header(h);
if (h->h_magic != CDF_MAGIC) {
DPRINTF(("Bad magic 0x%" INT64_T_FORMAT "x != 0x%"
INT64_T_FORMAT "x\n",
(unsigned long long)h->h_magic,
(unsigned long long)CDF_MAGIC));
goto out;
}
if (h->h_sec_size_p2 > 20) {
DPRINTF(("Bad sector size 0x%u\n", h->h_sec_size_p2));
goto out;
}
if (h->h_short_sec_size_p2 > 20) {
DPRINTF(("Bad short sector size 0x%u\n",
h->h_short_sec_size_p2));
goto out;
}
return 0;
out:
errno = EFTYPE;
return -1;
}
ssize_t
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SEC_SIZE(h);
size_t pos = CDF_SEC_POS(h, id);
assert(ss == len);
return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len);
}
ssize_t
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
size_t len, const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SHORT_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos + len, CDF_SEC_SIZE(h) * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
/*
* Read the sector allocation table.
*/
int
cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat)
{
size_t i, j, k;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t *msa, mid, sec;
size_t nsatpersec = (ss / sizeof(mid)) - 1;
for (i = 0; i < __arraycount(h->h_master_sat); i++)
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
#define CDF_SEC_LIMIT (UINT32_MAX / (4 * ss))
if ((nsatpersec > 0 &&
h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) ||
i > CDF_SEC_LIMIT) {
DPRINTF(("Number of sectors in master SAT too big %u %"
SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i));
errno = EFTYPE;
return -1;
}
sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i;
DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n",
sat->sat_len, ss));
if ((sat->sat_tab = CAST(cdf_secid_t *, calloc(sat->sat_len, ss)))
== NULL)
return -1;
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] < 0)
break;
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
h->h_master_sat[i]) != (ssize_t)ss) {
DPRINTF(("Reading sector %d", h->h_master_sat[i]));
goto out1;
}
}
if ((msa = CAST(cdf_secid_t *, calloc(1, ss))) == NULL)
goto out1;
mid = h->h_secid_first_sector_in_master_sat;
for (j = 0; j < h->h_num_sectors_in_master_sat; j++) {
if (mid < 0)
goto out;
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Reading master sector loop limit"));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) {
DPRINTF(("Reading master sector %d", mid));
goto out2;
}
for (k = 0; k < nsatpersec; k++, i++) {
sec = CDF_TOLE4((uint32_t)msa[k]);
if (sec < 0)
goto out;
if (i >= sat->sat_len) {
DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT
"u >= %" SIZE_T_FORMAT "u", i, sat->sat_len));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
sec) != (ssize_t)ss) {
DPRINTF(("Reading sector %d",
CDF_TOLE4(msa[k])));
goto out2;
}
}
mid = CDF_TOLE4((uint32_t)msa[nsatpersec]);
}
out:
sat->sat_len = i;
free(msa);
return 0;
out2:
free(msa);
out1:
free(sat->sat_tab);
return -1;
}
size_t
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
{
size_t i, j;
cdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size);
DPRINTF(("Chain:"));
for (j = i = 0; sid >= 0; i++, j++) {
DPRINTF((" %d", sid));
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Counting chain loop limit"));
errno = EFTYPE;
return (size_t)-1;
}
if (sid > maxsector) {
DPRINTF(("Sector %d > %d\n", sid, maxsector));
errno = EFTYPE;
return (size_t)-1;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
DPRINTF(("\n"));
return i;
}
int
cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
ssize_t nr;
scn->sst_len = cdf_count_chain(sat, sid, ss);
scn->sst_dirlen = len;
if (scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read long sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading long sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
scn->sst_len));
errno = EFTYPE;
goto out;
}
if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h,
sid)) != (ssize_t)ss) {
if (i == scn->sst_len - 1 && nr > 0) {
/* Last sector might be truncated */
return 0;
}
DPRINTF(("Reading long sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL)
return cdf_read_short_sector_chain(h, ssat, sst, sid, len,
scn);
else
return cdf_read_long_sector_chain(info, h, sat, sid, len, scn);
}
int
cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_dir_t *dir)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h), ns, nd;
char *buf;
cdf_secid_t sid = h->h_secid_first_directory;
ns = cdf_count_chain(sat, sid, ss);
if (ns == (size_t)-1)
return -1;
nd = ss / CDF_DIRECTORY_SIZE;
dir->dir_len = ns * nd;
dir->dir_tab = CAST(cdf_directory_t *,
calloc(dir->dir_len, sizeof(dir->dir_tab[0])));
if (dir->dir_tab == NULL)
return -1;
if ((buf = CAST(char *, malloc(ss))) == NULL) {
free(dir->dir_tab);
return -1;
}
for (j = i = 0; i < ns; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read dir loop limit"));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) {
DPRINTF(("Reading directory sector %d", sid));
goto out;
}
for (j = 0; j < nd; j++) {
cdf_unpack_dir(&dir->dir_tab[i * nd + j],
&buf[j * CDF_DIRECTORY_SIZE]);
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (NEED_SWAP)
for (i = 0; i < dir->dir_len; i++)
cdf_swap_dir(&dir->dir_tab[i]);
free(buf);
return 0;
out:
free(dir->dir_tab);
free(buf);
return -1;
}
int
cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_sat_t *ssat)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t sid = h->h_secid_first_sector_in_short_sat;
ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h));
if (ssat->sat_len == (size_t)-1)
return -1;
ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss));
if (ssat->sat_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sat sector loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= ssat->sat_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
ssat->sat_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) !=
(ssize_t)ss) {
DPRINTF(("Reading short sat sector %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(ssat->sat_tab);
return -1;
}
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
*root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
/* If the it is not there, just fake it; some docs don't have it */
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
*root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0)
goto out;
return cdf_read_long_sector_chain(info, h, sat,
d->d_stream_first_sector, d->d_size, scn);
out:
scn->sst_tab = NULL;
scn->sst_len = 0;
scn->sst_dirlen = 0;
return 0;
}
static int
cdf_namecmp(const char *d, const uint16_t *s, size_t l)
{
for (; l--; d++, s++)
if (*d != CDF_TOLE2(*s))
return (unsigned char)*d - CDF_TOLE2(*s);
return 0;
}
int
cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, cdf_stream_t *scn)
{
size_t i;
const cdf_directory_t *d;
static const char name[] = "\05SummaryInformation";
for (i = dir->dir_len; i > 0; i--)
if (dir->dir_tab[i - 1].d_type == CDF_DIR_TYPE_USER_STREAM &&
cdf_namecmp(name, dir->dir_tab[i - 1].d_name, sizeof(name))
== 0)
break;
if (i == 0) {
DPRINTF(("Cannot find summary information section\n"));
errno = ESRCH;
return -1;
}
d = &dir->dir_tab[i - 1];
return cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, scn);
}
int
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements; j++, i++) {
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
int
cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
{
size_t i, maxcount;
const cdf_summary_info_header_t *si =
CAST(const cdf_summary_info_header_t *, sst->sst_tab);
const cdf_section_declaration_t *sd =
CAST(const cdf_section_declaration_t *, (const void *)
((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
return -1;
ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
ssi->si_os_version = CDF_TOLE2(si->si_os_version);
ssi->si_os = CDF_TOLE2(si->si_os);
ssi->si_class = si->si_class;
cdf_swap_class(&ssi->si_class);
ssi->si_count = CDF_TOLE2(si->si_count);
*count = 0;
maxcount = 0;
*info = NULL;
for (i = 0; i < CDF_TOLE4(si->si_count); i++) {
if (i >= CDF_LOOP_LIMIT) {
DPRINTF(("Unpack summary info loop limit"));
errno = EFTYPE;
return -1;
}
if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset),
info, count, &maxcount) == -1) {
return -1;
}
}
return 0;
}
int
cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id)
{
return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-"
"%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0],
id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0],
id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4],
id->cl_six[5]);
}
static const struct {
uint32_t v;
const char *n;
} vn[] = {
{ CDF_PROPERTY_CODE_PAGE, "Code page" },
{ CDF_PROPERTY_TITLE, "Title" },
{ CDF_PROPERTY_SUBJECT, "Subject" },
{ CDF_PROPERTY_AUTHOR, "Author" },
{ CDF_PROPERTY_KEYWORDS, "Keywords" },
{ CDF_PROPERTY_COMMENTS, "Comments" },
{ CDF_PROPERTY_TEMPLATE, "Template" },
{ CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" },
{ CDF_PROPERTY_REVISION_NUMBER, "Revision Number" },
{ CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" },
{ CDF_PROPERTY_LAST_PRINTED, "Last Printed" },
{ CDF_PROPERTY_CREATE_TIME, "Create Time/Date" },
{ CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" },
{ CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" },
{ CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" },
{ CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" },
{ CDF_PROPERTY_THUMBNAIL, "Thumbnail" },
{ CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" },
{ CDF_PROPERTY_SECURITY, "Security" },
{ CDF_PROPERTY_LOCALE_ID, "Locale ID" },
};
int
cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p)
{
size_t i;
for (i = 0; i < __arraycount(vn); i++)
if (vn[i].v == p)
return snprintf(buf, bufsiz, "%s", vn[i].n);
return snprintf(buf, bufsiz, "0x%x", p);
}
int
cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts)
{
int len = 0;
int days, hours, mins, secs;
ts /= CDF_TIME_PREC;
secs = (int)(ts % 60);
ts /= 60;
mins = (int)(ts % 60);
ts /= 60;
hours = (int)(ts % 24);
ts /= 24;
days = (int)ts;
if (days) {
len += snprintf(buf + len, bufsiz - len, "%dd+", days);
if ((size_t)len >= bufsiz)
return len;
}
if (days || hours) {
len += snprintf(buf + len, bufsiz - len, "%.2d:", hours);
if ((size_t)len >= bufsiz)
return len;
}
len += snprintf(buf + len, bufsiz - len, "%.2d:", mins);
if ((size_t)len >= bufsiz)
return len;
len += snprintf(buf + len, bufsiz - len, "%.2d", secs);
return len;
}
#ifdef CDF_DEBUG
void
cdf_dump_header(const cdf_header_t *h)
{
size_t i;
#define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b)
#define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \
h->h_ ## b, 1 << h->h_ ## b)
DUMP("%d", revision);
DUMP("%d", version);
DUMP("0x%x", byte_order);
DUMP2("%d", sec_size_p2);
DUMP2("%d", short_sec_size_p2);
DUMP("%d", num_sectors_in_sat);
DUMP("%d", secid_first_directory);
DUMP("%d", min_size_standard_stream);
DUMP("%d", secid_first_sector_in_short_sat);
DUMP("%d", num_sectors_in_short_sat);
DUMP("%d", secid_first_sector_in_master_sat);
DUMP("%d", num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
(void)fprintf(stderr, "%35.35s[%.3zu] = %d\n",
"master_sat", i, h->h_master_sat[i]);
}
}
void
cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size)
{
size_t i, j, s = size / sizeof(cdf_secid_t);
for (i = 0; i < sat->sat_len; i++) {
(void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6"
SIZE_T_FORMAT "u: ", prefix, i, i * s);
for (j = 0; j < s; j++) {
(void)fprintf(stderr, "%5d, ",
CDF_TOLE4(sat->sat_tab[s * i + j]));
if ((j + 1) % 10 == 0)
(void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT
"u: ", i * s + j + 1);
}
(void)fprintf(stderr, "\n");
}
}
void
cdf_dump(void *v, size_t len)
{
size_t i, j;
unsigned char *p = v;
char abuf[16];
(void)fprintf(stderr, "%.4x: ", 0);
for (i = 0, j = 0; i < len; i++, p++) {
(void)fprintf(stderr, "%.2x ", *p);
abuf[j++] = isprint(*p) ? *p : '.';
if (j == 16) {
j = 0;
abuf[15] = '\0';
(void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ",
abuf, i + 1);
}
}
(void)fprintf(stderr, "\n");
}
void
cdf_dump_stream(const cdf_header_t *h, const cdf_stream_t *sst)
{
size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
cdf_dump(sst->sst_tab, ss * sst->sst_len);
}
void
cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir)
{
size_t i, j;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
cdf_stream_t scn;
struct timespec ts;
static const char *types[] = { "empty", "user storage",
"user stream", "lockbytes", "property", "root storage" };
for (i = 0; i < dir->dir_len; i++) {
char buf[26];
d = &dir->dir_tab[i];
for (j = 0; j < sizeof(name); j++)
name[j] = (char)CDF_TOLE2(d->d_name[j]);
(void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n",
i, name);
if (d->d_type < __arraycount(types))
(void)fprintf(stderr, "Type: %s\n", types[d->d_type]);
else
(void)fprintf(stderr, "Type: %d\n", d->d_type);
(void)fprintf(stderr, "Color: %s\n",
d->d_color ? "black" : "red");
(void)fprintf(stderr, "Left child: %d\n", d->d_left_child);
(void)fprintf(stderr, "Right child: %d\n", d->d_right_child);
(void)fprintf(stderr, "Flags: 0x%x\n", d->d_flags);
cdf_timestamp_to_timespec(&ts, d->d_created);
(void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf));
cdf_timestamp_to_timespec(&ts, d->d_modified);
(void)fprintf(stderr, "Modified %s",
cdf_ctime(&ts.tv_sec, buf));
(void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector);
(void)fprintf(stderr, "Size %d\n", d->d_size);
switch (d->d_type) {
case CDF_DIR_TYPE_USER_STORAGE:
(void)fprintf(stderr, "Storage: %d\n", d->d_storage);
break;
case CDF_DIR_TYPE_USER_STREAM:
if (sst == NULL)
break;
if (cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, &scn) == -1) {
warn("Can't read stream for %s at %d len %d",
name, d->d_stream_first_sector, d->d_size);
break;
}
cdf_dump_stream(h, &scn);
free(scn.sst_tab);
break;
default:
break;
}
}
}
void
cdf_dump_property_info(const cdf_property_info_t *info, size_t count)
{
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
size_t i, j;
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
(void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
(void)fprintf(stderr, "signed 16 [%hd]\n",
info[i].pi_s16);
break;
case CDF_SIGNED32:
(void)fprintf(stderr, "signed 32 [%d]\n",
info[i].pi_s32);
break;
case CDF_UNSIGNED32:
(void)fprintf(stderr, "unsigned 32 [%u]\n",
info[i].pi_u32);
break;
case CDF_FLOAT:
(void)fprintf(stderr, "float [%g]\n",
info[i].pi_f);
break;
case CDF_DOUBLE:
(void)fprintf(stderr, "double [%g]\n",
info[i].pi_d);
break;
case CDF_LENGTH32_STRING:
(void)fprintf(stderr, "string %u [%.*s]\n",
info[i].pi_str.s_len,
info[i].pi_str.s_len, info[i].pi_str.s_buf);
break;
case CDF_LENGTH32_WSTRING:
(void)fprintf(stderr, "string %u [",
info[i].pi_str.s_len);
for (j = 0; j < info[i].pi_str.s_len - 1; j++)
(void)fputc(info[i].pi_str.s_buf[j << 1], stderr);
(void)fprintf(stderr, "]\n");
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(buf, sizeof(buf), tp);
(void)fprintf(stderr, "timestamp %s\n", buf);
} else {
char buf[26];
cdf_timestamp_to_timespec(&ts, tp);
(void)fprintf(stderr, "timestamp %s",
cdf_ctime(&ts.tv_sec, buf));
}
break;
case CDF_CLIPBOARD:
(void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32);
break;
default:
DPRINTF(("Don't know how to deal with %x\n",
info[i].pi_type));
break;
}
}
}
void
cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst)
{
char buf[128];
cdf_summary_info_header_t ssi;
cdf_property_info_t *info;
size_t count;
(void)&h;
if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1)
return;
(void)fprintf(stderr, "Endian: %x\n", ssi.si_byte_order);
(void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff,
ssi.si_os_version >> 8);
(void)fprintf(stderr, "Os %d\n", ssi.si_os);
cdf_print_classid(buf, sizeof(buf), &ssi.si_class);
(void)fprintf(stderr, "Class %s\n", buf);
(void)fprintf(stderr, "Count %d\n", ssi.si_count);
cdf_dump_property_info(info, count);
free(info);
}
#endif
#ifdef TEST
int
main(int argc, char *argv[])
{
int i;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
cdf_info_t info;
if (argc < 2) {
(void)fprintf(stderr, "Usage: %s <filename>\n", getprogname());
return -1;
}
info.i_buf = NULL;
info.i_len = 0;
for (i = 1; i < argc; i++) {
if ((info.i_fd = open(argv[1], O_RDONLY)) == -1)
err(1, "Cannot open `%s'", argv[1]);
if (cdf_read_header(&info, &h) == -1)
err(1, "Cannot read header");
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if (cdf_read_sat(&info, &h, &sat) == -1)
err(1, "Cannot read sat");
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1)
err(1, "Cannot read ssat");
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if (cdf_read_dir(&info, &h, &sat, &dir) == -1)
err(1, "Cannot read dir");
if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst) == -1)
err(1, "Cannot read short stream");
#ifdef CDF_DEBUG
cdf_dump_stream(&h, &sst);
#endif
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn) == -1)
err(1, "Cannot read summary info");
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
(void)close(info.i_fd);
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2038_0 |
crossvul-cpp_data_good_2157_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2014 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: The typical suspects |
| Pollita <pollita@php.net> |
| Marcus Boerger <helly@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* {{{ includes */
#include "php.h"
#include "php_network.h"
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef PHP_WIN32
# include "win32/inet.h"
# include <winsock2.h>
# include <windows.h>
# include <Ws2tcpip.h>
#else /* This holds good for NetWare too, both for Winsock and Berkeley sockets */
#include <netinet/in.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <netdb.h>
#ifdef _OSD_POSIX
#undef STATUS
#undef T_UNSPEC
#endif
#if HAVE_ARPA_NAMESER_H
#ifdef DARWIN
# define BIND_8_COMPAT 1
#endif
#include <arpa/nameser.h>
#endif
#if HAVE_RESOLV_H
#include <resolv.h>
#endif
#ifdef HAVE_DNS_H
#include <dns.h>
#endif
#endif
/* Borrowed from SYS/SOCKET.H */
#if defined(NETWARE) && defined(USE_WINSOCK)
#define AF_INET 2 /* internetwork: UDP, TCP, etc. */
#endif
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 255
#endif
/* For the local hostname obtained via gethostname which is different from the
dns-related MAXHOSTNAMELEN constant above */
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif
#include "php_dns.h"
/* type compat */
#ifndef DNS_T_A
#define DNS_T_A 1
#endif
#ifndef DNS_T_NS
#define DNS_T_NS 2
#endif
#ifndef DNS_T_CNAME
#define DNS_T_CNAME 5
#endif
#ifndef DNS_T_SOA
#define DNS_T_SOA 6
#endif
#ifndef DNS_T_PTR
#define DNS_T_PTR 12
#endif
#ifndef DNS_T_HINFO
#define DNS_T_HINFO 13
#endif
#ifndef DNS_T_MINFO
#define DNS_T_MINFO 14
#endif
#ifndef DNS_T_MX
#define DNS_T_MX 15
#endif
#ifndef DNS_T_TXT
#define DNS_T_TXT 16
#endif
#ifndef DNS_T_AAAA
#define DNS_T_AAAA 28
#endif
#ifndef DNS_T_SRV
#define DNS_T_SRV 33
#endif
#ifndef DNS_T_NAPTR
#define DNS_T_NAPTR 35
#endif
#ifndef DNS_T_A6
#define DNS_T_A6 38
#endif
#ifndef DNS_T_ANY
#define DNS_T_ANY 255
#endif
/* }}} */
static char *php_gethostbyaddr(char *ip);
static char *php_gethostbyname(char *name);
#ifdef HAVE_GETHOSTNAME
/* {{{ proto string gethostname()
Get the host name of the current machine */
PHP_FUNCTION(gethostname)
{
char buf[HOST_NAME_MAX];
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (gethostname(buf, sizeof(buf) - 1)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to fetch host [%d]: %s", errno, strerror(errno));
RETURN_FALSE;
}
RETURN_STRING(buf, 1);
}
/* }}} */
#endif
/* TODO: Reimplement the gethostby* functions using the new winxp+ API, in dns_win32.c, then
we can have a dns.c, dns_unix.c and dns_win32.c instead of a messy dns.c full of #ifdef
*/
/* {{{ proto string gethostbyaddr(string ip_address)
Get the Internet host name corresponding to a given IP address */
PHP_FUNCTION(gethostbyaddr)
{
char *addr;
int addr_len;
char *hostname;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &addr, &addr_len) == FAILURE) {
return;
}
hostname = php_gethostbyaddr(addr);
if (hostname == NULL) {
#if HAVE_IPV6 && HAVE_INET_PTON
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Address is not a valid IPv4 or IPv6 address");
#else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Address is not in a.b.c.d form");
#endif
RETVAL_FALSE;
} else {
RETVAL_STRING(hostname, 0);
}
}
/* }}} */
/* {{{ php_gethostbyaddr */
static char *php_gethostbyaddr(char *ip)
{
#if HAVE_IPV6 && HAVE_INET_PTON
struct in6_addr addr6;
#endif
struct in_addr addr;
struct hostent *hp;
#if HAVE_IPV6 && HAVE_INET_PTON
if (inet_pton(AF_INET6, ip, &addr6)) {
hp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6);
} else if (inet_pton(AF_INET, ip, &addr)) {
hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);
} else {
return NULL;
}
#else
addr.s_addr = inet_addr(ip);
if (addr.s_addr == -1) {
return NULL;
}
hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);
#endif
if (!hp || hp->h_name == NULL || hp->h_name[0] == '\0') {
return estrdup(ip);
}
return estrdup(hp->h_name);
}
/* }}} */
/* {{{ proto string gethostbyname(string hostname)
Get the IP address corresponding to a given Internet host name */
PHP_FUNCTION(gethostbyname)
{
char *hostname;
int hostname_len;
char *addr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hostname, &hostname_len) == FAILURE) {
return;
}
addr = php_gethostbyname(hostname);
RETVAL_STRING(addr, 0);
}
/* }}} */
/* {{{ proto array gethostbynamel(string hostname)
Return a list of IP addresses that a given hostname resolves to. */
PHP_FUNCTION(gethostbynamel)
{
char *hostname;
int hostname_len;
struct hostent *hp;
struct in_addr in;
int i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &hostname, &hostname_len) == FAILURE) {
return;
}
hp = gethostbyname(hostname);
if (hp == NULL || hp->h_addr_list == NULL) {
RETURN_FALSE;
}
array_init(return_value);
for (i = 0 ; hp->h_addr_list[i] != 0 ; i++) {
in = *(struct in_addr *) hp->h_addr_list[i];
add_next_index_string(return_value, inet_ntoa(in), 1);
}
}
/* }}} */
/* {{{ php_gethostbyname */
static char *php_gethostbyname(char *name)
{
struct hostent *hp;
struct in_addr in;
hp = gethostbyname(name);
if (!hp || !*(hp->h_addr_list)) {
return estrdup(name);
}
memcpy(&in.s_addr, *(hp->h_addr_list), sizeof(in.s_addr));
return estrdup(inet_ntoa(in));
}
/* }}} */
#if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)
# define PHP_DNS_NUM_TYPES 12 /* Number of DNS Types Supported by PHP currently */
# define PHP_DNS_A 0x00000001
# define PHP_DNS_NS 0x00000002
# define PHP_DNS_CNAME 0x00000010
# define PHP_DNS_SOA 0x00000020
# define PHP_DNS_PTR 0x00000800
# define PHP_DNS_HINFO 0x00001000
# define PHP_DNS_MX 0x00004000
# define PHP_DNS_TXT 0x00008000
# define PHP_DNS_A6 0x01000000
# define PHP_DNS_SRV 0x02000000
# define PHP_DNS_NAPTR 0x04000000
# define PHP_DNS_AAAA 0x08000000
# define PHP_DNS_ANY 0x10000000
# define PHP_DNS_ALL (PHP_DNS_A|PHP_DNS_NS|PHP_DNS_CNAME|PHP_DNS_SOA|PHP_DNS_PTR|PHP_DNS_HINFO|PHP_DNS_MX|PHP_DNS_TXT|PHP_DNS_A6|PHP_DNS_SRV|PHP_DNS_NAPTR|PHP_DNS_AAAA)
#endif /* HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) */
/* Note: These functions are defined in ext/standard/dns_win32.c for Windows! */
#if !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE)))
#ifndef HFIXEDSZ
#define HFIXEDSZ 12 /* fixed data in header <arpa/nameser.h> */
#endif /* HFIXEDSZ */
#ifndef QFIXEDSZ
#define QFIXEDSZ 4 /* fixed data in query <arpa/nameser.h> */
#endif /* QFIXEDSZ */
#undef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 1024
#ifndef MAXRESOURCERECORDS
#define MAXRESOURCERECORDS 64
#endif /* MAXRESOURCERECORDS */
typedef union {
HEADER qb1;
u_char qb2[65536];
} querybuf;
/* just a hack to free resources allocated by glibc in __res_nsend()
* See also:
* res_thread_freeres() in glibc/resolv/res_init.c
* __libc_res_nsend() in resolv/res_send.c
* */
#if defined(__GLIBC__) && !defined(HAVE_DEPRECATED_DNS_FUNCS)
#define php_dns_free_res(__res__) _php_dns_free_res(__res__)
static void _php_dns_free_res(struct __res_state res) { /* {{{ */
int ns;
for (ns = 0; ns < MAXNS; ns++) {
if (res._u._ext.nsaddrs[ns] != NULL) {
free (res._u._ext.nsaddrs[ns]);
res._u._ext.nsaddrs[ns] = NULL;
}
}
} /* }}} */
#else
#define php_dns_free_res(__res__)
#endif
/* {{{ proto bool dns_check_record(string host [, string type])
Check DNS records corresponding to a given Internet host name or IP address */
PHP_FUNCTION(dns_check_record)
{
#ifndef MAXPACKET
#define MAXPACKET 8192 /* max packet size used internally by BIND */
#endif
u_char ans[MAXPACKET];
char *hostname, *rectype = NULL;
int hostname_len, rectype_len = 0;
int type = T_MX, i;
#if defined(HAVE_DNS_SEARCH)
struct sockaddr_storage from;
uint32_t fromsize = sizeof(from);
dns_handle_t handle;
#elif defined(HAVE_RES_NSEARCH)
struct __res_state state;
struct __res_state *handle = &state;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) {
return;
}
if (hostname_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Host cannot be empty");
RETURN_FALSE;
}
if (rectype) {
if (!strcasecmp("A", rectype)) type = T_A;
else if (!strcasecmp("NS", rectype)) type = DNS_T_NS;
else if (!strcasecmp("MX", rectype)) type = DNS_T_MX;
else if (!strcasecmp("PTR", rectype)) type = DNS_T_PTR;
else if (!strcasecmp("ANY", rectype)) type = DNS_T_ANY;
else if (!strcasecmp("SOA", rectype)) type = DNS_T_SOA;
else if (!strcasecmp("TXT", rectype)) type = DNS_T_TXT;
else if (!strcasecmp("CNAME", rectype)) type = DNS_T_CNAME;
else if (!strcasecmp("AAAA", rectype)) type = DNS_T_AAAA;
else if (!strcasecmp("SRV", rectype)) type = DNS_T_SRV;
else if (!strcasecmp("NAPTR", rectype)) type = DNS_T_NAPTR;
else if (!strcasecmp("A6", rectype)) type = DNS_T_A6;
else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%s' not supported", rectype);
RETURN_FALSE;
}
}
#if defined(HAVE_DNS_SEARCH)
handle = dns_open(NULL);
if (handle == NULL) {
RETURN_FALSE;
}
#elif defined(HAVE_RES_NSEARCH)
memset(&state, 0, sizeof(state));
if (res_ninit(handle)) {
RETURN_FALSE;
}
#else
res_init();
#endif
RETVAL_TRUE;
i = php_dns_search(handle, hostname, C_IN, type, ans, sizeof(ans));
if (i < 0) {
RETVAL_FALSE;
}
php_dns_free_handle(handle);
}
/* }}} */
#if HAVE_FULL_DNS_FUNCS
#define CHECKCP(n) do { \
if (cp + n > end) { \
return NULL; \
} \
} while (0)
/* {{{ php_parserr */
static u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray)
{
u_short type, class, dlen;
u_long ttl;
long n, i;
u_short s;
u_char *tp, *p;
char name[MAXHOSTNAMELEN];
int have_v6_break = 0, in_v6_break = 0;
*subarray = NULL;
n = dn_expand(answer->qb2, end, cp, name, sizeof(name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
CHECKCP(10);
GETSHORT(type, cp);
GETSHORT(class, cp);
GETLONG(ttl, cp);
GETSHORT(dlen, cp);
CHECKCP(dlen);
if (type_to_fetch != T_ANY && type != type_to_fetch) {
cp += dlen;
return cp;
}
if (!store) {
cp += dlen;
return cp;
}
ALLOC_INIT_ZVAL(*subarray);
array_init(*subarray);
add_assoc_string(*subarray, "host", name, 1);
add_assoc_string(*subarray, "class", "IN", 1);
add_assoc_long(*subarray, "ttl", ttl);
if (raw) {
add_assoc_long(*subarray, "type", type);
add_assoc_stringl(*subarray, "data", (char*) cp, (uint) dlen, 1);
cp += dlen;
return cp;
}
switch (type) {
case DNS_T_A:
CHECKCP(4);
add_assoc_string(*subarray, "type", "A", 1);
snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]);
add_assoc_string(*subarray, "ip", name, 1);
cp += dlen;
break;
case DNS_T_MX:
CHECKCP(2);
add_assoc_string(*subarray, "type", "MX", 1);
GETSHORT(n, cp);
add_assoc_long(*subarray, "pri", n);
/* no break; */
case DNS_T_CNAME:
if (type == DNS_T_CNAME) {
add_assoc_string(*subarray, "type", "CNAME", 1);
}
/* no break; */
case DNS_T_NS:
if (type == DNS_T_NS) {
add_assoc_string(*subarray, "type", "NS", 1);
}
/* no break; */
case DNS_T_PTR:
if (type == DNS_T_PTR) {
add_assoc_string(*subarray, "type", "PTR", 1);
}
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "target", name, 1);
break;
case DNS_T_HINFO:
/* See RFC 1010 for values */
add_assoc_string(*subarray, "type", "HINFO", 1);
CHECKCP(1);
n = *cp & 0xFF;
cp++;
CHECKCP(n);
add_assoc_stringl(*subarray, "cpu", (char*)cp, n, 1);
cp += n;
CHECKCP(1);
n = *cp & 0xFF;
cp++;
CHECKCP(n);
add_assoc_stringl(*subarray, "os", (char*)cp, n, 1);
cp += n;
break;
case DNS_T_TXT:
{
int l1 = 0, l2 = 0;
zval *entries = NULL;
add_assoc_string(*subarray, "type", "TXT", 1);
tp = emalloc(dlen + 1);
MAKE_STD_ZVAL(entries);
array_init(entries);
while (l1 < dlen) {
n = cp[l1];
if ((l1 + n) >= dlen) {
// Invalid chunk length, truncate
n = dlen - (l1 + 1);
}
if (n) {
memcpy(tp + l2 , cp + l1 + 1, n);
add_next_index_stringl(entries, cp + l1 + 1, n, 1);
}
l1 = l1 + n + 1;
l2 = l2 + n;
}
tp[l2] = '\0';
cp += dlen;
add_assoc_stringl(*subarray, "txt", tp, l2, 0);
add_assoc_zval(*subarray, "entries", entries);
}
break;
case DNS_T_SOA:
add_assoc_string(*subarray, "type", "SOA", 1);
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "mname", name, 1);
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "rname", name, 1);
CHECKCP(5*4);
GETLONG(n, cp);
add_assoc_long(*subarray, "serial", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "refresh", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "retry", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "expire", n);
GETLONG(n, cp);
add_assoc_long(*subarray, "minimum-ttl", n);
break;
case DNS_T_AAAA:
tp = (u_char*)name;
CHECKCP(8*2);
for(i=0; i < 8; i++) {
GETSHORT(s, cp);
if (s != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
tp += sprintf((char*)tp,"%x",s);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
}
if (have_v6_break && in_v6_break) {
tp[0] = ':';
tp++;
}
tp[0] = '\0';
add_assoc_string(*subarray, "type", "AAAA", 1);
add_assoc_string(*subarray, "ipv6", name, 1);
break;
case DNS_T_A6:
p = cp;
add_assoc_string(*subarray, "type", "A6", 1);
CHECKCP(1);
n = ((int)cp[0]) & 0xFF;
cp++;
add_assoc_long(*subarray, "masklen", n);
tp = (u_char*)name;
if (n > 15) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
}
if (n % 16 > 8) {
/* Partial short */
if (cp[0] != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
sprintf((char*)tp, "%x", cp[0] & 0xFF);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
cp++;
}
for (i = (n + 8) / 16; i < 8; i++) {
CHECKCP(2);
GETSHORT(s, cp);
if (s != 0) {
if (tp > (u_char *)name) {
in_v6_break = 0;
tp[0] = ':';
tp++;
}
tp += sprintf((char*)tp,"%x",s);
} else {
if (!have_v6_break) {
have_v6_break = 1;
in_v6_break = 1;
tp[0] = ':';
tp++;
} else if (!in_v6_break) {
tp[0] = ':';
tp++;
tp[0] = '0';
tp++;
}
}
}
if (have_v6_break && in_v6_break) {
tp[0] = ':';
tp++;
}
tp[0] = '\0';
add_assoc_string(*subarray, "ipv6", name, 1);
if (cp < p + dlen) {
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "chain", name, 1);
}
break;
case DNS_T_SRV:
CHECKCP(3*2);
add_assoc_string(*subarray, "type", "SRV", 1);
GETSHORT(n, cp);
add_assoc_long(*subarray, "pri", n);
GETSHORT(n, cp);
add_assoc_long(*subarray, "weight", n);
GETSHORT(n, cp);
add_assoc_long(*subarray, "port", n);
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "target", name, 1);
break;
case DNS_T_NAPTR:
CHECKCP(2*2);
add_assoc_string(*subarray, "type", "NAPTR", 1);
GETSHORT(n, cp);
add_assoc_long(*subarray, "order", n);
GETSHORT(n, cp);
add_assoc_long(*subarray, "pref", n);
CHECKCP(1);
n = (cp[0] & 0xFF);
cp++;
CHECKCP(n);
add_assoc_stringl(*subarray, "flags", (char*)cp, n, 1);
cp += n;
CHECKCP(1);
n = (cp[0] & 0xFF);
cp++;
CHECKCP(n);
add_assoc_stringl(*subarray, "services", (char*)cp, n, 1);
cp += n;
CHECKCP(1);
n = (cp[0] & 0xFF);
cp++;
CHECKCP(n);
add_assoc_stringl(*subarray, "regex", (char*)cp, n, 1);
cp += n;
n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
if (n < 0) {
return NULL;
}
cp += n;
add_assoc_string(*subarray, "replacement", name, 1);
break;
default:
zval_ptr_dtor(subarray);
*subarray = NULL;
cp += dlen;
break;
}
return cp;
}
/* }}} */
/* {{{ proto array|false dns_get_record(string hostname [, int type[, array authns, array addtl]])
Get any Resource Record corresponding to a given Internet host name */
PHP_FUNCTION(dns_get_record)
{
char *hostname;
int hostname_len;
long type_param = PHP_DNS_ANY;
zval *authns = NULL, *addtl = NULL;
int type_to_fetch;
#if defined(HAVE_DNS_SEARCH)
struct sockaddr_storage from;
uint32_t fromsize = sizeof(from);
dns_handle_t handle;
#elif defined(HAVE_RES_NSEARCH)
struct __res_state state;
struct __res_state *handle = &state;
#endif
HEADER *hp;
querybuf answer;
u_char *cp = NULL, *end = NULL;
int n, qd, an, ns = 0, ar = 0;
int type, first_query = 1, store_results = 1;
zend_bool raw = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz!z!b",
&hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) {
return;
}
if (authns) {
zval_dtor(authns);
array_init(authns);
}
if (addtl) {
zval_dtor(addtl);
array_init(addtl);
}
if (!raw) {
if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%ld' not supported", type_param);
RETURN_FALSE;
}
} else {
if ((type_param < 1) || (type_param > 0xFFFF)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Numeric DNS record type must be between 1 and 65535, '%ld' given", type_param);
RETURN_FALSE;
}
}
/* Initialize the return array */
array_init(return_value);
/* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 )
* If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 )
* store_results is used to skip storing the results retrieved in step
* NUMTYPES+1 when results were already fetched.
* - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 )
* - In case of raw mode, we query only the requestd type instead of looping type by type
* before going with the additional info stuff.
*/
if (raw) {
type = -1;
} else if (type_param == PHP_DNS_ANY) {
type = PHP_DNS_NUM_TYPES + 1;
} else {
type = 0;
}
for ( ;
type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query;
type++
) {
first_query = 0;
switch (type) {
case -1: /* raw */
type_to_fetch = type_param;
/* skip over the rest and go directly to additional records */
type = PHP_DNS_NUM_TYPES - 1;
break;
case 0:
type_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0;
break;
case 1:
type_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0;
break;
case 2:
type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0;
break;
case 3:
type_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0;
break;
case 4:
type_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0;
break;
case 5:
type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0;
break;
case 6:
type_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0;
break;
case 7:
type_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0;
break;
case 8:
type_to_fetch = type_param&PHP_DNS_AAAA ? DNS_T_AAAA : 0;
break;
case 9:
type_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0;
break;
case 10:
type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0;
break;
case 11:
type_to_fetch = type_param&PHP_DNS_A6 ? DNS_T_A6 : 0;
break;
case PHP_DNS_NUM_TYPES:
store_results = 0;
continue;
default:
case (PHP_DNS_NUM_TYPES + 1):
type_to_fetch = DNS_T_ANY;
break;
}
if (type_to_fetch) {
#if defined(HAVE_DNS_SEARCH)
handle = dns_open(NULL);
if (handle == NULL) {
zval_dtor(return_value);
RETURN_FALSE;
}
#elif defined(HAVE_RES_NSEARCH)
memset(&state, 0, sizeof(state));
if (res_ninit(handle)) {
zval_dtor(return_value);
RETURN_FALSE;
}
#else
res_init();
#endif
n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer);
if (n < 0) {
php_dns_free_handle(handle);
continue;
}
cp = answer.qb2 + HFIXEDSZ;
end = answer.qb2 + n;
hp = (HEADER *)&answer;
qd = ntohs(hp->qdcount);
an = ntohs(hp->ancount);
ns = ntohs(hp->nscount);
ar = ntohs(hp->arcount);
/* Skip QD entries, they're only used by dn_expand later on */
while (qd-- > 0) {
n = dn_skipname(cp, end);
if (n < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse DNS data received");
zval_dtor(return_value);
php_dns_free_handle(handle);
RETURN_FALSE;
}
cp += n + QFIXEDSZ;
}
/* YAY! Our real answers! */
while (an-- && cp && cp < end) {
zval *retval;
cp = php_parserr(cp, end, &answer, type_to_fetch, store_results, raw, &retval);
if (retval != NULL && store_results) {
add_next_index_zval(return_value, retval);
}
}
if (authns || addtl) {
/* List of Authoritative Name Servers
* Process when only requesting addtl so that we can skip through the section
*/
while (ns-- > 0 && cp && cp < end) {
zval *retval = NULL;
cp = php_parserr(cp, end, &answer, DNS_T_ANY, authns != NULL, raw, &retval);
if (retval != NULL) {
add_next_index_zval(authns, retval);
}
}
}
if (addtl) {
/* Additional records associated with authoritative name servers */
while (ar-- > 0 && cp && cp < end) {
zval *retval = NULL;
cp = php_parserr(cp, end, &answer, DNS_T_ANY, 1, raw, &retval);
if (retval != NULL) {
add_next_index_zval(addtl, retval);
}
}
}
php_dns_free_handle(handle);
}
}
}
/* }}} */
/* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight])
Get MX records corresponding to a given Internet host name */
PHP_FUNCTION(dns_get_mx)
{
char *hostname;
int hostname_len;
zval *mx_list, *weight_list = NULL;
int count, qdc;
u_short type, weight;
u_char ans[MAXPACKET];
char buf[MAXHOSTNAMELEN];
HEADER *hp;
u_char *cp, *end;
int i;
#if defined(HAVE_DNS_SEARCH)
struct sockaddr_storage from;
uint32_t fromsize = sizeof(from);
dns_handle_t handle;
#elif defined(HAVE_RES_NSEARCH)
struct __res_state state;
struct __res_state *handle = &state;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) {
return;
}
zval_dtor(mx_list);
array_init(mx_list);
if (weight_list) {
zval_dtor(weight_list);
array_init(weight_list);
}
#if defined(HAVE_DNS_SEARCH)
handle = dns_open(NULL);
if (handle == NULL) {
RETURN_FALSE;
}
#elif defined(HAVE_RES_NSEARCH)
memset(&state, 0, sizeof(state));
if (res_ninit(handle)) {
RETURN_FALSE;
}
#else
res_init();
#endif
i = php_dns_search(handle, hostname, C_IN, DNS_T_MX, (u_char *)&ans, sizeof(ans));
if (i < 0) {
RETURN_FALSE;
}
if (i > (int)sizeof(ans)) {
i = sizeof(ans);
}
hp = (HEADER *)&ans;
cp = (u_char *)&ans + HFIXEDSZ;
end = (u_char *)&ans +i;
for (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) {
if ((i = dn_skipname(cp, end)) < 0 ) {
php_dns_free_handle(handle);
RETURN_FALSE;
}
}
count = ntohs((unsigned short)hp->ancount);
while (--count >= 0 && cp < end) {
if ((i = dn_skipname(cp, end)) < 0 ) {
php_dns_free_handle(handle);
RETURN_FALSE;
}
cp += i;
GETSHORT(type, cp);
cp += INT16SZ + INT32SZ;
GETSHORT(i, cp);
if (type != DNS_T_MX) {
cp += i;
continue;
}
GETSHORT(weight, cp);
if ((i = dn_expand(ans, end, cp, buf, sizeof(buf)-1)) < 0) {
php_dns_free_handle(handle);
RETURN_FALSE;
}
cp += i;
add_next_index_string(mx_list, buf, 1);
if (weight_list) {
add_next_index_long(weight_list, weight);
}
}
php_dns_free_handle(handle);
RETURN_TRUE;
}
/* }}} */
#endif /* HAVE_FULL_DNS_FUNCS */
#endif /* !defined(PHP_WIN32) && (HAVE_DNS_SEARCH_FUNC && !(defined(__BEOS__) || defined(NETWARE))) */
#if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)
PHP_MINIT_FUNCTION(dns) {
REGISTER_LONG_CONSTANT("DNS_A", PHP_DNS_A, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_NS", PHP_DNS_NS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_CNAME", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_SOA", PHP_DNS_SOA, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_PTR", PHP_DNS_PTR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_HINFO", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_MX", PHP_DNS_MX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_TXT", PHP_DNS_TXT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_SRV", PHP_DNS_SRV, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_NAPTR", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_AAAA", PHP_DNS_AAAA, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_A6", PHP_DNS_A6, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_ANY", PHP_DNS_ANY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("DNS_ALL", PHP_DNS_ALL, CONST_CS | CONST_PERSISTENT);
return SUCCESS;
}
#endif /* HAVE_FULL_DNS_FUNCS */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2157_0 |
crossvul-cpp_data_good_3020_3 | /*
* Copyright (c) 2014-2015 Hisilicon Limited.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/io-64-nonatomic-hi-lo.h>
#include <linux/of_mdio.h>
#include "hns_dsaf_main.h"
#include "hns_dsaf_mac.h"
#include "hns_dsaf_xgmac.h"
#include "hns_dsaf_reg.h"
static const struct mac_stats_string g_xgmac_stats_string[] = {
{"xgmac_tx_bad_pkts_minto64", MAC_STATS_FIELD_OFF(tx_fragment_err)},
{"xgmac_tx_good_pkts_minto64", MAC_STATS_FIELD_OFF(tx_undersize)},
{"xgmac_tx_total_pkts_minto64", MAC_STATS_FIELD_OFF(tx_under_min_pkts)},
{"xgmac_tx_pkts_64", MAC_STATS_FIELD_OFF(tx_64bytes)},
{"xgmac_tx_pkts_65to127", MAC_STATS_FIELD_OFF(tx_65to127)},
{"xgmac_tx_pkts_128to255", MAC_STATS_FIELD_OFF(tx_128to255)},
{"xgmac_tx_pkts_256to511", MAC_STATS_FIELD_OFF(tx_256to511)},
{"xgmac_tx_pkts_512to1023", MAC_STATS_FIELD_OFF(tx_512to1023)},
{"xgmac_tx_pkts_1024to1518", MAC_STATS_FIELD_OFF(tx_1024to1518)},
{"xgmac_tx_pkts_1519tomax", MAC_STATS_FIELD_OFF(tx_1519tomax)},
{"xgmac_tx_good_pkts_1519tomax",
MAC_STATS_FIELD_OFF(tx_1519tomax_good)},
{"xgmac_tx_good_pkts_untralmax", MAC_STATS_FIELD_OFF(tx_oversize)},
{"xgmac_tx_bad_pkts_untralmax", MAC_STATS_FIELD_OFF(tx_jabber_err)},
{"xgmac_tx_good_pkts_all", MAC_STATS_FIELD_OFF(tx_good_pkts)},
{"xgmac_tx_good_byte_all", MAC_STATS_FIELD_OFF(tx_good_bytes)},
{"xgmac_tx_total_pkt", MAC_STATS_FIELD_OFF(tx_total_pkts)},
{"xgmac_tx_total_byt", MAC_STATS_FIELD_OFF(tx_total_bytes)},
{"xgmac_tx_uc_pkt", MAC_STATS_FIELD_OFF(tx_uc_pkts)},
{"xgmac_tx_mc_pkt", MAC_STATS_FIELD_OFF(tx_mc_pkts)},
{"xgmac_tx_bc_pkt", MAC_STATS_FIELD_OFF(tx_bc_pkts)},
{"xgmac_tx_pause_frame_num", MAC_STATS_FIELD_OFF(tx_pfc_tc0)},
{"xgmac_tx_pfc_per_1pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc1)},
{"xgmac_tx_pfc_per_2pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc2)},
{"xgmac_tx_pfc_per_3pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc3)},
{"xgmac_tx_pfc_per_4pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc4)},
{"xgmac_tx_pfc_per_5pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc5)},
{"xgmac_tx_pfc_per_6pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc6)},
{"xgmac_tx_pfc_per_7pause_framer", MAC_STATS_FIELD_OFF(tx_pfc_tc7)},
{"xgmac_tx_mac_ctrol_frame", MAC_STATS_FIELD_OFF(tx_ctrl)},
{"xgmac_tx_1731_pkts", MAC_STATS_FIELD_OFF(tx_1731_pkts)},
{"xgmac_tx_1588_pkts", MAC_STATS_FIELD_OFF(tx_1588_pkts)},
{"xgmac_rx_good_pkt_from_dsaf", MAC_STATS_FIELD_OFF(rx_good_from_sw)},
{"xgmac_rx_bad_pkt_from_dsaf", MAC_STATS_FIELD_OFF(rx_bad_from_sw)},
{"xgmac_tx_bad_pkt_64tomax", MAC_STATS_FIELD_OFF(tx_bad_pkts)},
{"xgmac_rx_bad_pkts_minto64", MAC_STATS_FIELD_OFF(rx_fragment_err)},
{"xgmac_rx_good_pkts_minto64", MAC_STATS_FIELD_OFF(rx_undersize)},
{"xgmac_rx_total_pkts_minto64", MAC_STATS_FIELD_OFF(rx_under_min)},
{"xgmac_rx_pkt_64", MAC_STATS_FIELD_OFF(rx_64bytes)},
{"xgmac_rx_pkt_65to127", MAC_STATS_FIELD_OFF(rx_65to127)},
{"xgmac_rx_pkt_128to255", MAC_STATS_FIELD_OFF(rx_128to255)},
{"xgmac_rx_pkt_256to511", MAC_STATS_FIELD_OFF(rx_256to511)},
{"xgmac_rx_pkt_512to1023", MAC_STATS_FIELD_OFF(rx_512to1023)},
{"xgmac_rx_pkt_1024to1518", MAC_STATS_FIELD_OFF(rx_1024to1518)},
{"xgmac_rx_pkt_1519tomax", MAC_STATS_FIELD_OFF(rx_1519tomax)},
{"xgmac_rx_good_pkt_1519tomax", MAC_STATS_FIELD_OFF(rx_1519tomax_good)},
{"xgmac_rx_good_pkt_untramax", MAC_STATS_FIELD_OFF(rx_oversize)},
{"xgmac_rx_bad_pkt_untramax", MAC_STATS_FIELD_OFF(rx_jabber_err)},
{"xgmac_rx_good_pkt", MAC_STATS_FIELD_OFF(rx_good_pkts)},
{"xgmac_rx_good_byt", MAC_STATS_FIELD_OFF(rx_good_bytes)},
{"xgmac_rx_pkt", MAC_STATS_FIELD_OFF(rx_total_pkts)},
{"xgmac_rx_byt", MAC_STATS_FIELD_OFF(rx_total_bytes)},
{"xgmac_rx_uc_pkt", MAC_STATS_FIELD_OFF(rx_uc_pkts)},
{"xgmac_rx_mc_pkt", MAC_STATS_FIELD_OFF(rx_mc_pkts)},
{"xgmac_rx_bc_pkt", MAC_STATS_FIELD_OFF(rx_bc_pkts)},
{"xgmac_rx_pause_frame_num", MAC_STATS_FIELD_OFF(rx_pfc_tc0)},
{"xgmac_rx_pfc_per_1pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc1)},
{"xgmac_rx_pfc_per_2pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc2)},
{"xgmac_rx_pfc_per_3pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc3)},
{"xgmac_rx_pfc_per_4pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc4)},
{"xgmac_rx_pfc_per_5pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc5)},
{"xgmac_rx_pfc_per_6pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc6)},
{"xgmac_rx_pfc_per_7pause_frame", MAC_STATS_FIELD_OFF(rx_pfc_tc7)},
{"xgmac_rx_mac_control", MAC_STATS_FIELD_OFF(rx_unknown_ctrl)},
{"xgmac_tx_good_pkt_todsaf", MAC_STATS_FIELD_OFF(tx_good_to_sw)},
{"xgmac_tx_bad_pkt_todsaf", MAC_STATS_FIELD_OFF(tx_bad_to_sw)},
{"xgmac_rx_1731_pkt", MAC_STATS_FIELD_OFF(rx_1731_pkts)},
{"xgmac_rx_symbol_err_pkt", MAC_STATS_FIELD_OFF(rx_symbol_err)},
{"xgmac_rx_fcs_pkt", MAC_STATS_FIELD_OFF(rx_fcs_err)}
};
/**
*hns_xgmac_tx_enable - xgmac port tx enable
*@drv: mac driver
*@value: value of enable
*/
static void hns_xgmac_tx_enable(struct mac_driver *drv, u32 value)
{
dsaf_set_dev_bit(drv, XGMAC_MAC_ENABLE_REG, XGMAC_ENABLE_TX_B, !!value);
}
/**
*hns_xgmac_rx_enable - xgmac port rx enable
*@drv: mac driver
*@value: value of enable
*/
static void hns_xgmac_rx_enable(struct mac_driver *drv, u32 value)
{
dsaf_set_dev_bit(drv, XGMAC_MAC_ENABLE_REG, XGMAC_ENABLE_RX_B, !!value);
}
/**
* hns_xgmac_tx_lf_rf_insert - insert lf rf control about xgmac
* @mac_drv: mac driver
* @mode: inserf rf or lf
*/
static void hns_xgmac_lf_rf_insert(struct mac_driver *mac_drv, u32 mode)
{
dsaf_set_dev_field(mac_drv, XGMAC_MAC_TX_LF_RF_CONTROL_REG,
XGMAC_LF_RF_INSERT_M, XGMAC_LF_RF_INSERT_S, mode);
}
/**
* hns_xgmac__lf_rf_control_init - initial the lf rf control register
* @mac_drv: mac driver
*/
static void hns_xgmac_lf_rf_control_init(struct mac_driver *mac_drv)
{
u32 val = 0;
dsaf_set_bit(val, XGMAC_UNIDIR_EN_B, 0);
dsaf_set_bit(val, XGMAC_RF_TX_EN_B, 1);
dsaf_set_field(val, XGMAC_LF_RF_INSERT_M, XGMAC_LF_RF_INSERT_S, 0);
dsaf_write_reg(mac_drv, XGMAC_MAC_TX_LF_RF_CONTROL_REG, val);
}
/**
*hns_xgmac_enable - enable xgmac port
*@drv: mac driver
*@mode: mode of mac port
*/
static void hns_xgmac_enable(void *mac_drv, enum mac_commom_mode mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
hns_xgmac_lf_rf_insert(drv, HNS_XGMAC_NO_LF_RF_INSERT);
/*enable XGE rX/tX */
if (mode == MAC_COMM_MODE_TX) {
hns_xgmac_tx_enable(drv, 1);
} else if (mode == MAC_COMM_MODE_RX) {
hns_xgmac_rx_enable(drv, 1);
} else if (mode == MAC_COMM_MODE_RX_AND_TX) {
hns_xgmac_tx_enable(drv, 1);
hns_xgmac_rx_enable(drv, 1);
} else {
dev_err(drv->dev, "error mac mode:%d\n", mode);
}
}
/**
*hns_xgmac_disable - disable xgmac port
*@mac_drv: mac driver
*@mode: mode of mac port
*/
static void hns_xgmac_disable(void *mac_drv, enum mac_commom_mode mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
if (mode == MAC_COMM_MODE_TX) {
hns_xgmac_tx_enable(drv, 0);
} else if (mode == MAC_COMM_MODE_RX) {
hns_xgmac_rx_enable(drv, 0);
} else if (mode == MAC_COMM_MODE_RX_AND_TX) {
hns_xgmac_tx_enable(drv, 0);
hns_xgmac_rx_enable(drv, 0);
}
hns_xgmac_lf_rf_insert(drv, HNS_XGMAC_LF_INSERT);
}
/**
*hns_xgmac_pma_fec_enable - xgmac PMA FEC enable
*@drv: mac driver
*@tx_value: tx value
*@rx_value: rx value
*return status
*/
static void hns_xgmac_pma_fec_enable(struct mac_driver *drv, u32 tx_value,
u32 rx_value)
{
u32 origin = dsaf_read_dev(drv, XGMAC_PMA_FEC_CONTROL_REG);
dsaf_set_bit(origin, XGMAC_PMA_FEC_CTL_TX_B, !!tx_value);
dsaf_set_bit(origin, XGMAC_PMA_FEC_CTL_RX_B, !!rx_value);
dsaf_write_dev(drv, XGMAC_PMA_FEC_CONTROL_REG, origin);
}
/* clr exc irq for xge*/
static void hns_xgmac_exc_irq_en(struct mac_driver *drv, u32 en)
{
u32 clr_vlue = 0xfffffffful;
u32 msk_vlue = en ? 0xfffffffful : 0; /*1 is en, 0 is dis*/
dsaf_write_dev(drv, XGMAC_INT_STATUS_REG, clr_vlue);
dsaf_write_dev(drv, XGMAC_INT_ENABLE_REG, msk_vlue);
}
/**
*hns_xgmac_init - initialize XGE
*@mac_drv: mac driver
*/
static void hns_xgmac_init(void *mac_drv)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct dsaf_device *dsaf_dev
= (struct dsaf_device *)dev_get_drvdata(drv->dev);
u32 port = drv->mac_id;
dsaf_dev->misc_op->xge_srst(dsaf_dev, port, 0);
mdelay(100);
dsaf_dev->misc_op->xge_srst(dsaf_dev, port, 1);
mdelay(100);
hns_xgmac_lf_rf_control_init(drv);
hns_xgmac_exc_irq_en(drv, 0);
hns_xgmac_pma_fec_enable(drv, 0x0, 0x0);
hns_xgmac_disable(mac_drv, MAC_COMM_MODE_RX_AND_TX);
}
/**
*hns_xgmac_config_pad_and_crc - set xgmac pad and crc enable the same time
*@mac_drv: mac driver
*@newval:enable of pad and crc
*/
static void hns_xgmac_config_pad_and_crc(void *mac_drv, u8 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 origin = dsaf_read_dev(drv, XGMAC_MAC_CONTROL_REG);
dsaf_set_bit(origin, XGMAC_CTL_TX_PAD_B, !!newval);
dsaf_set_bit(origin, XGMAC_CTL_TX_FCS_B, !!newval);
dsaf_set_bit(origin, XGMAC_CTL_RX_FCS_B, !!newval);
dsaf_write_dev(drv, XGMAC_MAC_CONTROL_REG, origin);
}
/**
*hns_xgmac_pausefrm_cfg - set pause param about xgmac
*@mac_drv: mac driver
*@newval:enable of pad and crc
*/
static void hns_xgmac_pausefrm_cfg(void *mac_drv, u32 rx_en, u32 tx_en)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 origin = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_CTRL_REG);
dsaf_set_bit(origin, XGMAC_PAUSE_CTL_TX_B, !!tx_en);
dsaf_set_bit(origin, XGMAC_PAUSE_CTL_RX_B, !!rx_en);
dsaf_write_dev(drv, XGMAC_MAC_PAUSE_CTRL_REG, origin);
}
static void hns_xgmac_set_pausefrm_mac_addr(void *mac_drv, char *mac_addr)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 high_val = mac_addr[1] | (mac_addr[0] << 8);
u32 low_val = mac_addr[5] | (mac_addr[4] << 8)
| (mac_addr[3] << 16) | (mac_addr[2] << 24);
dsaf_write_dev(drv, XGMAC_MAC_PAUSE_LOCAL_MAC_L_REG, low_val);
dsaf_write_dev(drv, XGMAC_MAC_PAUSE_LOCAL_MAC_H_REG, high_val);
}
/**
*hns_xgmac_set_rx_ignore_pause_frames - set rx pause param about xgmac
*@mac_drv: mac driver
*@enable:enable rx pause param
*/
static void hns_xgmac_set_rx_ignore_pause_frames(void *mac_drv, u32 enable)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_bit(drv, XGMAC_MAC_PAUSE_CTRL_REG,
XGMAC_PAUSE_CTL_RX_B, !!enable);
}
/**
*hns_xgmac_set_tx_auto_pause_frames - set tx pause param about xgmac
*@mac_drv: mac driver
*@enable:enable tx pause param
*/
static void hns_xgmac_set_tx_auto_pause_frames(void *mac_drv, u16 enable)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_set_dev_bit(drv, XGMAC_MAC_PAUSE_CTRL_REG,
XGMAC_PAUSE_CTL_TX_B, !!enable);
/*if enable is not zero ,set tx pause time */
if (enable)
dsaf_write_dev(drv, XGMAC_MAC_PAUSE_TIME_REG, enable);
}
/**
*hns_xgmac_config_max_frame_length - set xgmac max frame length
*@mac_drv: mac driver
*@newval:xgmac max frame length
*/
static void hns_xgmac_config_max_frame_length(void *mac_drv, u16 newval)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
dsaf_write_dev(drv, XGMAC_MAC_MAX_PKT_SIZE_REG, newval);
}
void hns_xgmac_update_stats(void *mac_drv)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct mac_hw_stats *hw_stats = &drv->mac_cb->hw_stats;
/* TX */
hw_stats->tx_fragment_err
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_FRAGMENT);
hw_stats->tx_undersize
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_UNDERSIZE);
hw_stats->tx_under_min_pkts
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_UNDERMIN);
hw_stats->tx_64bytes = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_64OCTETS);
hw_stats->tx_65to127
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_65TO127OCTETS);
hw_stats->tx_128to255
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_128TO255OCTETS);
hw_stats->tx_256to511
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_256TO511OCTETS);
hw_stats->tx_512to1023
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_512TO1023OCTETS);
hw_stats->tx_1024to1518
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_1024TO1518OCTETS);
hw_stats->tx_1519tomax
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_1519TOMAXOCTETS);
hw_stats->tx_1519tomax_good
= hns_mac_reg_read64(drv, XGMAC_TX_PKTS_1519TOMAXOCTETSOK);
hw_stats->tx_oversize = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_OVERSIZE);
hw_stats->tx_jabber_err = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_JABBER);
hw_stats->tx_good_pkts = hns_mac_reg_read64(drv, XGMAC_TX_GOODPKTS);
hw_stats->tx_good_bytes = hns_mac_reg_read64(drv, XGMAC_TX_GOODOCTETS);
hw_stats->tx_total_pkts = hns_mac_reg_read64(drv, XGMAC_TX_TOTAL_PKTS);
hw_stats->tx_total_bytes
= hns_mac_reg_read64(drv, XGMAC_TX_TOTALOCTETS);
hw_stats->tx_uc_pkts = hns_mac_reg_read64(drv, XGMAC_TX_UNICASTPKTS);
hw_stats->tx_mc_pkts = hns_mac_reg_read64(drv, XGMAC_TX_MULTICASTPKTS);
hw_stats->tx_bc_pkts = hns_mac_reg_read64(drv, XGMAC_TX_BROADCASTPKTS);
hw_stats->tx_pfc_tc0 = hns_mac_reg_read64(drv, XGMAC_TX_PRI0PAUSEPKTS);
hw_stats->tx_pfc_tc1 = hns_mac_reg_read64(drv, XGMAC_TX_PRI1PAUSEPKTS);
hw_stats->tx_pfc_tc2 = hns_mac_reg_read64(drv, XGMAC_TX_PRI2PAUSEPKTS);
hw_stats->tx_pfc_tc3 = hns_mac_reg_read64(drv, XGMAC_TX_PRI3PAUSEPKTS);
hw_stats->tx_pfc_tc4 = hns_mac_reg_read64(drv, XGMAC_TX_PRI4PAUSEPKTS);
hw_stats->tx_pfc_tc5 = hns_mac_reg_read64(drv, XGMAC_TX_PRI5PAUSEPKTS);
hw_stats->tx_pfc_tc6 = hns_mac_reg_read64(drv, XGMAC_TX_PRI6PAUSEPKTS);
hw_stats->tx_pfc_tc7 = hns_mac_reg_read64(drv, XGMAC_TX_PRI7PAUSEPKTS);
hw_stats->tx_ctrl = hns_mac_reg_read64(drv, XGMAC_TX_MACCTRLPKTS);
hw_stats->tx_1731_pkts = hns_mac_reg_read64(drv, XGMAC_TX_1731PKTS);
hw_stats->tx_1588_pkts = hns_mac_reg_read64(drv, XGMAC_TX_1588PKTS);
hw_stats->rx_good_from_sw
= hns_mac_reg_read64(drv, XGMAC_RX_FROMAPPGOODPKTS);
hw_stats->rx_bad_from_sw
= hns_mac_reg_read64(drv, XGMAC_RX_FROMAPPBADPKTS);
hw_stats->tx_bad_pkts = hns_mac_reg_read64(drv, XGMAC_TX_ERRALLPKTS);
/* RX */
hw_stats->rx_fragment_err
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_FRAGMENT);
hw_stats->rx_undersize
= hns_mac_reg_read64(drv, XGMAC_RX_PKTSUNDERSIZE);
hw_stats->rx_under_min
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_UNDERMIN);
hw_stats->rx_64bytes = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_64OCTETS);
hw_stats->rx_65to127
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_65TO127OCTETS);
hw_stats->rx_128to255
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_128TO255OCTETS);
hw_stats->rx_256to511
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_256TO511OCTETS);
hw_stats->rx_512to1023
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_512TO1023OCTETS);
hw_stats->rx_1024to1518
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_1024TO1518OCTETS);
hw_stats->rx_1519tomax
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_1519TOMAXOCTETS);
hw_stats->rx_1519tomax_good
= hns_mac_reg_read64(drv, XGMAC_RX_PKTS_1519TOMAXOCTETSOK);
hw_stats->rx_oversize = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_OVERSIZE);
hw_stats->rx_jabber_err = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_JABBER);
hw_stats->rx_good_pkts = hns_mac_reg_read64(drv, XGMAC_RX_GOODPKTS);
hw_stats->rx_good_bytes = hns_mac_reg_read64(drv, XGMAC_RX_GOODOCTETS);
hw_stats->rx_total_pkts = hns_mac_reg_read64(drv, XGMAC_RX_TOTAL_PKTS);
hw_stats->rx_total_bytes
= hns_mac_reg_read64(drv, XGMAC_RX_TOTALOCTETS);
hw_stats->rx_uc_pkts = hns_mac_reg_read64(drv, XGMAC_RX_UNICASTPKTS);
hw_stats->rx_mc_pkts = hns_mac_reg_read64(drv, XGMAC_RX_MULTICASTPKTS);
hw_stats->rx_bc_pkts = hns_mac_reg_read64(drv, XGMAC_RX_BROADCASTPKTS);
hw_stats->rx_pfc_tc0 = hns_mac_reg_read64(drv, XGMAC_RX_PRI0PAUSEPKTS);
hw_stats->rx_pfc_tc1 = hns_mac_reg_read64(drv, XGMAC_RX_PRI1PAUSEPKTS);
hw_stats->rx_pfc_tc2 = hns_mac_reg_read64(drv, XGMAC_RX_PRI2PAUSEPKTS);
hw_stats->rx_pfc_tc3 = hns_mac_reg_read64(drv, XGMAC_RX_PRI3PAUSEPKTS);
hw_stats->rx_pfc_tc4 = hns_mac_reg_read64(drv, XGMAC_RX_PRI4PAUSEPKTS);
hw_stats->rx_pfc_tc5 = hns_mac_reg_read64(drv, XGMAC_RX_PRI5PAUSEPKTS);
hw_stats->rx_pfc_tc6 = hns_mac_reg_read64(drv, XGMAC_RX_PRI6PAUSEPKTS);
hw_stats->rx_pfc_tc7 = hns_mac_reg_read64(drv, XGMAC_RX_PRI7PAUSEPKTS);
hw_stats->rx_unknown_ctrl
= hns_mac_reg_read64(drv, XGMAC_RX_MACCTRLPKTS);
hw_stats->tx_good_to_sw
= hns_mac_reg_read64(drv, XGMAC_TX_SENDAPPGOODPKTS);
hw_stats->tx_bad_to_sw
= hns_mac_reg_read64(drv, XGMAC_TX_SENDAPPBADPKTS);
hw_stats->rx_1731_pkts = hns_mac_reg_read64(drv, XGMAC_RX_1731PKTS);
hw_stats->rx_symbol_err
= hns_mac_reg_read64(drv, XGMAC_RX_SYMBOLERRPKTS);
hw_stats->rx_fcs_err = hns_mac_reg_read64(drv, XGMAC_RX_FCSERRPKTS);
}
/**
*hns_xgmac_free - free xgmac driver
*@mac_drv: mac driver
*/
static void hns_xgmac_free(void *mac_drv)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct dsaf_device *dsaf_dev
= (struct dsaf_device *)dev_get_drvdata(drv->dev);
u32 mac_id = drv->mac_id;
dsaf_dev->misc_op->xge_srst(dsaf_dev, mac_id, 0);
}
/**
*hns_xgmac_get_info - get xgmac information
*@mac_drv: mac driver
*@mac_info:mac information
*/
static void hns_xgmac_get_info(void *mac_drv, struct mac_info *mac_info)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 pause_time, pause_ctrl, port_mode, ctrl_val;
ctrl_val = dsaf_read_dev(drv, XGMAC_MAC_CONTROL_REG);
mac_info->pad_and_crc_en = dsaf_get_bit(ctrl_val, XGMAC_CTL_TX_PAD_B);
mac_info->auto_neg = 0;
pause_time = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_TIME_REG);
mac_info->tx_pause_time = pause_time;
port_mode = dsaf_read_dev(drv, XGMAC_PORT_MODE_REG);
mac_info->port_en = dsaf_get_field(port_mode, XGMAC_PORT_MODE_TX_M,
XGMAC_PORT_MODE_TX_S) &&
dsaf_get_field(port_mode, XGMAC_PORT_MODE_RX_M,
XGMAC_PORT_MODE_RX_S);
mac_info->duplex = 1;
mac_info->speed = MAC_SPEED_10000;
pause_ctrl = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_CTRL_REG);
mac_info->rx_pause_en = dsaf_get_bit(pause_ctrl, XGMAC_PAUSE_CTL_RX_B);
mac_info->tx_pause_en = dsaf_get_bit(pause_ctrl, XGMAC_PAUSE_CTL_TX_B);
}
/**
*hns_xgmac_get_pausefrm_cfg - get xgmac pause param
*@mac_drv: mac driver
*@rx_en:xgmac rx pause enable
*@tx_en:xgmac tx pause enable
*/
static void hns_xgmac_get_pausefrm_cfg(void *mac_drv, u32 *rx_en, u32 *tx_en)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 pause_ctrl;
pause_ctrl = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_CTRL_REG);
*rx_en = dsaf_get_bit(pause_ctrl, XGMAC_PAUSE_CTL_RX_B);
*tx_en = dsaf_get_bit(pause_ctrl, XGMAC_PAUSE_CTL_TX_B);
}
/**
*hns_xgmac_get_link_status - get xgmac link status
*@mac_drv: mac driver
*@link_stat: xgmac link stat
*/
static void hns_xgmac_get_link_status(void *mac_drv, u32 *link_stat)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
*link_stat = dsaf_read_dev(drv, XGMAC_LINK_STATUS_REG);
}
/**
*hns_xgmac_get_regs - dump xgmac regs
*@mac_drv: mac driver
*@cmd:ethtool cmd
*@data:data for value of regs
*/
static void hns_xgmac_get_regs(void *mac_drv, void *data)
{
u32 i = 0;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
u32 *regs = data;
u64 qtmp;
/* base config registers */
regs[0] = dsaf_read_dev(drv, XGMAC_INT_STATUS_REG);
regs[1] = dsaf_read_dev(drv, XGMAC_INT_ENABLE_REG);
regs[2] = dsaf_read_dev(drv, XGMAC_INT_SET_REG);
regs[3] = dsaf_read_dev(drv, XGMAC_IERR_U_INFO_REG);
regs[4] = dsaf_read_dev(drv, XGMAC_OVF_INFO_REG);
regs[5] = dsaf_read_dev(drv, XGMAC_OVF_CNT_REG);
regs[6] = dsaf_read_dev(drv, XGMAC_PORT_MODE_REG);
regs[7] = dsaf_read_dev(drv, XGMAC_CLK_ENABLE_REG);
regs[8] = dsaf_read_dev(drv, XGMAC_RESET_REG);
regs[9] = dsaf_read_dev(drv, XGMAC_LINK_CONTROL_REG);
regs[10] = dsaf_read_dev(drv, XGMAC_LINK_STATUS_REG);
regs[11] = dsaf_read_dev(drv, XGMAC_SPARE_REG);
regs[12] = dsaf_read_dev(drv, XGMAC_SPARE_CNT_REG);
regs[13] = dsaf_read_dev(drv, XGMAC_MAC_ENABLE_REG);
regs[14] = dsaf_read_dev(drv, XGMAC_MAC_CONTROL_REG);
regs[15] = dsaf_read_dev(drv, XGMAC_MAC_IPG_REG);
regs[16] = dsaf_read_dev(drv, XGMAC_MAC_MSG_CRC_EN_REG);
regs[17] = dsaf_read_dev(drv, XGMAC_MAC_MSG_IMG_REG);
regs[18] = dsaf_read_dev(drv, XGMAC_MAC_MSG_FC_CFG_REG);
regs[19] = dsaf_read_dev(drv, XGMAC_MAC_MSG_TC_CFG_REG);
regs[20] = dsaf_read_dev(drv, XGMAC_MAC_PAD_SIZE_REG);
regs[21] = dsaf_read_dev(drv, XGMAC_MAC_MIN_PKT_SIZE_REG);
regs[22] = dsaf_read_dev(drv, XGMAC_MAC_MAX_PKT_SIZE_REG);
regs[23] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_CTRL_REG);
regs[24] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_TIME_REG);
regs[25] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_GAP_REG);
regs[26] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_LOCAL_MAC_H_REG);
regs[27] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_LOCAL_MAC_L_REG);
regs[28] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_PEER_MAC_H_REG);
regs[29] = dsaf_read_dev(drv, XGMAC_MAC_PAUSE_PEER_MAC_L_REG);
regs[30] = dsaf_read_dev(drv, XGMAC_MAC_PFC_PRI_EN_REG);
regs[31] = dsaf_read_dev(drv, XGMAC_MAC_1588_CTRL_REG);
regs[32] = dsaf_read_dev(drv, XGMAC_MAC_1588_TX_PORT_DLY_REG);
regs[33] = dsaf_read_dev(drv, XGMAC_MAC_1588_RX_PORT_DLY_REG);
regs[34] = dsaf_read_dev(drv, XGMAC_MAC_1588_ASYM_DLY_REG);
regs[35] = dsaf_read_dev(drv, XGMAC_MAC_1588_ADJUST_CFG_REG);
regs[36] = dsaf_read_dev(drv, XGMAC_MAC_Y1731_ETH_TYPE_REG);
regs[37] = dsaf_read_dev(drv, XGMAC_MAC_MIB_CONTROL_REG);
regs[38] = dsaf_read_dev(drv, XGMAC_MAC_WAN_RATE_ADJUST_REG);
regs[39] = dsaf_read_dev(drv, XGMAC_MAC_TX_ERR_MARK_REG);
regs[40] = dsaf_read_dev(drv, XGMAC_MAC_TX_LF_RF_CONTROL_REG);
regs[41] = dsaf_read_dev(drv, XGMAC_MAC_RX_LF_RF_STATUS_REG);
regs[42] = dsaf_read_dev(drv, XGMAC_MAC_TX_RUNT_PKT_CNT_REG);
regs[43] = dsaf_read_dev(drv, XGMAC_MAC_RX_RUNT_PKT_CNT_REG);
regs[44] = dsaf_read_dev(drv, XGMAC_MAC_RX_PREAM_ERR_PKT_CNT_REG);
regs[45] = dsaf_read_dev(drv, XGMAC_MAC_TX_LF_RF_TERM_PKT_CNT_REG);
regs[46] = dsaf_read_dev(drv, XGMAC_MAC_TX_SN_MISMATCH_PKT_CNT_REG);
regs[47] = dsaf_read_dev(drv, XGMAC_MAC_RX_ERR_MSG_CNT_REG);
regs[48] = dsaf_read_dev(drv, XGMAC_MAC_RX_ERR_EFD_CNT_REG);
regs[49] = dsaf_read_dev(drv, XGMAC_MAC_ERR_INFO_REG);
regs[50] = dsaf_read_dev(drv, XGMAC_MAC_DBG_INFO_REG);
regs[51] = dsaf_read_dev(drv, XGMAC_PCS_BASER_SYNC_THD_REG);
regs[52] = dsaf_read_dev(drv, XGMAC_PCS_STATUS1_REG);
regs[53] = dsaf_read_dev(drv, XGMAC_PCS_BASER_STATUS1_REG);
regs[54] = dsaf_read_dev(drv, XGMAC_PCS_BASER_STATUS2_REG);
regs[55] = dsaf_read_dev(drv, XGMAC_PCS_BASER_SEEDA_0_REG);
regs[56] = dsaf_read_dev(drv, XGMAC_PCS_BASER_SEEDA_1_REG);
regs[57] = dsaf_read_dev(drv, XGMAC_PCS_BASER_SEEDB_0_REG);
regs[58] = dsaf_read_dev(drv, XGMAC_PCS_BASER_SEEDB_1_REG);
regs[59] = dsaf_read_dev(drv, XGMAC_PCS_BASER_TEST_CONTROL_REG);
regs[60] = dsaf_read_dev(drv, XGMAC_PCS_BASER_TEST_ERR_CNT_REG);
regs[61] = dsaf_read_dev(drv, XGMAC_PCS_DBG_INFO_REG);
regs[62] = dsaf_read_dev(drv, XGMAC_PCS_DBG_INFO1_REG);
regs[63] = dsaf_read_dev(drv, XGMAC_PCS_DBG_INFO2_REG);
regs[64] = dsaf_read_dev(drv, XGMAC_PCS_DBG_INFO3_REG);
regs[65] = dsaf_read_dev(drv, XGMAC_PMA_ENABLE_REG);
regs[66] = dsaf_read_dev(drv, XGMAC_PMA_CONTROL_REG);
regs[67] = dsaf_read_dev(drv, XGMAC_PMA_SIGNAL_STATUS_REG);
regs[68] = dsaf_read_dev(drv, XGMAC_PMA_DBG_INFO_REG);
regs[69] = dsaf_read_dev(drv, XGMAC_PMA_FEC_ABILITY_REG);
regs[70] = dsaf_read_dev(drv, XGMAC_PMA_FEC_CONTROL_REG);
regs[71] = dsaf_read_dev(drv, XGMAC_PMA_FEC_CORR_BLOCK_CNT__REG);
regs[72] = dsaf_read_dev(drv, XGMAC_PMA_FEC_UNCORR_BLOCK_CNT__REG);
/* status registers */
#define hns_xgmac_cpy_q(p, q) \
do {\
*(p) = (u32)(q);\
*((p) + 1) = (u32)((q) >> 32);\
} while (0)
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_FRAGMENT);
hns_xgmac_cpy_q(®s[73], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_UNDERSIZE);
hns_xgmac_cpy_q(®s[75], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_UNDERMIN);
hns_xgmac_cpy_q(®s[77], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_64OCTETS);
hns_xgmac_cpy_q(®s[79], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_65TO127OCTETS);
hns_xgmac_cpy_q(®s[81], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_128TO255OCTETS);
hns_xgmac_cpy_q(®s[83], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_256TO511OCTETS);
hns_xgmac_cpy_q(®s[85], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_512TO1023OCTETS);
hns_xgmac_cpy_q(®s[87], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_1024TO1518OCTETS);
hns_xgmac_cpy_q(®s[89], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_1519TOMAXOCTETS);
hns_xgmac_cpy_q(®s[91], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_1519TOMAXOCTETSOK);
hns_xgmac_cpy_q(®s[93], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_OVERSIZE);
hns_xgmac_cpy_q(®s[95], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PKTS_JABBER);
hns_xgmac_cpy_q(®s[97], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_GOODPKTS);
hns_xgmac_cpy_q(®s[99], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_GOODOCTETS);
hns_xgmac_cpy_q(®s[101], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_TOTAL_PKTS);
hns_xgmac_cpy_q(®s[103], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_TOTALOCTETS);
hns_xgmac_cpy_q(®s[105], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_UNICASTPKTS);
hns_xgmac_cpy_q(®s[107], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_MULTICASTPKTS);
hns_xgmac_cpy_q(®s[109], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_BROADCASTPKTS);
hns_xgmac_cpy_q(®s[111], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI0PAUSEPKTS);
hns_xgmac_cpy_q(®s[113], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI1PAUSEPKTS);
hns_xgmac_cpy_q(®s[115], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI2PAUSEPKTS);
hns_xgmac_cpy_q(®s[117], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI3PAUSEPKTS);
hns_xgmac_cpy_q(®s[119], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI4PAUSEPKTS);
hns_xgmac_cpy_q(®s[121], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI5PAUSEPKTS);
hns_xgmac_cpy_q(®s[123], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI6PAUSEPKTS);
hns_xgmac_cpy_q(®s[125], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_PRI7PAUSEPKTS);
hns_xgmac_cpy_q(®s[127], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_MACCTRLPKTS);
hns_xgmac_cpy_q(®s[129], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_1731PKTS);
hns_xgmac_cpy_q(®s[131], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_1588PKTS);
hns_xgmac_cpy_q(®s[133], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_FROMAPPGOODPKTS);
hns_xgmac_cpy_q(®s[135], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_FROMAPPBADPKTS);
hns_xgmac_cpy_q(®s[137], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_ERRALLPKTS);
hns_xgmac_cpy_q(®s[139], qtmp);
/* RX */
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_FRAGMENT);
hns_xgmac_cpy_q(®s[141], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTSUNDERSIZE);
hns_xgmac_cpy_q(®s[143], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_UNDERMIN);
hns_xgmac_cpy_q(®s[145], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_64OCTETS);
hns_xgmac_cpy_q(®s[147], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_65TO127OCTETS);
hns_xgmac_cpy_q(®s[149], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_128TO255OCTETS);
hns_xgmac_cpy_q(®s[151], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_256TO511OCTETS);
hns_xgmac_cpy_q(®s[153], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_512TO1023OCTETS);
hns_xgmac_cpy_q(®s[155], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_1024TO1518OCTETS);
hns_xgmac_cpy_q(®s[157], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_1519TOMAXOCTETS);
hns_xgmac_cpy_q(®s[159], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_1519TOMAXOCTETSOK);
hns_xgmac_cpy_q(®s[161], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_OVERSIZE);
hns_xgmac_cpy_q(®s[163], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PKTS_JABBER);
hns_xgmac_cpy_q(®s[165], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_GOODPKTS);
hns_xgmac_cpy_q(®s[167], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_GOODOCTETS);
hns_xgmac_cpy_q(®s[169], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_TOTAL_PKTS);
hns_xgmac_cpy_q(®s[171], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_TOTALOCTETS);
hns_xgmac_cpy_q(®s[173], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_UNICASTPKTS);
hns_xgmac_cpy_q(®s[175], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_MULTICASTPKTS);
hns_xgmac_cpy_q(®s[177], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_BROADCASTPKTS);
hns_xgmac_cpy_q(®s[179], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI0PAUSEPKTS);
hns_xgmac_cpy_q(®s[181], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI1PAUSEPKTS);
hns_xgmac_cpy_q(®s[183], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI2PAUSEPKTS);
hns_xgmac_cpy_q(®s[185], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI3PAUSEPKTS);
hns_xgmac_cpy_q(®s[187], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI4PAUSEPKTS);
hns_xgmac_cpy_q(®s[189], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI5PAUSEPKTS);
hns_xgmac_cpy_q(®s[191], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI6PAUSEPKTS);
hns_xgmac_cpy_q(®s[193], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_PRI7PAUSEPKTS);
hns_xgmac_cpy_q(®s[195], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_MACCTRLPKTS);
hns_xgmac_cpy_q(®s[197], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_SENDAPPGOODPKTS);
hns_xgmac_cpy_q(®s[199], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_TX_SENDAPPBADPKTS);
hns_xgmac_cpy_q(®s[201], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_1731PKTS);
hns_xgmac_cpy_q(®s[203], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_SYMBOLERRPKTS);
hns_xgmac_cpy_q(®s[205], qtmp);
qtmp = hns_mac_reg_read64(drv, XGMAC_RX_FCSERRPKTS);
hns_xgmac_cpy_q(®s[207], qtmp);
/* mark end of mac regs */
for (i = 208; i < 214; i++)
regs[i] = 0xaaaaaaaa;
}
/**
*hns_xgmac_get_stats - get xgmac statistic
*@mac_drv: mac driver
*@data:data for value of stats regs
*/
static void hns_xgmac_get_stats(void *mac_drv, u64 *data)
{
u32 i;
u64 *buf = data;
struct mac_driver *drv = (struct mac_driver *)mac_drv;
struct mac_hw_stats *hw_stats = NULL;
hw_stats = &drv->mac_cb->hw_stats;
for (i = 0; i < ARRAY_SIZE(g_xgmac_stats_string); i++) {
buf[i] = DSAF_STATS_READ(hw_stats,
g_xgmac_stats_string[i].offset);
}
}
/**
*hns_xgmac_get_strings - get xgmac strings name
*@stringset: type of values in data
*@data:data for value of string name
*/
static void hns_xgmac_get_strings(u32 stringset, u8 *data)
{
char *buff = (char *)data;
u32 i;
if (stringset != ETH_SS_STATS)
return;
for (i = 0; i < ARRAY_SIZE(g_xgmac_stats_string); i++) {
snprintf(buff, ETH_GSTRING_LEN, g_xgmac_stats_string[i].desc);
buff = buff + ETH_GSTRING_LEN;
}
}
/**
*hns_xgmac_get_sset_count - get xgmac string set count
*@stringset: type of values in data
*return xgmac string set count
*/
static int hns_xgmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS)
return ARRAY_SIZE(g_xgmac_stats_string);
return 0;
}
/**
*hns_xgmac_get_regs_count - get xgmac regs count
*return xgmac regs count
*/
static int hns_xgmac_get_regs_count(void)
{
return HNS_XGMAC_DUMP_NUM;
}
void *hns_xgmac_config(struct hns_mac_cb *mac_cb, struct mac_params *mac_param)
{
struct mac_driver *mac_drv;
mac_drv = devm_kzalloc(mac_cb->dev, sizeof(*mac_drv), GFP_KERNEL);
if (!mac_drv)
return NULL;
mac_drv->mac_init = hns_xgmac_init;
mac_drv->mac_enable = hns_xgmac_enable;
mac_drv->mac_disable = hns_xgmac_disable;
mac_drv->mac_id = mac_param->mac_id;
mac_drv->mac_mode = mac_param->mac_mode;
mac_drv->io_base = mac_param->vaddr;
mac_drv->dev = mac_param->dev;
mac_drv->mac_cb = mac_cb;
mac_drv->set_mac_addr = hns_xgmac_set_pausefrm_mac_addr;
mac_drv->set_an_mode = NULL;
mac_drv->config_loopback = NULL;
mac_drv->config_pad_and_crc = hns_xgmac_config_pad_and_crc;
mac_drv->config_half_duplex = NULL;
mac_drv->set_rx_ignore_pause_frames =
hns_xgmac_set_rx_ignore_pause_frames;
mac_drv->mac_free = hns_xgmac_free;
mac_drv->adjust_link = NULL;
mac_drv->set_tx_auto_pause_frames = hns_xgmac_set_tx_auto_pause_frames;
mac_drv->config_max_frame_length = hns_xgmac_config_max_frame_length;
mac_drv->mac_pausefrm_cfg = hns_xgmac_pausefrm_cfg;
mac_drv->autoneg_stat = NULL;
mac_drv->get_info = hns_xgmac_get_info;
mac_drv->get_pause_enable = hns_xgmac_get_pausefrm_cfg;
mac_drv->get_link_status = hns_xgmac_get_link_status;
mac_drv->get_regs = hns_xgmac_get_regs;
mac_drv->get_ethtool_stats = hns_xgmac_get_stats;
mac_drv->get_sset_count = hns_xgmac_get_sset_count;
mac_drv->get_regs_count = hns_xgmac_get_regs_count;
mac_drv->get_strings = hns_xgmac_get_strings;
mac_drv->update_stats = hns_xgmac_update_stats;
return (void *)mac_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3020_3 |
crossvul-cpp_data_bad_5756_0 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/types.h>
#include <asm/uaccess.h>
/*
* If read and write race, the read will still atomically read a valid
* value.
*/
int uml_exitcode = 0;
static int exitcode_proc_show(struct seq_file *m, void *v)
{
int val;
/*
* Save uml_exitcode in a local so that we don't need to guarantee
* that sprintf accesses it atomically.
*/
val = uml_exitcode;
seq_printf(m, "%d\n", val);
return 0;
}
static int exitcode_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, exitcode_proc_show, NULL);
}
static ssize_t exitcode_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char *end, buf[sizeof("nnnnn\0")];
int tmp;
if (copy_from_user(buf, buffer, count))
return -EFAULT;
tmp = simple_strtol(buf, &end, 0);
if ((*end != '\0') && !isspace(*end))
return -EINVAL;
uml_exitcode = tmp;
return count;
}
static const struct file_operations exitcode_proc_fops = {
.owner = THIS_MODULE,
.open = exitcode_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = exitcode_proc_write,
};
static int make_proc_exitcode(void)
{
struct proc_dir_entry *ent;
ent = proc_create("exitcode", 0600, NULL, &exitcode_proc_fops);
if (ent == NULL) {
printk(KERN_WARNING "make_proc_exitcode : Failed to register "
"/proc/exitcode\n");
return 0;
}
return 0;
}
__initcall(make_proc_exitcode);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5756_0 |
crossvul-cpp_data_bad_5589_1 | /*
* linux/kernel/printk.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Modified to make sys_syslog() more flexible: added commands to
* return the last 4k of kernel messages, regardless of whether
* they've been read or not. Added option to suppress kernel printk's
* to the console. Added hook for sending the console messages
* elsewhere, in preparation for a serial line console (someday).
* Ted Ts'o, 2/11/93.
* Modified for sysctl support, 1/8/97, Chris Horn.
* Fixed SMP synchronization, 08/08/99, Manfred Spraul
* manfred@colorfullife.com
* Rewrote bits to get rid of console_lock
* 01Mar01 Andrew Morton
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/nmi.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/interrupt.h> /* For in_interrupt() */
#include <linux/delay.h>
#include <linux/smp.h>
#include <linux/security.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <linux/syscalls.h>
#include <linux/kexec.h>
#include <linux/kdb.h>
#include <linux/ratelimit.h>
#include <linux/kmsg_dump.h>
#include <linux/syslog.h>
#include <linux/cpu.h>
#include <linux/notifier.h>
#include <linux/rculist.h>
#include <asm/uaccess.h>
#define CREATE_TRACE_POINTS
#include <trace/events/printk.h>
/*
* Architectures can override it:
*/
void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
{
}
#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
/* printk's without a loglevel use this.. */
#define DEFAULT_MESSAGE_LOGLEVEL CONFIG_DEFAULT_MESSAGE_LOGLEVEL
/* We show everything that is MORE important than this.. */
#define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
#define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
DECLARE_WAIT_QUEUE_HEAD(log_wait);
int console_printk[4] = {
DEFAULT_CONSOLE_LOGLEVEL, /* console_loglevel */
DEFAULT_MESSAGE_LOGLEVEL, /* default_message_loglevel */
MINIMUM_CONSOLE_LOGLEVEL, /* minimum_console_loglevel */
DEFAULT_CONSOLE_LOGLEVEL, /* default_console_loglevel */
};
/*
* Low level drivers may need that to know if they can schedule in
* their unblank() callback or not. So let's export it.
*/
int oops_in_progress;
EXPORT_SYMBOL(oops_in_progress);
/*
* console_sem protects the console_drivers list, and also
* provides serialisation for access to the entire console
* driver system.
*/
static DEFINE_SEMAPHORE(console_sem);
struct console *console_drivers;
EXPORT_SYMBOL_GPL(console_drivers);
/*
* This is used for debugging the mess that is the VT code by
* keeping track if we have the console semaphore held. It's
* definitely not the perfect debug tool (we don't know if _WE_
* hold it are racing, but it helps tracking those weird code
* path in the console code where we end up in places I want
* locked without the console sempahore held
*/
static int console_locked, console_suspended;
/*
* logbuf_lock protects log_buf, log_start, log_end, con_start and logged_chars
* It is also used in interesting ways to provide interlocking in
* console_unlock();.
*/
static DEFINE_RAW_SPINLOCK(logbuf_lock);
#define LOG_BUF_MASK (log_buf_len-1)
#define LOG_BUF(idx) (log_buf[(idx) & LOG_BUF_MASK])
/*
* The indices into log_buf are not constrained to log_buf_len - they
* must be masked before subscripting
*/
static unsigned log_start; /* Index into log_buf: next char to be read by syslog() */
static unsigned con_start; /* Index into log_buf: next char to be sent to consoles */
static unsigned log_end; /* Index into log_buf: most-recently-written-char + 1 */
/*
* If exclusive_console is non-NULL then only this console is to be printed to.
*/
static struct console *exclusive_console;
/*
* Array of consoles built from command line options (console=)
*/
struct console_cmdline
{
char name[8]; /* Name of the driver */
int index; /* Minor dev. to use */
char *options; /* Options for the driver */
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
char *brl_options; /* Options for braille driver */
#endif
};
#define MAX_CMDLINECONSOLES 8
static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
static int selected_console = -1;
static int preferred_console = -1;
int console_set_on_cmdline;
EXPORT_SYMBOL(console_set_on_cmdline);
/* Flag: console code may call schedule() */
static int console_may_schedule;
#ifdef CONFIG_PRINTK
static char __log_buf[__LOG_BUF_LEN];
static char *log_buf = __log_buf;
static int log_buf_len = __LOG_BUF_LEN;
static unsigned logged_chars; /* Number of chars produced since last read+clear operation */
static int saved_console_loglevel = -1;
#ifdef CONFIG_KEXEC
/*
* This appends the listed symbols to /proc/vmcoreinfo
*
* /proc/vmcoreinfo is used by various utiilties, like crash and makedumpfile to
* obtain access to symbols that are otherwise very difficult to locate. These
* symbols are specifically used so that utilities can access and extract the
* dmesg log from a vmcore file after a crash.
*/
void log_buf_kexec_setup(void)
{
VMCOREINFO_SYMBOL(log_buf);
VMCOREINFO_SYMBOL(log_end);
VMCOREINFO_SYMBOL(log_buf_len);
VMCOREINFO_SYMBOL(logged_chars);
}
#endif
/* requested log_buf_len from kernel cmdline */
static unsigned long __initdata new_log_buf_len;
/* save requested log_buf_len since it's too early to process it */
static int __init log_buf_len_setup(char *str)
{
unsigned size = memparse(str, &str);
if (size)
size = roundup_pow_of_two(size);
if (size > log_buf_len)
new_log_buf_len = size;
return 0;
}
early_param("log_buf_len", log_buf_len_setup);
void __init setup_log_buf(int early)
{
unsigned long flags;
unsigned start, dest_idx, offset;
char *new_log_buf;
int free;
if (!new_log_buf_len)
return;
if (early) {
unsigned long mem;
mem = memblock_alloc(new_log_buf_len, PAGE_SIZE);
if (!mem)
return;
new_log_buf = __va(mem);
} else {
new_log_buf = alloc_bootmem_nopanic(new_log_buf_len);
}
if (unlikely(!new_log_buf)) {
pr_err("log_buf_len: %ld bytes not available\n",
new_log_buf_len);
return;
}
raw_spin_lock_irqsave(&logbuf_lock, flags);
log_buf_len = new_log_buf_len;
log_buf = new_log_buf;
new_log_buf_len = 0;
free = __LOG_BUF_LEN - log_end;
offset = start = min(con_start, log_start);
dest_idx = 0;
while (start != log_end) {
unsigned log_idx_mask = start & (__LOG_BUF_LEN - 1);
log_buf[dest_idx] = __log_buf[log_idx_mask];
start++;
dest_idx++;
}
log_start -= offset;
con_start -= offset;
log_end -= offset;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
pr_info("log_buf_len: %d\n", log_buf_len);
pr_info("early log buf free: %d(%d%%)\n",
free, (free * 100) / __LOG_BUF_LEN);
}
#ifdef CONFIG_BOOT_PRINTK_DELAY
static int boot_delay; /* msecs delay after each printk during bootup */
static unsigned long long loops_per_msec; /* based on boot_delay */
static int __init boot_delay_setup(char *str)
{
unsigned long lpj;
lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
get_option(&str, &boot_delay);
if (boot_delay > 10 * 1000)
boot_delay = 0;
pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
"HZ: %d, loops_per_msec: %llu\n",
boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
return 1;
}
__setup("boot_delay=", boot_delay_setup);
static void boot_delay_msec(void)
{
unsigned long long k;
unsigned long timeout;
if (boot_delay == 0 || system_state != SYSTEM_BOOTING)
return;
k = (unsigned long long)loops_per_msec * boot_delay;
timeout = jiffies + msecs_to_jiffies(boot_delay);
while (k) {
k--;
cpu_relax();
/*
* use (volatile) jiffies to prevent
* compiler reduction; loop termination via jiffies
* is secondary and may or may not happen.
*/
if (time_after(jiffies, timeout))
break;
touch_nmi_watchdog();
}
}
#else
static inline void boot_delay_msec(void)
{
}
#endif
#ifdef CONFIG_SECURITY_DMESG_RESTRICT
int dmesg_restrict = 1;
#else
int dmesg_restrict;
#endif
static int syslog_action_restricted(int type)
{
if (dmesg_restrict)
return 1;
/* Unless restricted, we allow "read all" and "get buffer size" for everybody */
return type != SYSLOG_ACTION_READ_ALL && type != SYSLOG_ACTION_SIZE_BUFFER;
}
static int check_syslog_permissions(int type, bool from_file)
{
/*
* If this is from /proc/kmsg and we've already opened it, then we've
* already done the capabilities checks at open time.
*/
if (from_file && type != SYSLOG_ACTION_OPEN)
return 0;
if (syslog_action_restricted(type)) {
if (capable(CAP_SYSLOG))
return 0;
/* For historical reasons, accept CAP_SYS_ADMIN too, with a warning */
if (capable(CAP_SYS_ADMIN)) {
printk_once(KERN_WARNING "%s (%d): "
"Attempt to access syslog with CAP_SYS_ADMIN "
"but no CAP_SYSLOG (deprecated).\n",
current->comm, task_pid_nr(current));
return 0;
}
return -EPERM;
}
return 0;
}
int do_syslog(int type, char __user *buf, int len, bool from_file)
{
unsigned i, j, limit, count;
int do_clear = 0;
char c;
int error;
error = check_syslog_permissions(type, from_file);
if (error)
goto out;
error = security_syslog(type);
if (error)
return error;
switch (type) {
case SYSLOG_ACTION_CLOSE: /* Close log */
break;
case SYSLOG_ACTION_OPEN: /* Open log */
break;
case SYSLOG_ACTION_READ: /* Read from log */
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
error = wait_event_interruptible(log_wait,
(log_start - log_end));
if (error)
goto out;
i = 0;
raw_spin_lock_irq(&logbuf_lock);
while (!error && (log_start != log_end) && i < len) {
c = LOG_BUF(log_start);
log_start++;
raw_spin_unlock_irq(&logbuf_lock);
error = __put_user(c,buf);
buf++;
i++;
cond_resched();
raw_spin_lock_irq(&logbuf_lock);
}
raw_spin_unlock_irq(&logbuf_lock);
if (!error)
error = i;
break;
/* Read/clear last kernel messages */
case SYSLOG_ACTION_READ_CLEAR:
do_clear = 1;
/* FALL THRU */
/* Read last kernel messages */
case SYSLOG_ACTION_READ_ALL:
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
count = len;
if (count > log_buf_len)
count = log_buf_len;
raw_spin_lock_irq(&logbuf_lock);
if (count > logged_chars)
count = logged_chars;
if (do_clear)
logged_chars = 0;
limit = log_end;
/*
* __put_user() could sleep, and while we sleep
* printk() could overwrite the messages
* we try to copy to user space. Therefore
* the messages are copied in reverse. <manfreds>
*/
for (i = 0; i < count && !error; i++) {
j = limit-1-i;
if (j + log_buf_len < log_end)
break;
c = LOG_BUF(j);
raw_spin_unlock_irq(&logbuf_lock);
error = __put_user(c,&buf[count-1-i]);
cond_resched();
raw_spin_lock_irq(&logbuf_lock);
}
raw_spin_unlock_irq(&logbuf_lock);
if (error)
break;
error = i;
if (i != count) {
int offset = count-error;
/* buffer overflow during copy, correct user buffer. */
for (i = 0; i < error; i++) {
if (__get_user(c,&buf[i+offset]) ||
__put_user(c,&buf[i])) {
error = -EFAULT;
break;
}
cond_resched();
}
}
break;
/* Clear ring buffer */
case SYSLOG_ACTION_CLEAR:
logged_chars = 0;
break;
/* Disable logging to console */
case SYSLOG_ACTION_CONSOLE_OFF:
if (saved_console_loglevel == -1)
saved_console_loglevel = console_loglevel;
console_loglevel = minimum_console_loglevel;
break;
/* Enable logging to console */
case SYSLOG_ACTION_CONSOLE_ON:
if (saved_console_loglevel != -1) {
console_loglevel = saved_console_loglevel;
saved_console_loglevel = -1;
}
break;
/* Set level of messages printed to console */
case SYSLOG_ACTION_CONSOLE_LEVEL:
error = -EINVAL;
if (len < 1 || len > 8)
goto out;
if (len < minimum_console_loglevel)
len = minimum_console_loglevel;
console_loglevel = len;
/* Implicitly re-enable logging to console */
saved_console_loglevel = -1;
error = 0;
break;
/* Number of chars in the log buffer */
case SYSLOG_ACTION_SIZE_UNREAD:
error = log_end - log_start;
break;
/* Size of the log buffer */
case SYSLOG_ACTION_SIZE_BUFFER:
error = log_buf_len;
break;
default:
error = -EINVAL;
break;
}
out:
return error;
}
SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
{
return do_syslog(type, buf, len, SYSLOG_FROM_CALL);
}
#ifdef CONFIG_KGDB_KDB
/* kdb dmesg command needs access to the syslog buffer. do_syslog()
* uses locks so it cannot be used during debugging. Just tell kdb
* where the start and end of the physical and logical logs are. This
* is equivalent to do_syslog(3).
*/
void kdb_syslog_data(char *syslog_data[4])
{
syslog_data[0] = log_buf;
syslog_data[1] = log_buf + log_buf_len;
syslog_data[2] = log_buf + log_end -
(logged_chars < log_buf_len ? logged_chars : log_buf_len);
syslog_data[3] = log_buf + log_end;
}
#endif /* CONFIG_KGDB_KDB */
/*
* Call the console drivers on a range of log_buf
*/
static void __call_console_drivers(unsigned start, unsigned end)
{
struct console *con;
for_each_console(con) {
if (exclusive_console && con != exclusive_console)
continue;
if ((con->flags & CON_ENABLED) && con->write &&
(cpu_online(smp_processor_id()) ||
(con->flags & CON_ANYTIME)))
con->write(con, &LOG_BUF(start), end - start);
}
}
static bool __read_mostly ignore_loglevel;
static int __init ignore_loglevel_setup(char *str)
{
ignore_loglevel = 1;
printk(KERN_INFO "debug: ignoring loglevel setting.\n");
return 0;
}
early_param("ignore_loglevel", ignore_loglevel_setup);
module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
"print all kernel messages to the console.");
/*
* Write out chars from start to end - 1 inclusive
*/
static void _call_console_drivers(unsigned start,
unsigned end, int msg_log_level)
{
trace_console(&LOG_BUF(0), start, end, log_buf_len);
if ((msg_log_level < console_loglevel || ignore_loglevel) &&
console_drivers && start != end) {
if ((start & LOG_BUF_MASK) > (end & LOG_BUF_MASK)) {
/* wrapped write */
__call_console_drivers(start & LOG_BUF_MASK,
log_buf_len);
__call_console_drivers(0, end & LOG_BUF_MASK);
} else {
__call_console_drivers(start, end);
}
}
}
/*
* Parse the syslog header <[0-9]*>. The decimal value represents 32bit, the
* lower 3 bit are the log level, the rest are the log facility. In case
* userspace passes usual userspace syslog messages to /dev/kmsg or
* /dev/ttyprintk, the log prefix might contain the facility. Printk needs
* to extract the correct log level for in-kernel processing, and not mangle
* the original value.
*
* If a prefix is found, the length of the prefix is returned. If 'level' is
* passed, it will be filled in with the log level without a possible facility
* value. If 'special' is passed, the special printk prefix chars are accepted
* and returned. If no valid header is found, 0 is returned and the passed
* variables are not touched.
*/
static size_t log_prefix(const char *p, unsigned int *level, char *special)
{
unsigned int lev = 0;
char sp = '\0';
size_t len;
if (p[0] != '<' || !p[1])
return 0;
if (p[2] == '>') {
/* usual single digit level number or special char */
switch (p[1]) {
case '0' ... '7':
lev = p[1] - '0';
break;
case 'c': /* KERN_CONT */
case 'd': /* KERN_DEFAULT */
sp = p[1];
break;
default:
return 0;
}
len = 3;
} else {
/* multi digit including the level and facility number */
char *endp = NULL;
lev = (simple_strtoul(&p[1], &endp, 10) & 7);
if (endp == NULL || endp[0] != '>')
return 0;
len = (endp + 1) - p;
}
/* do not accept special char if not asked for */
if (sp && !special)
return 0;
if (special) {
*special = sp;
/* return special char, do not touch level */
if (sp)
return len;
}
if (level)
*level = lev;
return len;
}
/*
* Call the console drivers, asking them to write out
* log_buf[start] to log_buf[end - 1].
* The console_lock must be held.
*/
static void call_console_drivers(unsigned start, unsigned end)
{
unsigned cur_index, start_print;
static int msg_level = -1;
BUG_ON(((int)(start - end)) > 0);
cur_index = start;
start_print = start;
while (cur_index != end) {
if (msg_level < 0 && ((end - cur_index) > 2)) {
/* strip log prefix */
cur_index += log_prefix(&LOG_BUF(cur_index), &msg_level, NULL);
start_print = cur_index;
}
while (cur_index != end) {
char c = LOG_BUF(cur_index);
cur_index++;
if (c == '\n') {
if (msg_level < 0) {
/*
* printk() has already given us loglevel tags in
* the buffer. This code is here in case the
* log buffer has wrapped right round and scribbled
* on those tags
*/
msg_level = default_message_loglevel;
}
_call_console_drivers(start_print, cur_index, msg_level);
msg_level = -1;
start_print = cur_index;
break;
}
}
}
_call_console_drivers(start_print, end, msg_level);
}
static void emit_log_char(char c)
{
LOG_BUF(log_end) = c;
log_end++;
if (log_end - log_start > log_buf_len)
log_start = log_end - log_buf_len;
if (log_end - con_start > log_buf_len)
con_start = log_end - log_buf_len;
if (logged_chars < log_buf_len)
logged_chars++;
}
/*
* Zap console related locks when oopsing. Only zap at most once
* every 10 seconds, to leave time for slow consoles to print a
* full oops.
*/
static void zap_locks(void)
{
static unsigned long oops_timestamp;
if (time_after_eq(jiffies, oops_timestamp) &&
!time_after(jiffies, oops_timestamp + 30 * HZ))
return;
oops_timestamp = jiffies;
debug_locks_off();
/* If a crash is occurring, make sure we can't deadlock */
raw_spin_lock_init(&logbuf_lock);
/* And make sure that we print immediately */
sema_init(&console_sem, 1);
}
#if defined(CONFIG_PRINTK_TIME)
static bool printk_time = 1;
#else
static bool printk_time = 0;
#endif
module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
static bool always_kmsg_dump;
module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
/* Check if we have any console registered that can be called early in boot. */
static int have_callable_console(void)
{
struct console *con;
for_each_console(con)
if (con->flags & CON_ANYTIME)
return 1;
return 0;
}
/**
* printk - print a kernel message
* @fmt: format string
*
* This is printk(). It can be called from any context. We want it to work.
*
* We try to grab the console_lock. If we succeed, it's easy - we log the output and
* call the console drivers. If we fail to get the semaphore we place the output
* into the log buffer and return. The current holder of the console_sem will
* notice the new output in console_unlock(); and will send it to the
* consoles before releasing the lock.
*
* One effect of this deferred printing is that code which calls printk() and
* then changes console_loglevel may break. This is because console_loglevel
* is inspected when the actual printing occurs.
*
* See also:
* printf(3)
*
* See the vsnprintf() documentation for format string extensions over C99.
*/
asmlinkage int printk(const char *fmt, ...)
{
va_list args;
int r;
#ifdef CONFIG_KGDB_KDB
if (unlikely(kdb_trap_printk)) {
va_start(args, fmt);
r = vkdb_printf(fmt, args);
va_end(args);
return r;
}
#endif
va_start(args, fmt);
r = vprintk(fmt, args);
va_end(args);
return r;
}
/* cpu currently holding logbuf_lock */
static volatile unsigned int printk_cpu = UINT_MAX;
/*
* Can we actually use the console at this time on this cpu?
*
* Console drivers may assume that per-cpu resources have
* been allocated. So unless they're explicitly marked as
* being able to cope (CON_ANYTIME) don't call them until
* this CPU is officially up.
*/
static inline int can_use_console(unsigned int cpu)
{
return cpu_online(cpu) || have_callable_console();
}
/*
* Try to get console ownership to actually show the kernel
* messages from a 'printk'. Return true (and with the
* console_lock held, and 'console_locked' set) if it
* is successful, false otherwise.
*
* This gets called with the 'logbuf_lock' spinlock held and
* interrupts disabled. It should return with 'lockbuf_lock'
* released but interrupts still disabled.
*/
static int console_trylock_for_printk(unsigned int cpu)
__releases(&logbuf_lock)
{
int retval = 0, wake = 0;
if (console_trylock()) {
retval = 1;
/*
* If we can't use the console, we need to release
* the console semaphore by hand to avoid flushing
* the buffer. We need to hold the console semaphore
* in order to do this test safely.
*/
if (!can_use_console(cpu)) {
console_locked = 0;
wake = 1;
retval = 0;
}
}
printk_cpu = UINT_MAX;
if (wake)
up(&console_sem);
raw_spin_unlock(&logbuf_lock);
return retval;
}
static const char recursion_bug_msg [] =
KERN_CRIT "BUG: recent printk recursion!\n";
static int recursion_bug;
static int new_text_line = 1;
static char printk_buf[1024];
int printk_delay_msec __read_mostly;
static inline void printk_delay(void)
{
if (unlikely(printk_delay_msec)) {
int m = printk_delay_msec;
while (m--) {
mdelay(1);
touch_nmi_watchdog();
}
}
}
asmlinkage int vprintk(const char *fmt, va_list args)
{
int printed_len = 0;
int current_log_level = default_message_loglevel;
unsigned long flags;
int this_cpu;
char *p;
size_t plen;
char special;
boot_delay_msec();
printk_delay();
/* This stops the holder of console_sem just where we want him */
local_irq_save(flags);
this_cpu = smp_processor_id();
/*
* Ouch, printk recursed into itself!
*/
if (unlikely(printk_cpu == this_cpu)) {
/*
* If a crash is occurring during printk() on this CPU,
* then try to get the crash message out but make sure
* we can't deadlock. Otherwise just return to avoid the
* recursion and return - but flag the recursion so that
* it can be printed at the next appropriate moment:
*/
if (!oops_in_progress && !lockdep_recursing(current)) {
recursion_bug = 1;
goto out_restore_irqs;
}
zap_locks();
}
lockdep_off();
raw_spin_lock(&logbuf_lock);
printk_cpu = this_cpu;
if (recursion_bug) {
recursion_bug = 0;
strcpy(printk_buf, recursion_bug_msg);
printed_len = strlen(recursion_bug_msg);
}
/* Emit the output into the temporary buffer */
printed_len += vscnprintf(printk_buf + printed_len,
sizeof(printk_buf) - printed_len, fmt, args);
p = printk_buf;
/* Read log level and handle special printk prefix */
plen = log_prefix(p, ¤t_log_level, &special);
if (plen) {
p += plen;
switch (special) {
case 'c': /* Strip <c> KERN_CONT, continue line */
plen = 0;
break;
case 'd': /* Strip <d> KERN_DEFAULT, start new line */
plen = 0;
default:
if (!new_text_line) {
emit_log_char('\n');
new_text_line = 1;
}
}
}
/*
* Copy the output into log_buf. If the caller didn't provide
* the appropriate log prefix, we insert them here
*/
for (; *p; p++) {
if (new_text_line) {
new_text_line = 0;
if (plen) {
/* Copy original log prefix */
int i;
for (i = 0; i < plen; i++)
emit_log_char(printk_buf[i]);
printed_len += plen;
} else {
/* Add log prefix */
emit_log_char('<');
emit_log_char(current_log_level + '0');
emit_log_char('>');
printed_len += 3;
}
if (printk_time) {
/* Add the current time stamp */
char tbuf[50], *tp;
unsigned tlen;
unsigned long long t;
unsigned long nanosec_rem;
t = cpu_clock(printk_cpu);
nanosec_rem = do_div(t, 1000000000);
tlen = sprintf(tbuf, "[%5lu.%06lu] ",
(unsigned long) t,
nanosec_rem / 1000);
for (tp = tbuf; tp < tbuf + tlen; tp++)
emit_log_char(*tp);
printed_len += tlen;
}
if (!*p)
break;
}
emit_log_char(*p);
if (*p == '\n')
new_text_line = 1;
}
/*
* Try to acquire and then immediately release the
* console semaphore. The release will do all the
* actual magic (print out buffers, wake up klogd,
* etc).
*
* The console_trylock_for_printk() function
* will release 'logbuf_lock' regardless of whether it
* actually gets the semaphore or not.
*/
if (console_trylock_for_printk(this_cpu))
console_unlock();
lockdep_on();
out_restore_irqs:
local_irq_restore(flags);
return printed_len;
}
EXPORT_SYMBOL(printk);
EXPORT_SYMBOL(vprintk);
#else
static void call_console_drivers(unsigned start, unsigned end)
{
}
#endif
static int __add_preferred_console(char *name, int idx, char *options,
char *brl_options)
{
struct console_cmdline *c;
int i;
/*
* See if this tty is not yet registered, and
* if we have a slot free.
*/
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
if (strcmp(console_cmdline[i].name, name) == 0 &&
console_cmdline[i].index == idx) {
if (!brl_options)
selected_console = i;
return 0;
}
if (i == MAX_CMDLINECONSOLES)
return -E2BIG;
if (!brl_options)
selected_console = i;
c = &console_cmdline[i];
strlcpy(c->name, name, sizeof(c->name));
c->options = options;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
c->brl_options = brl_options;
#endif
c->index = idx;
return 0;
}
/*
* Set up a list of consoles. Called from init/main.c
*/
static int __init console_setup(char *str)
{
char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
char *s, *options, *brl_options = NULL;
int idx;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (!memcmp(str, "brl,", 4)) {
brl_options = "";
str += 4;
} else if (!memcmp(str, "brl=", 4)) {
brl_options = str + 4;
str = strchr(brl_options, ',');
if (!str) {
printk(KERN_ERR "need port name after brl=\n");
return 1;
}
*(str++) = 0;
}
#endif
/*
* Decode str into name, index, options.
*/
if (str[0] >= '0' && str[0] <= '9') {
strcpy(buf, "ttyS");
strncpy(buf + 4, str, sizeof(buf) - 5);
} else {
strncpy(buf, str, sizeof(buf) - 1);
}
buf[sizeof(buf) - 1] = 0;
if ((options = strchr(str, ',')) != NULL)
*(options++) = 0;
#ifdef __sparc__
if (!strcmp(str, "ttya"))
strcpy(buf, "ttyS0");
if (!strcmp(str, "ttyb"))
strcpy(buf, "ttyS1");
#endif
for (s = buf; *s; s++)
if ((*s >= '0' && *s <= '9') || *s == ',')
break;
idx = simple_strtoul(s, NULL, 10);
*s = 0;
__add_preferred_console(buf, idx, options, brl_options);
console_set_on_cmdline = 1;
return 1;
}
__setup("console=", console_setup);
/**
* add_preferred_console - add a device to the list of preferred consoles.
* @name: device name
* @idx: device index
* @options: options for this console
*
* The last preferred console added will be used for kernel messages
* and stdin/out/err for init. Normally this is used by console_setup
* above to handle user-supplied console arguments; however it can also
* be used by arch-specific code either to override the user or more
* commonly to provide a default console (ie from PROM variables) when
* the user has not supplied one.
*/
int add_preferred_console(char *name, int idx, char *options)
{
return __add_preferred_console(name, idx, options, NULL);
}
int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
{
struct console_cmdline *c;
int i;
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
if (strcmp(console_cmdline[i].name, name) == 0 &&
console_cmdline[i].index == idx) {
c = &console_cmdline[i];
strlcpy(c->name, name_new, sizeof(c->name));
c->name[sizeof(c->name) - 1] = 0;
c->options = options;
c->index = idx_new;
return i;
}
/* not found */
return -1;
}
bool console_suspend_enabled = 1;
EXPORT_SYMBOL(console_suspend_enabled);
static int __init console_suspend_disable(char *str)
{
console_suspend_enabled = 0;
return 1;
}
__setup("no_console_suspend", console_suspend_disable);
module_param_named(console_suspend, console_suspend_enabled,
bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
" and hibernate operations");
/**
* suspend_console - suspend the console subsystem
*
* This disables printk() while we go into suspend states
*/
void suspend_console(void)
{
if (!console_suspend_enabled)
return;
printk("Suspending console(s) (use no_console_suspend to debug)\n");
console_lock();
console_suspended = 1;
up(&console_sem);
}
void resume_console(void)
{
if (!console_suspend_enabled)
return;
down(&console_sem);
console_suspended = 0;
console_unlock();
}
/**
* console_cpu_notify - print deferred console messages after CPU hotplug
* @self: notifier struct
* @action: CPU hotplug event
* @hcpu: unused
*
* If printk() is called from a CPU that is not online yet, the messages
* will be spooled but will not show up on the console. This function is
* called when a new CPU comes online (or fails to come up), and ensures
* that any such output gets printed.
*/
static int __cpuinit console_cpu_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
switch (action) {
case CPU_ONLINE:
case CPU_DEAD:
case CPU_DYING:
case CPU_DOWN_FAILED:
case CPU_UP_CANCELED:
console_lock();
console_unlock();
}
return NOTIFY_OK;
}
/**
* console_lock - lock the console system for exclusive use.
*
* Acquires a lock which guarantees that the caller has
* exclusive access to the console system and the console_drivers list.
*
* Can sleep, returns nothing.
*/
void console_lock(void)
{
BUG_ON(in_interrupt());
down(&console_sem);
if (console_suspended)
return;
console_locked = 1;
console_may_schedule = 1;
}
EXPORT_SYMBOL(console_lock);
/**
* console_trylock - try to lock the console system for exclusive use.
*
* Tried to acquire a lock which guarantees that the caller has
* exclusive access to the console system and the console_drivers list.
*
* returns 1 on success, and 0 on failure to acquire the lock.
*/
int console_trylock(void)
{
if (down_trylock(&console_sem))
return 0;
if (console_suspended) {
up(&console_sem);
return 0;
}
console_locked = 1;
console_may_schedule = 0;
return 1;
}
EXPORT_SYMBOL(console_trylock);
int is_console_locked(void)
{
return console_locked;
}
/*
* Delayed printk facility, for scheduler-internal messages:
*/
#define PRINTK_BUF_SIZE 512
#define PRINTK_PENDING_WAKEUP 0x01
#define PRINTK_PENDING_SCHED 0x02
static DEFINE_PER_CPU(int, printk_pending);
static DEFINE_PER_CPU(char [PRINTK_BUF_SIZE], printk_sched_buf);
void printk_tick(void)
{
if (__this_cpu_read(printk_pending)) {
int pending = __this_cpu_xchg(printk_pending, 0);
if (pending & PRINTK_PENDING_SCHED) {
char *buf = __get_cpu_var(printk_sched_buf);
printk(KERN_WARNING "[sched_delayed] %s", buf);
}
if (pending & PRINTK_PENDING_WAKEUP)
wake_up_interruptible(&log_wait);
}
}
int printk_needs_cpu(int cpu)
{
if (cpu_is_offline(cpu))
printk_tick();
return __this_cpu_read(printk_pending);
}
void wake_up_klogd(void)
{
if (waitqueue_active(&log_wait))
this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
}
/**
* console_unlock - unlock the console system
*
* Releases the console_lock which the caller holds on the console system
* and the console driver list.
*
* While the console_lock was held, console output may have been buffered
* by printk(). If this is the case, console_unlock(); emits
* the output prior to releasing the lock.
*
* If there is output waiting for klogd, we wake it up.
*
* console_unlock(); may be called from any context.
*/
void console_unlock(void)
{
unsigned long flags;
unsigned _con_start, _log_end;
unsigned wake_klogd = 0, retry = 0;
if (console_suspended) {
up(&console_sem);
return;
}
console_may_schedule = 0;
again:
for ( ; ; ) {
raw_spin_lock_irqsave(&logbuf_lock, flags);
wake_klogd |= log_start - log_end;
if (con_start == log_end)
break; /* Nothing to print */
_con_start = con_start;
_log_end = log_end;
con_start = log_end; /* Flush */
raw_spin_unlock(&logbuf_lock);
stop_critical_timings(); /* don't trace print latency */
call_console_drivers(_con_start, _log_end);
start_critical_timings();
local_irq_restore(flags);
}
console_locked = 0;
/* Release the exclusive_console once it is used */
if (unlikely(exclusive_console))
exclusive_console = NULL;
raw_spin_unlock(&logbuf_lock);
up(&console_sem);
/*
* Someone could have filled up the buffer again, so re-check if there's
* something to flush. In case we cannot trylock the console_sem again,
* there's a new owner and the console_unlock() from them will do the
* flush, no worries.
*/
raw_spin_lock(&logbuf_lock);
if (con_start != log_end)
retry = 1;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
if (retry && console_trylock())
goto again;
if (wake_klogd)
wake_up_klogd();
}
EXPORT_SYMBOL(console_unlock);
/**
* console_conditional_schedule - yield the CPU if required
*
* If the console code is currently allowed to sleep, and
* if this CPU should yield the CPU to another task, do
* so here.
*
* Must be called within console_lock();.
*/
void __sched console_conditional_schedule(void)
{
if (console_may_schedule)
cond_resched();
}
EXPORT_SYMBOL(console_conditional_schedule);
void console_unblank(void)
{
struct console *c;
/*
* console_unblank can no longer be called in interrupt context unless
* oops_in_progress is set to 1..
*/
if (oops_in_progress) {
if (down_trylock(&console_sem) != 0)
return;
} else
console_lock();
console_locked = 1;
console_may_schedule = 0;
for_each_console(c)
if ((c->flags & CON_ENABLED) && c->unblank)
c->unblank();
console_unlock();
}
/*
* Return the console tty driver structure and its associated index
*/
struct tty_driver *console_device(int *index)
{
struct console *c;
struct tty_driver *driver = NULL;
console_lock();
for_each_console(c) {
if (!c->device)
continue;
driver = c->device(c, index);
if (driver)
break;
}
console_unlock();
return driver;
}
/*
* Prevent further output on the passed console device so that (for example)
* serial drivers can disable console output before suspending a port, and can
* re-enable output afterwards.
*/
void console_stop(struct console *console)
{
console_lock();
console->flags &= ~CON_ENABLED;
console_unlock();
}
EXPORT_SYMBOL(console_stop);
void console_start(struct console *console)
{
console_lock();
console->flags |= CON_ENABLED;
console_unlock();
}
EXPORT_SYMBOL(console_start);
static int __read_mostly keep_bootcon;
static int __init keep_bootcon_setup(char *str)
{
keep_bootcon = 1;
printk(KERN_INFO "debug: skip boot console de-registration.\n");
return 0;
}
early_param("keep_bootcon", keep_bootcon_setup);
/*
* The console driver calls this routine during kernel initialization
* to register the console printing procedure with printk() and to
* print any messages that were printed by the kernel before the
* console driver was initialized.
*
* This can happen pretty early during the boot process (because of
* early_printk) - sometimes before setup_arch() completes - be careful
* of what kernel features are used - they may not be initialised yet.
*
* There are two types of consoles - bootconsoles (early_printk) and
* "real" consoles (everything which is not a bootconsole) which are
* handled differently.
* - Any number of bootconsoles can be registered at any time.
* - As soon as a "real" console is registered, all bootconsoles
* will be unregistered automatically.
* - Once a "real" console is registered, any attempt to register a
* bootconsoles will be rejected
*/
void register_console(struct console *newcon)
{
int i;
unsigned long flags;
struct console *bcon = NULL;
/*
* before we register a new CON_BOOT console, make sure we don't
* already have a valid console
*/
if (console_drivers && newcon->flags & CON_BOOT) {
/* find the last or real console */
for_each_console(bcon) {
if (!(bcon->flags & CON_BOOT)) {
printk(KERN_INFO "Too late to register bootconsole %s%d\n",
newcon->name, newcon->index);
return;
}
}
}
if (console_drivers && console_drivers->flags & CON_BOOT)
bcon = console_drivers;
if (preferred_console < 0 || bcon || !console_drivers)
preferred_console = selected_console;
if (newcon->early_setup)
newcon->early_setup();
/*
* See if we want to use this console driver. If we
* didn't select a console we take the first one
* that registers here.
*/
if (preferred_console < 0) {
if (newcon->index < 0)
newcon->index = 0;
if (newcon->setup == NULL ||
newcon->setup(newcon, NULL) == 0) {
newcon->flags |= CON_ENABLED;
if (newcon->device) {
newcon->flags |= CON_CONSDEV;
preferred_console = 0;
}
}
}
/*
* See if this console matches one we selected on
* the command line.
*/
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
i++) {
if (strcmp(console_cmdline[i].name, newcon->name) != 0)
continue;
if (newcon->index >= 0 &&
newcon->index != console_cmdline[i].index)
continue;
if (newcon->index < 0)
newcon->index = console_cmdline[i].index;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (console_cmdline[i].brl_options) {
newcon->flags |= CON_BRL;
braille_register_console(newcon,
console_cmdline[i].index,
console_cmdline[i].options,
console_cmdline[i].brl_options);
return;
}
#endif
if (newcon->setup &&
newcon->setup(newcon, console_cmdline[i].options) != 0)
break;
newcon->flags |= CON_ENABLED;
newcon->index = console_cmdline[i].index;
if (i == selected_console) {
newcon->flags |= CON_CONSDEV;
preferred_console = selected_console;
}
break;
}
if (!(newcon->flags & CON_ENABLED))
return;
/*
* If we have a bootconsole, and are switching to a real console,
* don't print everything out again, since when the boot console, and
* the real console are the same physical device, it's annoying to
* see the beginning boot messages twice
*/
if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
newcon->flags &= ~CON_PRINTBUFFER;
/*
* Put this console in the list - keep the
* preferred driver at the head of the list.
*/
console_lock();
if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
newcon->next = console_drivers;
console_drivers = newcon;
if (newcon->next)
newcon->next->flags &= ~CON_CONSDEV;
} else {
newcon->next = console_drivers->next;
console_drivers->next = newcon;
}
if (newcon->flags & CON_PRINTBUFFER) {
/*
* console_unlock(); will print out the buffered messages
* for us.
*/
raw_spin_lock_irqsave(&logbuf_lock, flags);
con_start = log_start;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
/*
* We're about to replay the log buffer. Only do this to the
* just-registered console to avoid excessive message spam to
* the already-registered consoles.
*/
exclusive_console = newcon;
}
console_unlock();
console_sysfs_notify();
/*
* By unregistering the bootconsoles after we enable the real console
* we get the "console xxx enabled" message on all the consoles -
* boot consoles, real consoles, etc - this is to ensure that end
* users know there might be something in the kernel's log buffer that
* went to the bootconsole (that they do not see on the real console)
*/
if (bcon &&
((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
!keep_bootcon) {
/* we need to iterate through twice, to make sure we print
* everything out, before we unregister the console(s)
*/
printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
newcon->name, newcon->index);
for_each_console(bcon)
if (bcon->flags & CON_BOOT)
unregister_console(bcon);
} else {
printk(KERN_INFO "%sconsole [%s%d] enabled\n",
(newcon->flags & CON_BOOT) ? "boot" : "" ,
newcon->name, newcon->index);
}
}
EXPORT_SYMBOL(register_console);
int unregister_console(struct console *console)
{
struct console *a, *b;
int res = 1;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (console->flags & CON_BRL)
return braille_unregister_console(console);
#endif
console_lock();
if (console_drivers == console) {
console_drivers=console->next;
res = 0;
} else if (console_drivers) {
for (a=console_drivers->next, b=console_drivers ;
a; b=a, a=b->next) {
if (a == console) {
b->next = a->next;
res = 0;
break;
}
}
}
/*
* If this isn't the last console and it has CON_CONSDEV set, we
* need to set it on the next preferred console.
*/
if (console_drivers != NULL && console->flags & CON_CONSDEV)
console_drivers->flags |= CON_CONSDEV;
console_unlock();
console_sysfs_notify();
return res;
}
EXPORT_SYMBOL(unregister_console);
static int __init printk_late_init(void)
{
struct console *con;
for_each_console(con) {
if (!keep_bootcon && con->flags & CON_BOOT) {
printk(KERN_INFO "turn off boot console %s%d\n",
con->name, con->index);
unregister_console(con);
}
}
hotcpu_notifier(console_cpu_notify, 0);
return 0;
}
late_initcall(printk_late_init);
#if defined CONFIG_PRINTK
int printk_sched(const char *fmt, ...)
{
unsigned long flags;
va_list args;
char *buf;
int r;
local_irq_save(flags);
buf = __get_cpu_var(printk_sched_buf);
va_start(args, fmt);
r = vsnprintf(buf, PRINTK_BUF_SIZE, fmt, args);
va_end(args);
__this_cpu_or(printk_pending, PRINTK_PENDING_SCHED);
local_irq_restore(flags);
return r;
}
/*
* printk rate limiting, lifted from the networking subsystem.
*
* This enforces a rate limit: not more than 10 kernel messages
* every 5s to make a denial-of-service attack impossible.
*/
DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
int __printk_ratelimit(const char *func)
{
return ___ratelimit(&printk_ratelimit_state, func);
}
EXPORT_SYMBOL(__printk_ratelimit);
/**
* printk_timed_ratelimit - caller-controlled printk ratelimiting
* @caller_jiffies: pointer to caller's state
* @interval_msecs: minimum interval between prints
*
* printk_timed_ratelimit() returns true if more than @interval_msecs
* milliseconds have elapsed since the last time printk_timed_ratelimit()
* returned true.
*/
bool printk_timed_ratelimit(unsigned long *caller_jiffies,
unsigned int interval_msecs)
{
if (*caller_jiffies == 0
|| !time_in_range(jiffies, *caller_jiffies,
*caller_jiffies
+ msecs_to_jiffies(interval_msecs))) {
*caller_jiffies = jiffies;
return true;
}
return false;
}
EXPORT_SYMBOL(printk_timed_ratelimit);
static DEFINE_SPINLOCK(dump_list_lock);
static LIST_HEAD(dump_list);
/**
* kmsg_dump_register - register a kernel log dumper.
* @dumper: pointer to the kmsg_dumper structure
*
* Adds a kernel log dumper to the system. The dump callback in the
* structure will be called when the kernel oopses or panics and must be
* set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
*/
int kmsg_dump_register(struct kmsg_dumper *dumper)
{
unsigned long flags;
int err = -EBUSY;
/* The dump callback needs to be set */
if (!dumper->dump)
return -EINVAL;
spin_lock_irqsave(&dump_list_lock, flags);
/* Don't allow registering multiple times */
if (!dumper->registered) {
dumper->registered = 1;
list_add_tail_rcu(&dumper->list, &dump_list);
err = 0;
}
spin_unlock_irqrestore(&dump_list_lock, flags);
return err;
}
EXPORT_SYMBOL_GPL(kmsg_dump_register);
/**
* kmsg_dump_unregister - unregister a kmsg dumper.
* @dumper: pointer to the kmsg_dumper structure
*
* Removes a dump device from the system. Returns zero on success and
* %-EINVAL otherwise.
*/
int kmsg_dump_unregister(struct kmsg_dumper *dumper)
{
unsigned long flags;
int err = -EINVAL;
spin_lock_irqsave(&dump_list_lock, flags);
if (dumper->registered) {
dumper->registered = 0;
list_del_rcu(&dumper->list);
err = 0;
}
spin_unlock_irqrestore(&dump_list_lock, flags);
synchronize_rcu();
return err;
}
EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
/**
* kmsg_dump - dump kernel log to kernel message dumpers.
* @reason: the reason (oops, panic etc) for dumping
*
* Iterate through each of the dump devices and call the oops/panic
* callbacks with the log buffer.
*/
void kmsg_dump(enum kmsg_dump_reason reason)
{
unsigned long end;
unsigned chars;
struct kmsg_dumper *dumper;
const char *s1, *s2;
unsigned long l1, l2;
unsigned long flags;
if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
return;
/* Theoretically, the log could move on after we do this, but
there's not a lot we can do about that. The new messages
will overwrite the start of what we dump. */
raw_spin_lock_irqsave(&logbuf_lock, flags);
end = log_end & LOG_BUF_MASK;
chars = logged_chars;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
if (chars > end) {
s1 = log_buf + log_buf_len - chars + end;
l1 = chars - end;
s2 = log_buf;
l2 = end;
} else {
s1 = "";
l1 = 0;
s2 = log_buf + end - chars;
l2 = chars;
}
rcu_read_lock();
list_for_each_entry_rcu(dumper, &dump_list, list)
dumper->dump(dumper, reason, s1, l1, s2, l2);
rcu_read_unlock();
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5589_1 |
crossvul-cpp_data_bad_160_1 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Lexer (convert JsVar strings into a series of tokens)
* ----------------------------------------------------------------------------
*/
#include "jslex.h"
JsLex *lex;
JsLex *jslSetLex(JsLex *l) {
JsLex *old = lex;
lex = l;
return old;
}
void jslCharPosFree(JslCharPos *pos) {
jsvStringIteratorFree(&pos->it);
}
JslCharPos jslCharPosClone(JslCharPos *pos) {
JslCharPos p;
p.it = jsvStringIteratorClone(&pos->it);
p.currCh = pos->currCh;
return p;
}
/// Return the next character (do not move to the next character)
static ALWAYS_INLINE char jslNextCh() {
return (char)(lex->it.ptr ? READ_FLASH_UINT8(&lex->it.ptr[lex->it.charIdx]) : 0);
}
/// Move on to the next character
static void NO_INLINE jslGetNextCh() {
lex->currCh = jslNextCh();
/** NOTE: In this next bit, we DON'T LOCK OR UNLOCK.
* The String iterator we're basing on does, so every
* time we touch the iterator we have to re-lock it
*/
lex->it.charIdx++;
if (lex->it.charIdx >= lex->it.charsInVar) {
lex->it.charIdx -= lex->it.charsInVar;
if (lex->it.var && jsvGetLastChild(lex->it.var)) {
lex->it.var = _jsvGetAddressOf(jsvGetLastChild(lex->it.var));
lex->it.ptr = &lex->it.var->varData.str[0];
lex->it.varIndex += lex->it.charsInVar;
lex->it.charsInVar = jsvGetCharactersInVar(lex->it.var);
} else {
lex->it.var = 0;
lex->it.ptr = 0;
lex->it.varIndex += lex->it.charsInVar;
lex->it.charsInVar = 0;
}
}
}
static ALWAYS_INLINE void jslTokenAppendChar(char ch) {
/* Add character to buffer but check it isn't too big.
* Also Leave ONE character at the end for null termination */
if (lex->tokenl < JSLEX_MAX_TOKEN_LENGTH-1) {
lex->token[lex->tokenl++] = ch;
}
}
static bool jslIsToken(const char *token, int startOffset) {
int i;
for (i=startOffset;i<lex->tokenl;i++) {
if (lex->token[i]!=token[i]) return false;
// if token is smaller than lex->token, there will be a null char
// which will be different from the token
}
return token[lex->tokenl] == 0; // only match if token ends now
}
typedef enum {
JSLJT_ID,
JSLJT_NUMBER,
JSLJT_STRING,
JSLJT_SINGLECHAR,
JSLJT_EXCLAMATION,
JSLJT_PLUS,
JSLJT_MINUS,
JSLJT_AND,
JSLJT_OR,
JSLJT_PERCENT,
JSLJT_STAR,
JSLJT_TOPHAT,
JSLJT_FORWARDSLASH,
JSLJT_LESSTHAN,
JSLJT_EQUAL,
JSLJT_GREATERTHAN,
} PACKED_FLAGS jslJumpTableEnum;
#define jslJumpTableStart 33 // '!' - the first handled character
#define jslJumpTableEnd 124 // '|' - the last handled character
const jslJumpTableEnum jslJumpTable[jslJumpTableEnd+1-jslJumpTableStart] = {
// 33
JSLJT_EXCLAMATION, // !
JSLJT_STRING, // "
JSLJT_SINGLECHAR, // #
JSLJT_ID, // $
JSLJT_PERCENT, // %
JSLJT_AND, // &
JSLJT_STRING, // '
JSLJT_SINGLECHAR, // (
JSLJT_SINGLECHAR, // )
JSLJT_STAR, // *
JSLJT_PLUS, // +
JSLJT_SINGLECHAR, // ,
JSLJT_MINUS, // -
JSLJT_NUMBER, // . - special :/
JSLJT_FORWARDSLASH, // /
// 48
JSLJT_NUMBER, // 0
JSLJT_NUMBER, // 1
JSLJT_NUMBER, // 2
JSLJT_NUMBER, // 3
JSLJT_NUMBER, // 4
JSLJT_NUMBER, // 5
JSLJT_NUMBER, // 6
JSLJT_NUMBER, // 7
JSLJT_NUMBER, // 8
JSLJT_NUMBER, // 9
JSLJT_SINGLECHAR, // :
JSLJT_SINGLECHAR, // ;
JSLJT_LESSTHAN, // <
JSLJT_EQUAL, // =
JSLJT_GREATERTHAN, // >
JSLJT_SINGLECHAR, // ?
// 64
JSLJT_SINGLECHAR, // @
JSLJT_ID, // A
JSLJT_ID, // B
JSLJT_ID, // C
JSLJT_ID, // D
JSLJT_ID, // E
JSLJT_ID, // F
JSLJT_ID, // G
JSLJT_ID, // H
JSLJT_ID, // I
JSLJT_ID, // J
JSLJT_ID, // K
JSLJT_ID, // L
JSLJT_ID, // M
JSLJT_ID, // N
JSLJT_ID, // O
JSLJT_ID, // P
JSLJT_ID, // Q
JSLJT_ID, // R
JSLJT_ID, // S
JSLJT_ID, // T
JSLJT_ID, // U
JSLJT_ID, // V
JSLJT_ID, // W
JSLJT_ID, // X
JSLJT_ID, // Y
JSLJT_ID, // Z
JSLJT_SINGLECHAR, // [
JSLJT_SINGLECHAR, // \ char
JSLJT_SINGLECHAR, // ]
JSLJT_TOPHAT, // ^
JSLJT_ID, // _
// 96
JSLJT_STRING, // `
JSLJT_ID, // A lowercase
JSLJT_ID, // B lowercase
JSLJT_ID, // C lowercase
JSLJT_ID, // D lowercase
JSLJT_ID, // E lowercase
JSLJT_ID, // F lowercase
JSLJT_ID, // G lowercase
JSLJT_ID, // H lowercase
JSLJT_ID, // I lowercase
JSLJT_ID, // J lowercase
JSLJT_ID, // K lowercase
JSLJT_ID, // L lowercase
JSLJT_ID, // M lowercase
JSLJT_ID, // N lowercase
JSLJT_ID, // O lowercase
JSLJT_ID, // P lowercase
JSLJT_ID, // Q lowercase
JSLJT_ID, // R lowercase
JSLJT_ID, // S lowercase
JSLJT_ID, // T lowercase
JSLJT_ID, // U lowercase
JSLJT_ID, // V lowercase
JSLJT_ID, // W lowercase
JSLJT_ID, // X lowercase
JSLJT_ID, // Y lowercase
JSLJT_ID, // Z lowercase
JSLJT_SINGLECHAR, // {
JSLJT_OR, // |
// everything past here is handled as a single char
// JSLJT_SINGLECHAR, // }
// JSLJT_SINGLECHAR, // ~
};
// handle a single char
static ALWAYS_INLINE void jslSingleChar() {
lex->tk = (unsigned char)lex->currCh;
jslGetNextCh();
}
static void jslLexString() {
char delim = lex->currCh;
lex->tokenValue = jsvNewFromEmptyString();
if (!lex->tokenValue) {
lex->tk = LEX_EOF;
return;
}
JsvStringIterator it;
jsvStringIteratorNew(&it, lex->tokenValue, 0);
// strings...
jslGetNextCh();
while (lex->currCh && lex->currCh!=delim) {
if (lex->currCh == '\\') {
jslGetNextCh();
char ch = lex->currCh;
switch (lex->currCh) {
case 'n' : ch = 0x0A; jslGetNextCh(); break;
case 'b' : ch = 0x08; jslGetNextCh(); break;
case 'f' : ch = 0x0C; jslGetNextCh(); break;
case 'r' : ch = 0x0D; jslGetNextCh(); break;
case 't' : ch = 0x09; jslGetNextCh(); break;
case 'v' : ch = 0x0B; jslGetNextCh(); break;
case 'u' :
case 'x' : { // hex digits
char buf[5] = "0x??";
if (lex->currCh == 'u') {
// We don't support unicode, so we just take the bottom 8 bits
// of the unicode character
jslGetNextCh();
jslGetNextCh();
}
jslGetNextCh();
buf[2] = lex->currCh; jslGetNextCh();
buf[3] = lex->currCh; jslGetNextCh();
ch = (char)stringToInt(buf);
} break;
default:
if (lex->currCh>='0' && lex->currCh<='7') {
// octal digits
char buf[5] = "0";
buf[1] = lex->currCh;
int n=2;
jslGetNextCh();
if (lex->currCh>='0' && lex->currCh<='7') {
buf[n++] = lex->currCh; jslGetNextCh();
if (lex->currCh>='0' && lex->currCh<='7') {
buf[n++] = lex->currCh; jslGetNextCh();
}
}
buf[n]=0;
ch = (char)stringToInt(buf);
} else {
// for anything else, just push the character through
jslGetNextCh();
}
break;
}
jslTokenAppendChar(ch);
jsvStringIteratorAppend(&it, ch);
} else if (lex->currCh=='\n' && delim!='`') {
/* Was a newline - this is now allowed
* unless we're a template string */
break;
} else {
jslTokenAppendChar(lex->currCh);
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
}
}
jsvStringIteratorFree(&it);
if (delim=='`')
lex->tk = LEX_TEMPLATE_LITERAL;
else lex->tk = LEX_STR;
// unfinished strings
if (lex->currCh!=delim)
lex->tk++; // +1 gets you to 'unfinished X'
jslGetNextCh();
}
static void jslLexRegex() {
lex->tokenValue = jsvNewFromEmptyString();
if (!lex->tokenValue) {
lex->tk = LEX_EOF;
return;
}
JsvStringIterator it;
jsvStringIteratorNew(&it, lex->tokenValue, 0);
jsvStringIteratorAppend(&it, '/');
// strings...
jslGetNextCh();
while (lex->currCh && lex->currCh!='/') {
if (lex->currCh == '\\') {
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
} else if (lex->currCh=='\n') {
/* Was a newline - this is now allowed
* unless we're a template string */
break;
}
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
}
lex->tk = LEX_REGEX;
if (lex->currCh!='/') {
lex->tk++; // +1 gets you to 'unfinished X'
} else {
jsvStringIteratorAppend(&it, '/');
jslGetNextCh();
// regex modifiers
while (lex->currCh=='g' ||
lex->currCh=='i' ||
lex->currCh=='m' ||
lex->currCh=='y' ||
lex->currCh=='u') {
jslTokenAppendChar(lex->currCh);
jsvStringIteratorAppend(&it, lex->currCh);
jslGetNextCh();
}
}
jsvStringIteratorFree(&it);
}
void jslGetNextToken() {
jslGetNextToken_start:
// Skip whitespace
while (isWhitespace(lex->currCh))
jslGetNextCh();
// Search for comments
if (lex->currCh=='/') {
// newline comments
if (jslNextCh()=='/') {
while (lex->currCh && lex->currCh!='\n') jslGetNextCh();
jslGetNextCh();
goto jslGetNextToken_start;
}
// block comments
if (jslNextCh()=='*') {
jslGetNextCh();
jslGetNextCh();
while (lex->currCh && !(lex->currCh=='*' && jslNextCh()=='/'))
jslGetNextCh();
if (!lex->currCh) {
lex->tk = LEX_UNFINISHED_COMMENT;
return; /* an unfinished multi-line comment. When in interactive console,
detect this and make sure we accept new lines */
}
jslGetNextCh();
jslGetNextCh();
goto jslGetNextToken_start;
}
}
int lastToken = lex->tk;
lex->tk = LEX_EOF;
lex->tokenl = 0; // clear token string
if (lex->tokenValue) {
jsvUnLock(lex->tokenValue);
lex->tokenValue = 0;
}
// record beginning of this token
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it) - 1;
/* we don't lock here, because we know that the string itself will be locked
* because of lex->sourceVar */
lex->tokenStart.it = lex->it;
lex->tokenStart.currCh = lex->currCh;
// tokens
if (((unsigned char)lex->currCh) < jslJumpTableStart ||
((unsigned char)lex->currCh) > jslJumpTableEnd) {
// if unhandled by the jump table, just pass it through as a single character
jslSingleChar();
} else {
switch(jslJumpTable[((unsigned char)lex->currCh) - jslJumpTableStart]) {
case JSLJT_ID: {
while (isAlpha(lex->currCh) || isNumeric(lex->currCh) || lex->currCh=='$') {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
}
lex->tk = LEX_ID;
// We do fancy stuff here to reduce number of compares (hopefully GCC creates a jump table)
switch (lex->token[0]) {
case 'b': if (jslIsToken("break", 1)) lex->tk = LEX_R_BREAK;
break;
case 'c': if (jslIsToken("case", 1)) lex->tk = LEX_R_CASE;
else if (jslIsToken("catch", 1)) lex->tk = LEX_R_CATCH;
else if (jslIsToken("class", 1)) lex->tk = LEX_R_CLASS;
else if (jslIsToken("const", 1)) lex->tk = LEX_R_CONST;
else if (jslIsToken("continue", 1)) lex->tk = LEX_R_CONTINUE;
break;
case 'd': if (jslIsToken("default", 1)) lex->tk = LEX_R_DEFAULT;
else if (jslIsToken("delete", 1)) lex->tk = LEX_R_DELETE;
else if (jslIsToken("do", 1)) lex->tk = LEX_R_DO;
else if (jslIsToken("debugger", 1)) lex->tk = LEX_R_DEBUGGER;
break;
case 'e': if (jslIsToken("else", 1)) lex->tk = LEX_R_ELSE;
else if (jslIsToken("extends", 1)) lex->tk = LEX_R_EXTENDS;
break;
case 'f': if (jslIsToken("false", 1)) lex->tk = LEX_R_FALSE;
else if (jslIsToken("finally", 1)) lex->tk = LEX_R_FINALLY;
else if (jslIsToken("for", 1)) lex->tk = LEX_R_FOR;
else if (jslIsToken("function", 1)) lex->tk = LEX_R_FUNCTION;
break;
case 'i': if (jslIsToken("if", 1)) lex->tk = LEX_R_IF;
else if (jslIsToken("in", 1)) lex->tk = LEX_R_IN;
else if (jslIsToken("instanceof", 1)) lex->tk = LEX_R_INSTANCEOF;
break;
case 'l': if (jslIsToken("let", 1)) lex->tk = LEX_R_LET;
break;
case 'n': if (jslIsToken("new", 1)) lex->tk = LEX_R_NEW;
else if (jslIsToken("null", 1)) lex->tk = LEX_R_NULL;
break;
case 'r': if (jslIsToken("return", 1)) lex->tk = LEX_R_RETURN;
break;
case 's': if (jslIsToken("static", 1)) lex->tk = LEX_R_STATIC;
else if (jslIsToken("super", 1)) lex->tk = LEX_R_SUPER;
else if (jslIsToken("switch", 1)) lex->tk = LEX_R_SWITCH;
break;
case 't': if (jslIsToken("this", 1)) lex->tk = LEX_R_THIS;
else if (jslIsToken("throw", 1)) lex->tk = LEX_R_THROW;
else if (jslIsToken("true", 1)) lex->tk = LEX_R_TRUE;
else if (jslIsToken("try", 1)) lex->tk = LEX_R_TRY;
else if (jslIsToken("typeof", 1)) lex->tk = LEX_R_TYPEOF;
break;
case 'u': if (jslIsToken("undefined", 1)) lex->tk = LEX_R_UNDEFINED;
break;
case 'w': if (jslIsToken("while", 1)) lex->tk = LEX_R_WHILE;
break;
case 'v': if (jslIsToken("var", 1)) lex->tk = LEX_R_VAR;
else if (jslIsToken("void", 1)) lex->tk = LEX_R_VOID;
break;
default: break;
} break;
case JSLJT_NUMBER: {
// TODO: check numbers aren't the wrong format
bool canBeFloating = true;
if (lex->currCh=='.') {
jslGetNextCh();
if (isNumeric(lex->currCh)) {
// it is a float
lex->tk = LEX_FLOAT;
jslTokenAppendChar('.');
} else {
// it wasn't a number after all
lex->tk = '.';
break;
}
} else {
if (lex->currCh=='0') {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
if ((lex->currCh=='x' || lex->currCh=='X') ||
(lex->currCh=='b' || lex->currCh=='B') ||
(lex->currCh=='o' || lex->currCh=='O')) {
canBeFloating = false;
jslTokenAppendChar(lex->currCh); jslGetNextCh();
}
}
lex->tk = LEX_INT;
while (isNumeric(lex->currCh) || (!canBeFloating && isHexadecimal(lex->currCh))) {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
}
if (canBeFloating && lex->currCh=='.') {
lex->tk = LEX_FLOAT;
jslTokenAppendChar('.');
jslGetNextCh();
}
}
// parse fractional part
if (lex->tk == LEX_FLOAT) {
while (isNumeric(lex->currCh)) {
jslTokenAppendChar(lex->currCh);
jslGetNextCh();
}
}
// do fancy e-style floating point
if (canBeFloating && (lex->currCh=='e'||lex->currCh=='E')) {
lex->tk = LEX_FLOAT;
jslTokenAppendChar(lex->currCh); jslGetNextCh();
if (lex->currCh=='-' || lex->currCh=='+') { jslTokenAppendChar(lex->currCh); jslGetNextCh(); }
while (isNumeric(lex->currCh)) {
jslTokenAppendChar(lex->currCh); jslGetNextCh();
}
}
} break;
case JSLJT_STRING: jslLexString(); break;
case JSLJT_EXCLAMATION: jslSingleChar();
if (lex->currCh=='=') { // !=
lex->tk = LEX_NEQUAL;
jslGetNextCh();
if (lex->currCh=='=') { // !==
lex->tk = LEX_NTYPEEQUAL;
jslGetNextCh();
}
} break;
case JSLJT_PLUS: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_PLUSEQUAL;
jslGetNextCh();
} else if (lex->currCh=='+') {
lex->tk = LEX_PLUSPLUS;
jslGetNextCh();
} break;
case JSLJT_MINUS: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_MINUSEQUAL;
jslGetNextCh();
} else if (lex->currCh=='-') {
lex->tk = LEX_MINUSMINUS;
jslGetNextCh();
} break;
case JSLJT_AND: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_ANDEQUAL;
jslGetNextCh();
} else if (lex->currCh=='&') {
lex->tk = LEX_ANDAND;
jslGetNextCh();
} break;
case JSLJT_OR: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_OREQUAL;
jslGetNextCh();
} else if (lex->currCh=='|') {
lex->tk = LEX_OROR;
jslGetNextCh();
} break;
case JSLJT_TOPHAT: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_XOREQUAL;
jslGetNextCh();
} break;
case JSLJT_STAR: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_MULEQUAL;
jslGetNextCh();
} break;
case JSLJT_FORWARDSLASH:
// yay! JS is so awesome.
if (lastToken==LEX_EOF ||
lastToken=='!' ||
lastToken=='%' ||
lastToken=='&' ||
lastToken=='*' ||
lastToken=='+' ||
lastToken=='-' ||
lastToken=='/' ||
lastToken=='<' ||
lastToken=='=' ||
lastToken=='>' ||
lastToken=='?' ||
(lastToken>=_LEX_OPERATOR_START && lastToken<=_LEX_OPERATOR_END) ||
(lastToken>=_LEX_R_LIST_START && lastToken<=_LEX_R_LIST_END) || // keywords
lastToken==LEX_R_CASE ||
lastToken==LEX_R_NEW ||
lastToken=='[' ||
lastToken=='{' ||
lastToken=='}' ||
lastToken=='(' ||
lastToken==',' ||
lastToken==';' ||
lastToken==':' ||
lastToken==LEX_ARROW_FUNCTION) {
// EOF operator keyword case new [ { } ( , ; : =>
// phew. We're a regex
jslLexRegex();
} else {
jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_DIVEQUAL;
jslGetNextCh();
}
} break;
case JSLJT_PERCENT: jslSingleChar();
if (lex->currCh=='=') {
lex->tk = LEX_MODEQUAL;
jslGetNextCh();
} break;
case JSLJT_EQUAL: jslSingleChar();
if (lex->currCh=='=') { // ==
lex->tk = LEX_EQUAL;
jslGetNextCh();
if (lex->currCh=='=') { // ===
lex->tk = LEX_TYPEEQUAL;
jslGetNextCh();
}
} else if (lex->currCh=='>') { // =>
lex->tk = LEX_ARROW_FUNCTION;
jslGetNextCh();
} break;
case JSLJT_LESSTHAN: jslSingleChar();
if (lex->currCh=='=') { // <=
lex->tk = LEX_LEQUAL;
jslGetNextCh();
} else if (lex->currCh=='<') { // <<
lex->tk = LEX_LSHIFT;
jslGetNextCh();
if (lex->currCh=='=') { // <<=
lex->tk = LEX_LSHIFTEQUAL;
jslGetNextCh();
}
} break;
case JSLJT_GREATERTHAN: jslSingleChar();
if (lex->currCh=='=') { // >=
lex->tk = LEX_GEQUAL;
jslGetNextCh();
} else if (lex->currCh=='>') { // >>
lex->tk = LEX_RSHIFT;
jslGetNextCh();
if (lex->currCh=='=') { // >>=
lex->tk = LEX_RSHIFTEQUAL;
jslGetNextCh();
} else if (lex->currCh=='>') { // >>>
jslGetNextCh();
if (lex->currCh=='=') { // >>>=
lex->tk = LEX_RSHIFTUNSIGNEDEQUAL;
jslGetNextCh();
} else {
lex->tk = LEX_RSHIFTUNSIGNED;
}
}
} break;
case JSLJT_SINGLECHAR: jslSingleChar(); break;
default: assert(0);break;
}
}
}
}
static ALWAYS_INLINE void jslPreload() {
// set up..
jslGetNextCh();
jslGetNextToken();
}
void jslInit(JsVar *var) {
lex->sourceVar = jsvLockAgain(var);
// reset stuff
lex->tk = 0;
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
lex->tokenLastStart = 0;
lex->tokenl = 0;
lex->tokenValue = 0;
lex->lineNumberOffset = 0;
// set up iterator
jsvStringIteratorNew(&lex->it, lex->sourceVar, 0);
jsvUnLock(lex->it.var); // see jslGetNextCh
jslPreload();
}
void jslKill() {
lex->tk = LEX_EOF; // safety ;)
if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh
jsvStringIteratorFree(&lex->it);
if (lex->tokenValue) {
jsvUnLock(lex->tokenValue);
lex->tokenValue = 0;
}
jsvUnLock(lex->sourceVar);
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
}
void jslSeekTo(size_t seekToChar) {
if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh
jsvStringIteratorFree(&lex->it);
jsvStringIteratorNew(&lex->it, lex->sourceVar, seekToChar);
jsvUnLock(lex->it.var); // see jslGetNextCh
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
jslPreload();
}
void jslSeekToP(JslCharPos *seekToChar) {
if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh
jsvStringIteratorFree(&lex->it);
lex->it = jsvStringIteratorClone(&seekToChar->it);
jsvUnLock(lex->it.var); // see jslGetNextCh
lex->currCh = seekToChar->currCh;
lex->tokenStart.it.var = 0;
lex->tokenStart.currCh = 0;
jslGetNextToken();
}
void jslReset() {
jslSeekTo(0);
}
/** When printing out a function, with pretokenise a
* character could end up being a special token. This
* handles that case. */
void jslFunctionCharAsString(unsigned char ch, char *str, size_t len) {
if (ch >= LEX_TOKEN_START) {
jslTokenAsString(ch, str, len);
} else {
str[0] = (char)ch;
str[1] = 0;
}
}
void jslTokenAsString(int token, char *str, size_t len) {
// see JS_ERROR_TOKEN_BUF_SIZE
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
// reserved words
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
strncpy(str, "?[",len);
itostr(token, &str[2], 10);
strncat(str, "]",len);
}
void jslGetTokenString(char *str, size_t len) {
if (lex->tk == LEX_ID) {
strncpy(str, "ID:", len);
strncat(str, jslGetTokenValueAsString(), len);
} else if (lex->tk == LEX_STR) {
strncpy(str, "String:'", len);
strncat(str, jslGetTokenValueAsString(), len);
strncat(str, "'", len);
} else
jslTokenAsString(lex->tk, str, len);
}
char *jslGetTokenValueAsString() {
assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH);
lex->token[lex->tokenl] = 0; // add final null
return lex->token;
}
int jslGetTokenLength() {
return lex->tokenl;
}
JsVar *jslGetTokenValueAsVar() {
if (lex->tokenValue) {
return jsvLockAgain(lex->tokenValue);
} else {
assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH);
lex->token[lex->tokenl] = 0; // add final null
return jsvNewFromString(lex->token);
}
}
bool jslIsIDOrReservedWord() {
return lex->tk == LEX_ID ||
(lex->tk >= _LEX_R_LIST_START && lex->tk <= _LEX_R_LIST_END);
}
/* Match failed - report error message */
static void jslMatchError(int expected_tk) {
char gotStr[30];
char expStr[30];
jslGetTokenString(gotStr, sizeof(gotStr));
jslTokenAsString(expected_tk, expStr, sizeof(expStr));
size_t oldPos = lex->tokenLastStart;
lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1;
jsExceptionHere(JSET_SYNTAXERROR, "Got %s expected %s", gotStr, expStr);
lex->tokenLastStart = oldPos;
// Sod it, skip this token anyway - stops us looping
jslGetNextToken();
}
/// Match, and return true on success, false on failure
bool jslMatch(int expected_tk) {
if (lex->tk != expected_tk) {
jslMatchError(expected_tk);
return false;
}
jslGetNextToken();
return true;
}
JsVar *jslNewTokenisedStringFromLexer(JslCharPos *charFrom, size_t charTo) {
// New method - tokenise functions
// save old lex
JsLex *oldLex = lex;
JsLex newLex;
lex = &newLex;
// work out length
size_t length = 0;
jslInit(oldLex->sourceVar);
jslSeekToP(charFrom);
int lastTk = LEX_EOF;
while (lex->tk!=LEX_EOF && jsvStringIteratorGetIndex(&lex->it)<=charTo+1) {
if ((lex->tk==LEX_ID || lex->tk==LEX_FLOAT || lex->tk==LEX_INT) &&
( lastTk==LEX_ID || lastTk==LEX_FLOAT || lastTk==LEX_INT)) {
jsExceptionHere(JSET_SYNTAXERROR, "ID/number following ID/number isn't valid JS");
length = 0;
break;
}
if (lex->tk==LEX_ID ||
lex->tk==LEX_INT ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL) {
length += jsvStringIteratorGetIndex(&lex->it)-jsvStringIteratorGetIndex(&lex->tokenStart.it);
} else {
length++;
}
lastTk = lex->tk;
jslGetNextToken();
}
// Try and create a flat string first
JsVar *var = jsvNewStringOfLength((unsigned int)length, NULL);
if (var) { // out of memory
JsvStringIterator dstit;
jsvStringIteratorNew(&dstit, var, 0);
// now start appending
jslSeekToP(charFrom);
while (lex->tk!=LEX_EOF && jsvStringIteratorGetIndex(&lex->it)<=charTo+1) {
if (lex->tk==LEX_ID ||
lex->tk==LEX_INT ||
lex->tk==LEX_FLOAT ||
lex->tk==LEX_STR ||
lex->tk==LEX_TEMPLATE_LITERAL) {
jsvStringIteratorSetCharAndNext(&dstit, lex->tokenStart.currCh);
JsvStringIterator it = jsvStringIteratorClone(&lex->tokenStart.it);
while (jsvStringIteratorGetIndex(&it)+1 < jsvStringIteratorGetIndex(&lex->it)) {
jsvStringIteratorSetCharAndNext(&dstit, jsvStringIteratorGetChar(&it));
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
} else {
jsvStringIteratorSetCharAndNext(&dstit, (char)lex->tk);
}
lastTk = lex->tk;
jslGetNextToken();
}
jsvStringIteratorFree(&dstit);
}
// restore lex
jslKill();
lex = oldLex;
return var;
}
JsVar *jslNewStringFromLexer(JslCharPos *charFrom, size_t charTo) {
// Original method - just copy it verbatim
size_t maxLength = charTo + 1 - jsvStringIteratorGetIndex(&charFrom->it);
assert(maxLength>0); // will fail if 0
// Try and create a flat string first
JsVar *var = 0;
if (maxLength > JSV_FLAT_STRING_BREAK_EVEN) {
var = jsvNewFlatStringOfLength((unsigned int)maxLength);
if (var) {
// Flat string
char *flatPtr = jsvGetFlatStringPointer(var);
*(flatPtr++) = charFrom->currCh;
JsvStringIterator it = jsvStringIteratorClone(&charFrom->it);
while (jsvStringIteratorHasChar(&it) && (--maxLength>0)) {
*(flatPtr++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
return var;
}
}
// Non-flat string...
var = jsvNewFromEmptyString();
if (!var) { // out of memory
return 0;
}
//jsvAppendStringVar(var, lex->sourceVar, charFrom->it->index, (int)(charTo-charFrom));
JsVar *block = jsvLockAgain(var);
block->varData.str[0] = charFrom->currCh;
size_t blockChars = 1;
size_t l = maxLength;
// now start appending
JsvStringIterator it = jsvStringIteratorClone(&charFrom->it);
while (jsvStringIteratorHasChar(&it) && (--maxLength>0)) {
char ch = jsvStringIteratorGetChar(&it);
if (blockChars >= jsvGetMaxCharactersInVar(block)) {
jsvSetCharactersInVar(block, blockChars);
JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0);
if (!next) break; // out of memory
// we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner)
jsvSetLastChild(block, jsvGetRef(next));
jsvUnLock(block);
block = next;
blockChars=0; // it's new, so empty
}
block->varData.str[blockChars++] = ch;
jsvStringIteratorNext(&it);
}
jsvSetCharactersInVar(block, blockChars);
jsvUnLock(block);
// Just make sure we only assert if there's a bug here. If we just ran out of memory or at end of string it's ok
assert((l == jsvGetStringLength(var)) || (jsErrorFlags&JSERR_MEMORY) || !jsvStringIteratorHasChar(&it));
jsvStringIteratorFree(&it);
return var;
}
/// Return the line number at the current character position (this isn't fast as it searches the string)
unsigned int jslGetLineNumber() {
size_t line;
size_t col;
jsvGetLineAndCol(lex->sourceVar, jsvStringIteratorGetIndex(&lex->tokenStart.it)-1, &line, &col);
return (unsigned int)line;
}
/// Do we need a space between these two characters when printing a function's text?
bool jslNeedSpaceBetween(unsigned char lastch, unsigned char ch) {
return (lastch>=_LEX_R_LIST_START || ch>=_LEX_R_LIST_START) &&
(lastch>=_LEX_R_LIST_START || isAlpha((char)lastch) || isNumeric((char)lastch)) &&
(ch>=_LEX_R_LIST_START || isAlpha((char)ch) || isNumeric((char)ch));
}
void jslPrintPosition(vcbprintf_callback user_callback, void *user_data, size_t tokenPos) {
size_t line,col;
jsvGetLineAndCol(lex->sourceVar, tokenPos, &line, &col);
if (lex->lineNumberOffset)
line += (size_t)lex->lineNumberOffset - 1;
cbprintf(user_callback, user_data, "line %d col %d\n", line, col);
}
void jslPrintTokenLineMarker(vcbprintf_callback user_callback, void *user_data, size_t tokenPos, char *prefix) {
size_t line = 1,col = 1;
jsvGetLineAndCol(lex->sourceVar, tokenPos, &line, &col);
size_t startOfLine = jsvGetIndexFromLineAndCol(lex->sourceVar, line, 1);
size_t lineLength = jsvGetCharsOnLine(lex->sourceVar, line);
size_t prefixLength = 0;
if (prefix) {
user_callback(prefix, user_data);
prefixLength = strlen(prefix);
}
if (lineLength>60 && tokenPos-startOfLine>30) {
cbprintf(user_callback, user_data, "...");
size_t skipChars = tokenPos-30 - startOfLine;
startOfLine += 3+skipChars;
if (skipChars<=col)
col -= skipChars;
else
col = 0;
lineLength -= skipChars;
}
// print the string until the end of the line, or 60 chars (whichever is less)
int chars = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, lex->sourceVar, startOfLine);
unsigned char lastch = 0;
while (jsvStringIteratorHasChar(&it) && chars<60) {
unsigned char ch = (unsigned char)jsvStringIteratorGetChar(&it);
if (ch == '\n') break;
if (jslNeedSpaceBetween(lastch, ch)) {
col++;
user_callback(" ", user_data);
}
char buf[32];
jslFunctionCharAsString(ch, buf, sizeof(buf));
size_t len = strlen(buf);
col += len-1;
user_callback(buf, user_data);
chars++;
lastch = ch;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
if (lineLength > 60)
user_callback("...", user_data);
user_callback("\n", user_data);
col += prefixLength;
while (col-- > 1) user_callback(" ", user_data);
user_callback("^\n", user_data);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_160_1 |
crossvul-cpp_data_good_5291_0 | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Marcus Boerger <helly@php.net> |
| Etienne Kneuss <colder@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/php_array.h"
#include "ext/standard/php_var.h"
#include "zend_smart_str.h"
#include "zend_interfaces.h"
#include "zend_exceptions.h"
#include "php_spl.h"
#include "spl_functions.h"
#include "spl_engine.h"
#include "spl_observer.h"
#include "spl_iterators.h"
#include "spl_array.h"
#include "spl_exceptions.h"
SPL_METHOD(SplObserver, update);
SPL_METHOD(SplSubject, attach);
SPL_METHOD(SplSubject, detach);
SPL_METHOD(SplSubject, notify);
ZEND_BEGIN_ARG_INFO(arginfo_SplObserver_update, 0)
ZEND_ARG_OBJ_INFO(0, SplSubject, SplSubject, 0)
ZEND_END_ARG_INFO();
static const zend_function_entry spl_funcs_SplObserver[] = {
SPL_ABSTRACT_ME(SplObserver, update, arginfo_SplObserver_update)
{NULL, NULL, NULL}
};
ZEND_BEGIN_ARG_INFO(arginfo_SplSubject_attach, 0)
ZEND_ARG_OBJ_INFO(0, SplObserver, SplObserver, 0)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_SplSubject_void, 0)
ZEND_END_ARG_INFO();
/*ZEND_BEGIN_ARG_INFO_EX(arginfo_SplSubject_notify, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, ignore, SplObserver, 1)
ZEND_END_ARG_INFO();*/
static const zend_function_entry spl_funcs_SplSubject[] = {
SPL_ABSTRACT_ME(SplSubject, attach, arginfo_SplSubject_attach)
SPL_ABSTRACT_ME(SplSubject, detach, arginfo_SplSubject_attach)
SPL_ABSTRACT_ME(SplSubject, notify, arginfo_SplSubject_void)
{NULL, NULL, NULL}
};
PHPAPI zend_class_entry *spl_ce_SplObserver;
PHPAPI zend_class_entry *spl_ce_SplSubject;
PHPAPI zend_class_entry *spl_ce_SplObjectStorage;
PHPAPI zend_class_entry *spl_ce_MultipleIterator;
PHPAPI zend_object_handlers spl_handler_SplObjectStorage;
typedef struct _spl_SplObjectStorage { /* {{{ */
HashTable storage;
zend_long index;
HashPosition pos;
zend_long flags;
zend_function *fptr_get_hash;
zval *gcdata;
size_t gcdata_num;
zend_object std;
} spl_SplObjectStorage; /* }}} */
/* {{{ storage is an assoc aray of [zend_object*]=>[zval *obj, zval *inf] */
typedef struct _spl_SplObjectStorageElement {
zval obj;
zval inf;
} spl_SplObjectStorageElement; /* }}} */
static inline spl_SplObjectStorage *spl_object_storage_from_obj(zend_object *obj) /* {{{ */ {
return (spl_SplObjectStorage*)((char*)(obj) - XtOffsetOf(spl_SplObjectStorage, std));
}
/* }}} */
#define Z_SPLOBJSTORAGE_P(zv) spl_object_storage_from_obj(Z_OBJ_P((zv)))
void spl_SplObjectStorage_free_storage(zend_object *object) /* {{{ */
{
spl_SplObjectStorage *intern = spl_object_storage_from_obj(object);
zend_object_std_dtor(&intern->std);
zend_hash_destroy(&intern->storage);
if (intern->gcdata != NULL) {
efree(intern->gcdata);
}
} /* }}} */
static zend_string *spl_object_storage_get_hash(spl_SplObjectStorage *intern, zval *this, zval *obj) {
if (intern->fptr_get_hash) {
zval rv;
zend_call_method_with_1_params(this, intern->std.ce, &intern->fptr_get_hash, "getHash", &rv, obj);
if (!Z_ISUNDEF(rv)) {
if (Z_TYPE(rv) == IS_STRING) {
return Z_STR(rv);
} else {
zend_throw_exception(spl_ce_RuntimeException, "Hash needs to be a string", 0);
zval_ptr_dtor(&rv);
return NULL;
}
} else {
return NULL;
}
} else {
zend_string *hash = zend_string_alloc(sizeof(zend_object*), 0);
memcpy(ZSTR_VAL(hash), (void*)&Z_OBJ_P(obj), sizeof(zend_object*));
ZSTR_VAL(hash)[ZSTR_LEN(hash)] = '\0';
return hash;
}
}
static void spl_object_storage_free_hash(spl_SplObjectStorage *intern, zend_string *hash) {
zend_string_release(hash);
}
static void spl_object_storage_dtor(zval *element) /* {{{ */
{
spl_SplObjectStorageElement *el = Z_PTR_P(element);
zval_ptr_dtor(&el->obj);
zval_ptr_dtor(&el->inf);
efree(el);
} /* }}} */
spl_SplObjectStorageElement* spl_object_storage_get(spl_SplObjectStorage *intern, zend_string *hash) /* {{{ */
{
return (spl_SplObjectStorageElement*)zend_hash_find_ptr(&intern->storage, hash);
} /* }}} */
spl_SplObjectStorageElement *spl_object_storage_attach(spl_SplObjectStorage *intern, zval *this, zval *obj, zval *inf) /* {{{ */
{
spl_SplObjectStorageElement *pelement, element;
zend_string *hash = spl_object_storage_get_hash(intern, this, obj);
if (!hash) {
return NULL;
}
pelement = spl_object_storage_get(intern, hash);
if (pelement) {
zval_ptr_dtor(&pelement->inf);
if (inf) {
ZVAL_COPY(&pelement->inf, inf);
} else {
ZVAL_NULL(&pelement->inf);
}
spl_object_storage_free_hash(intern, hash);
return pelement;
}
ZVAL_COPY(&element.obj, obj);
if (inf) {
ZVAL_COPY(&element.inf, inf);
} else {
ZVAL_NULL(&element.inf);
}
pelement = zend_hash_update_mem(&intern->storage, hash, &element, sizeof(spl_SplObjectStorageElement));
spl_object_storage_free_hash(intern, hash);
return pelement;
} /* }}} */
int spl_object_storage_detach(spl_SplObjectStorage *intern, zval *this, zval *obj) /* {{{ */
{
int ret = FAILURE;
zend_string *hash = spl_object_storage_get_hash(intern, this, obj);
if (!hash) {
return ret;
}
ret = zend_hash_del(&intern->storage, hash);
spl_object_storage_free_hash(intern, hash);
return ret;
} /* }}}*/
void spl_object_storage_addall(spl_SplObjectStorage *intern, zval *this, spl_SplObjectStorage *other) { /* {{{ */
spl_SplObjectStorageElement *element;
ZEND_HASH_FOREACH_PTR(&other->storage, element) {
spl_object_storage_attach(intern, this, &element->obj, &element->inf);
} ZEND_HASH_FOREACH_END();
intern->index = 0;
} /* }}} */
static zend_object *spl_object_storage_new_ex(zend_class_entry *class_type, zval *orig) /* {{{ */
{
spl_SplObjectStorage *intern;
zend_class_entry *parent = class_type;
intern = emalloc(sizeof(spl_SplObjectStorage) + zend_object_properties_size(parent));
memset(intern, 0, sizeof(spl_SplObjectStorage) - sizeof(zval));
intern->pos = HT_INVALID_IDX;
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
zend_hash_init(&intern->storage, 0, NULL, spl_object_storage_dtor, 0);
intern->std.handlers = &spl_handler_SplObjectStorage;
while (parent) {
if (parent == spl_ce_SplObjectStorage) {
if (class_type != spl_ce_SplObjectStorage) {
intern->fptr_get_hash = zend_hash_str_find_ptr(&class_type->function_table, "gethash", sizeof("gethash") - 1);
if (intern->fptr_get_hash->common.scope == spl_ce_SplObjectStorage) {
intern->fptr_get_hash = NULL;
}
}
break;
}
parent = parent->parent;
}
if (orig) {
spl_SplObjectStorage *other = Z_SPLOBJSTORAGE_P(orig);
spl_object_storage_addall(intern, orig, other);
}
return &intern->std;
}
/* }}} */
/* {{{ spl_object_storage_clone */
static zend_object *spl_object_storage_clone(zval *zobject)
{
zend_object *old_object;
zend_object *new_object;
old_object = Z_OBJ_P(zobject);
new_object = spl_object_storage_new_ex(old_object->ce, zobject);
zend_objects_clone_members(new_object, old_object);
return new_object;
}
/* }}} */
static HashTable* spl_object_storage_debug_info(zval *obj, int *is_temp) /* {{{ */
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(obj);
spl_SplObjectStorageElement *element;
HashTable *props;
zval tmp, storage;
zend_string *md5str;
zend_string *zname;
HashTable *debug_info;
*is_temp = 1;
props = Z_OBJPROP_P(obj);
ALLOC_HASHTABLE(debug_info);
ZEND_INIT_SYMTABLE_EX(debug_info, zend_hash_num_elements(props) + 1, 0);
zend_hash_copy(debug_info, props, (copy_ctor_func_t)zval_add_ref);
array_init(&storage);
ZEND_HASH_FOREACH_PTR(&intern->storage, element) {
md5str = php_spl_object_hash(&element->obj);
array_init(&tmp);
/* Incrementing the refcount of obj and inf would confuse the garbage collector.
* Prefer to null the destructor */
Z_ARRVAL_P(&tmp)->pDestructor = NULL;
add_assoc_zval_ex(&tmp, "obj", sizeof("obj") - 1, &element->obj);
add_assoc_zval_ex(&tmp, "inf", sizeof("inf") - 1, &element->inf);
zend_hash_update(Z_ARRVAL(storage), md5str, &tmp);
zend_string_release(md5str);
} ZEND_HASH_FOREACH_END();
zname = spl_gen_private_prop_name(spl_ce_SplObjectStorage, "storage", sizeof("storage")-1);
zend_symtable_update(debug_info, zname, &storage);
zend_string_release(zname);
return debug_info;
}
/* }}} */
/* overriden for garbage collection */
static HashTable *spl_object_storage_get_gc(zval *obj, zval **table, int *n) /* {{{ */
{
int i = 0;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(obj);
spl_SplObjectStorageElement *element;
if (intern->storage.nNumOfElements * 2 > intern->gcdata_num) {
intern->gcdata_num = intern->storage.nNumOfElements * 2;
intern->gcdata = (zval*)erealloc(intern->gcdata, sizeof(zval) * intern->gcdata_num);
}
ZEND_HASH_FOREACH_PTR(&intern->storage, element) {
ZVAL_COPY_VALUE(&intern->gcdata[i++], &element->obj);
ZVAL_COPY_VALUE(&intern->gcdata[i++], &element->inf);
} ZEND_HASH_FOREACH_END();
*table = intern->gcdata;
*n = i;
return std_object_handlers.get_properties(obj);
}
/* }}} */
static int spl_object_storage_compare_info(zval *e1, zval *e2) /* {{{ */
{
spl_SplObjectStorageElement *s1 = (spl_SplObjectStorageElement*)Z_PTR_P(e1);
spl_SplObjectStorageElement *s2 = (spl_SplObjectStorageElement*)Z_PTR_P(e2);
zval result;
if (compare_function(&result, &s1->inf, &s2->inf) == FAILURE) {
return 1;
}
return Z_LVAL(result) > 0 ? 1 : (Z_LVAL(result) < 0 ? -1 : 0);
}
/* }}} */
static int spl_object_storage_compare_objects(zval *o1, zval *o2) /* {{{ */
{
zend_object *zo1 = (zend_object *)Z_OBJ_P(o1);
zend_object *zo2 = (zend_object *)Z_OBJ_P(o2);
if (zo1->ce != spl_ce_SplObjectStorage || zo2->ce != spl_ce_SplObjectStorage) {
return 1;
}
return zend_hash_compare(&(Z_SPLOBJSTORAGE_P(o1))->storage, &(Z_SPLOBJSTORAGE_P(o2))->storage, (compare_func_t)spl_object_storage_compare_info, 0);
}
/* }}} */
/* {{{ spl_array_object_new */
static zend_object *spl_SplObjectStorage_new(zend_class_entry *class_type)
{
return spl_object_storage_new_ex(class_type, NULL);
}
/* }}} */
int spl_object_storage_contains(spl_SplObjectStorage *intern, zval *this, zval *obj) /* {{{ */
{
int found;
zend_string *hash = spl_object_storage_get_hash(intern, this, obj);
if (!hash) {
return 0;
}
found = zend_hash_exists(&intern->storage, hash);
spl_object_storage_free_hash(intern, hash);
return found;
} /* }}} */
/* {{{ proto void SplObjectStorage::attach(object obj, mixed inf = NULL)
Attaches an object to the storage if not yet contained */
SPL_METHOD(SplObjectStorage, attach)
{
zval *obj, *inf = NULL;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o|z!", &obj, &inf) == FAILURE) {
return;
}
spl_object_storage_attach(intern, getThis(), obj, inf);
} /* }}} */
/* {{{ proto void SplObjectStorage::detach(object obj)
Detaches an object from the storage */
SPL_METHOD(SplObjectStorage, detach)
{
zval *obj;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &obj) == FAILURE) {
return;
}
spl_object_storage_detach(intern, getThis(), obj);
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
intern->index = 0;
} /* }}} */
/* {{{ proto string SplObjectStorage::getHash(object obj)
Returns the hash of an object */
SPL_METHOD(SplObjectStorage, getHash)
{
zval *obj;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &obj) == FAILURE) {
return;
}
RETURN_NEW_STR(php_spl_object_hash(obj));
} /* }}} */
/* {{{ proto mixed SplObjectStorage::offsetGet(object obj)
Returns associated information for a stored object */
SPL_METHOD(SplObjectStorage, offsetGet)
{
zval *obj;
spl_SplObjectStorageElement *element;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
zend_string *hash;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &obj) == FAILURE) {
return;
}
hash = spl_object_storage_get_hash(intern, getThis(), obj);
if (!hash) {
return;
}
element = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (!element) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Object not found");
} else {
zval *value = &element->inf;
ZVAL_DEREF(value);
ZVAL_COPY(return_value, value);
}
} /* }}} */
/* {{{ proto bool SplObjectStorage::addAll(SplObjectStorage $os)
Add all elements contained in $os */
SPL_METHOD(SplObjectStorage, addAll)
{
zval *obj;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
spl_SplObjectStorage *other;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &obj, spl_ce_SplObjectStorage) == FAILURE) {
return;
}
other = Z_SPLOBJSTORAGE_P(obj);
spl_object_storage_addall(intern, getThis(), other);
RETURN_LONG(zend_hash_num_elements(&intern->storage));
} /* }}} */
/* {{{ proto bool SplObjectStorage::removeAll(SplObjectStorage $os)
Remove all elements contained in $os */
SPL_METHOD(SplObjectStorage, removeAll)
{
zval *obj;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
spl_SplObjectStorage *other;
spl_SplObjectStorageElement *element;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &obj, spl_ce_SplObjectStorage) == FAILURE) {
return;
}
other = Z_SPLOBJSTORAGE_P(obj);
zend_hash_internal_pointer_reset(&other->storage);
while ((element = zend_hash_get_current_data_ptr(&other->storage)) != NULL) {
if (spl_object_storage_detach(intern, getThis(), &element->obj) == FAILURE) {
zend_hash_move_forward(&other->storage);
}
}
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
intern->index = 0;
RETURN_LONG(zend_hash_num_elements(&intern->storage));
} /* }}} */
/* {{{ proto bool SplObjectStorage::removeAllExcept(SplObjectStorage $os)
Remove elements not common to both this SplObjectStorage instance and $os */
SPL_METHOD(SplObjectStorage, removeAllExcept)
{
zval *obj;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
spl_SplObjectStorage *other;
spl_SplObjectStorageElement *element;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &obj, spl_ce_SplObjectStorage) == FAILURE) {
return;
}
other = Z_SPLOBJSTORAGE_P(obj);
ZEND_HASH_FOREACH_PTR(&intern->storage, element) {
if (!spl_object_storage_contains(other, getThis(), &element->obj)) {
spl_object_storage_detach(intern, getThis(), &element->obj);
}
} ZEND_HASH_FOREACH_END();
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
intern->index = 0;
RETURN_LONG(zend_hash_num_elements(&intern->storage));
}
/* }}} */
/* {{{ proto bool SplObjectStorage::contains(object obj)
Determine whethe an object is contained in the storage */
SPL_METHOD(SplObjectStorage, contains)
{
zval *obj;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &obj) == FAILURE) {
return;
}
RETURN_BOOL(spl_object_storage_contains(intern, getThis(), obj));
} /* }}} */
/* {{{ proto int SplObjectStorage::count()
Determine number of objects in storage */
SPL_METHOD(SplObjectStorage, count)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
zend_long mode = COUNT_NORMAL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
return;
}
if (mode == COUNT_RECURSIVE) {
zend_long ret = zend_hash_num_elements(&intern->storage);
zval *element;
ZEND_HASH_FOREACH_VAL(&intern->storage, element) {
ret += php_count_recursive(element, mode);
} ZEND_HASH_FOREACH_END();
RETURN_LONG(ret);
return;
}
RETURN_LONG(zend_hash_num_elements(&intern->storage));
} /* }}} */
/* {{{ proto void SplObjectStorage::rewind()
Rewind to first position */
SPL_METHOD(SplObjectStorage, rewind)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
intern->index = 0;
} /* }}} */
/* {{{ proto bool SplObjectStorage::valid()
Returns whether current position is valid */
SPL_METHOD(SplObjectStorage, valid)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(zend_hash_has_more_elements_ex(&intern->storage, &intern->pos) == SUCCESS);
} /* }}} */
/* {{{ proto mixed SplObjectStorage::key()
Returns current key */
SPL_METHOD(SplObjectStorage, key)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->index);
} /* }}} */
/* {{{ proto mixed SplObjectStorage::current()
Returns current element */
SPL_METHOD(SplObjectStorage, current)
{
spl_SplObjectStorageElement *element;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) == NULL) {
return;
}
ZVAL_COPY(return_value, &element->obj);
} /* }}} */
/* {{{ proto mixed SplObjectStorage::getInfo()
Returns associated information to current element */
SPL_METHOD(SplObjectStorage, getInfo)
{
spl_SplObjectStorageElement *element;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) == NULL) {
return;
}
ZVAL_COPY(return_value, &element->inf);
} /* }}} */
/* {{{ proto mixed SplObjectStorage::setInfo(mixed $inf)
Sets associated information of current element to $inf */
SPL_METHOD(SplObjectStorage, setInfo)
{
spl_SplObjectStorageElement *element;
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
zval *inf;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &inf) == FAILURE) {
return;
}
if ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) == NULL) {
return;
}
zval_ptr_dtor(&element->inf);
ZVAL_COPY(&element->inf, inf);
} /* }}} */
/* {{{ proto void SplObjectStorage::next()
Moves position forward */
SPL_METHOD(SplObjectStorage, next)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_hash_move_forward_ex(&intern->storage, &intern->pos);
intern->index++;
} /* }}} */
/* {{{ proto string SplObjectStorage::serialize()
Serializes storage */
SPL_METHOD(SplObjectStorage, serialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
spl_SplObjectStorageElement *element;
zval members, flags;
HashPosition pos;
php_serialize_data_t var_hash;
smart_str buf = {0};
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHP_VAR_SERIALIZE_INIT(var_hash);
/* storage */
smart_str_appendl(&buf, "x:", 2);
ZVAL_LONG(&flags, zend_hash_num_elements(&intern->storage));
php_var_serialize(&buf, &flags, &var_hash);
zval_ptr_dtor(&flags);
zend_hash_internal_pointer_reset_ex(&intern->storage, &pos);
while (zend_hash_has_more_elements_ex(&intern->storage, &pos) == SUCCESS) {
if ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &pos)) == NULL) {
smart_str_free(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
RETURN_NULL();
}
php_var_serialize(&buf, &element->obj, &var_hash);
smart_str_appendc(&buf, ',');
php_var_serialize(&buf, &element->inf, &var_hash);
smart_str_appendc(&buf, ';');
zend_hash_move_forward_ex(&intern->storage, &pos);
}
/* members */
smart_str_appendl(&buf, "m:", 2);
ZVAL_ARR(&members, zend_array_dup(zend_std_get_properties(getThis())));
php_var_serialize(&buf, &members, &var_hash); /* finishes the string */
zval_ptr_dtor(&members);
/* done */
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (buf.s) {
RETURN_NEW_STR(buf.s);
} else {
RETURN_NULL();
}
} /* }}} */
/* {{{ proto void SplObjectStorage::unserialize(string serialized)
Unserializes storage */
SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
char *buf;
size_t buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval entry, inf;
zval *pcount, *pmembers;
spl_SplObjectStorageElement *element;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
pcount = var_tmp_var(&var_hash);
if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
ZVAL_UNDEF(&entry);
ZVAL_UNDEF(&inf);
while (count-- > 0) {
spl_SplObjectStorageElement *pelement;
zend_string *hash;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
/* store reference to allow cross-references between different elements */
if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {
goto outexcept;
}
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {
zval_ptr_dtor(&entry);
goto outexcept;
}
}
if (Z_TYPE(entry) != IS_OBJECT) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
hash = spl_object_storage_get_hash(intern, getThis(), &entry);
if (!hash) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (pelement) {
if (!Z_ISUNDEF(pelement->inf)) {
var_push_dtor(&var_hash, &pelement->inf);
}
if (!Z_ISUNDEF(pelement->obj)) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);
var_replace(&var_hash, &entry, &element->obj);
var_replace(&var_hash, &inf, &element->inf);
zval_ptr_dtor(&entry);
ZVAL_UNDEF(&entry);
zval_ptr_dtor(&inf);
ZVAL_UNDEF(&inf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
pmembers = var_tmp_var(&var_hash);
if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {
goto outexcept;
}
/* copy members */
object_properties_load(&intern->std, Z_ARRVAL_P(pmembers));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
Iterator that iterates over several iterators one after the other */
SPL_METHOD(MultipleIterator, __construct)
{
spl_SplObjectStorage *intern;
zend_long flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC;
if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "|l", &flags) == FAILURE) {
return;
}
intern = Z_SPLOBJSTORAGE_P(getThis());
intern->flags = flags;
}
/* }}} */
/* {{{ proto int MultipleIterator::getFlags()
Return current flags */
SPL_METHOD(MultipleIterator, getFlags)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags);
}
/* }}} */
/* {{{ proto int MultipleIterator::setFlags(int flags)
Set flags */
SPL_METHOD(MultipleIterator, setFlags)
{
spl_SplObjectStorage *intern;
intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &intern->flags) == FAILURE) {
return;
}
}
/* }}} */
/* {{{ proto void attachIterator(Iterator iterator[, mixed info]) throws InvalidArgumentException
Attach a new iterator */
SPL_METHOD(MultipleIterator, attachIterator)
{
spl_SplObjectStorage *intern;
zval *iterator = NULL, *info = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|z!", &iterator, zend_ce_iterator, &info) == FAILURE) {
return;
}
intern = Z_SPLOBJSTORAGE_P(getThis());
if (info != NULL) {
spl_SplObjectStorageElement *element;
if (Z_TYPE_P(info) != IS_LONG && Z_TYPE_P(info) != IS_STRING) {
zend_throw_exception(spl_ce_InvalidArgumentException, "Info must be NULL, integer or string", 0);
return;
}
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
while ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) != NULL) {
if (fast_is_identical_function(info, &element->inf)) {
zend_throw_exception(spl_ce_InvalidArgumentException, "Key duplication error", 0);
return;
}
zend_hash_move_forward_ex(&intern->storage, &intern->pos);
}
}
spl_object_storage_attach(intern, getThis(), iterator, info);
}
/* }}} */
/* {{{ proto void MultipleIterator::rewind()
Rewind all attached iterator instances */
SPL_METHOD(MultipleIterator, rewind)
{
spl_SplObjectStorage *intern;
spl_SplObjectStorageElement *element;
zval *it;
intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
while ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) != NULL && !EG(exception)) {
it = &element->obj;
zend_call_method_with_0_params(it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_rewind, "rewind", NULL);
zend_hash_move_forward_ex(&intern->storage, &intern->pos);
}
}
/* }}} */
/* {{{ proto void MultipleIterator::next()
Move all attached iterator instances forward */
SPL_METHOD(MultipleIterator, next)
{
spl_SplObjectStorage *intern;
spl_SplObjectStorageElement *element;
zval *it;
intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
while ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) != NULL && !EG(exception)) {
it = &element->obj;
zend_call_method_with_0_params(it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_next, "next", NULL);
zend_hash_move_forward_ex(&intern->storage, &intern->pos);
}
}
/* }}} */
/* {{{ proto bool MultipleIterator::valid()
Return whether all or one sub iterator is valid depending on flags */
SPL_METHOD(MultipleIterator, valid)
{
spl_SplObjectStorage *intern;
spl_SplObjectStorageElement *element;
zval *it, retval;
zend_long expect, valid;
intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!zend_hash_num_elements(&intern->storage)) {
RETURN_FALSE;
}
expect = (intern->flags & MIT_NEED_ALL) ? 1 : 0;
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
while ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) != NULL && !EG(exception)) {
it = &element->obj;
zend_call_method_with_0_params(it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_valid, "valid", &retval);
if (!Z_ISUNDEF(retval)) {
valid = (Z_TYPE(retval) == IS_TRUE);
zval_ptr_dtor(&retval);
} else {
valid = 0;
}
if (expect != valid) {
RETURN_BOOL(!expect);
}
zend_hash_move_forward_ex(&intern->storage, &intern->pos);
}
RETURN_BOOL(expect);
}
/* }}} */
static void spl_multiple_iterator_get_all(spl_SplObjectStorage *intern, int get_type, zval *return_value) /* {{{ */
{
spl_SplObjectStorageElement *element;
zval *it, retval;
int valid = 1, num_elements;
num_elements = zend_hash_num_elements(&intern->storage);
if (num_elements < 1) {
RETURN_FALSE;
}
array_init_size(return_value, num_elements);
zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos);
while ((element = zend_hash_get_current_data_ptr_ex(&intern->storage, &intern->pos)) != NULL && !EG(exception)) {
it = &element->obj;
zend_call_method_with_0_params(it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_valid, "valid", &retval);
if (!Z_ISUNDEF(retval)) {
valid = Z_TYPE(retval) == IS_TRUE;
zval_ptr_dtor(&retval);
} else {
valid = 0;
}
if (valid) {
if (SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT == get_type) {
zend_call_method_with_0_params(it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_current, "current", &retval);
} else {
zend_call_method_with_0_params(it, Z_OBJCE_P(it), &Z_OBJCE_P(it)->iterator_funcs.zf_key, "key", &retval);
}
if (Z_ISUNDEF(retval)) {
zend_throw_exception(spl_ce_RuntimeException, "Failed to call sub iterator method", 0);
return;
}
} else if (intern->flags & MIT_NEED_ALL) {
if (SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT == get_type) {
zend_throw_exception(spl_ce_RuntimeException, "Called current() with non valid sub iterator", 0);
} else {
zend_throw_exception(spl_ce_RuntimeException, "Called key() with non valid sub iterator", 0);
}
return;
} else {
ZVAL_NULL(&retval);
}
if (intern->flags & MIT_KEYS_ASSOC) {
switch (Z_TYPE(element->inf)) {
case IS_LONG:
add_index_zval(return_value, Z_LVAL(element->inf), &retval);
break;
case IS_STRING:
zend_symtable_update(Z_ARRVAL_P(return_value), Z_STR(element->inf), &retval);
break;
default:
zval_ptr_dtor(&retval);
zend_throw_exception(spl_ce_InvalidArgumentException, "Sub-Iterator is associated with NULL", 0);
return;
}
} else {
add_next_index_zval(return_value, &retval);
}
zend_hash_move_forward_ex(&intern->storage, &intern->pos);
}
}
/* }}} */
/* {{{ proto array current() throws RuntimeException throws InvalidArgumentException
Return an array of all registered Iterator instances current() result */
SPL_METHOD(MultipleIterator, current)
{
spl_SplObjectStorage *intern;
intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_multiple_iterator_get_all(intern, SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT, return_value);
}
/* }}} */
/* {{{ proto array MultipleIterator::key()
Return an array of all registered Iterator instances key() result */
SPL_METHOD(MultipleIterator, key)
{
spl_SplObjectStorage *intern;
intern = Z_SPLOBJSTORAGE_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_multiple_iterator_get_all(intern, SPL_MULTIPLE_ITERATOR_GET_ALL_KEY, return_value);
}
/* }}} */
ZEND_BEGIN_ARG_INFO_EX(arginfo_MultipleIterator_attachIterator, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, iterator, Iterator, 0)
ZEND_ARG_INFO(0, infos)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_MultipleIterator_detachIterator, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, iterator, Iterator, 0)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_MultipleIterator_containsIterator, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, iterator, Iterator, 0)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_MultipleIterator_setflags, 0, 0, 1)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO();
static const zend_function_entry spl_funcs_MultipleIterator[] = {
SPL_ME(MultipleIterator, __construct, arginfo_MultipleIterator_setflags, 0)
SPL_ME(MultipleIterator, getFlags, arginfo_splobject_void, 0)
SPL_ME(MultipleIterator, setFlags, arginfo_MultipleIterator_setflags, 0)
SPL_ME(MultipleIterator, attachIterator, arginfo_MultipleIterator_attachIterator, 0)
SPL_MA(MultipleIterator, detachIterator, SplObjectStorage, detach, arginfo_MultipleIterator_detachIterator, 0)
SPL_MA(MultipleIterator, containsIterator, SplObjectStorage, contains, arginfo_MultipleIterator_containsIterator, 0)
SPL_MA(MultipleIterator, countIterators, SplObjectStorage, count, arginfo_splobject_void, 0)
/* Iterator */
SPL_ME(MultipleIterator, rewind, arginfo_splobject_void, 0)
SPL_ME(MultipleIterator, valid, arginfo_splobject_void, 0)
SPL_ME(MultipleIterator, key, arginfo_splobject_void, 0)
SPL_ME(MultipleIterator, current, arginfo_splobject_void, 0)
SPL_ME(MultipleIterator, next, arginfo_splobject_void, 0)
{NULL, NULL, NULL}
};
/* {{{ PHP_MINIT_FUNCTION(spl_observer) */
PHP_MINIT_FUNCTION(spl_observer)
{
REGISTER_SPL_INTERFACE(SplObserver);
REGISTER_SPL_INTERFACE(SplSubject);
REGISTER_SPL_STD_CLASS_EX(SplObjectStorage, spl_SplObjectStorage_new, spl_funcs_SplObjectStorage);
memcpy(&spl_handler_SplObjectStorage, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_handler_SplObjectStorage.offset = XtOffsetOf(spl_SplObjectStorage, std);
spl_handler_SplObjectStorage.get_debug_info = spl_object_storage_debug_info;
spl_handler_SplObjectStorage.compare_objects = spl_object_storage_compare_objects;
spl_handler_SplObjectStorage.clone_obj = spl_object_storage_clone;
spl_handler_SplObjectStorage.get_gc = spl_object_storage_get_gc;
spl_handler_SplObjectStorage.dtor_obj = zend_objects_destroy_object;
spl_handler_SplObjectStorage.free_obj = spl_SplObjectStorage_free_storage;
REGISTER_SPL_IMPLEMENTS(SplObjectStorage, Countable);
REGISTER_SPL_IMPLEMENTS(SplObjectStorage, Iterator);
REGISTER_SPL_IMPLEMENTS(SplObjectStorage, Serializable);
REGISTER_SPL_IMPLEMENTS(SplObjectStorage, ArrayAccess);
REGISTER_SPL_STD_CLASS_EX(MultipleIterator, spl_SplObjectStorage_new, spl_funcs_MultipleIterator);
REGISTER_SPL_ITERATOR(MultipleIterator);
REGISTER_SPL_CLASS_CONST_LONG(MultipleIterator, "MIT_NEED_ANY", MIT_NEED_ANY);
REGISTER_SPL_CLASS_CONST_LONG(MultipleIterator, "MIT_NEED_ALL", MIT_NEED_ALL);
REGISTER_SPL_CLASS_CONST_LONG(MultipleIterator, "MIT_KEYS_NUMERIC", MIT_KEYS_NUMERIC);
REGISTER_SPL_CLASS_CONST_LONG(MultipleIterator, "MIT_KEYS_ASSOC", MIT_KEYS_ASSOC);
return SUCCESS;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: fdm=marker
* vim: noet sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5291_0 |
crossvul-cpp_data_good_342_6 | /*
* pkcs15-sc-hsm.c : Initialize PKCS#15 emulation
*
* Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#include "asn1.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strnlen.h"
#include "card-sc-hsm.h"
extern struct sc_aid sc_hsm_aid;
void sc_hsm_set_serialnr(sc_card_t *card, char *serial);
static struct ec_curve curves[] = {
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24},
{ (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24},
{ (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32},
{ (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32},
{ (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24},
{ (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24},
{ (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24},
{ (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49},
{ (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28},
{ (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28},
{ (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28},
{ (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57},
{ (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32},
{ (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32},
{ (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32},
{ (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65},
{ (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40},
{ (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40},
{ (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40},
{ (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81},
{ (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24},
{ (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24},
{ (unsigned char *) "\x01", 1}
},
{
{ (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32},
{ (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32},
{ (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65},
{ (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32},
{ (unsigned char *) "\x01", 1}
},
{
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0},
{ NULL, 0}
}
};
#define C_ASN1_CVC_PUBKEY_SIZE 10
static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = {
{ "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL },
{ "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL },
{ "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_BODY_SIZE 5
static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = {
{ "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL },
{ "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL },
{ "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVCERT_SIZE 3
static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = {
{ "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_CVC_SIZE 2
static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_AUTHREQ_SIZE 4
static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = {
{ "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL },
{ "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL },
{ "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_REQ_SIZE 2
static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = {
{ "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2],
u8 *efbin, size_t *len, int optional)
{
sc_path_t path;
int r;
sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
/* look this up with our AID */
path.aid = sc_hsm_aid;
/* we don't have a pre-known size of the file */
path.count = -1;
if (!p15card->opts.use_file_cache || !efbin
|| SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) {
/* avoid re-selection of SC-HSM */
path.aid.len = 0;
r = sc_select_file(p15card->card, &path, NULL);
if (r < 0) {
sc_log(p15card->card->ctx, "Could not select EF");
} else {
r = sc_read_binary(p15card->card, 0, efbin, *len, 0);
}
if (r < 0) {
sc_log(p15card->card->ctx, "Could not read EF");
if (!optional) {
return r;
}
/* optional files are saved as empty files to avoid card
* transactions. Parsing the file's data will reveal that they were
* missing. */
*len = 0;
} else {
*len = r;
}
if (p15card->opts.use_file_cache) {
/* save this with our AID */
path.aid = sc_hsm_aid;
sc_pkcs15_cache_file(p15card, &path, efbin, *len);
}
}
return SC_SUCCESS;
}
/*
* Decode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card,
const u8 ** buf, size_t *buflen,
sc_cvc_t *cvc)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE];
struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE];
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
unsigned int cla,tag;
size_t taglen;
size_t lenchr = sizeof(cvc->chr);
size_t lencar = sizeof(cvc->car);
size_t lenoutercar = sizeof(cvc->outer_car);
const u8 *tbuf;
int r;
memset(cvc, 0, sizeof(*cvc));
sc_copy_asn1_entry(c_asn1_req, asn1_req);
sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq);
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0);
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0);
sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0);
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0);
sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0);
sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0);
sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0);
/* sc_asn1_print_tags(*buf, *buflen); */
tbuf = *buf;
r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen);
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
/* Determine if we deal with an authenticated request, plain request or certificate */
if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) {
r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen);
} else {
r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen);
}
LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Encode a card verifiable certificate as defined in TR-03110.
*/
int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card,
sc_cvc_t *cvc,
u8 ** buf, size_t *buflen)
{
sc_card_t *card = p15card->card;
struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE];
struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE];
struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE];
struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE];
size_t lenchr;
size_t lencar;
int r;
sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc);
sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert);
sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body);
sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey);
asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL;
asn1_cvcert[1].flags = SC_ASN1_OPTIONAL;
sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1);
if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1);
if (cvc->coefficientB && (cvc->coefficientBlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1);
sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1);
if (cvc->publicPoint && (cvc->publicPointlen > 0)) {
sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1);
}
sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1);
}
if (cvc->modulusSize > 0) {
sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1);
}
sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1);
lencar = strnlen(cvc->car, sizeof cvc->car);
sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1);
sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1);
lenchr = strnlen(cvc->chr, sizeof cvc->chr);
sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1);
sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1);
if (cvc->signature && (cvc->signatureLen > 0)) {
sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1);
}
sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1);
r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen);
LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) {
*curve = &curves[i];
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid)
{
int i;
for (i = 0; curves[i].oid.value; i++) {
if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) {
*oid = &curves[i].oid;
return SC_SUCCESS;
}
}
return SC_ERROR_INVALID_DATA;
}
static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
pubkey->algorithm = SC_ALGORITHM_RSA;
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id)
return SC_ERROR_OUT_OF_MEMORY;
pubkey->alg_id->algorithm = SC_ALGORITHM_RSA;
pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen;
pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len);
pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen;
pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len);
if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len);
memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len);
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
struct sc_ec_parameters *ecp;
const struct sc_lv_data *oid;
int r;
pubkey->algorithm = SC_ALGORITHM_EC;
r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid);
if (r != SC_SUCCESS)
return r;
ecp = calloc(1, sizeof(struct sc_ec_parameters));
if (!ecp)
return SC_ERROR_OUT_OF_MEMORY;
ecp->der.len = oid->len + 2;
ecp->der.value = calloc(ecp->der.len, 1);
if (!ecp->der.value) {
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
*(ecp->der.value + 0) = 0x06;
*(ecp->der.value + 1) = (u8)oid->len;
memcpy(ecp->der.value + 2, oid->value, oid->len);
ecp->type = 1; // Named curve
pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id));
if (!pubkey->alg_id) {
free(ecp->der.value);
free(ecp);
return SC_ERROR_OUT_OF_MEMORY;
}
pubkey->alg_id->algorithm = SC_ALGORITHM_EC;
pubkey->alg_id->params = ecp;
pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen);
if (!pubkey->u.ec.ecpointQ.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen);
pubkey->u.ec.ecpointQ.len = cvc->publicPointlen;
pubkey->u.ec.params.der.value = malloc(ecp->der.len);
if (!pubkey->u.ec.params.der.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len);
pubkey->u.ec.params.der.len = ecp->der.len;
/* FIXME: check return value? */
sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params);
return SC_SUCCESS;
}
int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey)
{
if (cvc->publicPoint && cvc->publicPointlen) {
return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey);
} else {
return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey);
}
}
void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc)
{
if (cvc->signature) {
free(cvc->signature);
cvc->signature = NULL;
}
if (cvc->primeOrModulus) {
free(cvc->primeOrModulus);
cvc->primeOrModulus = NULL;
}
if (cvc->coefficientAorExponent) {
free(cvc->coefficientAorExponent);
cvc->coefficientAorExponent = NULL;
}
if (cvc->coefficientB) {
free(cvc->coefficientB);
cvc->coefficientB = NULL;
}
if (cvc->basePointG) {
free(cvc->basePointG);
cvc->basePointG = NULL;
}
if (cvc->order) {
free(cvc->order);
cvc->order = NULL;
}
if (cvc->publicPoint) {
free(cvc->publicPoint);
cvc->publicPoint = NULL;
}
if (cvc->cofactor) {
free(cvc->cofactor);
cvc->cofactor = NULL;
}
}
static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label)
{
struct sc_context *ctx = p15card->card->ctx;
sc_card_t *card = p15card->card;
sc_pkcs15_pubkey_info_t pubkey_info;
sc_pkcs15_object_t pubkey_obj;
struct sc_pkcs15_pubkey pubkey;
sc_cvc_t cvc;
u8 *cvcpo;
int r;
cvcpo = efbin;
memset(&cvc, 0, sizeof(cvc));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc);
LOG_TEST_RET(ctx, r, "Could decode certificate signing request");
memset(&pubkey, 0, sizeof(pubkey));
r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey);
LOG_TEST_RET(card->ctx, r, "Could not extract public key");
memset(&pubkey_info, 0, sizeof(pubkey_info));
memset(&pubkey_obj, 0, sizeof(pubkey_obj));
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len);
LOG_TEST_RET(ctx, r, "Could not encode public key");
pubkey_info.id = key_info->id;
strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label));
if (pubkey.algorithm == SC_ALGORITHM_RSA) {
pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP;
r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info);
} else {
/* TODO fix if support of non multiple of 8 curves are added */
pubkey_info.field_length = cvc.primeOrModuluslen << 3;
pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY;
r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info);
}
LOG_TEST_RET(ctx, r, "Could not add public key");
sc_pkcs15emu_sc_hsm_free_cvc(&cvc);
sc_pkcs15_erase_pubkey(&pubkey);
return SC_SUCCESS;
}
/*
* Add a key and the key description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t cert_info;
sc_pkcs15_object_t cert_obj;
struct sc_pkcs15_object prkd;
sc_pkcs15_prkey_info_t *key_info;
u8 fid[2];
/* enough to hold a complete certificate */
u8 efbin[4096];
u8 *ptr;
size_t len;
int r;
fid[0] = PRKD_PREFIX;
fid[1] = keyid;
/* Try to select a related EF containing the PKCS#15 description of the key */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
ptr = efbin;
memset(&prkd, 0, sizeof(prkd));
r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
/* All keys require user PIN authentication */
prkd.auth_id.len = 1;
prkd.auth_id.value[0] = 1;
/*
* Set private key flag as all keys are private anyway
*/
prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE;
key_info = (sc_pkcs15_prkey_info_t *)prkd.data;
key_info->key_reference = keyid;
key_info->path.aid.len = 0;
if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) {
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info);
} else {
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info);
}
LOG_TEST_RET(card->ctx, r, "Could not add private key to framework");
/* Check if we also have a certificate for the private key */
fid[0] = EE_CERTIFICATE_PREFIX;
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 0);
LOG_TEST_RET(card->ctx, r, "Could not read EF");
if (efbin[0] == 0x67) { /* Decode CSR and create public key object */
sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label);
free(key_info);
return SC_SUCCESS; /* Ignore any errors */
}
if (efbin[0] != 0x30) {
free(key_info);
return SC_SUCCESS;
}
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id = key_info->id;
sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
cert_info.path.count = -1;
if (p15card->opts.use_file_cache) {
/* look this up with our AID, which should already be cached from the
* call to `read_file`. This may have the side effect that OpenSC's
* caching layer re-selects our applet *if the cached file cannot be
* found/used* and we may loose the authentication status. We assume
* that caching works perfectly without this side effect. */
cert_info.path.aid = sc_hsm_aid;
}
strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
free(key_info);
LOG_TEST_RET(card->ctx, r, "Could not add certificate");
return SC_SUCCESS;
}
/*
* Add a data object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_data_info_t *data_info;
sc_pkcs15_object_t data_obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = DCOD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&data_obj, 0, sizeof(data_obj));
r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD");
data_info = (sc_pkcs15_data_info_t *)data_obj.data;
r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
/*
* Add a unrelated certificate object and description in PKCS#15 format to the framework
*/
static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t *cert_info;
sc_pkcs15_object_t obj;
u8 fid[2];
u8 efbin[512];
const u8 *ptr;
size_t len;
int r;
fid[0] = CD_PREFIX;
fid[1] = id;
/* Try to select a related EF containing the PKCS#15 description of the data */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD");
ptr = efbin;
memset(&obj, 0, sizeof(obj));
r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD");
cert_info = (sc_pkcs15_cert_info_t *)obj.data;
r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info);
LOG_TEST_RET(card->ctx, r, "Could not add data object to framework");
return SC_SUCCESS;
}
static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
int r;
u8 efbin[512];
size_t len;
LOG_FUNC_CALLED(card->ctx);
/* Read token info */
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/*
* Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects
*
*/
static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
if (len > 0) {
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) {
return sc_pkcs15emu_sc_hsm_init(p15card);
} else {
if (p15card->card->type != SC_CARD_TYPE_SC_HSM
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC
&& p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) {
return SC_ERROR_WRONG_CARD;
}
return sc_pkcs15emu_sc_hsm_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_342_6 |
crossvul-cpp_data_good_4233_0 | /* Copyright (C) 2001-2020 Artifex Software, Inc.
All Rights Reserved.
This software is provided AS-IS with no warranty, either express or
implied.
This software is distributed under license and may not be copied,
modified or distributed except as expressly authorized under the terms
of the license contained in the file LICENSE in this distribution.
Refer to licensing information at http://www.artifex.com or contact
Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato,
CA 94945, U.S.A., +1(415)492-9861, for further information.
*/
/* String operators */
#include "memory_.h"
#include "ghost.h"
#include "gsutil.h"
#include "ialloc.h"
#include "iname.h"
#include "ivmspace.h"
#include "oper.h"
#include "store.h"
/* The generic operators (copy, get, put, getinterval, putinterval, */
/* length, and forall) are implemented in zgeneric.c. */
/* <int> .bytestring <bytestring> */
static int
zbytestring(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
byte *sbody;
uint size;
check_int_leu(*op, max_int);
size = (uint)op->value.intval;
sbody = ialloc_bytes(size, ".bytestring");
if (sbody == 0)
return_error(gs_error_VMerror);
make_astruct(op, a_all | icurrent_space, sbody);
memset(sbody, 0, size);
return 0;
}
/* <int> string <string> */
int
zstring(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
byte *sbody;
uint size;
check_type(*op, t_integer);
if (op->value.intval < 0 )
return_error(gs_error_rangecheck);
if (op->value.intval > max_string_size )
return_error(gs_error_limitcheck); /* to match Distiller */
size = op->value.intval;
sbody = ialloc_string(size, "string");
if (sbody == 0)
return_error(gs_error_VMerror);
make_string(op, a_all | icurrent_space, size, sbody);
memset(sbody, 0, size);
return 0;
}
/* <name> .namestring <string> */
static int
znamestring(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
check_type(*op, t_name);
name_string_ref(imemory, op, op);
return 0;
}
/* <string> <pattern> anchorsearch <post> <match> -true- */
/* <string> <pattern> anchorsearch <string> -false- */
static int
zanchorsearch(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
uint size = r_size(op);
check_read_type(*op, t_string);
check_read_type(*op1, t_string);
if (size <= r_size(op1) && !memcmp(op1->value.bytes, op->value.bytes, size)) {
os_ptr op0 = op;
push(1);
*op0 = *op1;
r_set_size(op0, size);
op1->value.bytes += size;
r_dec_size(op1, size);
make_true(op);
} else
make_false(op);
return 0;
}
/* <string> <pattern> (r)search <post> <match> <pre> -true- */
/* <string> <pattern> (r)search <string> -false- */
static int
search_impl(i_ctx_t *i_ctx_p, bool forward)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
uint size = r_size(op);
uint count;
byte *pat;
byte *ptr;
byte ch;
int incr = forward ? 1 : -1;
check_read_type(*op1, t_string);
check_read_type(*op, t_string);
if (size > r_size(op1)) { /* can't match */
make_false(op);
return 0;
}
count = r_size(op1) - size;
ptr = op1->value.bytes;
if (size == 0)
goto found;
if (!forward)
ptr += count;
pat = op->value.bytes;
ch = pat[0];
do {
if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size)))
goto found;
ptr += incr;
}
while (count--);
/* No match */
make_false(op);
return 0;
found:
op->tas.type_attrs = op1->tas.type_attrs;
op->value.bytes = ptr; /* match */
op->tas.rsize = size; /* match */
push(2);
op[-1] = *op1; /* pre */
op[-3].value.bytes = ptr + size; /* post */
if (forward) {
op[-1].tas.rsize = ptr - op[-1].value.bytes; /* pre */
op[-3].tas.rsize = count; /* post */
} else {
op[-1].tas.rsize = count; /* pre */
op[-3].tas.rsize -= count + size; /* post */
}
make_true(op);
return 0;
}
/* Search from the start of the string */
static int
zsearch(i_ctx_t *i_ctx_p)
{
return search_impl(i_ctx_p, true);
}
/* Search from the end of the string */
static int
zrsearch(i_ctx_t *i_ctx_p)
{
return search_impl(i_ctx_p, false);
}
/* <string> <charstring> .stringbreak <int|null> */
static int
zstringbreak(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
uint i, j;
check_read_type(op[-1], t_string);
check_read_type(*op, t_string);
/* We can't use strpbrk here, because C doesn't allow nulls in strings. */
for (i = 0; i < r_size(op - 1); ++i)
for (j = 0; j < r_size(op); ++j)
if (op[-1].value.const_bytes[i] == op->value.const_bytes[j]) {
make_int(op - 1, i);
goto done;
}
make_null(op - 1);
done:
pop(1);
return 0;
}
/* <obj> <pattern> .stringmatch <bool> */
static int
zstringmatch(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
bool result;
check_read_type(*op, t_string);
switch (r_type(op1)) {
case t_string:
check_read(*op1);
goto cmp;
case t_name:
name_string_ref(imemory, op1, op1); /* can't fail */
cmp:
result = string_match(op1->value.const_bytes, r_size(op1),
op->value.const_bytes, r_size(op),
NULL);
break;
default:
result = (r_size(op) == 1 && *op->value.bytes == '*');
}
make_bool(op1, result);
pop(1);
return 0;
}
/* ------ Initialization procedure ------ */
const op_def zstring_op_defs[] =
{
{"1.bytestring", zbytestring},
{"2anchorsearch", zanchorsearch},
{"1.namestring", znamestring},
{"2search", zsearch},
{"2rsearch", zrsearch},
{"1string", zstring},
{"2.stringbreak", zstringbreak},
{"2.stringmatch", zstringmatch},
op_def_end(0)
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4233_0 |
crossvul-cpp_data_bad_2353_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.
*/
/*
* TODO:
* o resolve XXX as much as possible
* o MP support
* o BAP support
*/
#define NETDISSECT_REWORKED
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <tcpdump-stdinc.h>
#ifdef __bsdi__
#include <net/slcompress.h>
#include <net/if_ppp.h>
#endif
#include <stdlib.h>
#include "interface.h"
#include "extract.h"
#include "addrtoname.h"
#include "ppp.h"
#include "chdlc.h"
#include "ethertype.h"
#include "oui.h"
/*
* The following constatns are defined by IANA. Please refer to
* http://www.isi.edu/in-notes/iana/assignments/ppp-numbers
* for the up-to-date information.
*/
/* Protocol Codes defined in ppp.h */
static const struct tok ppptype2str[] = {
{ PPP_IP, "IP" },
{ PPP_OSI, "OSI" },
{ PPP_NS, "NS" },
{ PPP_DECNET, "DECNET" },
{ PPP_APPLE, "APPLE" },
{ PPP_IPX, "IPX" },
{ PPP_VJC, "VJC IP" },
{ PPP_VJNC, "VJNC IP" },
{ PPP_BRPDU, "BRPDU" },
{ PPP_STII, "STII" },
{ PPP_VINES, "VINES" },
{ PPP_MPLS_UCAST, "MPLS" },
{ PPP_MPLS_MCAST, "MPLS" },
{ PPP_COMP, "Compressed"},
{ PPP_ML, "MLPPP"},
{ PPP_IPV6, "IP6"},
{ PPP_HELLO, "HELLO" },
{ PPP_LUXCOM, "LUXCOM" },
{ PPP_SNS, "SNS" },
{ PPP_IPCP, "IPCP" },
{ PPP_OSICP, "OSICP" },
{ PPP_NSCP, "NSCP" },
{ PPP_DECNETCP, "DECNETCP" },
{ PPP_APPLECP, "APPLECP" },
{ PPP_IPXCP, "IPXCP" },
{ PPP_STIICP, "STIICP" },
{ PPP_VINESCP, "VINESCP" },
{ PPP_IPV6CP, "IP6CP" },
{ PPP_MPLSCP, "MPLSCP" },
{ PPP_LCP, "LCP" },
{ PPP_PAP, "PAP" },
{ PPP_LQM, "LQM" },
{ PPP_CHAP, "CHAP" },
{ PPP_EAP, "EAP" },
{ PPP_SPAP, "SPAP" },
{ PPP_SPAP_OLD, "Old-SPAP" },
{ PPP_BACP, "BACP" },
{ PPP_BAP, "BAP" },
{ PPP_MPCP, "MLPPP-CP" },
{ PPP_CCP, "CCP" },
{ 0, NULL }
};
/* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */
#define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */
#define CPCODES_CONF_REQ 1 /* Configure-Request */
#define CPCODES_CONF_ACK 2 /* Configure-Ack */
#define CPCODES_CONF_NAK 3 /* Configure-Nak */
#define CPCODES_CONF_REJ 4 /* Configure-Reject */
#define CPCODES_TERM_REQ 5 /* Terminate-Request */
#define CPCODES_TERM_ACK 6 /* Terminate-Ack */
#define CPCODES_CODE_REJ 7 /* Code-Reject */
#define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */
#define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */
#define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */
#define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */
#define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */
#define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */
#define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */
#define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */
static const struct tok cpcodes[] = {
{CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */
{CPCODES_CONF_REQ, "Conf-Request"},
{CPCODES_CONF_ACK, "Conf-Ack"},
{CPCODES_CONF_NAK, "Conf-Nack"},
{CPCODES_CONF_REJ, "Conf-Reject"},
{CPCODES_TERM_REQ, "Term-Request"},
{CPCODES_TERM_ACK, "Term-Ack"},
{CPCODES_CODE_REJ, "Code-Reject"},
{CPCODES_PROT_REJ, "Prot-Reject"},
{CPCODES_ECHO_REQ, "Echo-Request"},
{CPCODES_ECHO_RPL, "Echo-Reply"},
{CPCODES_DISC_REQ, "Disc-Req"},
{CPCODES_ID, "Ident"}, /* RFC1570 */
{CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */
{CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */
{CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */
{0, NULL}
};
/* LCP Config Options */
#define LCPOPT_VEXT 0
#define LCPOPT_MRU 1
#define LCPOPT_ACCM 2
#define LCPOPT_AP 3
#define LCPOPT_QP 4
#define LCPOPT_MN 5
#define LCPOPT_DEP6 6
#define LCPOPT_PFC 7
#define LCPOPT_ACFC 8
#define LCPOPT_FCSALT 9
#define LCPOPT_SDP 10
#define LCPOPT_NUMMODE 11
#define LCPOPT_DEP12 12
#define LCPOPT_CBACK 13
#define LCPOPT_DEP14 14
#define LCPOPT_DEP15 15
#define LCPOPT_DEP16 16
#define LCPOPT_MLMRRU 17
#define LCPOPT_MLSSNHF 18
#define LCPOPT_MLED 19
#define LCPOPT_PROP 20
#define LCPOPT_DCEID 21
#define LCPOPT_MPP 22
#define LCPOPT_LD 23
#define LCPOPT_LCPAOPT 24
#define LCPOPT_COBS 25
#define LCPOPT_PE 26
#define LCPOPT_MLHF 27
#define LCPOPT_I18N 28
#define LCPOPT_SDLOS 29
#define LCPOPT_PPPMUX 30
#define LCPOPT_MIN LCPOPT_VEXT
#define LCPOPT_MAX LCPOPT_PPPMUX
static const char *lcpconfopts[] = {
"Vend-Ext", /* (0) */
"MRU", /* (1) */
"ACCM", /* (2) */
"Auth-Prot", /* (3) */
"Qual-Prot", /* (4) */
"Magic-Num", /* (5) */
"deprecated(6)", /* used to be a Quality Protocol */
"PFC", /* (7) */
"ACFC", /* (8) */
"FCS-Alt", /* (9) */
"SDP", /* (10) */
"Num-Mode", /* (11) */
"deprecated(12)", /* used to be a Multi-Link-Procedure*/
"Call-Back", /* (13) */
"deprecated(14)", /* used to be a Connect-Time */
"deprecated(15)", /* used to be a Compund-Frames */
"deprecated(16)", /* used to be a Nominal-Data-Encap */
"MRRU", /* (17) */
"12-Bit seq #", /* (18) */
"End-Disc", /* (19) */
"Proprietary", /* (20) */
"DCE-Id", /* (21) */
"MP+", /* (22) */
"Link-Disc", /* (23) */
"LCP-Auth-Opt", /* (24) */
"COBS", /* (25) */
"Prefix-elision", /* (26) */
"Multilink-header-Form",/* (27) */
"I18N", /* (28) */
"SDL-over-SONET/SDH", /* (29) */
"PPP-Muxing", /* (30) */
};
/* ECP - to be supported */
/* CCP Config Options */
#define CCPOPT_OUI 0 /* RFC1962 */
#define CCPOPT_PRED1 1 /* RFC1962 */
#define CCPOPT_PRED2 2 /* RFC1962 */
#define CCPOPT_PJUMP 3 /* RFC1962 */
/* 4-15 unassigned */
#define CCPOPT_HPPPC 16 /* RFC1962 */
#define CCPOPT_STACLZS 17 /* RFC1974 */
#define CCPOPT_MPPC 18 /* RFC2118 */
#define CCPOPT_GFZA 19 /* RFC1962 */
#define CCPOPT_V42BIS 20 /* RFC1962 */
#define CCPOPT_BSDCOMP 21 /* RFC1977 */
/* 22 unassigned */
#define CCPOPT_LZSDCP 23 /* RFC1967 */
#define CCPOPT_MVRCA 24 /* RFC1975 */
#define CCPOPT_DEC 25 /* RFC1976 */
#define CCPOPT_DEFLATE 26 /* RFC1979 */
/* 27-254 unassigned */
#define CCPOPT_RESV 255 /* RFC1962 */
static const struct tok ccpconfopts_values[] = {
{ CCPOPT_OUI, "OUI" },
{ CCPOPT_PRED1, "Pred-1" },
{ CCPOPT_PRED2, "Pred-2" },
{ CCPOPT_PJUMP, "Puddle" },
{ CCPOPT_HPPPC, "HP-PPC" },
{ CCPOPT_STACLZS, "Stac-LZS" },
{ CCPOPT_MPPC, "MPPC" },
{ CCPOPT_GFZA, "Gand-FZA" },
{ CCPOPT_V42BIS, "V.42bis" },
{ CCPOPT_BSDCOMP, "BSD-Comp" },
{ CCPOPT_LZSDCP, "LZS-DCP" },
{ CCPOPT_MVRCA, "MVRCA" },
{ CCPOPT_DEC, "DEC" },
{ CCPOPT_DEFLATE, "Deflate" },
{ CCPOPT_RESV, "Reserved"},
{0, NULL}
};
/* BACP Config Options */
#define BACPOPT_FPEER 1 /* RFC2125 */
static const struct tok bacconfopts_values[] = {
{ BACPOPT_FPEER, "Favored-Peer" },
{0, NULL}
};
/* SDCP - to be supported */
/* IPCP Config Options */
#define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */
#define IPCPOPT_IPCOMP 2 /* RFC1332 */
#define IPCPOPT_ADDR 3 /* RFC1332 */
#define IPCPOPT_MOBILE4 4 /* RFC2290 */
#define IPCPOPT_PRIDNS 129 /* RFC1877 */
#define IPCPOPT_PRINBNS 130 /* RFC1877 */
#define IPCPOPT_SECDNS 131 /* RFC1877 */
#define IPCPOPT_SECNBNS 132 /* RFC1877 */
static const struct tok ipcpopt_values[] = {
{ IPCPOPT_2ADDR, "IP-Addrs" },
{ IPCPOPT_IPCOMP, "IP-Comp" },
{ IPCPOPT_ADDR, "IP-Addr" },
{ IPCPOPT_MOBILE4, "Home-Addr" },
{ IPCPOPT_PRIDNS, "Pri-DNS" },
{ IPCPOPT_PRINBNS, "Pri-NBNS" },
{ IPCPOPT_SECDNS, "Sec-DNS" },
{ IPCPOPT_SECNBNS, "Sec-NBNS" },
{ 0, NULL }
};
#define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */
#define IPCPOPT_IPCOMP_MINLEN 14
static const struct tok ipcpopt_compproto_values[] = {
{ PPP_VJC, "VJ-Comp" },
{ IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" },
{ 0, NULL }
};
static const struct tok ipcpopt_compproto_subopt_values[] = {
{ 1, "RTP-Compression" },
{ 2, "Enhanced RTP-Compression" },
{ 0, NULL }
};
/* IP6CP Config Options */
#define IP6CP_IFID 1
static const struct tok ip6cpopt_values[] = {
{ IP6CP_IFID, "Interface-ID" },
{ 0, NULL }
};
/* ATCP - to be supported */
/* OSINLCP - to be supported */
/* BVCP - to be supported */
/* BCP - to be supported */
/* IPXCP - to be supported */
/* MPLSCP - to be supported */
/* Auth Algorithms */
/* 0-4 Reserved (RFC1994) */
#define AUTHALG_CHAPMD5 5 /* RFC1994 */
#define AUTHALG_MSCHAP1 128 /* RFC2433 */
#define AUTHALG_MSCHAP2 129 /* RFC2795 */
static const struct tok authalg_values[] = {
{ AUTHALG_CHAPMD5, "MD5" },
{ AUTHALG_MSCHAP1, "MS-CHAPv1" },
{ AUTHALG_MSCHAP2, "MS-CHAPv2" },
{ 0, NULL }
};
/* FCS Alternatives - to be supported */
/* Multilink Endpoint Discriminator (RFC1717) */
#define MEDCLASS_NULL 0 /* Null Class */
#define MEDCLASS_LOCAL 1 /* Locally Assigned */
#define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */
#define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */
#define MEDCLASS_MNB 4 /* PPP Magic Number Block */
#define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */
/* PPP LCP Callback */
#define CALLBACK_AUTH 0 /* Location determined by user auth */
#define CALLBACK_DSTR 1 /* Dialing string */
#define CALLBACK_LID 2 /* Location identifier */
#define CALLBACK_E164 3 /* E.164 number */
#define CALLBACK_X500 4 /* X.500 distinguished name */
#define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */
static const struct tok ppp_callback_values[] = {
{ CALLBACK_AUTH, "UserAuth" },
{ CALLBACK_DSTR, "DialString" },
{ CALLBACK_LID, "LocalID" },
{ CALLBACK_E164, "E.164" },
{ CALLBACK_X500, "X.500" },
{ CALLBACK_CBCP, "CBCP" },
{ 0, NULL }
};
/* CHAP */
#define CHAP_CHAL 1
#define CHAP_RESP 2
#define CHAP_SUCC 3
#define CHAP_FAIL 4
static const struct tok chapcode_values[] = {
{ CHAP_CHAL, "Challenge" },
{ CHAP_RESP, "Response" },
{ CHAP_SUCC, "Success" },
{ CHAP_FAIL, "Fail" },
{ 0, NULL}
};
/* PAP */
#define PAP_AREQ 1
#define PAP_AACK 2
#define PAP_ANAK 3
static const struct tok papcode_values[] = {
{ PAP_AREQ, "Auth-Req" },
{ PAP_AACK, "Auth-ACK" },
{ PAP_ANAK, "Auth-NACK" },
{ 0, NULL }
};
/* BAP */
#define BAP_CALLREQ 1
#define BAP_CALLRES 2
#define BAP_CBREQ 3
#define BAP_CBRES 4
#define BAP_LDQREQ 5
#define BAP_LDQRES 6
#define BAP_CSIND 7
#define BAP_CSRES 8
static int print_lcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ipcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int);
static int print_ccp_config_options(netdissect_options *, const u_char *p, int);
static int print_bacp_config_options(netdissect_options *, const u_char *p, int);
static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length);
/* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */
static void
handle_ctrl_proto(netdissect_options *ndo,
u_int proto, const u_char *pptr, int length)
{
const char *typestr;
u_int code, len;
int (*pfunc)(netdissect_options *, const u_char *, int);
int x, j;
const u_char *tptr;
tptr=pptr;
typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto);
ND_PRINT((ndo, "%s, ", typestr));
if (length < 4) /* FIXME weak boundary checking */
goto trunc;
ND_TCHECK2(*tptr, 2);
code = *tptr++;
ND_PRINT((ndo, "%s (0x%02x), id %u, length %u",
tok2str(cpcodes, "Unknown Opcode",code),
code,
*tptr++, /* ID */
length + 2));
if (!ndo->ndo_vflag)
return;
if (length <= 4)
return; /* there may be a NULL confreq etc. */
ND_TCHECK2(*tptr, 2);
len = EXTRACT_16BITS(tptr);
tptr += 2;
ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr - 2, "\n\t", 6);
switch (code) {
case CPCODES_VEXT:
if (length < 11)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
tptr += 4;
ND_TCHECK2(*tptr, 3);
ND_PRINT((ndo, " Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)),
EXTRACT_24BITS(tptr)));
/* XXX: need to decode Kind and Value(s)? */
break;
case CPCODES_CONF_REQ:
case CPCODES_CONF_ACK:
case CPCODES_CONF_NAK:
case CPCODES_CONF_REJ:
x = len - 4; /* Code(1), Identifier(1) and Length(2) */
do {
switch (proto) {
case PPP_LCP:
pfunc = print_lcp_config_options;
break;
case PPP_IPCP:
pfunc = print_ipcp_config_options;
break;
case PPP_IPV6CP:
pfunc = print_ip6cp_config_options;
break;
case PPP_CCP:
pfunc = print_ccp_config_options;
break;
case PPP_BACP:
pfunc = print_bacp_config_options;
break;
default:
/*
* No print routine for the options for
* this protocol.
*/
pfunc = NULL;
break;
}
if (pfunc == NULL) /* catch the above null pointer if unknown CP */
break;
if ((j = (*pfunc)(ndo, tptr, len)) == 0)
break;
x -= j;
tptr += j;
} while (x > 0);
break;
case CPCODES_TERM_REQ:
case CPCODES_TERM_ACK:
/* XXX: need to decode Data? */
break;
case CPCODES_CODE_REJ:
/* XXX: need to decode Rejected-Packet? */
break;
case CPCODES_PROT_REJ:
if (length < 6)
break;
ND_TCHECK2(*tptr, 2);
ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)",
tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
/* XXX: need to decode Rejected-Information? - hexdump for now */
if (len > 6) {
ND_PRINT((ndo, "\n\t Rejected Packet"));
print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2);
}
break;
case CPCODES_ECHO_REQ:
case CPCODES_ECHO_RPL:
case CPCODES_DISC_REQ:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* XXX: need to decode Data? - hexdump for now */
if (len > 8) {
ND_PRINT((ndo, "\n\t -----trailing data-----"));
ND_TCHECK2(tptr[4], len - 8);
print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8);
}
break;
case CPCODES_ID:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* RFC 1661 says this is intended to be human readable */
if (len > 8) {
ND_PRINT((ndo, "\n\t Message\n\t "));
if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend))
goto trunc;
}
break;
case CPCODES_TIME_REM:
if (length < 12)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4)));
/* XXX: need to decode Message? */
break;
default:
/* XXX this is dirty but we do not get the
* original pointer passed to the begin
* the PPP packet */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2);
break;
}
return;
trunc:
ND_PRINT((ndo, "[|%s]", typestr));
}
/* LCP config options */
static int
print_lcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
lcpconfopts[opt], opt, len));
else
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return 0;
}
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len));
else {
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return len;
}
switch (opt) {
case LCPOPT_VEXT:
if (len < 6) {
ND_PRINT((ndo, " (length bogus, should be >= 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 3);
ND_PRINT((ndo, ": Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)),
EXTRACT_24BITS(p + 2)));
#if 0
ND_TCHECK(p[5]);
ND_PRINT((ndo, ", kind: 0x%02x", p[5]));
ND_PRINT((ndo, ", Value: 0x"));
for (i = 0; i < len - 6; i++) {
ND_TCHECK(p[6 + i]);
ND_PRINT((ndo, "%02x", p[6 + i]));
}
#endif
break;
case LCPOPT_MRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_ACCM:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_AP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2))));
switch (EXTRACT_16BITS(p+2)) {
case PPP_CHAP:
ND_TCHECK(p[4]);
ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4])));
break;
case PPP_PAP: /* fall through */
case PPP_EAP:
case PPP_SPAP:
case PPP_SPAP_OLD:
break;
default:
print_unknown_data(ndo, p, "\n\t", len);
}
break;
case LCPOPT_QP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
if (EXTRACT_16BITS(p+2) == PPP_LQM)
ND_PRINT((ndo, ": LQR"));
else
ND_PRINT((ndo, ": unknown"));
break;
case LCPOPT_MN:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_PFC:
break;
case LCPOPT_ACFC:
break;
case LCPOPT_LD:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_CBACK:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_PRINT((ndo, ": "));
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Callback Operation %s (%u)",
tok2str(ppp_callback_values, "Unknown", p[2]),
p[2]));
break;
case LCPOPT_MLMRRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_MLED:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_TCHECK(p[2]);
switch (p[2]) { /* class */
case MEDCLASS_NULL:
ND_PRINT((ndo, ": Null"));
break;
case MEDCLASS_LOCAL:
ND_PRINT((ndo, ": Local")); /* XXX */
break;
case MEDCLASS_IPV4:
if (len != 7) {
ND_PRINT((ndo, " (length bogus, should be = 7)"));
return 0;
}
ND_TCHECK2(*(p + 3), 4);
ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3)));
break;
case MEDCLASS_MAC:
if (len != 9) {
ND_PRINT((ndo, " (length bogus, should be = 9)"));
return 0;
}
ND_TCHECK2(*(p + 3), 6);
ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3)));
break;
case MEDCLASS_MNB:
ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */
break;
case MEDCLASS_PSNDN:
ND_PRINT((ndo, ": PSNDN")); /* XXX */
break;
default:
ND_PRINT((ndo, ": Unknown class %u", p[2]));
break;
}
break;
/* XXX: to be supported */
#if 0
case LCPOPT_DEP6:
case LCPOPT_FCSALT:
case LCPOPT_SDP:
case LCPOPT_NUMMODE:
case LCPOPT_DEP12:
case LCPOPT_DEP14:
case LCPOPT_DEP15:
case LCPOPT_DEP16:
case LCPOPT_MLSSNHF:
case LCPOPT_PROP:
case LCPOPT_DCEID:
case LCPOPT_MPP:
case LCPOPT_LCPAOPT:
case LCPOPT_COBS:
case LCPOPT_PE:
case LCPOPT_MLHF:
case LCPOPT_I18N:
case LCPOPT_SDLOS:
case LCPOPT_PPPMUX:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|lcp]"));
return 0;
}
/* ML-PPP*/
static const struct tok ppp_ml_flag_values[] = {
{ 0x80, "begin" },
{ 0x40, "end" },
{ 0, NULL }
};
static void
handle_mlppp(netdissect_options *ndo,
const u_char *p, int length) {
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
/* CHAP */
static void
handle_chap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int val_size, name_size, msg_size;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|chap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|chap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "CHAP, %s (0x%02x)",
tok2str(chapcode_values,"unknown",code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
/*
* Note that this is a generic CHAP decoding routine. Since we
* don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1,
* MS-CHAPv2) is used at this point, we can't decode packet
* specifically to each algorithms. Instead, we simply decode
* the GCD (Gratest Common Denominator) for all algorithms.
*/
switch (code) {
case CHAP_CHAL:
case CHAP_RESP:
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
val_size = *p; /* value size */
p++;
if (length - (p - p0) < val_size)
return;
ND_PRINT((ndo, ", Value "));
for (i = 0; i < val_size; i++) {
ND_TCHECK(*p);
ND_PRINT((ndo, "%02x", *p++));
}
name_size = len - (p - p0);
ND_PRINT((ndo, ", Name "));
for (i = 0; i < name_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case CHAP_SUCC:
case CHAP_FAIL:
msg_size = len - (p - p0);
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|chap]"));
}
/* PAP (see RFC 1334) */
static void
handle_pap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int peerid_len, passwd_len, msg_len;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|pap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|pap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "PAP, %s (0x%02x)",
tok2str(papcode_values, "unknown", code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
if ((int)len > length) {
ND_PRINT((ndo, ", length %u > packet size", len));
return;
}
length = len;
if (length < (p - p0)) {
ND_PRINT((ndo, ", length %u < PAP header length", length));
return;
}
switch (code) {
case PAP_AREQ:
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:
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
msg_len = *p; /* Msg-Length */
p++;
if (length - (p - p0) < msg_len)
return;
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pap]"));
}
/* BAP */
static void
handle_bap(netdissect_options *ndo _U_,
const u_char *p _U_, int length _U_)
{
/* XXX: to be supported!! */
}
/* IPCP config options */
static int
print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
/* IP6CP config options */
static int
print_ip6cp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IP6CP_IFID:
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 2), 8);
ND_PRINT((ndo, ": %04x:%04x:%04x:%04x",
EXTRACT_16BITS(p + 2),
EXTRACT_16BITS(p + 4),
EXTRACT_16BITS(p + 6),
EXTRACT_16BITS(p + 8)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ip6cp]"));
return 0;
}
/* CCP config options */
static int
print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unkown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
/* BACP config options */
static int
print_bacp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case BACPOPT_FPEER:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|bacp]"));
return 0;
}
static void
ppp_hdlc(netdissect_options *ndo,
const u_char *p, int length)
{
u_char *b, *s, *t, c;
int i, proto;
const void *se;
if (length <= 0)
return;
b = (uint8_t *)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 = (u_char *)p, t = b, i = length; i > 0; i--) {
c = *s++;
if (c == 0x7d) {
if (i > 1) {
i--;
c = *s++ ^ 0x20;
} else
continue;
}
*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, 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 (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-119/c/bad_2353_0 |
crossvul-cpp_data_good_344_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by David Mattes <david.mattes@boeing.com> */
/* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "internal.h"
#include "pkcs15.h"
#define MANU_ID "Gemplus"
#define APPLET_NAME "GemSAFE V1"
#define DRIVER_SERIAL_NUMBER "v0.9"
#define GEMSAFE_APP_PATH "3F001600"
#define GEMSAFE_PATH "3F0016000004"
/* Apparently, the Applet max read "quanta" is 248 bytes
* Gemalto ClassicClient reads files in chunks of 238 bytes
*/
#define GEMSAFE_READ_QUANTUM 248
#define GEMSAFE_MAX_OBJLEN 28672
int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *);
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags);
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags);
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags);
typedef struct cdata_st {
char *label;
int authority;
const char *path;
size_t index;
size_t count;
const char *id;
int obj_flags;
} cdata;
const unsigned int gemsafe_cert_max = 12;
cdata gemsafe_cert[] = {
{"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE},
{"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE},
};
typedef struct pdata_st {
const u8 atr[SC_MAX_ATR_SIZE];
const size_t atr_len;
const char *id;
const char *label;
const char *path;
const int ref;
const int type;
const unsigned int maxlen;
const unsigned int minlen;
const int flags;
const int tries_left;
const char pad_char;
const int obj_flags;
} pindata;
const unsigned int gemsafe_pin_max = 2;
const pindata gemsafe_pin[] = {
/* ATR-specific PIN policies, first match found is used: */
{ {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65,
0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC,
8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE },
/* default PIN policy comes last: */
{ { 0 }, 0,
"01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD,
16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL,
3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }
};
typedef struct prdata_st {
const char *id;
char *label;
unsigned int modulus_len;
int usage;
const char *path;
int ref;
const char *auth_id;
int obj_flags;
} prdata;
#define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION
#define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP
#define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \
SC_PKCS15_PRKEY_USAGE_DECRYPT | \
SC_PKCS15_PRKEY_USAGE_WRAP | \
SC_PKCS15_PRKEY_USAGE_UNWRAP | \
SC_PKCS15_PRKEY_USAGE_SIGN
prdata gemsafe_prkeys[] = {
{ "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE},
{ "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE},
};
static int gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01 && i < gemsafe_cert_max) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
static int gemsafe_detect_card( sc_pkcs15_card_t *p15card)
{
if (strcmp(p15card->card->name, "GemSAFE V1"))
return SC_ERROR_WRONG_CARD;
return SC_SUCCESS;
}
static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card)
{
int r;
unsigned int i;
struct sc_path path;
struct sc_file *file = NULL;
struct sc_card *card = p15card->card;
struct sc_apdu apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_log(p15card->card->ctx, "Setting pkcs15 parameters");
if (p15card->tokeninfo->label)
free(p15card->tokeninfo->label);
p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1);
if (!p15card->tokeninfo->label)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->label, APPLET_NAME);
if (p15card->tokeninfo->serial_number)
free(p15card->tokeninfo->serial_number);
p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1);
if (!p15card->tokeninfo->serial_number)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER);
/* the GemSAFE applet version number */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
/* Manual says Le=0x05, but should be 0x08 to return full version number */
apdu.le = 0x08;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* the manufacturer ID, in this case GemPlus */
if (p15card->tokeninfo->manufacturer_id)
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1);
if (!p15card->tokeninfo->manufacturer_id)
return SC_ERROR_INTERNAL;
strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID);
/* determine allocated key containers and length of certificates */
r = gemsafe_get_cert_len(card);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
/* set certs */
sc_log(p15card->card->ctx, "Setting certificates");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
if (gemsafe_cert[i].label == NULL)
continue;
sc_format_path(gemsafe_cert[i].path, &path);
sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id);
path.index = gemsafe_cert[i].index;
path.count = gemsafe_cert[i].count;
sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509,
gemsafe_cert[i].authority, &path, &p15Id,
gemsafe_cert[i].label, gemsafe_cert[i].obj_flags);
}
/* set gemsafe_pin */
sc_log(p15card->card->ctx, "Setting PIN");
for (i=0; i < gemsafe_pin_max; i++) {
struct sc_pkcs15_id p15Id;
struct sc_path path;
sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id);
sc_format_path(gemsafe_pin[i].path, &path);
if (gemsafe_pin[i].atr_len == 0 ||
(gemsafe_pin[i].atr_len == p15card->card->atr.len &&
memcmp(p15card->card->atr.value, gemsafe_pin[i].atr,
p15card->card->atr.len) == 0)) {
sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label,
&path, gemsafe_pin[i].ref, gemsafe_pin[i].type,
gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen,
gemsafe_pin[i].flags, gemsafe_pin[i].tries_left,
gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags);
break;
}
};
/* set private keys */
sc_log(p15card->card->ctx, "Setting private keys");
for (i = 0; i < gemsafe_cert_max; i++) {
struct sc_pkcs15_id p15Id, authId, *pauthId;
struct sc_path path;
int key_ref = 0x03;
if (gemsafe_prkeys[i].label == NULL)
continue;
sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id);
if (gemsafe_prkeys[i].auth_id) {
sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId);
pauthId = &authId;
} else
pauthId = NULL;
sc_format_path(gemsafe_prkeys[i].path, &path);
/*
* The key ref may be different for different sites;
* by adding flags=n where the low order 4 bits can be
* the key ref we can force it.
*/
if ( p15card->card->flags & 0x0F) {
key_ref = p15card->card->flags & 0x0F;
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Overriding key_ref %d with %d\n",
gemsafe_prkeys[i].ref, key_ref);
} else
key_ref = gemsafe_prkeys[i].ref;
sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label,
SC_PKCS15_TYPE_PRKEY_RSA,
gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage,
&path, key_ref, pauthId,
gemsafe_prkeys[i].obj_flags);
}
/* select the application DF */
sc_log(p15card->card->ctx, "Selecting application DF");
sc_format_path(GEMSAFE_APP_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* set the application DF */
if (p15card->file_app)
free(p15card->file_app);
p15card->file_app = file;
return SC_SUCCESS;
}
int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_gemsafeV1_init(p15card);
else {
int r = gemsafe_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_gemsafeV1_init(p15card);
}
}
static sc_pkcs15_df_t *
sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type)
{
sc_pkcs15_df_t *df;
sc_file_t *file;
int created = 0;
while (1) {
for (df = p15card->df_list; df; df = df->next) {
if (df->type == type) {
if (created)
df->enumerated = 1;
return df;
}
}
assert(created == 0);
file = sc_file_new();
if (!file)
return NULL;
sc_format_path("11001101", &file->path);
sc_pkcs15_add_df(p15card, type, &file->path);
sc_file_free(file);
created++;
}
}
static int
sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type,
const char *label, void *data,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_object_t *obj;
int df_type;
obj = calloc(1, sizeof(*obj));
obj->type = type;
obj->data = data;
if (label)
strncpy(obj->label, label, sizeof(obj->label)-1);
obj->flags = obj_flags;
if (auth_id)
obj->auth_id = *auth_id;
switch (type & SC_PKCS15_TYPE_CLASS_MASK) {
case SC_PKCS15_TYPE_AUTH:
df_type = SC_PKCS15_AODF;
break;
case SC_PKCS15_TYPE_PRKEY:
df_type = SC_PKCS15_PRKDF;
break;
case SC_PKCS15_TYPE_PUBKEY:
df_type = SC_PKCS15_PUKDF;
break;
case SC_PKCS15_TYPE_CERT:
df_type = SC_PKCS15_CDF;
break;
default:
sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type);
free(obj);
return SC_ERROR_INVALID_ARGUMENTS;
}
obj->df = sc_pkcs15emu_get_df(p15card, df_type);
sc_pkcs15_add_object(p15card, obj);
return 0;
}
static int
sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id, const char *label,
const sc_path_t *path, int ref, int type,
unsigned int min_length,
unsigned int max_length,
int flags, int tries_left, const char pad_char, int obj_flags)
{
sc_pkcs15_auth_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
info->auth_method = SC_AC_CHV;
info->auth_id = *id;
info->attrs.pin.min_length = min_length;
info->attrs.pin.max_length = max_length;
info->attrs.pin.stored_length = max_length;
info->attrs.pin.type = type;
info->attrs.pin.reference = ref;
info->attrs.pin.flags = flags;
info->attrs.pin.pad_char = pad_char;
info->tries_left = tries_left;
info->logged_in = SC_PIN_STATE_UNKNOWN;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card,
int type, int authority,
const sc_path_t *path,
const sc_pkcs15_id_t *id,
const char *label, int obj_flags)
{
sc_pkcs15_cert_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->authority = authority;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags);
}
static int
sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card,
const sc_pkcs15_id_t *id,
const char *label,
int type, unsigned int modulus_length, int usage,
const sc_path_t *path, int ref,
const sc_pkcs15_id_t *auth_id, int obj_flags)
{
sc_pkcs15_prkey_info_t *info;
info = calloc(1, sizeof(*info));
if (!info)
{
LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
info->id = *id;
info->modulus_length = modulus_length;
info->usage = usage;
info->native = 1;
info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE
| SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE
| SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE
| SC_PKCS15_PRKEY_ACCESS_LOCAL;
info->key_reference = ref;
if (path)
info->path = *path;
return sc_pkcs15emu_add_object(p15card, type, label,
info, auth_id, obj_flags);
}
/* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_344_5 |
crossvul-cpp_data_bad_3111_0 | /**********************************************************************
* $Id$
*
* Project: MapServer
* Purpose: OGC Filter Encoding implementation
* Author: Y. Assefa, DM Solutions Group (assefa@dmsolutions.ca)
*
**********************************************************************
* Copyright (c) 2003, Y. Assefa, DM Solutions Group Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies of this Software or works derived from this 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
****************************************************************************/
#define _GNU_SOURCE
#include "mapserver-config.h"
#ifdef USE_OGR
#include "cpl_minixml.h"
#include "cpl_string.h"
#endif
#include "mapogcfilter.h"
#include "mapserver.h"
#include "mapowscommon.h"
#include "maptime.h"
#include "mapows.h"
#include <ctype.h>
#if 0
static int FLTHasUniqueTopLevelDuringFilter(FilterEncodingNode *psFilterNode);
#endif
int FLTIsNumeric(const char *pszValue)
{
if (pszValue != NULL && *pszValue != '\0' && !isspace(*pszValue)) {
/*the regex seems to have a problem on windows when mapserver is built using
PHP regex*/
#if defined(_WIN32) && !defined(__CYGWIN__)
int i = 0, nLength=0, bString=0;
nLength = strlen(pszValue);
for (i=0; i<nLength; i++) {
if (i == 0) {
if (!isdigit(pszValue[i]) && pszValue[i] != '-') {
bString = 1;
break;
}
} else if (!isdigit(pszValue[i]) && pszValue[i] != '.') {
bString = 1;
break;
}
}
if (!bString)
return MS_TRUE;
#else
char * p;
strtod(pszValue, &p);
if ( p != pszValue && *p == '\0') return MS_TRUE;
#endif
}
return MS_FALSE;
}
/*
** Apply an expression to the layer's filter element.
**
*/
int FLTApplyExpressionToLayer(layerObj *lp, const char *pszExpression)
{
char *pszFinalExpression=NULL, *pszBuffer = NULL;
/*char *escapedTextString=NULL;*/
int bConcatWhere=0, bHasAWhere=0;
if (lp && pszExpression) {
if (lp->connectiontype == MS_POSTGIS || lp->connectiontype == MS_ORACLESPATIAL ||
lp->connectiontype == MS_PLUGIN) {
pszFinalExpression = msStrdup("(");
pszFinalExpression = msStringConcatenate(pszFinalExpression, pszExpression);
pszFinalExpression = msStringConcatenate(pszFinalExpression, ")");
} else if (lp->connectiontype == MS_OGR) {
pszFinalExpression = msStrdup(pszExpression);
if (lp->filter.type != MS_EXPRESSION) {
bConcatWhere = 1;
} else {
if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6)) {
bHasAWhere = 1;
bConcatWhere =1;
}
}
} else
pszFinalExpression = msStrdup(pszExpression);
if (bConcatWhere)
pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
/* if the filter is set and it's an expression type, concatenate it with
this filter. If not just free it */
if (lp->filter.string && lp->filter.type == MS_EXPRESSION) {
pszBuffer = msStringConcatenate(pszBuffer, "((");
if (bHasAWhere)
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
else
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
pszBuffer = msStringConcatenate(pszBuffer, ") and ");
} else if (lp->filter.string)
msFreeExpression(&lp->filter);
pszBuffer = msStringConcatenate(pszBuffer, pszFinalExpression);
if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
pszBuffer = msStringConcatenate(pszBuffer, ")");
/*assuming that expression was properly escaped
escapedTextString = msStringEscape(pszBuffer);
msLoadExpressionString(&lp->filter,
(char*)CPLSPrintf("%s", escapedTextString));
msFree(escapedTextString);
*/
msLoadExpressionString(&lp->filter, pszBuffer);
msFree(pszFinalExpression);
if (pszBuffer)
msFree(pszBuffer);
return MS_TRUE;
}
return MS_FALSE;
}
char *FLTGetExpressionForValuesRanges(layerObj *lp, const char *item, const char *value, int forcecharcter)
{
int bIscharacter, bSqlLayer=MS_FALSE;
char *pszExpression = NULL, *pszEscapedStr=NULL, *pszTmpExpression=NULL;
char **paszElements = NULL, **papszRangeElements=NULL;
int numelements,i,nrangeelements;
/* TODO: remove the bSqlLayer checks since we want to write MapServer expressions only. */
/* double minval, maxval; */
if (lp && item && value) {
if (strstr(value, "/") == NULL) {
/*value(s)*/
paszElements = msStringSplit (value, ',', &numelements);
if (paszElements && numelements > 0) {
if (forcecharcter)
bIscharacter = MS_TRUE;
bIscharacter= !FLTIsNumeric(paszElements[0]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
for (i=0; i<numelements; i++) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
if (bIscharacter)
pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
if (bIscharacter)
pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
}
if (bIscharacter) {
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = '");
else
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = \"");
} else
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = ");
pszEscapedStr = msLayerEscapeSQLParam(lp, paszElements[i]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
if (bIscharacter) {
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, "'");
else
pszTmpExpression = msStringConcatenate(pszTmpExpression, "\"");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
pszExpression = msStringConcatenate(pszExpression, pszTmpExpression);
msFree(pszTmpExpression);
pszTmpExpression = NULL;
}
pszExpression = msStringConcatenate(pszExpression, ")");
}
msFreeCharArray(paszElements, numelements);
} else {
/*range(s)*/
paszElements = msStringSplit (value, ',', &numelements);
if (paszElements && numelements > 0) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
for (i=0; i<numelements; i++) {
papszRangeElements = msStringSplit (paszElements[i], '/', &nrangeelements);
if (papszRangeElements && nrangeelements > 0) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
if (nrangeelements == 2 || nrangeelements == 3) {
/*
minval = atof(papszRangeElements[0]);
maxval = atof(papszRangeElements[1]);
*/
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, " >= ");
pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[0]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
pszTmpExpression = msStringConcatenate(pszTmpExpression, " AND ");
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, " <= ");
pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[1]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
} else if (nrangeelements == 1) {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "(");
if (bSqlLayer)
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
else {
pszTmpExpression = msStringConcatenate(pszTmpExpression, "[");
pszTmpExpression = msStringConcatenate(pszTmpExpression, item);
pszTmpExpression = msStringConcatenate(pszTmpExpression, "]");
}
pszTmpExpression = msStringConcatenate(pszTmpExpression, " = ");
pszEscapedStr = msLayerEscapeSQLParam(lp, papszRangeElements[0]);
pszTmpExpression = msStringConcatenate(pszTmpExpression, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
pszTmpExpression = msStringConcatenate(pszTmpExpression, ")");
}
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
pszExpression = msStringConcatenate(pszExpression, pszTmpExpression);
msFree(pszTmpExpression);
pszTmpExpression = NULL;
}
msFreeCharArray(papszRangeElements, nrangeelements);
}
pszExpression = msStringConcatenate(pszExpression, ")");
}
msFreeCharArray(paszElements, numelements);
}
}
msFree(pszTmpExpression);
return pszExpression;
}
#ifdef USE_OGR
int FLTogrConvertGeometry(OGRGeometryH hGeometry, shapeObj *psShape,
OGRwkbGeometryType nType)
{
return msOGRGeometryToShape(hGeometry, psShape, nType);
}
static
int FLTShapeFromGMLTree(CPLXMLNode *psTree, shapeObj *psShape , char **ppszSRS)
{
const char *pszSRS = NULL;
if (psTree && psShape) {
CPLXMLNode *psNext = psTree->psNext;
OGRGeometryH hGeometry = NULL;
psTree->psNext = NULL;
hGeometry = OGR_G_CreateFromGMLTree(psTree );
psTree->psNext = psNext;
if (hGeometry) {
OGRwkbGeometryType nType;
nType = OGR_G_GetGeometryType(hGeometry);
if (nType == wkbPolygon25D || nType == wkbMultiPolygon25D)
nType = wkbPolygon;
else if (nType == wkbLineString25D || nType == wkbMultiLineString25D)
nType = wkbLineString;
else if (nType == wkbPoint25D || nType == wkbMultiPoint25D)
nType = wkbPoint;
FLTogrConvertGeometry(hGeometry, psShape, nType);
OGR_G_DestroyGeometry(hGeometry);
pszSRS = CPLGetXMLValue(psTree, "srsName", NULL);
if (ppszSRS && pszSRS)
*ppszSRS = msStrdup(pszSRS);
return MS_TRUE;
}
}
return MS_FALSE;
}
int FLTGetGeosOperator(char *pszValue)
{
if (!pszValue)
return -1;
if (strcasecmp(pszValue, "Equals") == 0)
return MS_GEOS_EQUALS;
else if (strcasecmp(pszValue, "Intersect") == 0 ||
strcasecmp(pszValue, "Intersects") == 0)
return MS_GEOS_INTERSECTS;
else if (strcasecmp(pszValue, "Disjoint") == 0)
return MS_GEOS_DISJOINT;
else if (strcasecmp(pszValue, "Touches") == 0)
return MS_GEOS_TOUCHES;
else if (strcasecmp(pszValue, "Crosses") == 0)
return MS_GEOS_CROSSES;
else if (strcasecmp(pszValue, "Within") == 0)
return MS_GEOS_WITHIN;
else if (strcasecmp(pszValue, "Contains") == 0)
return MS_GEOS_CONTAINS;
else if (strcasecmp(pszValue, "Overlaps") == 0)
return MS_GEOS_OVERLAPS;
else if (strcasecmp(pszValue, "Beyond") == 0)
return MS_GEOS_BEYOND;
else if (strcasecmp(pszValue, "DWithin") == 0)
return MS_GEOS_DWITHIN;
return -1;
}
int FLTIsGeosNode(char *pszValue)
{
if (FLTGetGeosOperator(pszValue) == -1)
return MS_FALSE;
return MS_TRUE;
}
/************************************************************************/
/* FLTIsSimpleFilterNoSpatial */
/* */
/* Filter encoding with only attribute queries */
/************************************************************************/
int FLTIsSimpleFilterNoSpatial(FilterEncodingNode *psNode)
{
if (FLTIsSimpleFilter(psNode) && FLTNumberOfFilterType(psNode, "BBOX") == 0)
return MS_TRUE;
return MS_FALSE;
}
/************************************************************************/
/* FLTApplySimpleSQLFilter() */
/************************************************************************/
int FLTApplySimpleSQLFilter(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
layerObj *lp = NULL;
char *szExpression = NULL;
rectObj sQueryRect = map->extent;
const char *szEPSG = NULL;
projectionObj sProjTmp;
char *pszBuffer = NULL;
int bConcatWhere = 0;
int bHasAWhere =0;
char *pszTmp = NULL, *pszTmp2 = NULL;
char *tmpfilename = NULL;
const char* pszTimeField = NULL;
const char* pszTimeValue = NULL;
lp = (GET_LAYER(map, iLayerIndex));
/* if there is a bbox use it */
szEPSG = FLTGetBBOX(psNode, &sQueryRect);
if(szEPSG && map->projection.numargs > 0) {
msInitProjection(&sProjTmp);
/* Use the non EPSG variant since axis swapping is done in FLTDoAxisSwappingIfNecessary */
if (msLoadProjectionString(&sProjTmp, szEPSG) == 0) {
msProjectRect(&sProjTmp, &map->projection, &sQueryRect);
}
msFreeProjection(&sProjTmp);
}
if( lp->connectiontype == MS_OGR ) {
pszTimeValue = FLTGetDuring(psNode, &pszTimeField);
}
/* make sure that the layer can be queried*/
if (!lp->template) lp->template = msStrdup("ttt.html");
/* if there is no class, create at least one, so that query by rect would work */
if (lp->numclasses == 0) {
if (msGrowLayerClasses(lp) == NULL)
return MS_FAILURE;
initClass(lp->class[0]);
}
bConcatWhere = 0;
bHasAWhere = 0;
if (lp->connectiontype == MS_POSTGIS || lp->connectiontype == MS_ORACLESPATIAL ||
lp->connectiontype == MS_PLUGIN) {
szExpression = FLTGetSQLExpression(psNode, lp);
if (szExpression) {
pszTmp = msStrdup("(");
pszTmp = msStringConcatenate(pszTmp, szExpression);
pszTmp = msStringConcatenate(pszTmp, ")");
msFree(szExpression);
szExpression = pszTmp;
}
}
/* concatenates the WHERE clause for OGR layers. This only applies if
the expression was empty or not of an expression string. If there
is an sql type expression, it is assumed to have the WHERE clause.
If it is an expression and does not have a WHERE it is assumed to be a mapserver
type expression*/
else if (lp->connectiontype == MS_OGR) {
if (lp->filter.type != MS_EXPRESSION) {
szExpression = FLTGetSQLExpression(psNode, lp);
bConcatWhere = 1;
} else {
if (lp->filter.string && EQUALN(lp->filter.string,"WHERE ",6)) {
szExpression = FLTGetSQLExpression(psNode, lp);
bHasAWhere = 1;
bConcatWhere =1;
} else {
szExpression = FLTGetCommonExpression(psNode, lp);
}
}
} else {
szExpression = FLTGetCommonExpression(psNode, lp);
}
if (szExpression) {
if (bConcatWhere)
pszBuffer = msStringConcatenate(pszBuffer, "WHERE ");
/* if the filter is set and it's an expression type, concatenate it with
this filter. If not just free it */
if (lp->filter.string && lp->filter.type == MS_EXPRESSION) {
pszBuffer = msStringConcatenate(pszBuffer, "((");
if (bHasAWhere)
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string+6);
else
pszBuffer = msStringConcatenate(pszBuffer, lp->filter.string);
pszBuffer = msStringConcatenate(pszBuffer, ") and ");
} else if (lp->filter.string)
msFreeExpression(&lp->filter);
pszBuffer = msStringConcatenate(pszBuffer, szExpression);
if(lp->filter.string && lp->filter.type == MS_EXPRESSION)
pszBuffer = msStringConcatenate(pszBuffer, ")");
msLoadExpressionString(&lp->filter, pszBuffer);
free(szExpression);
}
if (pszTimeField && pszTimeValue)
msLayerSetTimeFilter(lp, pszTimeValue, pszTimeField);
if (pszBuffer)
free(pszBuffer);
map->query.type = MS_QUERY_BY_RECT;
map->query.mode = MS_QUERY_MULTIPLE;
map->query.layer = lp->index;
map->query.rect = sQueryRect;
if(map->debug == MS_DEBUGLEVEL_VVV) {
tmpfilename = msTmpFile(map, map->mappath, NULL, "_filter.map");
if (tmpfilename == NULL) {
tmpfilename = msTmpFile(map, NULL, NULL, "_filter.map" );
}
if (tmpfilename) {
msSaveMap(map,tmpfilename);
msDebug("FLTApplySimpleSQLFilter(): Map file after Filter was applied %s\n", tmpfilename);
msFree(tmpfilename);
}
}
/*for oracle connection, if we have a simple filter with no spatial constraints
we should set the connection function to NONE to have a better performance
(#2725)*/
if (lp->connectiontype == MS_ORACLESPATIAL && FLTIsSimpleFilterNoSpatial(psNode)) {
if (strcasestr(lp->data, "USING") == 0)
lp->data = msStringConcatenate(lp->data, " USING NONE");
else if (strcasestr(lp->data, "NONE") == 0) {
/*if one of the functions is used, just replace it with NONE*/
if (strcasestr(lp->data, "FILTER"))
lp->data = msCaseReplaceSubstring(lp->data, "FILTER", "NONE");
else if (strcasestr(lp->data, "GEOMRELATE"))
lp->data = msCaseReplaceSubstring(lp->data, "GEOMRELATE", "NONE");
else if (strcasestr(lp->data, "RELATE"))
lp->data = msCaseReplaceSubstring(lp->data, "RELATE", "NONE");
else if (strcasestr(lp->data, "VERSION")) {
/*should add NONE just before the VERSION. Cases are:
DATA "ORA_GEOMETRY FROM data USING VERSION 10g
DATA "ORA_GEOMETRY FROM data USING UNIQUE FID VERSION 10g"
*/
pszTmp = (char *)strcasestr(lp->data, "VERSION");
pszTmp2 = msStringConcatenate(pszTmp2, " NONE ");
pszTmp2 = msStringConcatenate(pszTmp2, pszTmp);
lp->data = msCaseReplaceSubstring(lp->data, pszTmp, pszTmp2);
msFree(pszTmp2);
} else if (strcasestr(lp->data, "SRID")) {
lp->data = msStringConcatenate(lp->data, " NONE");
}
}
}
return msQueryByRect(map);
/* return MS_SUCCESS; */
}
/************************************************************************/
/* FLTIsSimpleFilter */
/* */
/* Filter encoding with only attribute queries and only one bbox. */
/************************************************************************/
int FLTIsSimpleFilter(FilterEncodingNode *psNode)
{
if (FLTValidForBBoxFilter(psNode)) {
if (FLTNumberOfFilterType(psNode, "DWithin") == 0 &&
FLTNumberOfFilterType(psNode, "Intersect") == 0 &&
FLTNumberOfFilterType(psNode, "Intersects") == 0 &&
FLTNumberOfFilterType(psNode, "Equals") == 0 &&
FLTNumberOfFilterType(psNode, "Disjoint") == 0 &&
FLTNumberOfFilterType(psNode, "Touches") == 0 &&
FLTNumberOfFilterType(psNode, "Crosses") == 0 &&
FLTNumberOfFilterType(psNode, "Within") == 0 &&
FLTNumberOfFilterType(psNode, "Contains") == 0 &&
FLTNumberOfFilterType(psNode, "Overlaps") == 0 &&
FLTNumberOfFilterType(psNode, "Beyond") == 0)
return TRUE;
}
return FALSE;
}
/************************************************************************/
/* FLTApplyFilterToLayer */
/* */
/* Use the filter encoding node to create mapserver expressions */
/* and apply it to the layer. */
/************************************************************************/
int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
layerObj *layer = GET_LAYER(map, iLayerIndex);
if ( ! layer->vtable) {
int rv = msInitializeVirtualTable(layer);
if (rv != MS_SUCCESS)
return rv;
}
return layer->vtable->LayerApplyFilterToLayer(psNode, map, iLayerIndex);
}
/************************************************************************/
/* FLTLayerApplyCondSQLFilterToLayer */
/* */
/* Helper function for layer virtual table architecture */
/************************************************************************/
int FLTLayerApplyCondSQLFilterToLayer(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
return FLTLayerApplyPlainFilterToLayer(psNode, map, iLayerIndex);
}
/************************************************************************/
/* FLTGetTopBBOX */
/* */
/* Return the "top" BBOX if there's a unique one. */
/************************************************************************/
static int FLTGetTopBBOXInternal(FilterEncodingNode *psNode, FilterEncodingNode** ppsTopBBOX, int *pnCount)
{
if (psNode->pszValue && strcasecmp(psNode->pszValue, "BBOX") == 0) {
(*pnCount) ++;
if( *pnCount == 1 )
{
*ppsTopBBOX = psNode;
return TRUE;
}
*ppsTopBBOX = NULL;
return FALSE;
}
else if (psNode->pszValue && strcasecmp(psNode->pszValue, "AND") == 0) {
return FLTGetTopBBOXInternal(psNode->psLeftNode, ppsTopBBOX, pnCount) &&
FLTGetTopBBOXInternal(psNode->psRightNode, ppsTopBBOX, pnCount);
}
else
{
return TRUE;
}
}
static FilterEncodingNode* FLTGetTopBBOX(FilterEncodingNode *psNode)
{
int nCount = 0;
FilterEncodingNode* psTopBBOX = NULL;
FLTGetTopBBOXInternal(psNode, &psTopBBOX, &nCount);
return psTopBBOX;
}
/************************************************************************/
/* FLTLayerApplyPlainFilterToLayer */
/* */
/* Helper function for layer virtual table architecture */
/************************************************************************/
int FLTLayerApplyPlainFilterToLayer(FilterEncodingNode *psNode, mapObj *map,
int iLayerIndex)
{
char *pszExpression =NULL;
int status =MS_FALSE;
layerObj* lp = GET_LAYER(map, iLayerIndex);
pszExpression = FLTGetCommonExpression(psNode, lp);
if (pszExpression) {
const char* pszUseDefaultExtent;
FilterEncodingNode* psTopBBOX;
rectObj rect = map->extent;
pszUseDefaultExtent = msOWSLookupMetadata(&(lp->metadata), "F",
"use_default_extent_for_getfeature");
if( pszUseDefaultExtent && !CSLTestBoolean(pszUseDefaultExtent) &&
lp->connectiontype == MS_OGR )
{
const rectObj rectInvalid = MS_INIT_INVALID_RECT;
rect = rectInvalid;
}
psTopBBOX = FLTGetTopBBOX(psNode);
if( psTopBBOX )
{
int can_remove_expression = MS_TRUE;
const char* pszEPSG = FLTGetBBOX(psNode, &rect);
if(pszEPSG && map->projection.numargs > 0) {
projectionObj sProjTmp;
msInitProjection(&sProjTmp);
/* Use the non EPSG variant since axis swapping is done in FLTDoAxisSwappingIfNecessary */
if (msLoadProjectionString(&sProjTmp, pszEPSG) == 0) {
rectObj oldRect = rect;
msProjectRect(&sProjTmp, &map->projection, &rect);
/* If reprojection is involved, do not remove the expression */
if( rect.minx != oldRect.minx ||
rect.miny != oldRect.miny ||
rect.maxx != oldRect.maxx ||
rect.maxy != oldRect.maxy )
{
can_remove_expression = MS_FALSE;
}
}
msFreeProjection(&sProjTmp);
}
/* Small optimization: if the query is just a BBOX, then do a */
/* msQueryByRect() */
if( psTopBBOX == psNode && can_remove_expression )
{
msFree(pszExpression);
pszExpression = NULL;
}
}
if(map->debug == MS_DEBUGLEVEL_VVV)
{
if( pszExpression )
msDebug("FLTLayerApplyPlainFilterToLayer(): %s, rect=%.15g,%.15g,%.15g,%.15g\n", pszExpression, rect.minx, rect.miny, rect.maxx, rect.maxy);
else
msDebug("FLTLayerApplyPlainFilterToLayer(): rect=%.15g,%.15g,%.15g,%.15g\n", rect.minx, rect.miny, rect.maxx, rect.maxy);
}
status = FLTApplyFilterToLayerCommonExpressionWithRect(map, iLayerIndex,
pszExpression, rect);
msFree(pszExpression);
}
return status;
}
/************************************************************************/
/* FilterNode *FLTPaserFilterEncoding(char *szXMLString) */
/* */
/* Parses an Filter Encoding XML string and creates a */
/* FilterEncodingNodes corresponding to the string. */
/* Returns a pointer to the first node or NULL if */
/* unsuccessfull. */
/* Calling function should use FreeFilterEncodingNode function */
/* to free memeory. */
/************************************************************************/
FilterEncodingNode *FLTParseFilterEncoding(const char *szXMLString)
{
CPLXMLNode *psRoot = NULL, *psChild=NULL, *psFilter=NULL;
FilterEncodingNode *psFilterNode = NULL;
if (szXMLString == NULL || strlen(szXMLString) <= 0 ||
(strstr(szXMLString, "Filter") == NULL))
return NULL;
psRoot = CPLParseXMLString(szXMLString);
if( psRoot == NULL)
return NULL;
/* strip namespaces. We srtip all name spaces (#1350)*/
CPLStripXMLNamespace(psRoot, NULL, 1);
/* -------------------------------------------------------------------- */
/* get the root element (Filter). */
/* -------------------------------------------------------------------- */
psFilter = CPLGetXMLNode(psRoot, "=Filter");
if (!psFilter)
{
CPLDestroyXMLNode( psRoot );
return NULL;
}
psChild = psFilter->psChild;
while (psChild) {
if (FLTIsSupportedFilterType(psChild)) {
psFilterNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode, psChild);
break;
} else
psChild = psChild->psNext;
}
CPLDestroyXMLNode( psRoot );
/* -------------------------------------------------------------------- */
/* validate the node tree to make sure that all the nodes are valid.*/
/* -------------------------------------------------------------------- */
if (!FLTValidFilterNode(psFilterNode)) {
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
return psFilterNode;
}
/************************************************************************/
/* int FLTValidFilterNode(FilterEncodingNode *psFilterNode) */
/* */
/* Validate that all the nodes are filled properly. We could */
/* have parts of the nodes that are correct and part which */
/* could be incorrect if the filter string sent is corrupted */
/* (eg missing a value :<PropertyName><PropertyName>) */
/************************************************************************/
int FLTValidFilterNode(FilterEncodingNode *psFilterNode)
{
int bReturn = 0;
if (!psFilterNode)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_UNDEFINED)
return 0;
if (psFilterNode->psLeftNode) {
bReturn = FLTValidFilterNode(psFilterNode->psLeftNode);
if (bReturn == 0)
return 0;
else if (psFilterNode->psRightNode)
return FLTValidFilterNode(psFilterNode->psRightNode);
}
return 1;
}
/************************************************************************/
/* FLTIsGeometryFilterNodeType */
/************************************************************************/
static int FLTIsGeometryFilterNodeType(int eType)
{
return (eType == FILTER_NODE_TYPE_GEOMETRY_POINT ||
eType == FILTER_NODE_TYPE_GEOMETRY_LINE ||
eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON);
}
/************************************************************************/
/* FLTFreeFilterEncodingNode */
/* */
/* recursive freeing of Filer Encoding nodes. */
/************************************************************************/
void FLTFreeFilterEncodingNode(FilterEncodingNode *psFilterNode)
{
if (psFilterNode) {
if (psFilterNode->psLeftNode) {
FLTFreeFilterEncodingNode(psFilterNode->psLeftNode);
psFilterNode->psLeftNode = NULL;
}
if (psFilterNode->psRightNode) {
FLTFreeFilterEncodingNode(psFilterNode->psRightNode);
psFilterNode->psRightNode = NULL;
}
if (psFilterNode->pszSRS)
free( psFilterNode->pszSRS);
if( psFilterNode->pOther ) {
if (psFilterNode->pszValue != NULL &&
strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0) {
FEPropertyIsLike* propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
if( propIsLike->pszWildCard )
free( propIsLike->pszWildCard );
if( propIsLike->pszSingleChar )
free( propIsLike->pszSingleChar );
if( propIsLike->pszEscapeChar )
free( propIsLike->pszEscapeChar );
} else if (FLTIsGeometryFilterNodeType(psFilterNode->eType)) {
msFreeShape((shapeObj *)(psFilterNode->pOther));
}
/* else */
/* TODO free pOther special fields */
free( psFilterNode->pOther );
}
/* Cannot free pszValue before, 'cause we are testing it above */
if( psFilterNode->pszValue )
free( psFilterNode->pszValue );
free(psFilterNode);
}
}
/************************************************************************/
/* FLTCreateFilterEncodingNode */
/* */
/* return a FilerEncoding node. */
/************************************************************************/
FilterEncodingNode *FLTCreateFilterEncodingNode(void)
{
FilterEncodingNode *psFilterNode = NULL;
psFilterNode =
(FilterEncodingNode *)malloc(sizeof (FilterEncodingNode));
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
psFilterNode->pszValue = NULL;
psFilterNode->pOther = NULL;
psFilterNode->pszSRS = NULL;
psFilterNode->psLeftNode = NULL;
psFilterNode->psRightNode = NULL;
return psFilterNode;
}
FilterEncodingNode *FLTCreateBinaryCompFilterEncodingNode(void)
{
FilterEncodingNode *psFilterNode = NULL;
psFilterNode = FLTCreateFilterEncodingNode();
/* used to store case sensitivity flag. Default is 0 meaning the
comparing is case sensititive */
psFilterNode->pOther = (int *)malloc(sizeof(int));
(*(int *)(psFilterNode->pOther)) = 0;
return psFilterNode;
}
/************************************************************************/
/* FLTFindGeometryNode */
/* */
/************************************************************************/
static CPLXMLNode* FLTFindGeometryNode(CPLXMLNode* psXMLNode,
int* pbPoint,
int* pbLine,
int* pbPolygon)
{
CPLXMLNode *psGMLElement = NULL;
psGMLElement = CPLGetXMLNode(psXMLNode, "Point");
if (!psGMLElement)
psGMLElement = CPLGetXMLNode(psXMLNode, "PointType");
if (psGMLElement)
*pbPoint =1;
else {
psGMLElement= CPLGetXMLNode(psXMLNode, "Polygon");
if (psGMLElement)
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPolygon")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Surface")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiSurface")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Box")))
*pbPolygon = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "LineString")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiLineString")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "Curve")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiCurve")))
*pbLine = 1;
else if ((psGMLElement= CPLGetXMLNode(psXMLNode, "MultiPoint")))
*pbPoint = 1;
}
return psGMLElement;
}
/************************************************************************/
/* FLTGetPropertyName */
/************************************************************************/
static const char* FLTGetPropertyName(CPLXMLNode* psXMLNode)
{
const char* pszPropertyName;
pszPropertyName = CPLGetXMLValue(psXMLNode, "PropertyName", NULL);
if( pszPropertyName == NULL ) /* FE 2.0 ? */
pszPropertyName = CPLGetXMLValue(psXMLNode, "ValueReference", NULL);
return pszPropertyName;
}
/************************************************************************/
/* FLTGetFirstChildNode */
/************************************************************************/
static CPLXMLNode* FLTGetFirstChildNode(CPLXMLNode* psXMLNode)
{
if( psXMLNode == NULL )
return NULL;
psXMLNode = psXMLNode->psChild;
while( psXMLNode != NULL )
{
if( psXMLNode->eType == CXT_Element )
return psXMLNode;
psXMLNode = psXMLNode->psNext;
}
return NULL;
}
/************************************************************************/
/* FLTGetNextSibblingNode */
/************************************************************************/
static CPLXMLNode* FLTGetNextSibblingNode(CPLXMLNode* psXMLNode)
{
if( psXMLNode == NULL )
return NULL;
psXMLNode = psXMLNode->psNext;
while( psXMLNode != NULL )
{
if( psXMLNode->eType == CXT_Element )
return psXMLNode;
psXMLNode = psXMLNode->psNext;
}
return NULL;
}
/************************************************************************/
/* FLTInsertElementInNode */
/* */
/* Utility function to parse an XML node and transfter the */
/* contennts into the Filer Encoding node structure. */
/************************************************************************/
void FLTInsertElementInNode(FilterEncodingNode *psFilterNode,
CPLXMLNode *psXMLNode)
{
int nStrLength = 0;
char *pszTmp = NULL;
FilterEncodingNode *psCurFilNode= NULL;
CPLXMLNode *psCurXMLNode = NULL;
CPLXMLNode *psTmpNode = NULL;
CPLXMLNode *psFeatureIdNode = NULL;
const char *pszFeatureId=NULL;
char *pszFeatureIdList=NULL;
if (psFilterNode && psXMLNode && psXMLNode->pszValue) {
psFilterNode->pszValue = msStrdup(psXMLNode->pszValue);
psFilterNode->psLeftNode = NULL;
psFilterNode->psRightNode = NULL;
/* -------------------------------------------------------------------- */
/* Logical filter. AND, OR and NOT are supported. Example of */
/* filer using logical filters : */
/* <Filter> */
/* <And> */
/* <PropertyIsGreaterThan> */
/* <PropertyName>Person/Age</PropertyName> */
/* <Literal>50</Literal> */
/* </PropertyIsGreaterThan> */
/* <PropertyIsEqualTo> */
/* <PropertyName>Person/Address/City</PropertyName> */
/* <Literal>Toronto</Literal> */
/* </PropertyIsEqualTo> */
/* </And> */
/* </Filter> */
/* -------------------------------------------------------------------- */
if (FLTIsLogicalFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_LOGICAL;
if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) {
CPLXMLNode* psFirstNode = FLTGetFirstChildNode(psXMLNode);
CPLXMLNode* psSecondNode = FLTGetNextSibblingNode(psFirstNode);
if (psFirstNode && psSecondNode) {
/*2 operators */
CPLXMLNode* psNextNode = FLTGetNextSibblingNode(psSecondNode);
if (psNextNode == NULL) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode->psLeftNode, psFirstNode);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode->psRightNode, psSecondNode);
} else {
psCurXMLNode = psFirstNode;
psCurFilNode = psFilterNode;
while(psCurXMLNode) {
psNextNode = FLTGetNextSibblingNode(psCurXMLNode);
if (FLTGetNextSibblingNode(psNextNode)) {
psCurFilNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psCurFilNode->psLeftNode, psCurXMLNode);
psCurFilNode->psRightNode = FLTCreateFilterEncodingNode();
psCurFilNode->psRightNode->eType = FILTER_NODE_TYPE_LOGICAL;
psCurFilNode->psRightNode->pszValue = msStrdup(psFilterNode->pszValue);
psCurFilNode = psCurFilNode->psRightNode;
psCurXMLNode = psNextNode;
} else { /*last 2 operators*/
psCurFilNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psCurFilNode->psLeftNode, psCurXMLNode);
psCurFilNode->psRightNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psCurFilNode->psRightNode, psNextNode);
break;
}
}
}
}
else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
CPLXMLNode* psFirstNode = FLTGetFirstChildNode(psXMLNode);
if (psFirstNode) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
FLTInsertElementInNode(psFilterNode->psLeftNode,
psFirstNode);
}
else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}/* end if is logical */
/* -------------------------------------------------------------------- */
/* Spatial Filter. */
/* BBOX : */
/* <Filter> */
/* <BBOX> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
/* <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
/* </gml:Box> */
/* </BBOX> */
/* </Filter> */
/* */
/* DWithin */
/* */
/* <xsd:element name="DWithin" */
/* type="ogc:DistanceBufferType" */
/* substitutionGroup="ogc:spatialOps"/> */
/* */
/* <xsd:complexType name="DistanceBufferType"> */
/* <xsd:complexContent> */
/* <xsd:extension base="ogc:SpatialOpsType"> */
/* <xsd:sequence> */
/* <xsd:element ref="ogc:PropertyName"/> */
/* <xsd:element ref="gml:_Geometry"/> */
/* <xsd:element name="Distance" type="ogc:DistanceType"/>*/
/* </xsd:sequence> */
/* </xsd:extension> */
/* </xsd:complexContent> */
/* </xsd:complexType> */
/* */
/* */
/* <Filter> */
/* <DWithin> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Point> */
/* <gml:coordinates>13.0983,31.5899</gml:coordinates> */
/* </gml:Point> */
/* <Distance units="url#m">10</Distance> */
/* </DWithin> */
/* </Filter> */
/* */
/* Intersect */
/* */
/* type="ogc:BinarySpatialOpType" substitutionGroup="ogc:spatialOps"/>*/
/* <xsd:element name="Intersects" */
/* type="ogc:BinarySpatialOpType" */
/* substitutionGroup="ogc:spatialOps"/> */
/* */
/* <xsd:complexType name="BinarySpatialOpType"> */
/* <xsd:complexContent> */
/* <xsd:extension base="ogc:SpatialOpsType"> */
/* <xsd:sequence> */
/* <xsd:element ref="ogc:PropertyName"/> */
/* <xsd:choice> */
/* <xsd:element ref="gml:_Geometry"/> */
/* <xsd:element ref="gml:Box"/> */
/* </xsd:sequence> */
/* </xsd:extension> */
/* </xsd:complexContent> */
/* </xsd:complexType> */
/* -------------------------------------------------------------------- */
else if (FLTIsSpatialFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_SPATIAL;
if (strcasecmp(psXMLNode->pszValue, "BBOX") == 0) {
char *pszSRS = NULL;
const char* pszPropertyName = NULL;
CPLXMLNode *psBox = NULL, *psEnvelope=NULL;
rectObj sBox;
int bCoordinatesValid = 0;
pszPropertyName = FLTGetPropertyName(psXMLNode);
psBox = CPLGetXMLNode(psXMLNode, "Box");
if (!psBox)
psBox = CPLGetXMLNode(psXMLNode, "BoxType");
/*FE 1.0 used box FE1.1 uses envelop*/
if (psBox)
bCoordinatesValid = FLTParseGMLBox(psBox, &sBox, &pszSRS);
else if ((psEnvelope = CPLGetXMLNode(psXMLNode, "Envelope")))
bCoordinatesValid = FLTParseGMLEnvelope(psEnvelope, &sBox, &pszSRS);
if (bCoordinatesValid) {
/*set the srs if available*/
if (pszSRS)
psFilterNode->pszSRS = pszSRS;
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
/* PropertyName is optional since FE 1.1.0, in which case */
/* the BBOX must apply to all geometry fields. As we support */
/* currently only one geometry field, this doesn't make much */
/* difference to further processing. */
if( pszPropertyName != NULL ) {
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
}
/* coordinates */
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BBOX;
psFilterNode->psRightNode->pOther =
(rectObj *)msSmallMalloc(sizeof(rectObj));
((rectObj *)psFilterNode->psRightNode->pOther)->minx = sBox.minx;
((rectObj *)psFilterNode->psRightNode->pOther)->miny = sBox.miny;
((rectObj *)psFilterNode->psRightNode->pOther)->maxx = sBox.maxx;
((rectObj *)psFilterNode->psRightNode->pOther)->maxy = sBox.maxy;
} else {
msFree(pszSRS);
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
} else if (strcasecmp(psXMLNode->pszValue, "DWithin") == 0 ||
strcasecmp(psXMLNode->pszValue, "Beyond") == 0)
{
shapeObj *psShape = NULL;
int bPoint = 0, bLine = 0, bPolygon = 0;
const char *pszUnits = NULL;
const char* pszDistance = NULL;
const char* pszPropertyName;
char *pszSRS = NULL;
CPLXMLNode *psGMLElement = NULL, *psDistance=NULL;
pszPropertyName = FLTGetPropertyName(psXMLNode);
psGMLElement = FLTFindGeometryNode(psXMLNode, &bPoint, &bLine, &bPolygon);
psDistance = CPLGetXMLNode(psXMLNode, "Distance");
if( psDistance != NULL )
pszDistance = CPLGetXMLValue(psDistance, NULL, NULL );
if (pszPropertyName != NULL && psGMLElement && psDistance != NULL ) {
pszUnits = CPLGetXMLValue(psDistance, "units", NULL);
if( pszUnits == NULL ) /* FE 2.0 */
pszUnits = CPLGetXMLValue(psDistance, "uom", NULL);
psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
msInitShape(psShape);
if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
{
/*set the srs if available*/
if (pszSRS)
psFilterNode->pszSRS = pszSRS;
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
if (bPoint)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
else if (bLine)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
else if (bPolygon)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
/*the value will be distance;units*/
psFilterNode->psRightNode->pszValue = msStrdup(pszDistance);
if (pszUnits) {
psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, ";");
psFilterNode->psRightNode->pszValue= msStringConcatenate(psFilterNode->psRightNode->pszValue, pszUnits);
}
}
else
{
free(psShape);
msFree(pszSRS);
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else if (strcasecmp(psXMLNode->pszValue, "Intersect") == 0 ||
strcasecmp(psXMLNode->pszValue, "Intersects") == 0 ||
strcasecmp(psXMLNode->pszValue, "Equals") == 0 ||
strcasecmp(psXMLNode->pszValue, "Disjoint") == 0 ||
strcasecmp(psXMLNode->pszValue, "Touches") == 0 ||
strcasecmp(psXMLNode->pszValue, "Crosses") == 0 ||
strcasecmp(psXMLNode->pszValue, "Within") == 0 ||
strcasecmp(psXMLNode->pszValue, "Contains") == 0 ||
strcasecmp(psXMLNode->pszValue, "Overlaps") == 0) {
shapeObj *psShape = NULL;
int bLine = 0, bPolygon = 0, bPoint=0;
char *pszSRS = NULL;
const char* pszPropertyName;
CPLXMLNode *psGMLElement = NULL;
pszPropertyName = FLTGetPropertyName(psXMLNode);
psGMLElement = FLTFindGeometryNode(psXMLNode, &bPoint, &bLine, &bPolygon);
if (pszPropertyName != NULL && psGMLElement) {
psShape = (shapeObj *)msSmallMalloc(sizeof(shapeObj));
msInitShape(psShape);
if (FLTShapeFromGMLTree(psGMLElement, psShape, &pszSRS))
{
/*set the srs if available*/
if (pszSRS)
psFilterNode->pszSRS = pszSRS;
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
if (bPoint)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POINT;
else if (bLine)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_LINE;
else if (bPolygon)
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_GEOMETRY_POLYGON;
psFilterNode->psRightNode->pOther = (shapeObj *)psShape;
}
else
{
free(psShape);
msFree(pszSRS);
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
}/* end of is spatial */
/* -------------------------------------------------------------------- */
/* Comparison Filter */
/* -------------------------------------------------------------------- */
else if (FLTIsComparisonFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_COMPARISON;
/* -------------------------------------------------------------------- */
/* binary comaparison types. Example : */
/* */
/* <Filter> */
/* <PropertyIsEqualTo> */
/* <PropertyName>SomeProperty</PropertyName> */
/* <Literal>100</Literal> */
/* </PropertyIsEqualTo> */
/* </Filter> */
/* -------------------------------------------------------------------- */
if (FLTIsBinaryComparisonFilterType(psXMLNode->pszValue)) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
if (pszPropertyName != NULL ) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psTmpNode = CPLSearchXMLNode(psXMLNode, "Literal");
if (psTmpNode) {
const char* pszLiteral = CPLGetXMLValue(psTmpNode, NULL, NULL);
psFilterNode->psRightNode = FLTCreateBinaryCompFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
if (pszLiteral != NULL) {
const char* pszMatchCase;
psFilterNode->psRightNode->pszValue = msStrdup(pszLiteral);
pszMatchCase = CPLGetXMLValue(psXMLNode, "matchCase", NULL);
/*check if the matchCase attribute is set*/
if( pszMatchCase != NULL && strcasecmp( pszMatchCase, "false") == 0) {
(*(int *)psFilterNode->psRightNode->pOther) = 1;
}
}
/* special case where the user puts an empty value */
/* for the Literal so it can end up as an empty */
/* string query in the expression */
else
psFilterNode->psRightNode->pszValue = NULL;
}
}
if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL)
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
/* -------------------------------------------------------------------- */
/* PropertyIsBetween filter : extract property name and boudary */
/* values. The boundary values are stored in the right */
/* node. The values are separated by a semi-column (;) */
/* Eg of Filter : */
/* <PropertyIsBetween> */
/* <PropertyName>DEPTH</PropertyName> */
/* <LowerBoundary><Literal>400</Literal></LowerBoundary> */
/* <UpperBoundary><Literal>800</Literal></UpperBoundary> */
/* </PropertyIsBetween> */
/* */
/* Or */
/* <PropertyIsBetween> */
/* <PropertyName>DEPTH</PropertyName> */
/* <LowerBoundary>400</LowerBoundary> */
/* <UpperBoundary>800</UpperBoundary> */
/* </PropertyIsBetween> */
/* -------------------------------------------------------------------- */
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsBetween") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
CPLXMLNode* psLowerBoundary = CPLGetXMLNode(psXMLNode, "LowerBoundary");
CPLXMLNode* psUpperBoundary = CPLGetXMLNode(psXMLNode, "UpperBoundary");
const char* pszLowerNode = NULL;
const char* pszUpperNode = NULL;
if( psLowerBoundary != NULL )
{
/* check if the <Literal> is there */
if (CPLGetXMLNode(psLowerBoundary, "Literal") != NULL)
pszLowerNode = CPLGetXMLValue(psLowerBoundary, "Literal", NULL);
else
pszLowerNode = CPLGetXMLValue(psLowerBoundary, NULL, NULL);
}
if( psUpperBoundary != NULL )
{
if (CPLGetXMLNode(psUpperBoundary, "Literal") != NULL)
pszUpperNode = CPLGetXMLValue(psUpperBoundary, "Literal", NULL);
else
pszUpperNode = CPLGetXMLValue(psUpperBoundary, NULL, NULL);
}
if (pszPropertyName != NULL && pszLowerNode != NULL && pszUpperNode != NULL) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_BOUNDARY;
/* adding a ; between bounary values */
nStrLength = strlen(pszLowerNode) + strlen(pszUpperNode) + 2;
psFilterNode->psRightNode->pszValue =
(char *)malloc(sizeof(char)*(nStrLength));
strcpy( psFilterNode->psRightNode->pszValue, pszLowerNode);
strlcat(psFilterNode->psRightNode->pszValue, ";", nStrLength);
strlcat(psFilterNode->psRightNode->pszValue, pszUpperNode, nStrLength);
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}/* end of PropertyIsBetween */
/* -------------------------------------------------------------------- */
/* PropertyIsLike */
/* */
/* <Filter> */
/* <PropertyIsLike wildCard="*" singleChar="#" escape="!"> */
/* <PropertyName>LAST_NAME</PropertyName> */
/* <Literal>JOHN*</Literal> */
/* </PropertyIsLike> */
/* </Filter> */
/* -------------------------------------------------------------------- */
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsLike") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
const char* pszLiteral = CPLGetXMLValue(psXMLNode, "Literal", NULL);
const char* pszWildCard = CPLGetXMLValue(psXMLNode, "wildCard", NULL);
const char* pszSingleChar = CPLGetXMLValue(psXMLNode, "singleChar", NULL);
const char* pszEscapeChar = CPLGetXMLValue(psXMLNode, "escape", NULL);
if( pszEscapeChar == NULL )
pszEscapeChar = CPLGetXMLValue(psXMLNode, "escapeChar", NULL);
if (pszPropertyName != NULL && pszLiteral != NULL &&
pszWildCard != NULL && pszSingleChar != NULL && pszEscapeChar != NULL)
{
FEPropertyIsLike* propIsLike;
propIsLike = (FEPropertyIsLike *)malloc(sizeof(FEPropertyIsLike));
psFilterNode->pOther = propIsLike;
propIsLike->bCaseInsensitive = 0;
propIsLike->pszWildCard = msStrdup(pszWildCard);
propIsLike->pszSingleChar = msStrdup(pszSingleChar);
propIsLike->pszEscapeChar = msStrdup(pszEscapeChar);
pszTmp = (char *)CPLGetXMLValue(psXMLNode, "matchCase", NULL);
if (pszTmp && strcasecmp(pszTmp, "false") == 0) {
propIsLike->bCaseInsensitive =1;
}
/* -------------------------------------------------------------------- */
/* Create left and right node for the attribute and the value. */
/* -------------------------------------------------------------------- */
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->pszValue = msStrdup(pszLiteral);
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsNull") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
if( pszPropertyName != NULL )
{
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
else if (strcasecmp(psXMLNode->pszValue, "PropertyIsNil") == 0) {
const char* pszPropertyName = FLTGetPropertyName(psXMLNode);
if( pszPropertyName != NULL )
{
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
}
/* -------------------------------------------------------------------- */
/* FeatureId Filter */
/* */
/* <ogc:Filter> */
/* <ogc:FeatureId fid="INWATERA_1M.1013"/> */
/* <ogc:FeatureId fid="INWATERA_1M.10"/> */
/* <ogc:FeatureId fid="INWATERA_1M.13"/> */
/* <ogc:FeatureId fid="INWATERA_1M.140"/> */
/* <ogc:FeatureId fid="INWATERA_1M.5001"/> */
/* <ogc:FeatureId fid="INWATERA_1M.2001"/> */
/* </ogc:Filter> */
/* */
/* */
/* Note that for FES1.1.0 the featureid has been depricated in */
/* favor of GmlObjectId */
/* <GmlObjectId gml:id="TREESA_1M.1234"/> */
/* */
/* And in FES 2.0, in favor of <fes:ResourceId rid="foo.1234"/> */
/* -------------------------------------------------------------------- */
else if (FLTIsFeatureIdFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
pszFeatureId = CPLGetXMLValue(psXMLNode, "fid", NULL);
/*for FE 1.1.0 GmlObjectId */
if (pszFeatureId == NULL)
pszFeatureId = CPLGetXMLValue(psXMLNode, "id", NULL);
/*for FE 2.0 ResourceId */
if (pszFeatureId == NULL)
pszFeatureId = CPLGetXMLValue(psXMLNode, "rid", NULL);
pszFeatureIdList = NULL;
psFeatureIdNode = psXMLNode;
while (psFeatureIdNode) {
pszFeatureId = CPLGetXMLValue(psFeatureIdNode, "fid", NULL);
if (!pszFeatureId)
pszFeatureId = CPLGetXMLValue(psFeatureIdNode, "id", NULL);
if (!pszFeatureId)
pszFeatureId = CPLGetXMLValue(psFeatureIdNode, "rid", NULL);
if (pszFeatureId) {
if (pszFeatureIdList)
pszFeatureIdList = msStringConcatenate(pszFeatureIdList, ",");
pszFeatureIdList = msStringConcatenate(pszFeatureIdList, pszFeatureId);
}
psFeatureIdNode = psFeatureIdNode->psNext;
}
if (pszFeatureIdList) {
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup(pszFeatureIdList);
msFree(pszFeatureIdList);
} else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
/* -------------------------------------------------------------------- */
/* Temporal Filter. */
/*
<fes:During>
<fes:ValueReference>gml:TimeInstant</fes:ValueReference>
<gml:TimePeriod gml:id="TP1">
<gml:begin>
<gml:TimeInstant gml:id="TI1">
<gml:timePosition>2005-05-17T00:00:00Z</gml:timePosition>
</gml:TimeInstant>
</gml:begin>
<gml:end>
<gml:TimeInstant gml:id="TI2">
<gml:timePosition>2005-05-23T00:00:00Z</gml:timePosition>
</gml:TimeInstant>
</gml:end>
</gml:TimePeriod>
</fes:During>
*/
/* -------------------------------------------------------------------- */
else if (FLTIsTemporalFilterType(psXMLNode->pszValue)) {
psFilterNode->eType = FILTER_NODE_TYPE_TEMPORAL;
if (strcasecmp(psXMLNode->pszValue, "During") == 0) {
const char* pszPropertyName = NULL;
const char* pszBeginTime;
const char* pszEndTime;
pszPropertyName = FLTGetPropertyName(psXMLNode);
pszBeginTime = CPLGetXMLValue(psXMLNode, "TimePeriod.begin.TimeInstant.timePosition", NULL);
if( pszBeginTime == NULL )
pszBeginTime = CPLGetXMLValue(psXMLNode, "TimePeriod.beginPosition", NULL);
pszEndTime = CPLGetXMLValue(psXMLNode, "TimePeriod.end.TimeInstant.timePosition", NULL);
if( pszEndTime == NULL )
pszEndTime = CPLGetXMLValue(psXMLNode, "TimePeriod.endPosition", NULL);
if (pszPropertyName && pszBeginTime && pszEndTime &&
strchr(pszBeginTime, '\'') == NULL && strchr(pszBeginTime, '\\') == NULL &&
strchr(pszEndTime, '\'') == NULL && strchr(pszEndTime, '\\') == NULL &&
msTimeGetResolution(pszBeginTime) >= 0 &&
msTimeGetResolution(pszEndTime) >= 0) {
psFilterNode->psLeftNode = FLTCreateFilterEncodingNode();
psFilterNode->psLeftNode->eType = FILTER_NODE_TYPE_PROPERTYNAME;
psFilterNode->psLeftNode->pszValue = msStrdup(pszPropertyName);
psFilterNode->psRightNode = FLTCreateFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_TIME_PERIOD;
psFilterNode->psRightNode->pszValue = msSmallMalloc( strlen(pszBeginTime) + strlen(pszEndTime) + 2 );
sprintf(psFilterNode->psRightNode->pszValue, "%s/%s", pszBeginTime, pszEndTime);
}
else
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
} else {
psFilterNode->eType = FILTER_NODE_TYPE_UNDEFINED;
}
}/* end of is temporal */
}
}
/************************************************************************/
/* int FLTIsLogicalFilterType((char *pszValue) */
/* */
/* return TRUE if the value of the node is of logical filter */
/* encoding type. */
/************************************************************************/
int FLTIsLogicalFilterType(const char *pszValue)
{
if (pszValue) {
if (strcasecmp(pszValue, "AND") == 0 ||
strcasecmp(pszValue, "OR") == 0 ||
strcasecmp(pszValue, "NOT") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsBinaryComparisonFilterType(char *pszValue) */
/* */
/* Binary comparison filter type. */
/************************************************************************/
int FLTIsBinaryComparisonFilterType(const char *pszValue)
{
if (pszValue) {
if (strcasecmp(pszValue, "PropertyIsEqualTo") == 0 ||
strcasecmp(pszValue, "PropertyIsNotEqualTo") == 0 ||
strcasecmp(pszValue, "PropertyIsLessThan") == 0 ||
strcasecmp(pszValue, "PropertyIsGreaterThan") == 0 ||
strcasecmp(pszValue, "PropertyIsLessThanOrEqualTo") == 0 ||
strcasecmp(pszValue, "PropertyIsGreaterThanOrEqualTo") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsComparisonFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of comparison filter */
/* encoding type. */
/************************************************************************/
int FLTIsComparisonFilterType(const char *pszValue)
{
if (pszValue) {
if (FLTIsBinaryComparisonFilterType(pszValue) ||
strcasecmp(pszValue, "PropertyIsLike") == 0 ||
strcasecmp(pszValue, "PropertyIsBetween") == 0 ||
strcasecmp(pszValue, "PropertyIsNull") == 0 ||
strcasecmp(pszValue, "PropertyIsNil") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsFeatureIdFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of featureid filter */
/* encoding type. */
/************************************************************************/
int FLTIsFeatureIdFilterType(const char *pszValue)
{
if (pszValue && (strcasecmp(pszValue, "FeatureId") == 0 ||
strcasecmp(pszValue, "GmlObjectId") == 0 ||
strcasecmp(pszValue, "ResourceId") == 0))
return MS_TRUE;
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsSpatialFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of spatial filter */
/* encoding type. */
/************************************************************************/
int FLTIsSpatialFilterType(const char *pszValue)
{
if (pszValue) {
if ( strcasecmp(pszValue, "BBOX") == 0 ||
strcasecmp(pszValue, "DWithin") == 0 ||
strcasecmp(pszValue, "Intersect") == 0 ||
strcasecmp(pszValue, "Intersects") == 0 ||
strcasecmp(pszValue, "Equals") == 0 ||
strcasecmp(pszValue, "Disjoint") == 0 ||
strcasecmp(pszValue, "Touches") == 0 ||
strcasecmp(pszValue, "Crosses") == 0 ||
strcasecmp(pszValue, "Within") == 0 ||
strcasecmp(pszValue, "Contains") == 0 ||
strcasecmp(pszValue, "Overlaps") == 0 ||
strcasecmp(pszValue, "Beyond") == 0)
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsTemportalFilterType(char *pszValue) */
/* */
/* return TRUE if the value of the node is of temporal filter */
/* encoding type. */
/************************************************************************/
int FLTIsTemporalFilterType(const char *pszValue)
{
if (pszValue) {
if ( strcasecmp(pszValue, "During") == 0 )
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* int FLTIsSupportedFilterType(CPLXMLNode *psXMLNode) */
/* */
/* Verfify if the value of the node is one of the supported */
/* filter type. */
/************************************************************************/
int FLTIsSupportedFilterType(CPLXMLNode *psXMLNode)
{
if (psXMLNode) {
if (FLTIsLogicalFilterType(psXMLNode->pszValue) ||
FLTIsSpatialFilterType(psXMLNode->pszValue) ||
FLTIsComparisonFilterType(psXMLNode->pszValue) ||
FLTIsFeatureIdFilterType(psXMLNode->pszValue) ||
FLTIsTemporalFilterType(psXMLNode->pszValue))
return MS_TRUE;
}
return MS_FALSE;
}
/************************************************************************/
/* FLTNumberOfFilterType */
/* */
/* Loop trhough the nodes and return the number of nodes of */
/* specified value. */
/************************************************************************/
int FLTNumberOfFilterType(FilterEncodingNode *psFilterNode, const char *szType)
{
int nCount = 0;
int nLeftNode=0 , nRightNode = 0;
if (!psFilterNode || !szType || !psFilterNode->pszValue)
return 0;
if (strcasecmp(psFilterNode->pszValue, (char*)szType) == 0)
nCount++;
if (psFilterNode->psLeftNode)
nLeftNode = FLTNumberOfFilterType(psFilterNode->psLeftNode, szType);
nCount += nLeftNode;
if (psFilterNode->psRightNode)
nRightNode = FLTNumberOfFilterType(psFilterNode->psRightNode, szType);
nCount += nRightNode;
return nCount;
}
/************************************************************************/
/* FLTValidForBBoxFilter */
/* */
/* Validate if there is only one BBOX filter node. Here is waht */
/* is supported (is valid) : */
/* - one node which is a BBOX */
/* - a logical AND with a valid BBOX */
/* */
/* eg 1: <Filter> */
/* <BBOX> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
/* <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
/* </gml:Box> */
/* </BBOX> */
/* </Filter> */
/* */
/* eg 2 :<Filter> */
/* <AND> */
/* <BBOX> */
/* <PropertyName>Geometry</PropertyName> */
/* <gml:Box srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">*/
/* <gml:coordinates>13.0983,31.5899 35.5472,42.8143</gml:coordinates>*/
/* </gml:Box> */
/* </BBOX> */
/* <PropertyIsEqualTo> */
/* <PropertyName>SomeProperty</PropertyName> */
/* <Literal>100</Literal> */
/* </PropertyIsEqualTo> */
/* </AND> */
/* </Filter> */
/* */
/************************************************************************/
int FLTValidForBBoxFilter(FilterEncodingNode *psFilterNode)
{
int nCount = 0;
if (!psFilterNode || !psFilterNode->pszValue)
return 1;
nCount = FLTNumberOfFilterType(psFilterNode, "BBOX");
if (nCount > 1)
return 0;
else if (nCount == 0)
return 1;
/* nCount ==1 */
if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
return 1;
if (strcasecmp(psFilterNode->pszValue, "AND") == 0) {
return FLTValidForBBoxFilter(psFilterNode->psLeftNode) &&
FLTValidForBBoxFilter(psFilterNode->psRightNode);
}
return 0;
}
#if 0
static int FLTHasUniqueTopLevelDuringFilter(FilterEncodingNode *psFilterNode)
{
int nCount = 0;
if (!psFilterNode || !psFilterNode->pszValue)
return 1;
nCount = FLTNumberOfFilterType(psFilterNode, "During");
if (nCount > 1)
return 0;
else if (nCount == 0)
return 1;
/* nCount ==1 */
if (strcasecmp(psFilterNode->pszValue, "During") == 0)
return 1;
if (strcasecmp(psFilterNode->pszValue, "AND") == 0) {
return FLTHasUniqueTopLevelDuringFilter(psFilterNode->psLeftNode) &&
FLTHasUniqueTopLevelDuringFilter(psFilterNode->psRightNode);
}
return 0;
}
#endif
int FLTIsLineFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_LINE)
return 1;
return 0;
}
int FLTIsPolygonFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POLYGON)
return 1;
return 0;
}
int FLTIsPointFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_GEOMETRY_POINT)
return 1;
return 0;
}
int FLTIsBBoxFilter(FilterEncodingNode *psFilterNode)
{
if (!psFilterNode || !psFilterNode->pszValue)
return 0;
if (strcasecmp(psFilterNode->pszValue, "BBOX") == 0)
return 1;
return 0;
}
shapeObj *FLTGetShape(FilterEncodingNode *psFilterNode, double *pdfDistance,
int *pnUnit)
{
char **tokens = NULL;
int nTokens = 0;
FilterEncodingNode *psNode = psFilterNode;
char *szUnitStr = NULL;
char *szUnit = NULL;
if (psNode) {
if (psNode->eType == FILTER_NODE_TYPE_SPATIAL && psNode->psRightNode)
psNode = psNode->psRightNode;
if (FLTIsGeometryFilterNodeType(psNode->eType)) {
if (psNode->pszValue && pdfDistance) {
/*
sytnax expected is "distance;unit" or just "distance"
if unit is there syntax is "URI#unit" (eg http://..../#m)
or just "unit"
*/
tokens = msStringSplit(psNode->pszValue,';', &nTokens);
if (tokens && nTokens >= 1) {
*pdfDistance = atof(tokens[0]);
if (nTokens == 2 && pnUnit) {
szUnitStr = msStrdup(tokens[1]);
msFreeCharArray(tokens, nTokens);
nTokens = 0;
tokens = msStringSplit(szUnitStr,'#', &nTokens);
msFree(szUnitStr);
if (tokens && nTokens >= 1) {
if (nTokens ==1)
szUnit = tokens[0];
else
szUnit = tokens[1];
if (strcasecmp(szUnit,"m") == 0 ||
strcasecmp(szUnit,"meters") == 0 )
*pnUnit = MS_METERS;
else if (strcasecmp(szUnit,"km") == 0 ||
strcasecmp(szUnit,"kilometers") == 0)
*pnUnit = MS_KILOMETERS;
else if (strcasecmp(szUnit,"NM") == 0 ||
strcasecmp(szUnit,"nauticalmiles") == 0)
*pnUnit = MS_NAUTICALMILES;
else if (strcasecmp(szUnit,"mi") == 0 ||
strcasecmp(szUnit,"miles") == 0)
*pnUnit = MS_MILES;
else if (strcasecmp(szUnit,"in") == 0 ||
strcasecmp(szUnit,"inches") == 0)
*pnUnit = MS_INCHES;
else if (strcasecmp(szUnit,"ft") == 0 ||
strcasecmp(szUnit,"feet") == 0)
*pnUnit = MS_FEET;
else if (strcasecmp(szUnit,"deg") == 0 ||
strcasecmp(szUnit,"dd") == 0)
*pnUnit = MS_DD;
else if (strcasecmp(szUnit,"px") == 0)
*pnUnit = MS_PIXELS;
}
}
}
msFreeCharArray(tokens, nTokens);
}
return (shapeObj *)psNode->pOther;
}
}
return NULL;
}
/************************************************************************/
/* FLTGetBBOX */
/* */
/* Loop through the nodes are return the coordinates of the */
/* first bbox node found. The retrun value is the epsg code of */
/* the bbox. */
/************************************************************************/
const char *FLTGetBBOX(FilterEncodingNode *psFilterNode, rectObj *psRect)
{
const char *pszReturn = NULL;
if (!psFilterNode || !psRect)
return NULL;
if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "BBOX") == 0) {
if (psFilterNode->psRightNode && psFilterNode->psRightNode->pOther) {
rectObj* pRect= (rectObj *)psFilterNode->psRightNode->pOther;
psRect->minx = pRect->minx;
psRect->miny = pRect->miny;
psRect->maxx = pRect->maxx;
psRect->maxy = pRect->maxy;
return psFilterNode->pszSRS;
}
} else {
pszReturn = FLTGetBBOX(psFilterNode->psLeftNode, psRect);
if (pszReturn)
return pszReturn;
else
return FLTGetBBOX(psFilterNode->psRightNode, psRect);
}
return pszReturn;
}
const char* FLTGetDuring(FilterEncodingNode *psFilterNode, const char** ppszTimeField)
{
const char *pszReturn = NULL;
if (!psFilterNode || !ppszTimeField)
return NULL;
if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "During") == 0) {
*ppszTimeField = psFilterNode->psLeftNode->pszValue;
return psFilterNode->psRightNode->pszValue;
} else {
pszReturn = FLTGetDuring(psFilterNode->psLeftNode, ppszTimeField);
if (pszReturn)
return pszReturn;
else
return FLTGetDuring(psFilterNode->psRightNode, ppszTimeField);
}
return pszReturn;
}
/************************************************************************/
/* GetMapserverExpression */
/* */
/* Return a mapserver expression base on the Filer encoding nodes. */
/************************************************************************/
char *FLTGetMapserverExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszExpression = NULL;
const char *pszAttribute = NULL;
char szTmp[256];
char **tokens = NULL;
int nTokens = 0, i=0,bString=0;
if (!psFilterNode)
return NULL;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) {
pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsBetween") == 0) {
pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLike") == 0) {
pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
}
}
} else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL) {
if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) {
pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
}
} else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL) {
/* TODO */
} else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID) {
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
if (psFilterNode->pszValue) {
pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
if (pszAttribute) {
tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
if (tokens && nTokens > 0) {
for (i=0; i<nTokens; i++) {
const char* pszId = tokens[i];
const char* pszDot = strchr(pszId, '.');
if( pszDot )
pszId = pszDot + 1;
if (i == 0) {
if(FLTIsNumeric(pszId) == MS_FALSE)
bString = 1;
}
if (bString)
snprintf(szTmp, sizeof(szTmp), "('[%s]' = '%s')" , pszAttribute, pszId);
else
snprintf(szTmp, sizeof(szTmp), "([%s] = %s)" , pszAttribute, pszId);
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
else
pszExpression = msStringConcatenate(pszExpression, "(");
pszExpression = msStringConcatenate(pszExpression, szTmp);
}
msFreeCharArray(tokens, nTokens);
}
}
/*opening and closing brackets are needed for mapserver expressions*/
if (pszExpression)
pszExpression = msStringConcatenate(pszExpression, ")");
}
#else
msSetError(MS_MISCERR, "OWS support is not available.",
"FLTGetMapserverExpression()");
return(MS_FAILURE);
#endif
}
return pszExpression;
}
/************************************************************************/
/* FLTGetSQLExpression */
/* */
/* Build SQL expressions from the mapserver nodes. */
/************************************************************************/
char *FLTGetSQLExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszExpression = NULL;
const char *pszAttribute = NULL;
char szTmp[256];
char **tokens = NULL;
int nTokens = 0, i=0, bString=0;
if (psFilterNode == NULL || lp == NULL)
return NULL;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON) {
if ( psFilterNode->psLeftNode && psFilterNode->psRightNode) {
if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue)) {
pszExpression =
FLTGetBinaryComparisonSQLExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsBetween") == 0) {
pszExpression =
FLTGetIsBetweenComparisonSQLExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLike") == 0) {
pszExpression =
FLTGetIsLikeComparisonSQLExpression(psFilterNode, lp);
}
}
} else if (psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL) {
if (strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) {
pszExpression =
FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
} else if (strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszExpression =
FLTGetLogicalComparisonSQLExpresssion(psFilterNode, lp);
}
}
else if (psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL) {
/* TODO */
} else if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID) {
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
if (psFilterNode->pszValue) {
pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
if (pszAttribute) {
tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
bString = 0;
if (tokens && nTokens > 0) {
for (i=0; i<nTokens; i++) {
char *pszEscapedStr = NULL;
const char* pszId = tokens[i];
const char* pszDot = strchr(pszId, '.');
if( pszDot )
pszId = pszDot + 1;
if (strlen(pszId) <= 0)
continue;
if (FLTIsNumeric(pszId) == MS_FALSE)
bString = 1;
pszEscapedStr = msLayerEscapeSQLParam(lp, pszId);
if (bString)
{
if( lp->connectiontype == MS_OGR || lp->connectiontype == MS_POSTGIS )
snprintf(szTmp, sizeof(szTmp), "(CAST(%s AS CHARACTER(255)) = '%s')" , pszAttribute, pszEscapedStr);
else
snprintf(szTmp, sizeof(szTmp), "(%s = '%s')" , pszAttribute, pszEscapedStr);
}
else
snprintf(szTmp, sizeof(szTmp), "(%s = %s)" , pszAttribute, pszEscapedStr);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (pszExpression != NULL)
pszExpression = msStringConcatenate(pszExpression, " OR ");
else
/*opening and closing brackets*/
pszExpression = msStringConcatenate(pszExpression, "(");
pszExpression = msStringConcatenate(pszExpression, szTmp);
}
msFreeCharArray(tokens, nTokens);
}
}
/*opening and closing brackets*/
if (pszExpression)
pszExpression = msStringConcatenate(pszExpression, ")");
}
#else
msSetError(MS_MISCERR, "OWS support is not available.",
"FLTGetSQLExpression()");
return(MS_FAILURE);
#endif
}
else if ( lp->connectiontype != MS_OGR &&
psFilterNode->eType == FILTER_NODE_TYPE_TEMPORAL )
pszExpression = FLTGetTimeExpression(psFilterNode, lp);
return pszExpression;
}
/************************************************************************/
/* FLTGetNodeExpression */
/* */
/* Return the expresion for a specific node. */
/************************************************************************/
char *FLTGetNodeExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszExpression = NULL;
if (!psFilterNode)
return NULL;
if (FLTIsLogicalFilterType(psFilterNode->pszValue))
pszExpression = FLTGetLogicalComparisonExpresssion(psFilterNode, lp);
else if (FLTIsComparisonFilterType(psFilterNode->pszValue)) {
if (FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
pszExpression = FLTGetBinaryComparisonExpresssion(psFilterNode, lp);
else if (strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0)
pszExpression = FLTGetIsBetweenComparisonExpresssion(psFilterNode, lp);
else if (strcasecmp(psFilterNode->pszValue, "PropertyIsLike") == 0)
pszExpression = FLTGetIsLikeComparisonExpression(psFilterNode);
}
return pszExpression;
}
/************************************************************************/
/* FLTGetLogicalComparisonSQLExpresssion */
/* */
/* Return the expression for logical comparison expression. */
/************************************************************************/
char *FLTGetLogicalComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
char *pszBuffer = NULL;
char *pszTmp = NULL;
int nTmp = 0;
if (lp == NULL)
return NULL;
/* ==================================================================== */
/* special case for BBOX node. */
/* ==================================================================== */
if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
((strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0) ||
(strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0))) {
if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0)
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
else
pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 1));
sprintf(pszBuffer, "%s", pszTmp);
}
/* ==================================================================== */
/* special case for temporal filter node (OGR layer only) */
/* ==================================================================== */
else if (lp->connectiontype == MS_OGR &&
psFilterNode->psLeftNode && psFilterNode->psRightNode &&
(psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_TEMPORAL ||
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_TEMPORAL) ) {
if (psFilterNode->psLeftNode->eType != FILTER_NODE_TYPE_TEMPORAL)
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
else
pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 1));
sprintf(pszBuffer, "%s", pszTmp);
}
/* -------------------------------------------------------------------- */
/* OR and AND */
/* -------------------------------------------------------------------- */
else if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) *
(strlen(pszTmp) +
strlen(psFilterNode->pszValue) + 5));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, " ");
strcat(pszBuffer, psFilterNode->pszValue);
strcat(pszBuffer, " ");
free( pszTmp );
nTmp = strlen(pszBuffer);
pszTmp = FLTGetSQLExpression(psFilterNode->psRightNode, lp);
if (!pszTmp) {
free(pszBuffer);
return NULL;
}
pszBuffer = (char *)realloc(pszBuffer,
sizeof(char) * (strlen(pszTmp) + nTmp +3));
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
}
/* -------------------------------------------------------------------- */
/* NOT */
/* -------------------------------------------------------------------- */
else if (psFilterNode->psLeftNode &&
strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszTmp = FLTGetSQLExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 9));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (NOT ");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
} else
return NULL;
/* -------------------------------------------------------------------- */
/* Cleanup. */
/* -------------------------------------------------------------------- */
if( pszTmp != NULL )
free( pszTmp );
return pszBuffer;
}
/************************************************************************/
/* FLTGetLogicalComparisonExpresssion */
/* */
/* Return the expression for logical comparison expression. */
/************************************************************************/
char *FLTGetLogicalComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
{
char *pszTmp = NULL;
char *pszBuffer = NULL;
int nTmp = 0;
if (!psFilterNode || !FLTIsLogicalFilterType(psFilterNode->pszValue))
return NULL;
/* ==================================================================== */
/* special case for BBOX node. */
/* ==================================================================== */
if (psFilterNode->psLeftNode && psFilterNode->psRightNode &&
(strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") == 0 ||
strcasecmp(psFilterNode->psRightNode->pszValue, "BBOX") == 0 ||
FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) ||
FLTIsGeosNode(psFilterNode->psRightNode->pszValue)))
{
/*strcat(szBuffer, " (");*/
if (strcasecmp(psFilterNode->psLeftNode->pszValue, "BBOX") != 0 &&
strcasecmp(psFilterNode->psLeftNode->pszValue, "DWithin") != 0 &&
FLTIsGeosNode(psFilterNode->psLeftNode->pszValue) == MS_FALSE)
pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
else
pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) * (strlen(pszTmp) + 3));
pszBuffer[0] = '\0';
/*
if (strcasecmp(psFilterNode->psLeftNode->pszValue, "PropertyIsLike") == 0 ||
strcasecmp(psFilterNode->psRightNode->pszValue, "PropertyIsLike") == 0)
sprintf(pszBuffer, "%s", pszTmp);
else
*/
sprintf(pszBuffer, "(%s)", pszTmp);
free(pszTmp);
return pszBuffer;
}
/* -------------------------------------------------------------------- */
/* OR and AND */
/* -------------------------------------------------------------------- */
if (psFilterNode->psLeftNode && psFilterNode->psRightNode) {
pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) *
(strlen(pszTmp) + strlen(psFilterNode->pszValue) + 5));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, " ");
strcat(pszBuffer, psFilterNode->pszValue);
strcat(pszBuffer, " ");
free(pszTmp);
pszTmp = FLTGetNodeExpression(psFilterNode->psRightNode, lp);
if (!pszTmp) {
msFree(pszBuffer);
return NULL;
}
nTmp = strlen(pszBuffer);
pszBuffer = (char *)realloc(pszBuffer,
sizeof(char) * (strlen(pszTmp) + nTmp +3));
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
free(pszTmp);
}
/* -------------------------------------------------------------------- */
/* NOT */
/* -------------------------------------------------------------------- */
else if (psFilterNode->psLeftNode &&
strcasecmp(psFilterNode->pszValue, "NOT") == 0) {
pszTmp = FLTGetNodeExpression(psFilterNode->psLeftNode, lp);
if (!pszTmp)
return NULL;
pszBuffer = (char *)malloc(sizeof(char) *
(strlen(pszTmp) + 9));
pszBuffer[0] = '\0';
strcat(pszBuffer, " (NOT ");
strcat(pszBuffer, pszTmp);
strcat(pszBuffer, ") ");
free(pszTmp);
} else
return NULL;
return pszBuffer;
}
/************************************************************************/
/* FLTGetBinaryComparisonExpresssion */
/* */
/* Return the expression for a binary comparison filter node. */
/************************************************************************/
char *FLTGetBinaryComparisonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
int bString=0;
char szTmp[256];
szBuffer[0] = '\0';
if (!psFilterNode || !FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
return NULL;
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (psFilterNode->psRightNode->pszValue) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
bString = 1;
}
/* specical case to be able to have empty strings in the expression. */
if (psFilterNode->psRightNode->pszValue == NULL)
bString = 1;
if (bString)
strlcat(szBuffer, " (\"[", bufferSize);
else
strlcat(szBuffer, " ([", bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "]\" ", bufferSize);
else
strlcat(szBuffer, "] ", bufferSize);
/* logical operator */
if (strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0) {
/*case insensitive set ? */
if (psFilterNode->psRightNode->pOther &&
(*(int *)psFilterNode->psRightNode->pOther) == 1) {
strlcat(szBuffer, "IEQ", bufferSize);
} else
strlcat(szBuffer, "=", bufferSize);
} else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsNotEqualTo") == 0)
strlcat(szBuffer, "!=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThan") == 0)
strlcat(szBuffer, "<", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThan") == 0)
strlcat(szBuffer, ">", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThanOrEqualTo") == 0)
strlcat(szBuffer, "<=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThanOrEqualTo") == 0)
strlcat(szBuffer, ">=", bufferSize);
strlcat(szBuffer, " ", bufferSize);
/* value */
if (bString)
strlcat(szBuffer, "\"", bufferSize);
if (psFilterNode->psRightNode->pszValue)
strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "\"", bufferSize);
strlcat(szBuffer, ") ", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetBinaryComparisonSQLExpresssion */
/* */
/* Return the expression for a binary comparison filter node. */
/************************************************************************/
char *FLTGetBinaryComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
int bString=0;
char szTmp[256];
char* pszEscapedStr = NULL;
szBuffer[0] = '\0';
if (!psFilterNode || !
FLTIsBinaryComparisonFilterType(psFilterNode->pszValue))
return NULL;
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (psFilterNode->psRightNode->pszValue) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(psFilterNode->psRightNode->pszValue) == MS_FALSE)
bString = 1;
}
/* specical case to be able to have empty strings in the expression. */
if (psFilterNode->psRightNode->pszValue == NULL)
bString = 1;
/*opening bracket*/
strlcat(szBuffer, " (", bufferSize);
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
/* attribute */
/*case insensitive set ? */
if (bString &&
strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0 &&
psFilterNode->psRightNode->pOther &&
(*(int *)psFilterNode->psRightNode->pOther) == 1) {
snprintf(szTmp, sizeof(szTmp), "lower(%s) ", pszEscapedStr);
strlcat(szBuffer, szTmp, bufferSize);
} else
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
/* logical operator */
if (strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0)
strlcat(szBuffer, "=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsNotEqualTo") == 0)
strlcat(szBuffer, "<>", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThan") == 0)
strlcat(szBuffer, "<", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThan") == 0)
strlcat(szBuffer, ">", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsLessThanOrEqualTo") == 0)
strlcat(szBuffer, "<=", bufferSize);
else if (strcasecmp(psFilterNode->pszValue,
"PropertyIsGreaterThanOrEqualTo") == 0)
strlcat(szBuffer, ">=", bufferSize);
strlcat(szBuffer, " ", bufferSize);
/* value */
if (bString &&
psFilterNode->psRightNode->pszValue &&
strcasecmp(psFilterNode->pszValue,
"PropertyIsEqualTo") == 0 &&
psFilterNode->psRightNode->pOther &&
(*(int *)psFilterNode->psRightNode->pOther) == 1) {
char* pszEscapedStr;
pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
snprintf(szTmp, sizeof(szTmp), "lower('%s') ", pszEscapedStr);
msFree(pszEscapedStr);
strlcat(szBuffer, szTmp, bufferSize);
} else {
if (bString)
strlcat(szBuffer, "'", bufferSize);
if (psFilterNode->psRightNode->pszValue) {
if (bString) {
char* pszEscapedStr;
pszEscapedStr = msLayerEscapeSQLParam(lp, psFilterNode->psRightNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
} else
strlcat(szBuffer, psFilterNode->psRightNode->pszValue, bufferSize);
}
if (bString)
strlcat(szBuffer, "'", bufferSize);
}
/*closing bracket*/
strlcat(szBuffer, ") ", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsBetweenComparisonSQLExpresssion */
/* */
/* Build an SQL expresssion for IsBteween Filter. */
/************************************************************************/
char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char **aszBounds = NULL;
int nBounds = 0;
int bString=0;
char szTmp[256];
char* pszEscapedStr;
szBuffer[0] = '\0';
if (!psFilterNode ||
!(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
return NULL;
if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the bounds value which are stored like boundmin;boundmax */
/* -------------------------------------------------------------------- */
aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
if (nBounds != 2) {
msFreeCharArray(aszBounds, nBounds);
return NULL;
}
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (aszBounds[0]) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
bString = 1;
}
if (!bString) {
if (aszBounds[1]) {
if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
bString = 1;
}
}
/* -------------------------------------------------------------------- */
/* build expresssion. */
/* -------------------------------------------------------------------- */
/*opening paranthesis */
strlcat(szBuffer, " (", bufferSize);
/* attribute */
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
/*between*/
strlcat(szBuffer, " BETWEEN ", bufferSize);
/*bound 1*/
if (bString)
strlcat(szBuffer,"'", bufferSize);
pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[0]);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (bString)
strlcat(szBuffer,"'", bufferSize);
strlcat(szBuffer, " AND ", bufferSize);
/*bound 2*/
if (bString)
strlcat(szBuffer, "'", bufferSize);
pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[1]);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (bString)
strlcat(szBuffer,"'", bufferSize);
/*closing paranthesis*/
strlcat(szBuffer, ")", bufferSize);
msFreeCharArray(aszBounds, nBounds);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsBetweenComparisonExpresssion */
/* */
/* Build expresssion for IsBteween Filter. */
/************************************************************************/
char *FLTGetIsBetweenComparisonExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char **aszBounds = NULL;
int nBounds = 0;
int bString=0;
char szTmp[256];
szBuffer[0] = '\0';
if (!psFilterNode ||
!(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
return NULL;
if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the bounds value which are stored like boundmin;boundmax */
/* -------------------------------------------------------------------- */
aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
if (nBounds != 2) {
msFreeCharArray(aszBounds, nBounds);
return NULL;
}
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (aszBounds[0]) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
bString = 1;
}
if (!bString) {
if (aszBounds[1]) {
if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
bString = 1;
}
}
/* -------------------------------------------------------------------- */
/* build expresssion. */
/* -------------------------------------------------------------------- */
if (bString)
strlcat(szBuffer, " (\"[", bufferSize);
else
strlcat(szBuffer, " ([", bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "]\" ", bufferSize);
else
strlcat(szBuffer, "] ", bufferSize);
strlcat(szBuffer, " >= ", bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, aszBounds[0], bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, " AND ", bufferSize);
if (bString)
strlcat(szBuffer, " \"[", bufferSize);
else
strlcat(szBuffer, " [", bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
if (bString)
strlcat(szBuffer, "]\" ", bufferSize);
else
strlcat(szBuffer, "] ", bufferSize);
strlcat(szBuffer, " <= ", bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, aszBounds[1], bufferSize);
if (bString)
strlcat(szBuffer,"\"", bufferSize);
strlcat(szBuffer, ")", bufferSize);
msFreeCharArray(aszBounds, nBounds);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsLikeComparisonExpression */
/* */
/* Build expression for IsLike filter. */
/************************************************************************/
char *FLTGetIsLikeComparisonExpression(FilterEncodingNode *psFilterNode)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char szTmp[256];
char *pszValue = NULL;
const char *pszWild = NULL;
const char *pszSingle = NULL;
const char *pszEscape = NULL;
int bCaseInsensitive = 0;
int nLength=0, i=0, iTmp=0;
FEPropertyIsLike* propIsLike;
if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
!psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
return NULL;
propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
pszWild = propIsLike->pszWildCard;
pszSingle = propIsLike->pszSingleChar;
pszEscape = propIsLike->pszEscapeChar;
bCaseInsensitive = propIsLike->bCaseInsensitive;
if (!pszWild || strlen(pszWild) == 0 ||
!pszSingle || strlen(pszSingle) == 0 ||
!pszEscape || strlen(pszEscape) == 0)
return NULL;
/* -------------------------------------------------------------------- */
/* Use operand with regular expressions. */
/* -------------------------------------------------------------------- */
szBuffer[0] = '\0';
sprintf(szTmp, "%s", " (\"[");
szTmp[4] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
/* attribute */
strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
/*#3521 */
if(bCaseInsensitive == 1)
sprintf(szTmp, "%s", "]\" ~* /");
else
sprintf(szTmp, "%s", "]\" =~ /");
szTmp[7] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
szBuffer[strlen(szBuffer)] = '\0';
pszValue = psFilterNode->psRightNode->pszValue;
nLength = strlen(pszValue);
iTmp =0;
if (nLength > 0 && pszValue[0] != pszWild[0] &&
pszValue[0] != pszSingle[0] &&
pszValue[0] != pszEscape[0]) {
szTmp[iTmp]= '^';
iTmp++;
}
for (i=0; i<nLength; i++) {
if (pszValue[i] != pszWild[0] &&
pszValue[i] != pszSingle[0] &&
pszValue[i] != pszEscape[0]) {
szTmp[iTmp] = pszValue[i];
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszSingle[0]) {
szTmp[iTmp] = '.';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszEscape[0]) {
szTmp[iTmp] = '\\';
iTmp++;
szTmp[iTmp] = '\0';
} else if (pszValue[i] == pszWild[0]) {
/* strcat(szBuffer, "[0-9,a-z,A-Z,\\s]*"); */
/* iBuffer+=17; */
szTmp[iTmp++] = '.';
szTmp[iTmp++] = '*';
szTmp[iTmp] = '\0';
}
}
szTmp[iTmp] = '/';
szTmp[++iTmp] = '\0';
strlcat(szBuffer, szTmp, bufferSize);
strlcat(szBuffer, ")", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTGetIsLikeComparisonSQLExpression */
/* */
/* Build an sql expression for IsLike filter. */
/************************************************************************/
char *FLTGetIsLikeComparisonSQLExpression(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char *pszValue = NULL;
const char *pszWild = NULL;
const char *pszSingle = NULL;
const char *pszEscape = NULL;
char szTmp[4];
int nLength=0, i=0, j=0;
int bCaseInsensitive = 0;
char *pszEscapedStr = NULL;
FEPropertyIsLike* propIsLike;
if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode ||
!psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue)
return NULL;
propIsLike = (FEPropertyIsLike *)psFilterNode->pOther;
pszWild = propIsLike->pszWildCard;
pszSingle = propIsLike->pszSingleChar;
pszEscape = propIsLike->pszEscapeChar;
bCaseInsensitive = propIsLike->bCaseInsensitive;
if (!pszWild || strlen(pszWild) == 0 ||
!pszSingle || strlen(pszSingle) == 0 ||
!pszEscape || strlen(pszEscape) == 0)
return NULL;
if (pszEscape[0] == '\'') {
/* This might be valid, but the risk of SQL injection is too high */
/* and the below code is not ready for that */
/* Someone who does this has clearly suspect intentions ! */
msSetError(MS_MISCERR, "Single quote character is not allowed as an escaping character.",
"FLTGetIsLikeComparisonSQLExpression()");
return NULL;
}
szBuffer[0] = '\0';
/*opening bracket*/
strlcat(szBuffer, " (", bufferSize);
/* attribute name */
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
if (lp->connectiontype == MS_POSTGIS) {
if (bCaseInsensitive == 1)
strlcat(szBuffer, "::text ilike '", bufferSize);
else
strlcat(szBuffer, "::text like '", bufferSize);
} else
strlcat(szBuffer, " like '", bufferSize);
pszValue = psFilterNode->psRightNode->pszValue;
nLength = strlen(pszValue);
pszEscapedStr = (char*) msSmallMalloc( 3 * nLength + 1);
for (i=0, j=0; i<nLength; i++) {
char c = pszValue[i];
if (c != pszWild[0] &&
c != pszSingle[0] &&
c != pszEscape[0]) {
if (c == '\'') {
pszEscapedStr[j++] = '\'';
pszEscapedStr[j++] = '\'';
} else if (c == '\\') {
pszEscapedStr[j++] = '\\';
pszEscapedStr[j++] = '\\';
} else
pszEscapedStr[j++] = c;
} else if (c == pszSingle[0]) {
pszEscapedStr[j++] = '_';
} else if (c == pszEscape[0]) {
pszEscapedStr[j++] = pszEscape[0];
if (i+1<nLength) {
char nextC = pszValue[i+1];
i++;
if (nextC == '\'') {
pszEscapedStr[j++] = '\'';
pszEscapedStr[j++] = '\'';
} else
pszEscapedStr[j++] = nextC;
}
} else if (c == pszWild[0]) {
pszEscapedStr[j++] = '%';
}
}
pszEscapedStr[j++] = 0;
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
strlcat(szBuffer, "'", bufferSize);
if (lp->connectiontype != MS_OGR) {
if (lp->connectiontype == MS_POSTGIS && pszEscape[0] == '\\')
strlcat(szBuffer, " escape E'", bufferSize);
else
strlcat(szBuffer, " escape '", bufferSize);
szTmp[0] = pszEscape[0];
if (pszEscape[0] == '\\') {
szTmp[1] = '\\';
szTmp[2] = '\'';
szTmp[3] = '\0';
} else {
szTmp[1] = '\'';
szTmp[2] = '\0';
}
strlcat(szBuffer, szTmp, bufferSize);
}
strlcat(szBuffer, ") ", bufferSize);
return msStrdup(szBuffer);
}
/************************************************************************/
/* FLTHasSpatialFilter */
/* */
/* Utility function to see if a spatial filter is included in */
/* the node. */
/************************************************************************/
int FLTHasSpatialFilter(FilterEncodingNode *psNode)
{
int bResult = MS_FALSE;
if (!psNode)
return MS_FALSE;
if (psNode->eType == FILTER_NODE_TYPE_LOGICAL) {
if (psNode->psLeftNode)
bResult = FLTHasSpatialFilter(psNode->psLeftNode);
if (bResult)
return MS_TRUE;
if (psNode->psRightNode)
bResult = FLTHasSpatialFilter(psNode->psRightNode);
if (bResult)
return MS_TRUE;
} else if (FLTIsBBoxFilter(psNode) || FLTIsPointFilter(psNode) ||
FLTIsLineFilter(psNode) || FLTIsPolygonFilter(psNode))
return MS_TRUE;
return MS_FALSE;
}
/************************************************************************/
/* FLTCreateFeatureIdFilterEncoding */
/* */
/* Utility function to create a filter node of FeatureId type. */
/************************************************************************/
FilterEncodingNode *FLTCreateFeatureIdFilterEncoding(const char *pszString)
{
FilterEncodingNode *psFilterNode = NULL;
if (pszString) {
psFilterNode = FLTCreateFilterEncodingNode();
psFilterNode->eType = FILTER_NODE_TYPE_FEATUREID;
psFilterNode->pszValue = msStrdup(pszString);
return psFilterNode;
}
return NULL;
}
/************************************************************************/
/* FLTParseGMLBox */
/* */
/* Parse gml box. Used for FE 1.0 */
/************************************************************************/
int FLTParseGMLBox(CPLXMLNode *psBox, rectObj *psBbox, char **ppszSRS)
{
int bCoordinatesValid = 0;
CPLXMLNode *psCoordinates = NULL;
CPLXMLNode *psCoord1 = NULL, *psCoord2 = NULL;
char **papszCoords=NULL, **papszMin=NULL, **papszMax = NULL;
int nCoords = 0, nCoordsMin = 0, nCoordsMax = 0;
const char *pszTmpCoord = NULL;
const char *pszSRS = NULL;
const char *pszTS = NULL;
const char *pszCS = NULL;
double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
if (psBox) {
pszSRS = CPLGetXMLValue(psBox, "srsName", NULL);
if (ppszSRS && pszSRS)
*ppszSRS = msStrdup(pszSRS);
psCoordinates = CPLGetXMLNode(psBox, "coordinates");
pszTS = CPLGetXMLValue(psCoordinates, "ts", NULL);
if( pszTS == NULL )
pszTS = " ";
pszCS = CPLGetXMLValue(psCoordinates, "cs", NULL);
if( pszCS == NULL )
pszCS = ",";
pszTmpCoord = CPLGetXMLValue(psCoordinates, NULL, NULL);
if (pszTmpCoord) {
papszCoords = msStringSplit(pszTmpCoord, pszTS[0], &nCoords);
if (papszCoords && nCoords == 2) {
papszMin = msStringSplit(papszCoords[0], pszCS[0], &nCoordsMin);
if (papszMin && nCoordsMin == 2) {
papszMax = msStringSplit(papszCoords[1], pszCS[0], &nCoordsMax);
}
if (papszMax && nCoordsMax == 2) {
bCoordinatesValid =1;
minx = atof(papszMin[0]);
miny = atof(papszMin[1]);
maxx = atof(papszMax[0]);
maxy = atof(papszMax[1]);
}
msFreeCharArray(papszMin, nCoordsMin);
msFreeCharArray(papszMax, nCoordsMax);
}
msFreeCharArray(papszCoords, nCoords);
} else {
psCoord1 = CPLGetXMLNode(psBox, "coord");
psCoord2 = FLTGetNextSibblingNode(psCoord1);
if (psCoord1 && psCoord2 && strcmp(psCoord2->pszValue, "coord") == 0) {
const char* pszX = CPLGetXMLValue(psCoord1, "X", NULL);
const char* pszY = CPLGetXMLValue(psCoord1, "Y", NULL);
if (pszX && pszY) {
minx = atof(pszX);
miny = atof(pszY);
pszX = CPLGetXMLValue(psCoord2, "X", NULL);
pszY = CPLGetXMLValue(psCoord2, "Y", NULL);
if (pszX && pszY) {
maxx = atof(pszX);
maxy = atof(pszY);
bCoordinatesValid = 1;
}
}
}
}
}
if (bCoordinatesValid) {
psBbox->minx = minx;
psBbox->miny = miny;
psBbox->maxx = maxx;
psBbox->maxy = maxy;
}
return bCoordinatesValid;
}
/************************************************************************/
/* FLTParseGMLEnvelope */
/* */
/* Utility function to parse a gml:Envelope (used for SOS and FE1.1)*/
/************************************************************************/
int FLTParseGMLEnvelope(CPLXMLNode *psRoot, rectObj *psBbox, char **ppszSRS)
{
CPLXMLNode *psUpperCorner=NULL, *psLowerCorner=NULL;
const char *pszLowerCorner=NULL, *pszUpperCorner=NULL;
int bValid = 0;
char **tokens;
int n;
if (psRoot && psBbox && psRoot->eType == CXT_Element &&
EQUAL(psRoot->pszValue,"Envelope")) {
/*Get the srs if available*/
if (ppszSRS) {
const char* pszSRS = CPLGetXMLValue(psRoot, "srsName", NULL);
if( pszSRS != NULL )
*ppszSRS = msStrdup(pszSRS);
}
psLowerCorner = CPLSearchXMLNode(psRoot, "lowerCorner");
psUpperCorner = CPLSearchXMLNode(psRoot, "upperCorner");
if (psLowerCorner && psUpperCorner) {
pszLowerCorner = CPLGetXMLValue(psLowerCorner, NULL, NULL);
pszUpperCorner = CPLGetXMLValue(psUpperCorner, NULL, NULL);
if (pszLowerCorner && pszUpperCorner) {
tokens = msStringSplit(pszLowerCorner, ' ', &n);
if (tokens && n >= 2) {
psBbox->minx = atof(tokens[0]);
psBbox->miny = atof(tokens[1]);
msFreeCharArray(tokens, n);
tokens = msStringSplit(pszUpperCorner, ' ', &n);
if (tokens && n >= 2) {
psBbox->maxx = atof(tokens[0]);
psBbox->maxy = atof(tokens[1]);
bValid = 1;
}
}
msFreeCharArray(tokens, n);
}
}
}
return bValid;
}
/************************************************************************/
/* FLTNeedSRSSwapping */
/************************************************************************/
static int FLTNeedSRSSwapping( const char* pszSRS )
{
int bNeedSwapping = MS_FALSE;
projectionObj sProjTmp;
msInitProjection(&sProjTmp);
if (msLoadProjectionStringEPSG(&sProjTmp, pszSRS) == 0) {
bNeedSwapping = msIsAxisInvertedProj(&sProjTmp);
}
msFreeProjection(&sProjTmp);
return bNeedSwapping;
}
/************************************************************************/
/* FLTDoAxisSwappingIfNecessary */
/* */
/* Explore all geometries and BBOX to do axis swapping when the */
/* SRS requires it. If no explicit SRS is attached to the geometry */
/* the bDefaultSRSNeedsAxisSwapping is taken into account. The */
/* caller will have to determine its value from a more general */
/* context. */
/************************************************************************/
void FLTDoAxisSwappingIfNecessary(FilterEncodingNode *psFilterNode,
int bDefaultSRSNeedsAxisSwapping)
{
if( psFilterNode == NULL )
return;
if( psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
psFilterNode->psRightNode->eType == FILTER_NODE_TYPE_BBOX )
{
rectObj* rect = (rectObj *)psFilterNode->psRightNode->pOther;
const char* pszSRS = psFilterNode->pszSRS;
if( (pszSRS != NULL && FLTNeedSRSSwapping(pszSRS)) ||
(pszSRS == NULL && bDefaultSRSNeedsAxisSwapping) )
{
double tmp;
tmp = rect->minx;
rect->minx = rect->miny;
rect->miny = tmp;
tmp = rect->maxx;
rect->maxx = rect->maxy;
rect->maxy = tmp;
}
}
else if( psFilterNode->eType == FILTER_NODE_TYPE_SPATIAL &&
FLTIsGeometryFilterNodeType(psFilterNode->psRightNode->eType) )
{
shapeObj* shape = (shapeObj *)(psFilterNode->psRightNode->pOther);
const char* pszSRS = psFilterNode->pszSRS;
if( (pszSRS != NULL && FLTNeedSRSSwapping(pszSRS)) ||
(pszSRS == NULL && bDefaultSRSNeedsAxisSwapping) )
{
msAxisSwapShape(shape);
}
}
else
{
FLTDoAxisSwappingIfNecessary(psFilterNode->psLeftNode, bDefaultSRSNeedsAxisSwapping);
FLTDoAxisSwappingIfNecessary(psFilterNode->psRightNode, bDefaultSRSNeedsAxisSwapping);
}
}
static void FLTReplacePropertyName(FilterEncodingNode *psFilterNode,
const char *pszOldName,
const char *pszNewName)
{
if (psFilterNode && pszOldName && pszNewName) {
if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
if (psFilterNode->pszValue &&
strcasecmp(psFilterNode->pszValue, pszOldName) == 0) {
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup(pszNewName);
}
}
if (psFilterNode->psLeftNode)
FLTReplacePropertyName(psFilterNode->psLeftNode, pszOldName,
pszNewName);
if (psFilterNode->psRightNode)
FLTReplacePropertyName(psFilterNode->psRightNode, pszOldName,
pszNewName);
}
}
static int FLTIsGMLDefaultProperty(const char* pszName)
{
return (strcmp(pszName, "gml:name") == 0 ||
strcmp(pszName, "gml:description") == 0 ||
strcmp(pszName, "gml:descriptionReference") == 0 ||
strcmp(pszName, "gml:identifier") == 0 ||
strcmp(pszName, "gml:boundedBy") == 0 ||
strcmp(pszName, "@gml:id") == 0);
}
static void FLTStripNameSpacesFromPropertyName(FilterEncodingNode *psFilterNode)
{
char **tokens=NULL;
int n=0;
if (psFilterNode) {
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME &&
FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) )
{
return;
}
if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
if (psFilterNode->pszValue &&
strstr(psFilterNode->pszValue, ":")) {
tokens = msStringSplit(psFilterNode->pszValue, ':', &n);
if (tokens && n==2) {
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup(tokens[1]);
}
msFreeCharArray(tokens, n);
}
}
if (psFilterNode->psLeftNode)
FLTStripNameSpacesFromPropertyName(psFilterNode->psLeftNode);
if (psFilterNode->psRightNode)
FLTStripNameSpacesFromPropertyName(psFilterNode->psRightNode);
}
}
static void FLTRemoveGroupName(FilterEncodingNode *psFilterNode,
gmlGroupListObj* groupList)
{
int i;
if (psFilterNode) {
if (psFilterNode->eType == FILTER_NODE_TYPE_PROPERTYNAME) {
if( psFilterNode->pszValue != NULL )
{
const char* pszPropertyName = psFilterNode->pszValue;
const char* pszSlash = strchr(pszPropertyName, '/');
if( pszSlash != NULL ) {
const char* pszColon = strchr(pszPropertyName, ':');
if( pszColon != NULL && pszColon < pszSlash )
pszPropertyName = pszColon + 1;
for(i=0;i<groupList->numgroups;i++) {
const char* pszGroupName = groupList->groups[i].name;
size_t nGroupNameLen = strlen(pszGroupName);
if(strncasecmp(pszPropertyName, pszGroupName, nGroupNameLen) == 0 &&
pszPropertyName[nGroupNameLen] == '/') {
char* pszTmp;
pszPropertyName = pszPropertyName + nGroupNameLen + 1;
pszColon = strchr(pszPropertyName, ':');
if( pszColon != NULL )
pszPropertyName = pszColon + 1;
pszTmp = msStrdup(pszPropertyName);
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = pszTmp;
break;
}
}
}
}
}
if (psFilterNode->psLeftNode)
FLTRemoveGroupName(psFilterNode->psLeftNode, groupList);
if (psFilterNode->psRightNode)
FLTRemoveGroupName(psFilterNode->psRightNode, groupList);
}
}
/************************************************************************/
/* FLTPreParseFilterForAliasAndGroup */
/* */
/* Utility function to replace aliased' and grouped attributes */
/* with their internal name. */
/************************************************************************/
void FLTPreParseFilterForAliasAndGroup(FilterEncodingNode *psFilterNode,
mapObj *map, int i, const char *namespaces)
{
layerObj *lp=NULL;
char szTmp[256];
const char *pszFullName = NULL;
int layerWasOpened = MS_FALSE;
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR)
if (psFilterNode && map && i>=0 && i<map->numlayers) {
/*strip name spaces before hand*/
FLTStripNameSpacesFromPropertyName(psFilterNode);
lp = GET_LAYER(map, i);
layerWasOpened = msLayerIsOpen(lp);
if (msLayerOpen(lp) == MS_SUCCESS && msLayerGetItems(lp) == MS_SUCCESS) {
/* Remove group names from property names if using groupname/itemname syntax */
gmlGroupListObj* groupList = msGMLGetGroups(lp, namespaces);
if( groupList && groupList->numgroups > 0 )
FLTRemoveGroupName(psFilterNode, groupList);
msGMLFreeGroups(groupList);
for(i=0; i<lp->numitems; i++) {
if (!lp->items[i] || strlen(lp->items[i]) <= 0)
continue;
snprintf(szTmp, sizeof(szTmp), "%s_alias", lp->items[i]);
pszFullName = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
if (pszFullName) {
FLTReplacePropertyName(psFilterNode, pszFullName,
lp->items[i]);
}
}
if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
msLayerClose(lp);
}
}
#else
msSetError(MS_MISCERR, "OWS support is not available.",
"FLTPreParseFilterForAlias()");
#endif
}
/************************************************************************/
/* FLTCheckFeatureIdFilters */
/* */
/* Check that FeatureId filters match features in the active */
/* layer. */
/************************************************************************/
int FLTCheckFeatureIdFilters(FilterEncodingNode *psFilterNode,
mapObj *map, int i)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_FEATUREID)
{
char** tokens;
int nTokens = 0;
layerObj* lp;
int j;
lp = GET_LAYER(map, i);
tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
for (j=0; j<nTokens; j++) {
const char* pszId = tokens[j];
const char* pszDot = strchr(pszId, '.');
if( pszDot )
{
if( pszDot - pszId != strlen(lp->name) ||
strncasecmp(pszId, lp->name, strlen(lp->name)) != 0 )
{
msSetError(MS_MISCERR, "Feature id %s not consistent with feature type name %s.",
"FLTPreParseFilterForAlias()", pszId, lp->name);
status = MS_FAILURE;
break;
}
}
}
msFreeCharArray(tokens, nTokens);
}
if (psFilterNode->psLeftNode)
{
status = FLTCheckFeatureIdFilters(psFilterNode->psLeftNode, map, i);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTCheckFeatureIdFilters(psFilterNode->psRightNode, map, i);
}
}
return status;
}
/************************************************************************/
/* FLTCheckInvalidOperand */
/* */
/* Check that the operand of a comparison operator is valid */
/* Currently only detects use of boundedBy in a binary comparison */
/************************************************************************/
int FLTCheckInvalidOperand(FilterEncodingNode *psFilterNode)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
{
if( strcmp(psFilterNode->psLeftNode->pszValue, "gml:boundedBy") == 0 &&
strcmp(psFilterNode->pszValue, "PropertyIsNull") != 0 &&
strcmp(psFilterNode->pszValue, "PropertyIsNil") != 0 )
{
msSetError(MS_MISCERR, "Operand '%s' is invalid in comparison.",
"FLTCheckInvalidOperand()", psFilterNode->psLeftNode->pszValue);
return MS_FAILURE;
}
}
if (psFilterNode->psLeftNode)
{
status = FLTCheckInvalidOperand(psFilterNode->psLeftNode);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTCheckInvalidOperand(psFilterNode->psRightNode);
}
}
return status;
}
/************************************************************************/
/* FLTProcessPropertyIsNull */
/* */
/* HACK for PropertyIsNull processing. PostGIS & Spatialite only */
/* for now. */
/************************************************************************/
int FLTProcessPropertyIsNull(FilterEncodingNode *psFilterNode,
mapObj *map, int i)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME &&
strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 &&
!FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) )
{
layerObj* lp;
int layerWasOpened;
lp = GET_LAYER(map, i);
layerWasOpened = msLayerIsOpen(lp);
/* Horrible HACK to compensate for the lack of null testing in MapServer */
if( (lp->connectiontype == MS_POSTGIS ||
(lp->connectiontype == MS_OGR && msOGRIsSpatialite(lp))) &&
strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 )
{
msFree(psFilterNode->pszValue);
psFilterNode->pszValue = msStrdup("PropertyIsEqualTo");
psFilterNode->psRightNode = FLTCreateBinaryCompFilterEncodingNode();
psFilterNode->psRightNode->eType = FILTER_NODE_TYPE_LITERAL;
psFilterNode->psRightNode->pszValue = msStrdup("_MAPSERVER_NULL_");
}
if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
msLayerClose(lp);
}
if (psFilterNode->psLeftNode)
{
status = FLTProcessPropertyIsNull(psFilterNode->psLeftNode, map, i);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTProcessPropertyIsNull(psFilterNode->psRightNode, map, i);
}
}
return status;
}
/************************************************************************/
/* FLTCheckInvalidProperty */
/* */
/* Check that property names are known */
/************************************************************************/
int FLTCheckInvalidProperty(FilterEncodingNode *psFilterNode,
mapObj *map, int i)
{
int status = MS_SUCCESS;
if (psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME)
{
layerObj* lp;
int layerWasOpened;
int bFound = MS_FALSE;
if ((strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 ||
strcmp(psFilterNode->pszValue, "PropertyIsNil") == 0) &&
FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) )
{
return MS_SUCCESS;
}
lp = GET_LAYER(map, i);
layerWasOpened = msLayerIsOpen(lp);
if ((layerWasOpened || msLayerOpen(lp) == MS_SUCCESS)
&& msLayerGetItems(lp) == MS_SUCCESS) {
int i;
gmlItemListObj* items = msGMLGetItems(lp, "G");
for(i=0; i<items->numitems; i++) {
if (!items->items[i].name || strlen(items->items[i].name) <= 0 ||
!items->items[i].visible)
continue;
if (strcasecmp(items->items[i].name, psFilterNode->psLeftNode->pszValue) == 0) {
bFound = MS_TRUE;
break;
}
}
msGMLFreeItems(items);
}
if (!layerWasOpened) /* do not close the layer if it has been opened somewhere else (paging?) */
msLayerClose(lp);
if( !bFound )
{
msSetError(MS_MISCERR, "Property '%s' is unknown.",
"FLTCheckInvalidProperty()", psFilterNode->psLeftNode->pszValue);
return MS_FAILURE;
}
}
if (psFilterNode->psLeftNode)
{
status = FLTCheckInvalidProperty(psFilterNode->psLeftNode, map, i);
if( status == MS_SUCCESS )
{
if (psFilterNode->psRightNode)
status = FLTCheckInvalidProperty(psFilterNode->psRightNode, map, i);
}
}
return status;
}
/************************************************************************/
/* FLTSimplify */
/* */
/* Simplify the expression by removing parts that evaluate to */
/* constants. */
/* The passed psFilterNode is potentially consumed by the function */
/* and replaced by the returned value. */
/* If the function returns NULL, *pnEvaluation = MS_FALSE means */
/* that the filter evaluates to FALSE, or MS_TRUE that it */
/* evaluates to TRUE */
/************************************************************************/
FilterEncodingNode* FLTSimplify(FilterEncodingNode *psFilterNode,
int* pnEvaluation)
{
*pnEvaluation = -1;
/* There are no nullable or nillable property in WFS currently */
/* except gml:name or gml:description that are null */
if( psFilterNode->eType == FILTER_NODE_TYPE_COMPARISON &&
(strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 ||
strcmp(psFilterNode->pszValue, "PropertyIsNil") == 0 ) &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psLeftNode->eType == FILTER_NODE_TYPE_PROPERTYNAME )
{
if( strcmp(psFilterNode->pszValue, "PropertyIsNull") == 0 &&
FLTIsGMLDefaultProperty(psFilterNode->psLeftNode->pszValue) &&
strcmp(psFilterNode->psLeftNode->pszValue, "@gml:id") != 0 &&
strcmp(psFilterNode->psLeftNode->pszValue, "gml:boundedBy") != 0)
*pnEvaluation = MS_TRUE;
else
*pnEvaluation = MS_FALSE;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
if( psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL &&
strcasecmp(psFilterNode->pszValue, "NOT") == 0 &&
psFilterNode->psLeftNode != NULL )
{
int nEvaluation;
psFilterNode->psLeftNode = FLTSimplify(psFilterNode->psLeftNode,
&nEvaluation);
if( psFilterNode->psLeftNode == NULL )
{
*pnEvaluation = 1 - nEvaluation;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
}
if( psFilterNode->eType == FILTER_NODE_TYPE_LOGICAL &&
(strcasecmp(psFilterNode->pszValue, "AND") == 0 ||
strcasecmp(psFilterNode->pszValue, "OR") == 0) &&
psFilterNode->psLeftNode != NULL &&
psFilterNode->psRightNode != NULL )
{
FilterEncodingNode* psOtherNode;
int nEvaluation;
int nExpectedValForFastExit;
psFilterNode->psLeftNode = FLTSimplify(psFilterNode->psLeftNode,
&nEvaluation);
if( strcasecmp(psFilterNode->pszValue, "AND") == 0 )
nExpectedValForFastExit = MS_FALSE;
else
nExpectedValForFastExit = MS_TRUE;
if( psFilterNode->psLeftNode == NULL )
{
if( nEvaluation == nExpectedValForFastExit )
{
*pnEvaluation = nEvaluation;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
psOtherNode = psFilterNode->psRightNode;
psFilterNode->psRightNode = NULL;
FLTFreeFilterEncodingNode(psFilterNode);
return FLTSimplify(psOtherNode, pnEvaluation);
}
psFilterNode->psRightNode = FLTSimplify(psFilterNode->psRightNode,
&nEvaluation);
if( psFilterNode->psRightNode == NULL )
{
if( nEvaluation == nExpectedValForFastExit )
{
*pnEvaluation = nEvaluation;
FLTFreeFilterEncodingNode(psFilterNode);
return NULL;
}
psOtherNode = psFilterNode->psLeftNode;
psFilterNode->psLeftNode = NULL;
FLTFreeFilterEncodingNode(psFilterNode);
return FLTSimplify(psOtherNode, pnEvaluation);
}
}
return psFilterNode;
}
#ifdef USE_LIBXML2
xmlNodePtr FLTGetCapabilities(xmlNsPtr psNsParent, xmlNsPtr psNsOgc, int bTemporal)
{
xmlNodePtr psRootNode = NULL, psNode = NULL, psSubNode = NULL, psSubSubNode = NULL;
psRootNode = xmlNewNode(psNsParent, BAD_CAST "Filter_Capabilities");
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Spatial_Capabilities", NULL);
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "GeometryOperands", NULL);
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Point");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:LineString");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Polygon");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "GeometryOperand", BAD_CAST "gml:Envelope");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "SpatialOperators", NULL);
#ifdef USE_GEOS
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Equals");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Disjoint");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Touches");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Within");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Overlaps");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Crosses");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Intersects");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Contains");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "DWithin");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "Beyond");
#endif
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "SpatialOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "BBOX");
if (bTemporal) {
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Temporal_Capabilities", NULL);
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperands", NULL);
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimePeriod");
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperand", BAD_CAST "gml:TimeInstant");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "TemporalOperators", NULL);
psSubSubNode = xmlNewChild(psSubNode, psNsOgc, BAD_CAST "TemporalOperator", NULL);
xmlNewProp(psSubSubNode, BAD_CAST "name", BAD_CAST "TM_Equals");
}
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Scalar_Capabilities", NULL);
xmlNewChild(psNode, psNsOgc, BAD_CAST "LogicalOperators", NULL);
psNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperators", NULL);
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThan");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThan");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "LessThanEqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "GreaterThanEqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "EqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "NotEqualTo");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Like");
psSubNode = xmlNewChild(psNode, psNsOgc, BAD_CAST "ComparisonOperator", BAD_CAST "Between");
psNode = xmlNewChild(psRootNode, psNsOgc, BAD_CAST "Id_Capabilities", NULL);
xmlNewChild(psNode, psNsOgc, BAD_CAST "EID", NULL);
xmlNewChild(psNode, psNsOgc, BAD_CAST "FID", NULL);
return psRootNode;
}
#endif
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3111_0 |
crossvul-cpp_data_bad_2769_0 | /*
zip_open.c -- open zip archive by name
Copyright (C) 1999-2016 Dieter Baron and Thomas Klausner
This file is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <libzip@nih.at>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 <sys/stat.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zipint.h"
typedef enum {
EXISTS_ERROR = -1,
EXISTS_NOT = 0,
EXISTS_EMPTY,
EXISTS_NONEMPTY,
} exists_t;
static zip_t *_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error);
static zip_int64_t _zip_checkcons(zip_t *za, zip_cdir_t *cdir, zip_error_t *error);
static zip_cdir_t *_zip_find_central_dir(zip_t *za, zip_uint64_t len);
static exists_t _zip_file_exists(zip_source_t *src, zip_error_t *error);
static int _zip_headercomp(const zip_dirent_t *, const zip_dirent_t *);
static unsigned char *_zip_memmem(const unsigned char *, size_t, const unsigned char *, size_t);
static zip_cdir_t *_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error);
static zip_cdir_t *_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error);
static zip_cdir_t *_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error);
ZIP_EXTERN zip_t *
zip_open(const char *fn, int _flags, int *zep)
{
zip_t *za;
zip_source_t *src;
struct zip_error error;
zip_error_init(&error);
if ((src = zip_source_file_create(fn, 0, -1, &error)) == NULL) {
_zip_set_open_error(zep, &error, 0);
zip_error_fini(&error);
return NULL;
}
if ((za = zip_open_from_source(src, _flags, &error)) == NULL) {
zip_source_free(src);
_zip_set_open_error(zep, &error, 0);
zip_error_fini(&error);
return NULL;
}
zip_error_fini(&error);
return za;
}
ZIP_EXTERN zip_t *
zip_open_from_source(zip_source_t *src, int _flags, zip_error_t *error)
{
static zip_int64_t needed_support_read = -1;
static zip_int64_t needed_support_write = -1;
unsigned int flags;
zip_int64_t supported;
exists_t exists;
if (_flags < 0 || src == NULL) {
zip_error_set(error, ZIP_ER_INVAL, 0);
return NULL;
}
flags = (unsigned int)_flags;
supported = zip_source_supports(src);
if (needed_support_read == -1) {
needed_support_read = zip_source_make_command_bitmap(ZIP_SOURCE_OPEN, ZIP_SOURCE_READ, ZIP_SOURCE_CLOSE, ZIP_SOURCE_SEEK, ZIP_SOURCE_TELL, ZIP_SOURCE_STAT, -1);
needed_support_write = zip_source_make_command_bitmap(ZIP_SOURCE_BEGIN_WRITE, ZIP_SOURCE_COMMIT_WRITE, ZIP_SOURCE_ROLLBACK_WRITE, ZIP_SOURCE_SEEK_WRITE, ZIP_SOURCE_TELL_WRITE, ZIP_SOURCE_REMOVE, -1);
}
if ((supported & needed_support_read) != needed_support_read) {
zip_error_set(error, ZIP_ER_OPNOTSUPP, 0);
return NULL;
}
if ((supported & needed_support_write) != needed_support_write) {
flags |= ZIP_RDONLY;
}
if ((flags & (ZIP_RDONLY|ZIP_TRUNCATE)) == (ZIP_RDONLY|ZIP_TRUNCATE)) {
zip_error_set(error, ZIP_ER_RDONLY, 0);
return NULL;
}
exists = _zip_file_exists(src, error);
switch (exists) {
case EXISTS_ERROR:
return NULL;
case EXISTS_NOT:
if ((flags & ZIP_CREATE) == 0) {
zip_error_set(error, ZIP_ER_NOENT, 0);
return NULL;
}
return _zip_allocate_new(src, flags, error);
default: {
zip_t *za;
if (flags & ZIP_EXCL) {
zip_error_set(error, ZIP_ER_EXISTS, 0);
return NULL;
}
if (zip_source_open(src) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if (flags & ZIP_TRUNCATE) {
za = _zip_allocate_new(src, flags, error);
}
else {
/* ZIP_CREATE gets ignored if file exists and not ZIP_EXCL, just like open() */
za = _zip_open(src, flags, error);
}
if (za == NULL) {
zip_source_close(src);
return NULL;
}
return za;
}
}
}
zip_t *
_zip_open(zip_source_t *src, unsigned int flags, zip_error_t *error)
{
zip_t *za;
zip_cdir_t *cdir;
struct zip_stat st;
zip_uint64_t len, idx;
zip_stat_init(&st);
if (zip_source_stat(src, &st) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if ((st.valid & ZIP_STAT_SIZE) == 0) {
zip_error_set(error, ZIP_ER_SEEK, EOPNOTSUPP);
return NULL;
}
len = st.size;
/* treat empty files as empty archives */
if (len == 0) {
if ((za=_zip_allocate_new(src, flags, error)) == NULL) {
zip_source_free(src);
return NULL;
}
return za;
}
if ((za=_zip_allocate_new(src, flags, error)) == NULL) {
return NULL;
}
if ((cdir = _zip_find_central_dir(za, len)) == NULL) {
_zip_error_copy(error, &za->error);
/* keep src so discard does not get rid of it */
zip_source_keep(src);
zip_discard(za);
return NULL;
}
za->entry = cdir->entry;
za->nentry = cdir->nentry;
za->nentry_alloc = cdir->nentry_alloc;
za->comment_orig = cdir->comment;
free(cdir);
_zip_hash_reserve_capacity(za->names, za->nentry, &za->error);
for (idx = 0; idx < za->nentry; idx++) {
const zip_uint8_t *name = _zip_string_get(za->entry[idx].orig->filename, NULL, 0, error);
if (name == NULL) {
/* keep src so discard does not get rid of it */
zip_source_keep(src);
zip_discard(za);
return NULL;
}
if (_zip_hash_add(za->names, name, idx, ZIP_FL_UNCHANGED, &za->error) == false) {
if (za->error.zip_err != ZIP_ER_EXISTS || (flags & ZIP_CHECKCONS)) {
_zip_error_copy(error, &za->error);
/* keep src so discard does not get rid of it */
zip_source_keep(src);
zip_discard(za);
return NULL;
}
}
}
za->ch_flags = za->flags;
return za;
}
void
_zip_set_open_error(int *zep, const zip_error_t *err, int ze)
{
if (err) {
ze = zip_error_code_zip(err);
if (zip_error_system_type(err) == ZIP_ET_SYS) {
errno = zip_error_code_system(err);
}
}
if (zep)
*zep = ze;
}
/* _zip_readcdir:
tries to find a valid end-of-central-directory at the beginning of
buf, and then the corresponding central directory entries.
Returns a struct zip_cdir which contains the central directory
entries, or NULL if unsuccessful. */
static zip_cdir_t *
_zip_read_cdir(zip_t *za, zip_buffer_t *buffer, zip_uint64_t buf_offset, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint16_t comment_len;
zip_uint64_t i, left;
zip_uint64_t eocd_offset = _zip_buffer_offset(buffer);
zip_buffer_t *cd_buffer;
if (_zip_buffer_left(buffer) < EOCDLEN) {
/* not enough bytes left for comment */
zip_error_set(error, ZIP_ER_NOZIP, 0);
return NULL;
}
/* check for end-of-central-dir magic */
if (memcmp(_zip_buffer_get(buffer, 4), EOCD_MAGIC, 4) != 0) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return NULL;
}
if (eocd_offset >= EOCD64LOCLEN && memcmp(_zip_buffer_data(buffer) + eocd_offset - EOCD64LOCLEN, EOCD64LOC_MAGIC, 4) == 0) {
_zip_buffer_set_offset(buffer, eocd_offset - EOCD64LOCLEN);
cd = _zip_read_eocd64(za->src, buffer, buf_offset, za->flags, error);
}
else {
_zip_buffer_set_offset(buffer, eocd_offset);
cd = _zip_read_eocd(buffer, buf_offset, za->flags, error);
}
if (cd == NULL)
return NULL;
_zip_buffer_set_offset(buffer, eocd_offset + 20);
comment_len = _zip_buffer_get_16(buffer);
if (cd->offset + cd->size > buf_offset + eocd_offset) {
/* cdir spans past EOCD record */
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_cdir_free(cd);
return NULL;
}
if (comment_len || (za->open_flags & ZIP_CHECKCONS)) {
zip_uint64_t tail_len;
_zip_buffer_set_offset(buffer, eocd_offset + EOCDLEN);
tail_len = _zip_buffer_left(buffer);
if (tail_len < comment_len || ((za->open_flags & ZIP_CHECKCONS) && tail_len != comment_len)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_cdir_free(cd);
return NULL;
}
if (comment_len) {
if ((cd->comment=_zip_string_new(_zip_buffer_get(buffer, comment_len), comment_len, ZIP_FL_ENC_GUESS, error)) == NULL) {
_zip_cdir_free(cd);
return NULL;
}
}
}
if (cd->offset >= buf_offset) {
zip_uint8_t *data;
/* if buffer already read in, use it */
_zip_buffer_set_offset(buffer, cd->offset - buf_offset);
if ((data = _zip_buffer_get(buffer, cd->size)) == NULL) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_cdir_free(cd);
return NULL;
}
if ((cd_buffer = _zip_buffer_new(data, cd->size)) == NULL) {
zip_error_set(error, ZIP_ER_MEMORY, 0);
_zip_cdir_free(cd);
return NULL;
}
}
else {
cd_buffer = NULL;
if (zip_source_seek(za->src, (zip_int64_t)cd->offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, za->src);
_zip_cdir_free(cd);
return NULL;
}
/* possible consistency check: cd->offset = len-(cd->size+cd->comment_len+EOCDLEN) ? */
if (zip_source_tell(za->src) != (zip_int64_t)cd->offset) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
_zip_cdir_free(cd);
return NULL;
}
}
left = (zip_uint64_t)cd->size;
i=0;
while (left > 0) {
bool grown = false;
zip_int64_t entry_size;
if (i == cd->nentry) {
/* InfoZIP has a hack to avoid using Zip64: it stores nentries % 0x10000 */
/* This hack isn't applicable if we're using Zip64, or if there is no central directory entry following. */
if (cd->is_zip64 || left < CDENTRYSIZE) {
break;
}
if (!_zip_cdir_grow(cd, 0x10000, error)) {
_zip_cdir_free(cd);
_zip_buffer_free(cd_buffer);
return NULL;
}
grown = true;
}
if ((cd->entry[i].orig=_zip_dirent_new()) == NULL || (entry_size = _zip_dirent_read(cd->entry[i].orig, za->src, cd_buffer, false, error)) < 0) {
if (grown && zip_error_code_zip(error) == ZIP_ER_NOZIP) {
zip_error_set(error, ZIP_ER_INCONS, 0);
}
_zip_cdir_free(cd);
_zip_buffer_free(cd_buffer);
return NULL;
}
i++;
left -= (zip_uint64_t)entry_size;
}
if (i != cd->nentry || left > 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_buffer_free(cd_buffer);
_zip_cdir_free(cd);
return NULL;
}
if (za->open_flags & ZIP_CHECKCONS) {
bool ok;
if (cd_buffer) {
ok = _zip_buffer_eof(cd_buffer);
}
else {
zip_int64_t offset = zip_source_tell(za->src);
if (offset < 0) {
_zip_error_set_from_source(error, za->src);
_zip_cdir_free(cd);
return NULL;
}
ok = ((zip_uint64_t)offset == cd->offset + cd->size);
}
if (!ok) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_buffer_free(cd_buffer);
_zip_cdir_free(cd);
return NULL;
}
}
_zip_buffer_free(cd_buffer);
return cd;
}
/* _zip_checkcons:
Checks the consistency of the central directory by comparing central
directory entries with local headers and checking for plausible
file and header offsets. Returns -1 if not plausible, else the
difference between the lowest and the highest fileposition reached */
static zip_int64_t
_zip_checkcons(zip_t *za, zip_cdir_t *cd, zip_error_t *error)
{
zip_uint64_t i;
zip_uint64_t min, max, j;
struct zip_dirent temp;
_zip_dirent_init(&temp);
if (cd->nentry) {
max = cd->entry[0].orig->offset;
min = cd->entry[0].orig->offset;
}
else
min = max = 0;
for (i=0; i<cd->nentry; i++) {
if (cd->entry[i].orig->offset < min)
min = cd->entry[i].orig->offset;
if (min > (zip_uint64_t)cd->offset) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return -1;
}
j = cd->entry[i].orig->offset + cd->entry[i].orig->comp_size
+ _zip_string_length(cd->entry[i].orig->filename) + LENTRYSIZE;
if (j > max)
max = j;
if (max > (zip_uint64_t)cd->offset) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return -1;
}
if (zip_source_seek(za->src, (zip_int64_t)cd->entry[i].orig->offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, za->src);
return -1;
}
if (_zip_dirent_read(&temp, za->src, NULL, true, error) == -1) {
_zip_dirent_finalize(&temp);
return -1;
}
if (_zip_headercomp(cd->entry[i].orig, &temp) != 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_dirent_finalize(&temp);
return -1;
}
cd->entry[i].orig->extra_fields = _zip_ef_merge(cd->entry[i].orig->extra_fields, temp.extra_fields);
cd->entry[i].orig->local_extra_fields_read = 1;
temp.extra_fields = NULL;
_zip_dirent_finalize(&temp);
}
return (max-min) < ZIP_INT64_MAX ? (zip_int64_t)(max-min) : ZIP_INT64_MAX;
}
/* _zip_headercomp:
compares a central directory entry and a local file header
Return 0 if they are consistent, -1 if not. */
static int
_zip_headercomp(const zip_dirent_t *central, const zip_dirent_t *local)
{
if ((central->version_needed < local->version_needed)
#if 0
/* some zip-files have different values in local
and global headers for the bitflags */
|| (central->bitflags != local->bitflags)
#endif
|| (central->comp_method != local->comp_method)
|| (central->last_mod != local->last_mod)
|| !_zip_string_equal(central->filename, local->filename))
return -1;
if ((central->crc != local->crc) || (central->comp_size != local->comp_size)
|| (central->uncomp_size != local->uncomp_size)) {
/* InfoZip stores valid values in local header even when data descriptor is used.
This is in violation of the appnote. */
if (((local->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0
|| local->crc != 0 || local->comp_size != 0 || local->uncomp_size != 0))
return -1;
}
return 0;
}
static zip_t *
_zip_allocate_new(zip_source_t *src, unsigned int flags, zip_error_t *error)
{
zip_t *za;
if ((za = _zip_new(error)) == NULL) {
return NULL;
}
za->src = src;
za->open_flags = flags;
if (flags & ZIP_RDONLY) {
za->flags |= ZIP_AFL_RDONLY;
za->ch_flags |= ZIP_AFL_RDONLY;
}
return za;
}
/*
* tests for file existence
*/
static exists_t
_zip_file_exists(zip_source_t *src, zip_error_t *error)
{
struct zip_stat st;
zip_stat_init(&st);
if (zip_source_stat(src, &st) != 0) {
zip_error_t *src_error = zip_source_error(src);
if (zip_error_code_zip(src_error) == ZIP_ER_READ && zip_error_code_system(src_error) == ENOENT) {
return EXISTS_NOT;
}
_zip_error_copy(error, src_error);
return EXISTS_ERROR;
}
return (st.valid & ZIP_STAT_SIZE) && st.size == 0 ? EXISTS_EMPTY : EXISTS_NONEMPTY;
}
static zip_cdir_t *
_zip_find_central_dir(zip_t *za, zip_uint64_t len)
{
zip_cdir_t *cdir, *cdirnew;
zip_uint8_t *match;
zip_int64_t buf_offset;
zip_uint64_t buflen;
zip_int64_t a;
zip_int64_t best;
zip_error_t error;
zip_buffer_t *buffer;
if (len < EOCDLEN) {
zip_error_set(&za->error, ZIP_ER_NOZIP, 0);
return NULL;
}
buflen = (len < CDBUFSIZE ? len : CDBUFSIZE);
if (zip_source_seek(za->src, -(zip_int64_t)buflen, SEEK_END) < 0) {
zip_error_t *src_error = zip_source_error(za->src);
if (zip_error_code_zip(src_error) != ZIP_ER_SEEK || zip_error_code_system(src_error) != EFBIG) {
/* seek before start of file on my machine */
_zip_error_copy(&za->error, src_error);
return NULL;
}
}
if ((buf_offset = zip_source_tell(za->src)) < 0) {
_zip_error_set_from_source(&za->error, za->src);
return NULL;
}
if ((buffer = _zip_buffer_new_from_source(za->src, buflen, NULL, &za->error)) == NULL) {
return NULL;
}
best = -1;
cdir = NULL;
if (buflen >= CDBUFSIZE) {
/* EOCD64 locator is before EOCD, so leave place for it */
_zip_buffer_set_offset(buffer, EOCD64LOCLEN);
}
zip_error_set(&error, ZIP_ER_NOZIP, 0);
match = _zip_buffer_get(buffer, 0);
while ((match=_zip_memmem(match, _zip_buffer_left(buffer)-(EOCDLEN-4), (const unsigned char *)EOCD_MAGIC, 4)) != NULL) {
_zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer)));
if ((cdirnew = _zip_read_cdir(za, buffer, (zip_uint64_t)buf_offset, &error)) != NULL) {
if (cdir) {
if (best <= 0) {
best = _zip_checkcons(za, cdir, &error);
}
a = _zip_checkcons(za, cdirnew, &error);
if (best < a) {
_zip_cdir_free(cdir);
cdir = cdirnew;
best = a;
}
else {
_zip_cdir_free(cdirnew);
}
}
else {
cdir = cdirnew;
if (za->open_flags & ZIP_CHECKCONS)
best = _zip_checkcons(za, cdir, &error);
else {
best = 0;
}
}
cdirnew = NULL;
}
match++;
_zip_buffer_set_offset(buffer, (zip_uint64_t)(match - _zip_buffer_data(buffer)));
}
_zip_buffer_free(buffer);
if (best < 0) {
_zip_error_copy(&za->error, &error);
_zip_cdir_free(cdir);
return NULL;
}
return cdir;
}
static unsigned char *
_zip_memmem(const unsigned char *big, size_t biglen, const unsigned char *little, size_t littlelen)
{
const unsigned char *p;
if ((biglen < littlelen) || (littlelen == 0))
return NULL;
p = big-1;
while ((p=(const unsigned char *)
memchr(p+1, little[0], (size_t)(big-(p+1))+(size_t)(biglen-littlelen)+1)) != NULL) {
if (memcmp(p+1, little+1, littlelen-1)==0)
return (unsigned char *)p;
}
return NULL;
}
static zip_cdir_t *
_zip_read_eocd(zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint64_t i, nentry, size, offset, eocd_offset;
if (_zip_buffer_left(buffer) < EOCDLEN) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
eocd_offset = _zip_buffer_offset(buffer);
_zip_buffer_get(buffer, 4); /* magic already verified */
if (_zip_buffer_get_32(buffer) != 0) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
return NULL;
}
/* number of cdir-entries on this disk */
i = _zip_buffer_get_16(buffer);
/* number of cdir-entries */
nentry = _zip_buffer_get_16(buffer);
if (nentry != i) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return NULL;
}
size = _zip_buffer_get_32(buffer);
offset = _zip_buffer_get_32(buffer);
if (offset+size < offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (offset+size > buf_offset + eocd_offset) {
/* cdir spans past EOCD record */
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((flags & ZIP_CHECKCONS) && offset+size != buf_offset + eocd_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((cd=_zip_cdir_new(nentry, error)) == NULL)
return NULL;
cd->is_zip64 = false;
cd->size = size;
cd->offset = offset;
return cd;
}
static zip_cdir_t *
_zip_read_eocd64(zip_source_t *src, zip_buffer_t *buffer, zip_uint64_t buf_offset, unsigned int flags, zip_error_t *error)
{
zip_cdir_t *cd;
zip_uint64_t offset;
zip_uint8_t eocd[EOCD64LEN];
zip_uint64_t eocd_offset;
zip_uint64_t size, nentry, i, eocdloc_offset;
bool free_buffer;
zip_uint32_t num_disks, num_disks64, eocd_disk, eocd_disk64;
eocdloc_offset = _zip_buffer_offset(buffer);
_zip_buffer_get(buffer, 4); /* magic already verified */
num_disks = _zip_buffer_get_16(buffer);
eocd_disk = _zip_buffer_get_16(buffer);
eocd_offset = _zip_buffer_get_64(buffer);
if (eocd_offset > ZIP_INT64_MAX || eocd_offset + EOCD64LEN < eocd_offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if (eocd_offset + EOCD64LEN > eocdloc_offset + buf_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if (eocd_offset >= buf_offset && eocd_offset + EOCD64LEN <= buf_offset + _zip_buffer_size(buffer)) {
_zip_buffer_set_offset(buffer, eocd_offset - buf_offset);
free_buffer = false;
}
else {
if (zip_source_seek(src, (zip_int64_t)eocd_offset, SEEK_SET) < 0) {
_zip_error_set_from_source(error, src);
return NULL;
}
if ((buffer = _zip_buffer_new_from_source(src, EOCD64LEN, eocd, error)) == NULL) {
return NULL;
}
free_buffer = true;
}
if (memcmp(_zip_buffer_get(buffer, 4), EOCD64_MAGIC, 4) != 0) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
if ((flags & ZIP_CHECKCONS) && size + eocd_offset + 12 != buf_offset + eocdloc_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
_zip_buffer_get(buffer, 4); /* skip version made by/needed */
num_disks64 = _zip_buffer_get_32(buffer);
eocd_disk64 = _zip_buffer_get_32(buffer);
/* if eocd values are 0xffff, we have to use eocd64 values.
otherwise, if the values are not the same, it's inconsistent;
in any case, if the value is not 0, we don't support it */
if (num_disks == 0xffff) {
num_disks = num_disks64;
}
if (eocd_disk == 0xffff) {
eocd_disk = eocd_disk64;
}
if ((flags & ZIP_CHECKCONS) && (eocd_disk != eocd_disk64 || num_disks != num_disks64)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (num_disks != 0 || eocd_disk != 0) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
nentry = _zip_buffer_get_64(buffer);
i = _zip_buffer_get_64(buffer);
if (nentry != i) {
zip_error_set(error, ZIP_ER_MULTIDISK, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
size = _zip_buffer_get_64(buffer);
offset = _zip_buffer_get_64(buffer);
if (!_zip_buffer_ok(buffer)) {
zip_error_set(error, ZIP_ER_INTERNAL, 0);
if (free_buffer) {
_zip_buffer_free(buffer);
}
return NULL;
}
if (free_buffer) {
_zip_buffer_free(buffer);
}
if (offset > ZIP_INT64_MAX || offset+size < offset) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return NULL;
}
if ((flags & ZIP_CHECKCONS) && offset+size != eocd_offset) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return NULL;
}
if ((cd=_zip_cdir_new(nentry, error)) == NULL)
return NULL;
cd->is_zip64 = true;
cd->size = size;
cd->offset = offset;
return cd;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2769_0 |
crossvul-cpp_data_good_3501_0 | /*
* SCSI Device emulation
*
* Copyright (c) 2006 CodeSourcery.
* Based on code by Fabrice Bellard
*
* Written by Paul Brook
* Modifications:
* 2009-Dec-12 Artyom Tarasenko : implemented stamdard inquiry for the case
* when the allocation length of CDB is smaller
* than 36.
* 2009-Oct-13 Artyom Tarasenko : implemented the block descriptor in the
* MODE SENSE response.
*
* This code is licensed under the LGPL.
*
* Note that this file only handles the SCSI architecture model and device
* commands. Emulation of interface/link layer protocols is handled by
* the host adapter emulator.
*/
//#define DEBUG_SCSI
#ifdef DEBUG_SCSI
#define DPRINTF(fmt, ...) \
do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
#else
#define DPRINTF(fmt, ...) do {} while(0)
#endif
#define BADF(fmt, ...) \
do { fprintf(stderr, "scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
#include "qemu-common.h"
#include "qemu-error.h"
#include "scsi.h"
#include "scsi-defs.h"
#include "sysemu.h"
#include "blockdev.h"
#include "block_int.h"
#define SCSI_DMA_BUF_SIZE 131072
#define SCSI_MAX_INQUIRY_LEN 256
#define SCSI_REQ_STATUS_RETRY 0x01
#define SCSI_REQ_STATUS_RETRY_TYPE_MASK 0x06
#define SCSI_REQ_STATUS_RETRY_READ 0x00
#define SCSI_REQ_STATUS_RETRY_WRITE 0x02
#define SCSI_REQ_STATUS_RETRY_FLUSH 0x04
typedef struct SCSIDiskState SCSIDiskState;
typedef struct SCSIDiskReq {
SCSIRequest req;
/* Both sector and sector_count are in terms of qemu 512 byte blocks. */
uint64_t sector;
uint32_t sector_count;
struct iovec iov;
QEMUIOVector qiov;
uint32_t status;
BlockAcctCookie acct;
} SCSIDiskReq;
struct SCSIDiskState
{
SCSIDevice qdev;
BlockDriverState *bs;
/* The qemu block layer uses a fixed 512 byte sector size.
This is the number of 512 byte blocks in a single scsi sector. */
int cluster_size;
uint32_t removable;
uint64_t max_lba;
QEMUBH *bh;
char *version;
char *serial;
bool tray_open;
bool tray_locked;
};
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type);
static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf);
static void scsi_free_request(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
qemu_vfree(r->iov.iov_base);
}
/* Helper function for command completion with sense. */
static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense)
{
DPRINTF("Command complete tag=0x%x sense=%d/%d/%d\n",
r->req.tag, sense.key, sense.asc, sense.ascq);
scsi_req_build_sense(&r->req, sense);
scsi_req_complete(&r->req, CHECK_CONDITION);
}
/* Cancel a pending data transfer. */
static void scsi_cancel_io(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
DPRINTF("Cancel tag=0x%x\n", req->tag);
if (r->req.aiocb) {
bdrv_aio_cancel(r->req.aiocb);
}
r->req.aiocb = NULL;
}
static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
static void scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
n = r->qiov.size / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->qiov.size);
}
static void scsi_flush_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret < 0) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_FLUSH)) {
return;
}
}
scsi_req_complete(&r->req, GOOD);
}
/* Read more data from scsi device into buffer. */
static void scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
n = scsi_init_iovec(r);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type)
{
int is_read = (type == SCSI_REQ_STATUS_RETRY_READ);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);
if (action == BLOCK_ERR_IGNORE) {
bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);
return 0;
}
if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
|| action == BLOCK_ERR_STOP_ANY) {
type &= SCSI_REQ_STATUS_RETRY_TYPE_MASK;
r->status |= SCSI_REQ_STATUS_RETRY | type;
bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);
vm_stop(VMSTOP_DISKFULL);
} else {
switch (error) {
case ENOMEM:
scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
break;
case EINVAL:
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
break;
default:
scsi_check_condition(r, SENSE_CODE(IO_ERROR));
break;
}
bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);
}
return 1;
}
static void scsi_write_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) {
return;
}
}
n = r->qiov.size / 512;
r->sector += n;
r->sector_count -= n;
if (r->sector_count == 0) {
scsi_req_complete(&r->req, GOOD);
} else {
scsi_init_iovec(r);
DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size);
scsi_req_data(&r->req, r->qiov.size);
}
}
static void scsi_write_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_write_complete(r, -EINVAL);
return;
}
n = r->qiov.size / 512;
if (n) {
if (s->tray_open) {
scsi_write_complete(r, -ENOMEDIUM);
}
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n,
scsi_write_complete, r);
if (r->req.aiocb == NULL) {
scsi_write_complete(r, -ENOMEM);
}
} else {
/* Called for the first time. Ask the driver to send us more data. */
scsi_write_complete(r, 0);
}
}
static void scsi_dma_restart_bh(void *opaque)
{
SCSIDiskState *s = opaque;
SCSIRequest *req;
SCSIDiskReq *r;
qemu_bh_delete(s->bh);
s->bh = NULL;
QTAILQ_FOREACH(req, &s->qdev.requests, next) {
r = DO_UPCAST(SCSIDiskReq, req, req);
if (r->status & SCSI_REQ_STATUS_RETRY) {
int status = r->status;
int ret;
r->status &=
~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK);
switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) {
case SCSI_REQ_STATUS_RETRY_READ:
scsi_read_data(&r->req);
break;
case SCSI_REQ_STATUS_RETRY_WRITE:
scsi_write_data(&r->req);
break;
case SCSI_REQ_STATUS_RETRY_FLUSH:
ret = scsi_disk_emulate_command(r, r->iov.iov_base);
if (ret == 0) {
scsi_req_complete(&r->req, GOOD);
}
}
}
}
}
static void scsi_dma_restart_cb(void *opaque, int running, int reason)
{
SCSIDiskState *s = opaque;
if (!running)
return;
if (!s->bh) {
s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
qemu_bh_schedule(s->bh);
}
}
/* Return a pointer to the data buffer. */
static uint8_t *scsi_get_buf(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
return (uint8_t *)r->iov.iov_base;
}
static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int buflen = 0;
if (req->cmd.buf[1] & 0x2) {
/* Command support data - optional, not implemented */
BADF("optional INQUIRY command support request not implemented\n");
return -1;
}
if (req->cmd.buf[1] & 0x1) {
/* Vital product data */
uint8_t page_code = req->cmd.buf[2];
if (req->cmd.xfer < 4) {
BADF("Error: Inquiry (EVPD[%02X]) buffer size %zd is "
"less than 4\n", page_code, req->cmd.xfer);
return -1;
}
if (s->qdev.type == TYPE_ROM) {
outbuf[buflen++] = 5;
} else {
outbuf[buflen++] = 0;
}
outbuf[buflen++] = page_code ; // this page
outbuf[buflen++] = 0x00;
switch (page_code) {
case 0x00: /* Supported page codes, mandatory */
{
int pages;
DPRINTF("Inquiry EVPD[Supported pages] "
"buffer size %zd\n", req->cmd.xfer);
pages = buflen++;
outbuf[buflen++] = 0x00; // list of supported pages (this page)
if (s->serial)
outbuf[buflen++] = 0x80; // unit serial number
outbuf[buflen++] = 0x83; // device identification
if (s->qdev.type == TYPE_DISK) {
outbuf[buflen++] = 0xb0; // block limits
outbuf[buflen++] = 0xb2; // thin provisioning
}
outbuf[pages] = buflen - pages - 1; // number of pages
break;
}
case 0x80: /* Device serial number, optional */
{
int l;
if (!s->serial) {
DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
return -1;
}
l = strlen(s->serial);
if (l > req->cmd.xfer)
l = req->cmd.xfer;
if (l > 20)
l = 20;
DPRINTF("Inquiry EVPD[Serial number] "
"buffer size %zd\n", req->cmd.xfer);
outbuf[buflen++] = l;
memcpy(outbuf+buflen, s->serial, l);
buflen += l;
break;
}
case 0x83: /* Device identification page, mandatory */
{
int max_len = 255 - 8;
int id_len = strlen(bdrv_get_device_name(s->bs));
if (id_len > max_len)
id_len = max_len;
DPRINTF("Inquiry EVPD[Device identification] "
"buffer size %zd\n", req->cmd.xfer);
outbuf[buflen++] = 4 + id_len;
outbuf[buflen++] = 0x2; // ASCII
outbuf[buflen++] = 0; // not officially assigned
outbuf[buflen++] = 0; // reserved
outbuf[buflen++] = id_len; // length of data following
memcpy(outbuf+buflen, bdrv_get_device_name(s->bs), id_len);
buflen += id_len;
break;
}
case 0xb0: /* block limits */
{
unsigned int unmap_sectors =
s->qdev.conf.discard_granularity / s->qdev.blocksize;
unsigned int min_io_size =
s->qdev.conf.min_io_size / s->qdev.blocksize;
unsigned int opt_io_size =
s->qdev.conf.opt_io_size / s->qdev.blocksize;
if (s->qdev.type == TYPE_ROM) {
DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
page_code);
return -1;
}
/* required VPD size with unmap support */
outbuf[3] = buflen = 0x3c;
memset(outbuf + 4, 0, buflen - 4);
/* optimal transfer length granularity */
outbuf[6] = (min_io_size >> 8) & 0xff;
outbuf[7] = min_io_size & 0xff;
/* optimal transfer length */
outbuf[12] = (opt_io_size >> 24) & 0xff;
outbuf[13] = (opt_io_size >> 16) & 0xff;
outbuf[14] = (opt_io_size >> 8) & 0xff;
outbuf[15] = opt_io_size & 0xff;
/* optimal unmap granularity */
outbuf[28] = (unmap_sectors >> 24) & 0xff;
outbuf[29] = (unmap_sectors >> 16) & 0xff;
outbuf[30] = (unmap_sectors >> 8) & 0xff;
outbuf[31] = unmap_sectors & 0xff;
break;
}
case 0xb2: /* thin provisioning */
{
outbuf[3] = buflen = 8;
outbuf[4] = 0;
outbuf[5] = 0x40; /* write same with unmap supported */
outbuf[6] = 0;
outbuf[7] = 0;
break;
}
default:
BADF("Error: unsupported Inquiry (EVPD[%02X]) "
"buffer size %zd\n", page_code, req->cmd.xfer);
return -1;
}
/* done with EVPD */
return buflen;
}
/* Standard INQUIRY data */
if (req->cmd.buf[2] != 0) {
BADF("Error: Inquiry (STANDARD) page or code "
"is non-zero [%02X]\n", req->cmd.buf[2]);
return -1;
}
/* PAGE CODE == 0 */
if (req->cmd.xfer < 5) {
BADF("Error: Inquiry (STANDARD) buffer size %zd "
"is less than 5\n", req->cmd.xfer);
return -1;
}
buflen = req->cmd.xfer;
if (buflen > SCSI_MAX_INQUIRY_LEN)
buflen = SCSI_MAX_INQUIRY_LEN;
memset(outbuf, 0, buflen);
outbuf[0] = s->qdev.type & 0x1f;
if (s->qdev.type == TYPE_ROM) {
outbuf[1] = 0x80;
memcpy(&outbuf[16], "QEMU CD-ROM ", 16);
} else {
outbuf[1] = s->removable ? 0x80 : 0;
memcpy(&outbuf[16], "QEMU HARDDISK ", 16);
}
memcpy(&outbuf[8], "QEMU ", 8);
memset(&outbuf[32], 0, 4);
memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
/*
* We claim conformance to SPC-3, which is required for guests
* to ask for modern features like READ CAPACITY(16) or the
* block characteristics VPD page by default. Not all of SPC-3
* is actually implemented, but we're good enough.
*/
outbuf[2] = 5;
outbuf[3] = 2; /* Format 2 */
if (buflen > 36) {
outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
} else {
/* If the allocation length of CDB is too small,
the additional length is not adjusted */
outbuf[4] = 36 - 5;
}
/* Sync data transfer and TCQ. */
outbuf[7] = 0x10 | (req->bus->tcq ? 0x02 : 0);
return buflen;
}
static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
int page_control)
{
BlockDriverState *bdrv = s->bs;
int cylinders, heads, secs;
uint8_t *p = *p_outbuf;
/*
* If Changeable Values are requested, a mask denoting those mode parameters
* that are changeable shall be returned. As we currently don't support
* parameter changes via MODE_SELECT all bits are returned set to zero.
* The buffer was already menset to zero by the caller of this function.
*/
switch (page) {
case 4: /* Rigid disk device geometry page. */
if (s->qdev.type == TYPE_ROM) {
return -1;
}
p[0] = 4;
p[1] = 0x16;
if (page_control == 1) { /* Changeable Values */
break;
}
/* if a geometry hint is available, use it */
bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
p[2] = (cylinders >> 16) & 0xff;
p[3] = (cylinders >> 8) & 0xff;
p[4] = cylinders & 0xff;
p[5] = heads & 0xff;
/* Write precomp start cylinder, disabled */
p[6] = (cylinders >> 16) & 0xff;
p[7] = (cylinders >> 8) & 0xff;
p[8] = cylinders & 0xff;
/* Reduced current start cylinder, disabled */
p[9] = (cylinders >> 16) & 0xff;
p[10] = (cylinders >> 8) & 0xff;
p[11] = cylinders & 0xff;
/* Device step rate [ns], 200ns */
p[12] = 0;
p[13] = 200;
/* Landing zone cylinder */
p[14] = 0xff;
p[15] = 0xff;
p[16] = 0xff;
/* Medium rotation rate [rpm], 5400 rpm */
p[20] = (5400 >> 8) & 0xff;
p[21] = 5400 & 0xff;
break;
case 5: /* Flexible disk device geometry page. */
if (s->qdev.type == TYPE_ROM) {
return -1;
}
p[0] = 5;
p[1] = 0x1e;
if (page_control == 1) { /* Changeable Values */
break;
}
/* Transfer rate [kbit/s], 5Mbit/s */
p[2] = 5000 >> 8;
p[3] = 5000 & 0xff;
/* if a geometry hint is available, use it */
bdrv_get_geometry_hint(bdrv, &cylinders, &heads, &secs);
p[4] = heads & 0xff;
p[5] = secs & 0xff;
p[6] = s->cluster_size * 2;
p[8] = (cylinders >> 8) & 0xff;
p[9] = cylinders & 0xff;
/* Write precomp start cylinder, disabled */
p[10] = (cylinders >> 8) & 0xff;
p[11] = cylinders & 0xff;
/* Reduced current start cylinder, disabled */
p[12] = (cylinders >> 8) & 0xff;
p[13] = cylinders & 0xff;
/* Device step rate [100us], 100us */
p[14] = 0;
p[15] = 1;
/* Device step pulse width [us], 1us */
p[16] = 1;
/* Device head settle delay [100us], 100us */
p[17] = 0;
p[18] = 1;
/* Motor on delay [0.1s], 0.1s */
p[19] = 1;
/* Motor off delay [0.1s], 0.1s */
p[20] = 1;
/* Medium rotation rate [rpm], 5400 rpm */
p[28] = (5400 >> 8) & 0xff;
p[29] = 5400 & 0xff;
break;
case 8: /* Caching page. */
p[0] = 8;
p[1] = 0x12;
if (page_control == 1) { /* Changeable Values */
break;
}
if (bdrv_enable_write_cache(s->bs)) {
p[2] = 4; /* WCE */
}
break;
case 0x2a: /* CD Capabilities and Mechanical Status page. */
if (s->qdev.type != TYPE_ROM) {
return -1;
}
p[0] = 0x2a;
p[1] = 0x14;
if (page_control == 1) { /* Changeable Values */
break;
}
p[2] = 3; // CD-R & CD-RW read
p[3] = 0; // Writing not supported
p[4] = 0x7f; /* Audio, composite, digital out,
mode 2 form 1&2, multi session */
p[5] = 0xff; /* CD DA, DA accurate, RW supported,
RW corrected, C2 errors, ISRC,
UPC, Bar code */
p[6] = 0x2d | (s->tray_locked ? 2 : 0);
/* Locking supported, jumper present, eject, tray */
p[7] = 0; /* no volume & mute control, no
changer */
p[8] = (50 * 176) >> 8; // 50x read speed
p[9] = (50 * 176) & 0xff;
p[10] = 0 >> 8; // No volume
p[11] = 0 & 0xff;
p[12] = 2048 >> 8; // 2M buffer
p[13] = 2048 & 0xff;
p[14] = (16 * 176) >> 8; // 16x read speed current
p[15] = (16 * 176) & 0xff;
p[18] = (16 * 176) >> 8; // 16x write speed
p[19] = (16 * 176) & 0xff;
p[20] = (16 * 176) >> 8; // 16x write speed current
p[21] = (16 * 176) & 0xff;
break;
default:
return -1;
}
*p_outbuf += p[1] + 2;
return p[1] + 2;
}
static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint64_t nb_sectors;
int page, dbd, buflen, ret, page_control;
uint8_t *p;
uint8_t dev_specific_param;
dbd = r->req.cmd.buf[1] & 0x8;
page = r->req.cmd.buf[2] & 0x3f;
page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
(r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
memset(outbuf, 0, r->req.cmd.xfer);
p = outbuf;
if (bdrv_is_read_only(s->bs)) {
dev_specific_param = 0x80; /* Readonly. */
} else {
dev_specific_param = 0x00;
}
if (r->req.cmd.buf[0] == MODE_SENSE) {
p[1] = 0; /* Default media type. */
p[2] = dev_specific_param;
p[3] = 0; /* Block descriptor length. */
p += 4;
} else { /* MODE_SENSE_10 */
p[2] = 0; /* Default media type. */
p[3] = dev_specific_param;
p[6] = p[7] = 0; /* Block descriptor length. */
p += 8;
}
bdrv_get_geometry(s->bs, &nb_sectors);
if (!dbd && nb_sectors) {
if (r->req.cmd.buf[0] == MODE_SENSE) {
outbuf[3] = 8; /* Block descriptor length */
} else { /* MODE_SENSE_10 */
outbuf[7] = 8; /* Block descriptor length */
}
nb_sectors /= s->cluster_size;
if (nb_sectors > 0xffffff)
nb_sectors = 0;
p[0] = 0; /* media density code */
p[1] = (nb_sectors >> 16) & 0xff;
p[2] = (nb_sectors >> 8) & 0xff;
p[3] = nb_sectors & 0xff;
p[4] = 0; /* reserved */
p[5] = 0; /* bytes 5-7 are the sector size in bytes */
p[6] = s->cluster_size * 2;
p[7] = 0;
p += 8;
}
if (page_control == 3) {
/* Saved Values */
scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
return -1;
}
if (page == 0x3f) {
for (page = 0; page <= 0x3e; page++) {
mode_sense_page(s, page, &p, page_control);
}
} else {
ret = mode_sense_page(s, page, &p, page_control);
if (ret == -1) {
return -1;
}
}
buflen = p - outbuf;
/*
* The mode data length field specifies the length in bytes of the
* following data that is available to be transferred. The mode data
* length does not include itself.
*/
if (r->req.cmd.buf[0] == MODE_SENSE) {
outbuf[0] = buflen - 1;
} else { /* MODE_SENSE_10 */
outbuf[0] = ((buflen - 2) >> 8) & 0xff;
outbuf[1] = (buflen - 2) & 0xff;
}
if (buflen > r->req.cmd.xfer)
buflen = r->req.cmd.xfer;
return buflen;
}
static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int start_track, format, msf, toclen;
uint64_t nb_sectors;
msf = req->cmd.buf[1] & 2;
format = req->cmd.buf[2] & 0xf;
start_track = req->cmd.buf[6];
bdrv_get_geometry(s->bs, &nb_sectors);
DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
nb_sectors /= s->cluster_size;
switch (format) {
case 0:
toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
break;
case 1:
/* multi session : only a single session defined */
toclen = 12;
memset(outbuf, 0, 12);
outbuf[1] = 0x0a;
outbuf[2] = 0x01;
outbuf[3] = 0x01;
break;
case 2:
toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
break;
default:
return -1;
}
if (toclen > req->cmd.xfer)
toclen = req->cmd.xfer;
return toclen;
}
static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
{
SCSIRequest *req = &r->req;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
bool start = req->cmd.buf[4] & 1;
bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
if (s->qdev.type == TYPE_ROM && loej) {
if (!start && !s->tray_open && s->tray_locked) {
scsi_check_condition(r,
bdrv_is_inserted(s->bs)
? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
: SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
return -1;
}
bdrv_eject(s->bs, !start);
s->tray_open = !start;
}
return 0;
}
static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf)
{
SCSIRequest *req = &r->req;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
uint64_t nb_sectors;
int buflen = 0;
switch (req->cmd.buf[0]) {
case TEST_UNIT_READY:
if (s->tray_open || !bdrv_is_inserted(s->bs))
goto not_ready;
break;
case INQUIRY:
buflen = scsi_disk_emulate_inquiry(req, outbuf);
if (buflen < 0)
goto illegal_request;
break;
case MODE_SENSE:
case MODE_SENSE_10:
buflen = scsi_disk_emulate_mode_sense(r, outbuf);
if (buflen < 0)
goto illegal_request;
break;
case READ_TOC:
buflen = scsi_disk_emulate_read_toc(req, outbuf);
if (buflen < 0)
goto illegal_request;
break;
case RESERVE:
if (req->cmd.buf[1] & 1)
goto illegal_request;
break;
case RESERVE_10:
if (req->cmd.buf[1] & 3)
goto illegal_request;
break;
case RELEASE:
if (req->cmd.buf[1] & 1)
goto illegal_request;
break;
case RELEASE_10:
if (req->cmd.buf[1] & 3)
goto illegal_request;
break;
case START_STOP:
if (scsi_disk_emulate_start_stop(r) < 0) {
return -1;
}
break;
case ALLOW_MEDIUM_REMOVAL:
s->tray_locked = req->cmd.buf[4] & 1;
bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1);
break;
case READ_CAPACITY_10:
/* The normal LEN field for this command is zero. */
memset(outbuf, 0, 8);
bdrv_get_geometry(s->bs, &nb_sectors);
if (!nb_sectors)
goto not_ready;
nb_sectors /= s->cluster_size;
/* Returned value is the address of the last sector. */
nb_sectors--;
/* Remember the new size for read/write sanity checking. */
s->max_lba = nb_sectors;
/* Clip to 2TB, instead of returning capacity modulo 2TB. */
if (nb_sectors > UINT32_MAX)
nb_sectors = UINT32_MAX;
outbuf[0] = (nb_sectors >> 24) & 0xff;
outbuf[1] = (nb_sectors >> 16) & 0xff;
outbuf[2] = (nb_sectors >> 8) & 0xff;
outbuf[3] = nb_sectors & 0xff;
outbuf[4] = 0;
outbuf[5] = 0;
outbuf[6] = s->cluster_size * 2;
outbuf[7] = 0;
buflen = 8;
break;
case GET_CONFIGURATION:
memset(outbuf, 0, 8);
/* ??? This should probably return much more information. For now
just return the basic header indicating the CD-ROM profile. */
outbuf[7] = 8; // CD-ROM
buflen = 8;
break;
case SERVICE_ACTION_IN_16:
/* Service Action In subcommands. */
if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
DPRINTF("SAI READ CAPACITY(16)\n");
memset(outbuf, 0, req->cmd.xfer);
bdrv_get_geometry(s->bs, &nb_sectors);
if (!nb_sectors)
goto not_ready;
nb_sectors /= s->cluster_size;
/* Returned value is the address of the last sector. */
nb_sectors--;
/* Remember the new size for read/write sanity checking. */
s->max_lba = nb_sectors;
outbuf[0] = (nb_sectors >> 56) & 0xff;
outbuf[1] = (nb_sectors >> 48) & 0xff;
outbuf[2] = (nb_sectors >> 40) & 0xff;
outbuf[3] = (nb_sectors >> 32) & 0xff;
outbuf[4] = (nb_sectors >> 24) & 0xff;
outbuf[5] = (nb_sectors >> 16) & 0xff;
outbuf[6] = (nb_sectors >> 8) & 0xff;
outbuf[7] = nb_sectors & 0xff;
outbuf[8] = 0;
outbuf[9] = 0;
outbuf[10] = s->cluster_size * 2;
outbuf[11] = 0;
outbuf[12] = 0;
outbuf[13] = get_physical_block_exp(&s->qdev.conf);
/* set TPE bit if the format supports discard */
if (s->qdev.conf.discard_granularity) {
outbuf[14] = 0x80;
}
/* Protection, exponent and lowest lba field left blank. */
buflen = req->cmd.xfer;
break;
}
DPRINTF("Unsupported Service Action In\n");
goto illegal_request;
case VERIFY_10:
break;
default:
scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
return -1;
}
return buflen;
not_ready:
if (s->tray_open || !bdrv_is_inserted(s->bs)) {
scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
} else {
scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
}
return -1;
illegal_request:
if (r->req.status == -1) {
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
}
return -1;
}
/* Execute a scsi command. Returns the length of the data expected by the
command. This will be Positive for data transfers from the device
(eg. disk reads), negative for transfers to the device (eg. disk writes),
and zero if the command does not transfer any data. */
static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int32_t len;
uint8_t command;
uint8_t *outbuf;
int rc;
command = buf[0];
outbuf = (uint8_t *)r->iov.iov_base;
DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);
#ifdef DEBUG_SCSI
{
int i;
for (i = 1; i < r->req.cmd.len; i++) {
printf(" 0x%02x", buf[i]);
}
printf("\n");
}
#endif
switch (command) {
case TEST_UNIT_READY:
case INQUIRY:
case MODE_SENSE:
case MODE_SENSE_10:
case RESERVE:
case RESERVE_10:
case RELEASE:
case RELEASE_10:
case START_STOP:
case ALLOW_MEDIUM_REMOVAL:
case READ_CAPACITY_10:
case READ_TOC:
case GET_CONFIGURATION:
case SERVICE_ACTION_IN_16:
case VERIFY_10:
rc = scsi_disk_emulate_command(r, outbuf);
if (rc < 0) {
return 0;
}
r->iov.iov_len = rc;
break;
case SYNCHRONIZE_CACHE:
bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH);
r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r);
if (r->req.aiocb == NULL) {
scsi_flush_complete(r, -EIO);
}
return 0;
case READ_6:
case READ_10:
case READ_12:
case READ_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba)
goto illegal_lba;
r->sector = r->req.cmd.lba * s->cluster_size;
r->sector_count = len * s->cluster_size;
break;
case WRITE_6:
case WRITE_10:
case WRITE_12:
case WRITE_16:
case WRITE_VERIFY_10:
case WRITE_VERIFY_12:
case WRITE_VERIFY_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
(command & 0xe) == 0xe ? "And Verify " : "",
r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba)
goto illegal_lba;
r->sector = r->req.cmd.lba * s->cluster_size;
r->sector_count = len * s->cluster_size;
break;
case MODE_SELECT:
DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
/* We don't support mode parameter changes.
Allow the mode parameter header + block descriptors only. */
if (r->req.cmd.xfer > 12) {
goto fail;
}
break;
case MODE_SELECT_10:
DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
/* We don't support mode parameter changes.
Allow the mode parameter header + block descriptors only. */
if (r->req.cmd.xfer > 16) {
goto fail;
}
break;
case SEEK_6:
case SEEK_10:
DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,
r->req.cmd.lba);
if (r->req.cmd.lba > s->max_lba) {
goto illegal_lba;
}
break;
case WRITE_SAME_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n",
r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba) {
goto illegal_lba;
}
/*
* We only support WRITE SAME with the unmap bit set for now.
*/
if (!(buf[1] & 0x8)) {
goto fail;
}
rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,
len * s->cluster_size);
if (rc < 0) {
/* XXX: better error code ?*/
goto fail;
}
break;
case REQUEST_SENSE:
abort();
default:
DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
return 0;
fail:
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
return 0;
illegal_lba:
scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
return 0;
}
if (r->sector_count == 0 && r->iov.iov_len == 0) {
scsi_req_complete(&r->req, GOOD);
}
len = r->sector_count * 512 + r->iov.iov_len;
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
return -len;
} else {
if (!r->sector_count)
r->sector_count = -1;
return len;
}
}
static void scsi_disk_reset(DeviceState *dev)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
uint64_t nb_sectors;
scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
bdrv_get_geometry(s->bs, &nb_sectors);
nb_sectors /= s->cluster_size;
if (nb_sectors) {
nb_sectors--;
}
s->max_lba = nb_sectors;
}
static void scsi_destroy(SCSIDevice *dev)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
blockdev_mark_auto_del(s->qdev.conf.bs);
}
static void scsi_cd_change_media_cb(void *opaque, bool load)
{
((SCSIDiskState *)opaque)->tray_open = !load;
}
static bool scsi_cd_is_tray_open(void *opaque)
{
return ((SCSIDiskState *)opaque)->tray_open;
}
static bool scsi_cd_is_medium_locked(void *opaque)
{
return ((SCSIDiskState *)opaque)->tray_locked;
}
static const BlockDevOps scsi_cd_block_ops = {
.change_media_cb = scsi_cd_change_media_cb,
.is_tray_open = scsi_cd_is_tray_open,
.is_medium_locked = scsi_cd_is_medium_locked,
};
static int scsi_initfn(SCSIDevice *dev, uint8_t scsi_type)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
DriveInfo *dinfo;
if (!s->qdev.conf.bs) {
error_report("scsi-disk: drive property not set");
return -1;
}
s->bs = s->qdev.conf.bs;
if (scsi_type == TYPE_DISK && !bdrv_is_inserted(s->bs)) {
error_report("Device needs media, but drive is empty");
return -1;
}
if (!s->serial) {
/* try to fall back to value set with legacy -drive serial=... */
dinfo = drive_get_by_blockdev(s->bs);
if (*dinfo->serial) {
s->serial = g_strdup(dinfo->serial);
}
}
if (!s->version) {
s->version = g_strdup(QEMU_VERSION);
}
if (bdrv_is_sg(s->bs)) {
error_report("scsi-disk: unwanted /dev/sg*");
return -1;
}
if (scsi_type == TYPE_ROM) {
bdrv_set_dev_ops(s->bs, &scsi_cd_block_ops, s);
s->qdev.blocksize = 2048;
} else if (scsi_type == TYPE_DISK) {
s->qdev.blocksize = s->qdev.conf.logical_block_size;
} else {
error_report("scsi-disk: Unhandled SCSI type %02x", scsi_type);
return -1;
}
s->cluster_size = s->qdev.blocksize / 512;
bdrv_set_buffer_alignment(s->bs, s->qdev.blocksize);
s->qdev.type = scsi_type;
qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, ",0");
return 0;
}
static int scsi_hd_initfn(SCSIDevice *dev)
{
return scsi_initfn(dev, TYPE_DISK);
}
static int scsi_cd_initfn(SCSIDevice *dev)
{
return scsi_initfn(dev, TYPE_ROM);
}
static int scsi_disk_initfn(SCSIDevice *dev)
{
DriveInfo *dinfo;
uint8_t scsi_type;
if (!dev->conf.bs) {
scsi_type = TYPE_DISK; /* will die in scsi_initfn() */
} else {
dinfo = drive_get_by_blockdev(dev->conf.bs);
scsi_type = dinfo->media_cd ? TYPE_ROM : TYPE_DISK;
}
return scsi_initfn(dev, scsi_type);
}
static SCSIReqOps scsi_disk_reqops = {
.size = sizeof(SCSIDiskReq),
.free_req = scsi_free_request,
.send_command = scsi_send_command,
.read_data = scsi_read_data,
.write_data = scsi_write_data,
.cancel_io = scsi_cancel_io,
.get_buf = scsi_get_buf,
};
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
uint32_t lun, void *hba_private)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
SCSIRequest *req;
SCSIDiskReq *r;
req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
r = DO_UPCAST(SCSIDiskReq, req, req);
r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);
return req;
}
#define DEFINE_SCSI_DISK_PROPERTIES() \
DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf), \
DEFINE_PROP_STRING("ver", SCSIDiskState, version), \
DEFINE_PROP_STRING("serial", SCSIDiskState, serial)
static SCSIDeviceInfo scsi_disk_info[] = {
{
.qdev.name = "scsi-hd",
.qdev.fw_name = "disk",
.qdev.desc = "virtual SCSI disk",
.qdev.size = sizeof(SCSIDiskState),
.qdev.reset = scsi_disk_reset,
.init = scsi_hd_initfn,
.destroy = scsi_destroy,
.alloc_req = scsi_new_request,
.qdev.props = (Property[]) {
DEFINE_SCSI_DISK_PROPERTIES(),
DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
DEFINE_PROP_END_OF_LIST(),
}
},{
.qdev.name = "scsi-cd",
.qdev.fw_name = "disk",
.qdev.desc = "virtual SCSI CD-ROM",
.qdev.size = sizeof(SCSIDiskState),
.qdev.reset = scsi_disk_reset,
.init = scsi_cd_initfn,
.destroy = scsi_destroy,
.alloc_req = scsi_new_request,
.qdev.props = (Property[]) {
DEFINE_SCSI_DISK_PROPERTIES(),
DEFINE_PROP_END_OF_LIST(),
},
},{
.qdev.name = "scsi-disk", /* legacy -device scsi-disk */
.qdev.fw_name = "disk",
.qdev.desc = "virtual SCSI disk or CD-ROM (legacy)",
.qdev.size = sizeof(SCSIDiskState),
.qdev.reset = scsi_disk_reset,
.init = scsi_disk_initfn,
.destroy = scsi_destroy,
.alloc_req = scsi_new_request,
.qdev.props = (Property[]) {
DEFINE_SCSI_DISK_PROPERTIES(),
DEFINE_PROP_BIT("removable", SCSIDiskState, removable, 0, false),
DEFINE_PROP_END_OF_LIST(),
}
}
};
static void scsi_disk_register_devices(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(scsi_disk_info); i++) {
scsi_qdev_register(&scsi_disk_info[i]);
}
}
device_init(scsi_disk_register_devices)
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3501_0 |
crossvul-cpp_data_bad_341_3 | /*
* card-tcos.c: Support for TCOS cards
*
* Copyright (C) 2011 Peter Koch <pk@opensc-project.org>
* Copyright (C) 2002 g10 Code GmbH
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table tcos_atrs[] = {
/* Infineon SLE44 */
{ "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66S */
{ "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX320P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Infineon SLE66CX322P */
{ "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL },
/* Philips P5CT072 */
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
/* Philips P5CT080 */
{ "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations tcos_ops;
static struct sc_card_driver tcos_drv = {
"TCOS 3.0",
"tcos",
&tcos_ops,
NULL, 0, NULL
};
static const struct sc_card_operations *iso_ops = NULL;
typedef struct tcos_data_st {
unsigned int pad_flags;
unsigned int next_sign;
} tcos_data;
static int tcos_finish(sc_card_t *card)
{
free(card->drv_data);
return 0;
}
static int tcos_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, tcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int tcos_init(sc_card_t *card)
{
unsigned long flags;
tcos_data *data = malloc(sizeof(tcos_data));
if (!data) return SC_ERROR_OUT_OF_MEMORY;
card->name = "TCOS";
card->drv_data = (void *)data;
card->cla = 0x00;
flags = SC_ALGORITHM_RSA_RAW;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
flags |= SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
if (card->type == SC_CARD_TYPE_TCOS_V3) {
card->caps |= SC_CARD_CAP_APDU_EXT;
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
}
return 0;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static int tcos_construct_fci(const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 *p = out;
u8 buf[64];
size_t n;
/* FIXME: possible buffer overflow */
*p++ = 0x6F; /* FCI */
p++;
/* File size */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x81, buf, 2, p, 16, &p);
/* File descriptor */
n = 0;
buf[n] = file->shareable ? 0x40 : 0;
switch (file->type) {
case SC_FILE_TYPE_WORKING_EF:
break;
case SC_FILE_TYPE_DF:
buf[0] |= 0x38;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
buf[n++] |= file->ef_structure & 7;
if ( (file->ef_structure & 7) > 1) {
/* record structured file */
buf[n++] = 0x41; /* indicate 3rd byte */
buf[n++] = file->record_length;
}
sc_asn1_put_tag(0x82, buf, n, p, 8, &p);
/* File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, 16, &p);
/* Directory name */
if (file->type == SC_FILE_TYPE_DF) {
if (file->namelen) {
sc_asn1_put_tag(0x84, file->name, file->namelen,
p, 16, &p);
}
else {
/* TCOS needs one, so we use a faked one */
snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu",
(unsigned long) time (NULL));
sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p);
}
}
/* File descriptor extension */
if (file->prop_attr_len && file->prop_attr) {
n = file->prop_attr_len;
memcpy(buf, file->prop_attr, n);
}
else {
n = 0;
buf[n++] = 0x01; /* not invalidated, permanent */
if (file->type == SC_FILE_TYPE_WORKING_EF)
buf[n++] = 0x00; /* generic data file */
}
sc_asn1_put_tag(0x85, buf, n, p, 16, &p);
/* Security attributes */
if (file->sec_attr_len && file->sec_attr) {
memcpy(buf, file->sec_attr, file->sec_attr_len);
n = file->sec_attr_len;
}
else {
/* no attributes given - fall back to default one */
memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */
memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */
memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */
memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/
n = 24;
}
sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p);
/* fixup length of FCI */
out[1] = p - out - 2;
*outlen = p - out;
return 0;
}
static int tcos_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
size_t len;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
len = SC_MAX_APDU_BUFFER_SIZE;
r = tcos_construct_fci(file, sbuf, &len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00);
apdu.cla |= 0x80; /* this is an proprietary extension */
apdu.lc = len;
apdu.datalen = len;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static unsigned int map_operations (int commandbyte )
{
unsigned int op = (unsigned int)-1;
switch ( (commandbyte & 0xfe) ) {
case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break;
case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break;
case 0xe0: /* create */ op = SC_AC_OP_CREATE; break;
case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break;
case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break;
case 0x82: /* external auth */ op = SC_AC_OP_READ; break;
case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break;
case 0x88: /* internal auth */ op = SC_AC_OP_READ; break;
case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break;
case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break;
case 0xb0: /* read binary */ op = SC_AC_OP_READ; break;
case 0xb2: /* read record */ op = SC_AC_OP_READ; break;
case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break;
case 0xa4: /* select */ op = SC_AC_OP_SELECT; break;
case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break;
case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break;
case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break;
case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break;
case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break;
case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break;
}
return op;
}
/* Hmmm, I don't know what to do. It seems that the ACL design of
OpenSC should be enhanced to allow for the command based security
attributes of TCOS. FIXME: This just allows to create a very basic
file. */
static void parse_sec_attr(sc_card_t *card,
sc_file_t *file, const u8 *buf, size_t len)
{
unsigned int op;
/* list directory is not covered by ACLs - so always add an entry */
sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
/* FIXME: check for what LOCK is used */
sc_file_add_acl_entry (file, SC_AC_OP_LOCK,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
for (; len >= 6; len -= 6, buf += 6) {
/* FIXME: temporary hacks */
if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */
sc_file_add_acl_entry (file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/
sc_file_add_acl_entry (file, SC_AC_OP_READ,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/
sc_file_add_acl_entry (file, SC_AC_OP_UPDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */
sc_file_add_acl_entry (file, SC_AC_OP_WRITE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_CREATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else {
/* the first byte tells use the command or the
command group. We have to mask bit 0
because this one distinguish between AND/OR
combination of PINs*/
op = map_operations (buf[0]);
if (op == (unsigned int)-1)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unknown security command byte %02x\n",
buf[0]);
continue;
}
if (!buf[1])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_CHV, buf[1]);
if (!buf[2] && !buf[3])
sc_file_add_acl_entry (file, op,
SC_AC_NONE,
SC_AC_KEY_REF_NONE);
else
sc_file_add_acl_entry (file, op,
SC_AC_TERM,
(buf[2]<<8)|buf[3]);
}
}
}
static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1;
int r, count = 0;
assert(card != NULL);
ctx = card->ctx;
for (p1=1; p1<=2; p1++) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue;
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed");
if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL;
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n",
apdu.resplen / 2, p1 == 1 ? "DF" : "EF");
memcpy(buf, apdu.resp, apdu.resplen);
buf += apdu.resplen;
buflen -= apdu.resplen;
count += apdu.resplen;
}
return count;
}
static int tcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
sbuf[0] = path->value[0];
sbuf[1] = path->value[1];
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p;
int r, default_key, tcos3;
tcos_data *data;
assert(card != NULL && env != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
}
if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT))
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"No Key-Reference in SecEnvironment\n");
else
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n",
env->key_ref[0], env->key_ref_len);
/* Key-Reference 0x80 ?? */
default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n", tcos3,
!!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
data->pad_flags = env->algorithm_flags;
data->next_sign = default_key;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8);
p = sbuf;
*p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10;
if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) {
*p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84;
*p++ = env->key_ref_len;
memcpy(p, env->key_ref, env->key_ref_len);
p += env->key_ref_len;
}
apdu.data = sbuf;
apdu.lc = apdu.datalen = (p - sbuf);
r=sc_transmit_apdu(card, &apdu);
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"%s: APDU transmit failed", sc_strerror(r));
return r;
}
if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Detected Signature-Only key\n");
if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS;
}
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
size_t i, dlen=datalen;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
int tcos3, r;
assert(card != NULL && data != NULL && out != NULL);
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
if(((tcos_data *)card->drv_data)->next_sign){
if(datalen>48){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
memcpy(sbuf, data, datalen);
dlen=datalen;
} else {
int keylen= tcos3 ? 256 : 128;
sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
}
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = tcos3 ? 256 : 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) {
int keylen=128;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86);
for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff;
sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00;
memcpy(sbuf+keylen-datalen+1, data, datalen);
dlen=keylen+1;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 128;
apdu.data = sbuf;
apdu.lc = apdu.datalen = dlen;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len = apdu.resplen>outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
/* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the
NullPIN method will be activated, otherwise the permanent operation
will be done on the active file. */
static int tcos_setperm(sc_card_t *card, int enable_nullpin)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = 0;
apdu.datalen = 0;
apdu.data = NULL;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
card->serialnr.len = sizeof card->serialnr.value;
r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0);
if (r < 0) {
card->serialnr.len = 0;
return r;
}
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_TCOS_SETPERM:
return tcos_setperm(card, !!ptr);
case SC_CARDCTL_GET_SERIALNR:
return tcos_get_serialnr(card, (sc_serial_number_t *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
struct sc_card_driver * sc_get_tcos_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (iso_ops == NULL) iso_ops = iso_drv->ops;
tcos_ops = *iso_drv->ops;
tcos_ops.match_card = tcos_match_card;
tcos_ops.init = tcos_init;
tcos_ops.finish = tcos_finish;
tcos_ops.create_file = tcos_create_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.select_file = tcos_select_file;
tcos_ops.list_files = tcos_list_files;
tcos_ops.delete_file = tcos_delete_file;
tcos_ops.set_security_env = tcos_set_security_env;
tcos_ops.compute_signature = tcos_compute_signature;
tcos_ops.decipher = tcos_decipher;
tcos_ops.restore_security_env = tcos_restore_security_env;
tcos_ops.card_ctl = tcos_card_ctl;
return &tcos_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_341_3 |
crossvul-cpp_data_good_507_4 | /******************************************************************************
** Copyright (c) 2015-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include "generator_common.h"
#include "generator_spgemm_csr_reader.h"
#if defined(LIBXSMM_OFFLOAD_TARGET)
# pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET))
#endif
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#if defined(LIBXSMM_OFFLOAD_TARGET)
# pragma offload_attribute(pop)
#endif
LIBXSMM_API_INTERN
void libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code,
const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
double** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT );
return;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csr_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN );
return;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) &&
0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count)
{
/* allocate CSC data-structure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1));
*o_values = (double*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csr_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA );
return;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1));
memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count));
memset(*o_values, 0, sizeof(double) * (*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count));
/* init column idx */
for ( l_i = 0; l_i <= *o_row_count; ++l_i )
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC );
fclose( l_csr_file_handle ); /* close mtx file */
return;
}
/* now we read the actual content */
} else {
unsigned int l_row = 0, l_column = 0;
double l_value = 0;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
fclose(l_csr_file_handle); /* close mtx file */
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS );
return;
}
/* adjust numbers to zero termination */
LIBXSMM_ASSERT(0 != l_row && 0 != l_column);
l_row--; l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id);
*o_row_idx = 0; *o_column_idx = 0; *o_values = 0;
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN );
return;
}
if ( l_row_idx_id != NULL ) {
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
free( l_row_idx_id );
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_507_4 |
crossvul-cpp_data_bad_252_4 | /**
* @file
* RFC2047 MIME extensions encoding / decoding routines
*
* @authors
* Copyright (C) 1996-2000,2010 Michael R. Elkins <me@mutt.org>
* Copyright (C) 2000-2002 Edmund Grimley Evans <edmundo@rano.org>
* Copyright (C) 2018 Pietro Cerutti <gahr@gahr.ch>
*
* @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 rfc2047 RFC2047 encoding / decoding functions
*
* RFC2047 MIME extensions encoding / decoding routines.
*/
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <string.h>
#include "rfc2047.h"
#include "base64.h"
#include "buffer.h"
#include "charset.h"
#include "mbyte.h"
#include "memory.h"
#include "mime.h"
#include "regex3.h"
#include "string2.h"
#define ENCWORD_LEN_MAX 75
#define ENCWORD_LEN_MIN 9 /* strlen ("=?.?.?.?=") */
#define HSPACE(x) (((x) == '\0') || ((x) == ' ') || ((x) == '\t'))
#define CONTINUATION_BYTE(c) (((c) &0xc0) == 0x80)
typedef size_t (*encoder_t)(char *str, const char *buf, size_t buflen, const char *tocode);
/**
* b_encoder - Base64 Encode a string
* @param str String to encode
* @param buf Buffer for result
* @param buflen Length of buffer
* @param tocode Character encoding
* @retval num Bytes written to buffer
*/
static size_t b_encoder(char *str, const char *buf, size_t buflen, const char *tocode)
{
char *s0 = str;
memcpy(str, "=?", 2);
str += 2;
memcpy(str, tocode, strlen(tocode));
str += strlen(tocode);
memcpy(str, "?B?", 3);
str += 3;
while (buflen)
{
char encoded[11];
size_t ret;
size_t in_len = MIN(3, buflen);
ret = mutt_b64_encode(encoded, buf, in_len, sizeof(encoded));
for (size_t i = 0; i < ret; i++)
*str++ = encoded[i];
buflen -= in_len;
buf += in_len;
}
memcpy(str, "?=", 2);
str += 2;
return (str - s0);
}
/**
* q_encoder - Quoted-printable Encode a string
* @param str String to encode
* @param buf Buffer for result
* @param buflen Length of buffer
* @param tocode Character encoding
* @retval num Bytes written to buffer
*/
static size_t q_encoder(char *str, const char *buf, size_t buflen, const char *tocode)
{
static const char hex[] = "0123456789ABCDEF";
char *s0 = str;
memcpy(str, "=?", 2);
str += 2;
memcpy(str, tocode, strlen(tocode));
str += strlen(tocode);
memcpy(str, "?Q?", 3);
str += 3;
while (buflen--)
{
unsigned char c = *buf++;
if (c == ' ')
*str++ = '_';
else if ((c >= 0x7f) || (c < 0x20) || (c == '_') || strchr(MimeSpecials, c))
{
*str++ = '=';
*str++ = hex[(c & 0xf0) >> 4];
*str++ = hex[c & 0x0f];
}
else
*str++ = c;
}
memcpy(str, "?=", 2);
str += 2;
return (str - s0);
}
/**
* parse_encoded_word - Parse a string and report RFC2047 elements
* @param[in] str String to parse
* @param[out] enc Content encoding found in the first RFC2047 word
* @param[out] charset Charset found in the first RFC2047 word
* @param[out] charsetlen Length of the charset string found
* @param[out] text Start of the first RFC2047 encoded text
* @param[out] textlen Length of the encoded text found
* @retval ptr Start of the RFC2047 encoded word
* @retval NULL None was found
*/
static char *parse_encoded_word(char *str, enum ContentEncoding *enc, char **charset,
size_t *charsetlen, char **text, size_t *textlen)
{
static struct Regex *re = NULL;
regmatch_t match[4];
size_t nmatch = 4;
if (re == NULL)
{
re = mutt_regex_compile("=\\?"
"([^][()<>@,;:\\\"/?. =]+)" /* charset */
"\\?"
"([qQbB])" /* encoding */
"\\?"
"([^?]+)" /* encoded text - we accept whitespace
as some mailers do that, see #1189. */
"\\?=",
REG_EXTENDED);
assert(re && "Something is wrong with your RE engine.");
}
int rc = regexec(re->regex, str, nmatch, match, 0);
if (rc != 0)
return NULL;
/* Charset */
*charset = str + match[1].rm_so;
*charsetlen = match[1].rm_eo - match[1].rm_so;
/* Encoding: either Q or B */
*enc = ((str[match[2].rm_so] == 'Q') || (str[match[2].rm_so] == 'q')) ?
ENCQUOTEDPRINTABLE :
ENCBASE64;
*text = str + match[3].rm_so;
*textlen = match[3].rm_eo - match[3].rm_so;
return (str + match[0].rm_so);
}
/**
* try_block - Attempt to convert a block of text
* @param d String to convert
* @param dlen Length of string
* @param fromcode Original encoding
* @param tocode New encoding
* @param encoder Encoding function
* @param wlen Number of characters converted
* @retval 0 Success, string converted
* @retval >0 Error, number of bytes that could be converted
*
* If the data could be conveted using encoder, then set *encoder and *wlen.
* Otherwise return an upper bound on the maximum length of the data which
* could be converted.
*
* The data is converted from fromcode (which must be stateless) to tocode,
* unless fromcode is NULL, in which case the data is assumed to be already in
* tocode, which should be 8-bit and stateless.
*/
static size_t try_block(const char *d, size_t dlen, const char *fromcode,
const char *tocode, encoder_t *encoder, size_t *wlen)
{
char buf[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
const char *ib = NULL;
char *ob = NULL;
size_t ibl, obl;
int count, len, len_b, len_q;
if (fromcode)
{
iconv_t cd = mutt_ch_iconv_open(tocode, fromcode, 0);
assert(cd != (iconv_t)(-1));
ib = d;
ibl = dlen;
ob = buf;
obl = sizeof(buf) - strlen(tocode);
if (iconv(cd, (ICONV_CONST char **) &ib, &ibl, &ob, &obl) == (size_t)(-1) ||
iconv(cd, NULL, NULL, &ob, &obl) == (size_t)(-1))
{
assert(errno == E2BIG);
iconv_close(cd);
assert(ib > d);
return (ib - d == dlen) ? dlen : ib - d + 1;
}
iconv_close(cd);
}
else
{
if (dlen > (sizeof(buf) - strlen(tocode)))
return (sizeof(buf) - strlen(tocode) + 1);
memcpy(buf, d, dlen);
ob = buf + dlen;
}
count = 0;
for (char *p = buf; p < ob; p++)
{
unsigned char c = *p;
assert(strchr(MimeSpecials, '?'));
if ((c >= 0x7f) || (c < 0x20) || (*p == '_') ||
((c != ' ') && strchr(MimeSpecials, *p)))
{
count++;
}
}
len = ENCWORD_LEN_MIN - 2 + strlen(tocode);
len_b = len + (((ob - buf) + 2) / 3) * 4;
len_q = len + (ob - buf) + 2 * count;
/* Apparently RFC1468 says to use B encoding for iso-2022-jp. */
if (mutt_str_strcasecmp(tocode, "ISO-2022-JP") == 0)
len_q = ENCWORD_LEN_MAX + 1;
if ((len_b < len_q) && (len_b <= ENCWORD_LEN_MAX))
{
*encoder = b_encoder;
*wlen = len_b;
return 0;
}
else if (len_q <= ENCWORD_LEN_MAX)
{
*encoder = q_encoder;
*wlen = len_q;
return 0;
}
else
return dlen;
}
/**
* encode_block - Encode a block of text using an encoder
* @param str String to convert
* @param buf Buffer for result
* @param buflen Buffer length
* @param fromcode Original encoding
* @param tocode New encoding
* @param encoder Encoding function
* @retval num Length of the encoded word
*
* Encode the data (buf, buflen) into str using the encoder.
*/
static size_t encode_block(char *str, char *buf, size_t buflen, const char *fromcode,
const char *tocode, encoder_t encoder)
{
if (!fromcode)
{
return (*encoder)(str, buf, buflen, tocode);
}
const iconv_t cd = mutt_ch_iconv_open(tocode, fromcode, 0);
assert(cd != (iconv_t)(-1));
const char *ib = buf;
size_t ibl = buflen;
char tmp[ENCWORD_LEN_MAX - ENCWORD_LEN_MIN + 1];
char *ob = tmp;
size_t obl = sizeof(tmp) - strlen(tocode);
const size_t n1 = iconv(cd, (ICONV_CONST char **) &ib, &ibl, &ob, &obl);
const size_t n2 = iconv(cd, NULL, NULL, &ob, &obl);
assert(n1 != (size_t)(-1) && n2 != (size_t)(-1));
iconv_close(cd);
return (*encoder)(str, tmp, ob - tmp, tocode);
}
/**
* choose_block - Calculate how much data can be converted
* @param d String to convert
* @param dlen Length of string
* @param col Starting column to convert
* @param fromcode Original encoding
* @param tocode New encoding
* @param encoder Encoding function
* @param wlen Number of characters converted
* @retval num Bytes that can be converted
*
* Discover how much of the data (d, dlen) can be converted into a single
* encoded word. Return how much data can be converted, and set the length
* *wlen of the encoded word and *encoder. We start in column col, which
* limits the length of the word.
*/
static size_t choose_block(char *d, size_t dlen, int col, const char *fromcode,
const char *tocode, encoder_t *encoder, size_t *wlen)
{
const int utf8 = fromcode && (mutt_str_strcasecmp(fromcode, "utf-8") == 0);
size_t n = dlen;
while (true)
{
assert(n > 0);
const size_t nn = try_block(d, n, fromcode, tocode, encoder, wlen);
if ((nn == 0) && ((col + *wlen) <= (ENCWORD_LEN_MAX + 1) || (n <= 1)))
break;
n = (nn ? nn : n) - 1;
assert(n > 0);
if (utf8)
while ((n > 1) && CONTINUATION_BYTE(d[n]))
n--;
}
return n;
}
/**
* finalize_chunk - Perform charset conversion and filtering
* @param[out] res Buffer where the resulting string is appended
* @param[in] buf Buffer with the input string
* @param[in] charset Charset to use for the conversion
* @param[in] charsetlen Length of the charset parameter
*
* The buffer buf is reinitialized at the end of this function.
*/
static void finalize_chunk(struct Buffer *res, struct Buffer *buf, char *charset, size_t charsetlen)
{
char end = charset[charsetlen];
charset[charsetlen] = '\0';
mutt_ch_convert_string(&buf->data, charset, Charset, MUTT_ICONV_HOOK_FROM);
charset[charsetlen] = end;
mutt_mb_filter_unprintable(&buf->data);
mutt_buffer_addstr(res, buf->data);
FREE(&buf->data);
mutt_buffer_init(buf);
}
/**
* rfc2047_decode_word - Decode an RFC2047-encoded string
* @param s String to decode
* @param len Length of the string
* @param enc Encoding type
* @retval ptr Decoded string
*
* @note The caller must free the returned string
*/
static char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc)
{
const char *it = s;
const char *end = s + len;
if (enc == ENCQUOTEDPRINTABLE)
{
struct Buffer buf = { 0 };
for (; it < end; ++it)
{
if (*it == '_')
{
mutt_buffer_addch(&buf, ' ');
}
else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) &&
(!(it[2] & ~127) && hexval(it[2]) != -1))
{
mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2]));
it += 2;
}
else
{
mutt_buffer_addch(&buf, *it);
}
}
mutt_buffer_addch(&buf, '\0');
return buf.data;
}
else if (enc == ENCBASE64)
{
char *out = mutt_mem_malloc(3 * len / 4 + 1);
int dlen = mutt_b64_decode(out, it);
if (dlen == -1)
{
FREE(&out);
return NULL;
}
out[dlen] = '\0';
return out;
}
assert(0); /* The enc parameter has an invalid value */
return NULL;
}
/**
* rfc2047_encode - RFC2047-encode a string
* @param d String to convert
* @param dlen Length of string
* @param col Starting column to convert
* @param fromcode Original encoding
* @param charsets List of allowable encodings (colon separated)
* @param e Encoded string
* @param elen Length of encoded string
* @param specials Special characters to be encoded
* @retval 0 Success
*/
static int rfc2047_encode(const char *d, size_t dlen, int col, const char *fromcode,
const char *charsets, char **e, size_t *elen, const char *specials)
{
int rc = 0;
char *buf = NULL;
size_t bufpos, buflen;
char *t0 = NULL, *t1 = NULL, *t = NULL;
char *s0 = NULL, *s1 = NULL;
size_t ulen, r, wlen = 0;
encoder_t encoder = NULL;
char *tocode1 = NULL;
const char *tocode = NULL;
char *icode = "utf-8";
/* Try to convert to UTF-8. */
char *u = mutt_str_substr_dup(d, d + dlen);
if (mutt_ch_convert_string(&u, fromcode, icode, 0) != 0)
{
rc = 1;
icode = 0;
}
ulen = mutt_str_strlen(u);
/* Find earliest and latest things we must encode. */
s0 = s1 = t0 = t1 = 0;
for (t = u; t < (u + ulen); t++)
{
if ((*t & 0x80) || ((*t == '=') && (t[1] == '?') && ((t == u) || HSPACE(*(t - 1)))))
{
if (!t0)
t0 = t;
t1 = t;
}
else if (specials && *t && strchr(specials, *t))
{
if (!s0)
s0 = t;
s1 = t;
}
}
/* If we have something to encode, include RFC822 specials */
if (t0 && s0 && (s0 < t0))
t0 = s0;
if (t1 && s1 && (s1 > t1))
t1 = s1;
if (!t0)
{
/* No encoding is required. */
*e = u;
*elen = ulen;
return rc;
}
/* Choose target charset. */
tocode = fromcode;
if (icode)
{
tocode1 = mutt_ch_choose(icode, charsets, u, ulen, 0, 0);
if (tocode1)
tocode = tocode1;
else
{
rc = 2;
icode = 0;
}
}
/* Hack to avoid labelling 8-bit data as us-ascii. */
if (!icode && mutt_ch_is_us_ascii(tocode))
tocode = "unknown-8bit";
/* Adjust t0 for maximum length of line. */
t = u + (ENCWORD_LEN_MAX + 1) - col - ENCWORD_LEN_MIN;
if (t < u)
t = u;
if (t < t0)
t0 = t;
/* Adjust t0 until we can encode a character after a space. */
for (; t0 > u; t0--)
{
if (!HSPACE(*(t0 - 1)))
continue;
t = t0 + 1;
if (icode)
while ((t < (u + ulen)) && CONTINUATION_BYTE(*t))
t++;
if ((try_block(t0, t - t0, icode, tocode, &encoder, &wlen) == 0) &&
((col + (t0 - u) + wlen) <= (ENCWORD_LEN_MAX + 1)))
{
break;
}
}
/* Adjust t1 until we can encode a character before a space. */
for (; t1 < (u + ulen); t1++)
{
if (!HSPACE(*t1))
continue;
t = t1 - 1;
if (icode)
while (CONTINUATION_BYTE(*t))
t--;
if ((try_block(t, t1 - t, icode, tocode, &encoder, &wlen) == 0) &&
((1 + wlen + (u + ulen - t1)) <= (ENCWORD_LEN_MAX + 1)))
{
break;
}
}
/* We shall encode the region [t0,t1). */
/* Initialise the output buffer with the us-ascii prefix. */
buflen = 2 * ulen;
buf = mutt_mem_malloc(buflen);
bufpos = t0 - u;
memcpy(buf, u, t0 - u);
col += t0 - u;
t = t0;
while (true)
{
/* Find how much we can encode. */
size_t n = choose_block(t, t1 - t, col, icode, tocode, &encoder, &wlen);
if (n == (t1 - t))
{
/* See if we can fit the us-ascii suffix, too. */
if ((col + wlen + (u + ulen - t1)) <= (ENCWORD_LEN_MAX + 1))
break;
n = t1 - t - 1;
if (icode)
while (CONTINUATION_BYTE(t[n]))
n--;
if (!n)
{
/* This should only happen in the really stupid case where the
only word that needs encoding is one character long, but
there is too much us-ascii stuff after it to use a single
encoded word. We add the next word to the encoded region
and try again. */
assert(t1 < (u + ulen));
for (t1++; (t1 < (u + ulen)) && !HSPACE(*t1); t1++)
;
continue;
}
n = choose_block(t, n, col, icode, tocode, &encoder, &wlen);
}
/* Add to output buffer. */
const char *line_break = "\n\t";
const int lb_len = 2; /* strlen(line_break) */
if ((bufpos + wlen + lb_len) > buflen)
{
buflen = bufpos + wlen + lb_len;
mutt_mem_realloc(&buf, buflen);
}
r = encode_block(buf + bufpos, t, n, icode, tocode, encoder);
assert(r == wlen);
bufpos += wlen;
memcpy(buf + bufpos, line_break, lb_len);
bufpos += lb_len;
col = 1;
t += n;
}
/* Add last encoded word and us-ascii suffix to buffer. */
buflen = bufpos + wlen + (u + ulen - t1);
mutt_mem_realloc(&buf, buflen + 1);
r = encode_block(buf + bufpos, t, t1 - t, icode, tocode, encoder);
assert(r == wlen);
bufpos += wlen;
memcpy(buf + bufpos, t1, u + ulen - t1);
FREE(&tocode1);
FREE(&u);
buf[buflen] = '\0';
*e = buf;
*elen = buflen + 1;
return rc;
}
/**
* mutt_rfc2047_encode - RFC-2047-encode a string
* @param[in,out] pd String to be encoded, and resulting encoded string
* @param[in] specials Special characters to be encoded
* @param[in] col Starting index in string
* @param[in] charsets List of charsets to choose from
*/
void mutt_rfc2047_encode(char **pd, const char *specials, int col, const char *charsets)
{
char *e = NULL;
size_t elen;
if (!Charset || !*pd)
return;
if (!charsets || !*charsets)
charsets = "utf-8";
rfc2047_encode(*pd, strlen(*pd), col, Charset, charsets, &e, &elen, specials);
FREE(pd);
*pd = e;
}
/**
* mutt_rfc2047_decode - Decode any RFC2047-encoded header fields
* @param[in,out] pd String to be decoded, and resulting decoded string
*
* Try to decode anything that looks like a valid RFC2047 encoded header field,
* ignoring RFC822 parsing rules. If decoding fails, for example due to an
* invalid base64 string, the original input is left untouched.
*/
void mutt_rfc2047_decode(char **pd)
{
if (!pd || !*pd)
return;
struct Buffer buf = { 0 }; /* Output buffer */
char *s = *pd; /* Read pointer */
char *beg; /* Begin of encoded word */
enum ContentEncoding enc; /* ENCBASE64 or ENCQUOTEDPRINTABLE */
char *charset; /* Which charset */
size_t charsetlen; /* Length of the charset */
char *text; /* Encoded text */
size_t textlen; /* Length of encoded text */
/* Keep some state in case the next decoded word is using the same charset
* and it happens to be split in the middle of a multibyte character.
* See https://github.com/neomutt/neomutt/issues/1015
*/
struct Buffer prev = { 0 }; /* Previously decoded word */
char *prev_charset = NULL; /* Previously used charset */
size_t prev_charsetlen = 0; /* Length of the previously used charset */
while (*s)
{
beg = parse_encoded_word(s, &enc, &charset, &charsetlen, &text, &textlen);
if (beg != s)
{
/* Some non-encoded text was found */
size_t holelen = beg ? beg - s : mutt_str_strlen(s);
/* Ignore whitespace between encoded words */
if (beg && mutt_str_lws_len(s, holelen) == holelen)
{
s = beg;
continue;
}
/* If we have some previously decoded text, add it now */
if (prev.data)
{
finalize_chunk(&buf, &prev, prev_charset, prev_charsetlen);
}
/* Add non-encoded part */
{
if (AssumedCharset && *AssumedCharset)
{
char *conv = mutt_str_substr_dup(s, s + holelen);
mutt_ch_convert_nonmime_string(&conv);
mutt_buffer_addstr(&buf, conv);
FREE(&conv);
}
else
{
mutt_buffer_add(&buf, s, holelen);
}
}
s += holelen;
}
if (beg)
{
/* Some encoded text was found */
text[textlen] = '\0';
char *decoded = rfc2047_decode_word(text, textlen, enc);
if (decoded == NULL)
{
return;
}
if (prev.data && ((prev_charsetlen != charsetlen) ||
(strncmp(prev_charset, charset, charsetlen) != 0)))
{
/* Different charset, convert the previous chunk and add it to the
* final result */
finalize_chunk(&buf, &prev, prev_charset, prev_charsetlen);
}
mutt_buffer_addstr(&prev, decoded);
FREE(&decoded);
prev_charset = charset;
prev_charsetlen = charsetlen;
s = text + textlen + 2; /* Skip final ?= */
}
}
/* Save the last chunk */
if (prev.data)
{
finalize_chunk(&buf, &prev, prev_charset, prev_charsetlen);
}
mutt_buffer_addch(&buf, '\0');
*pd = buf.data;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_252_4 |
crossvul-cpp_data_bad_3635_0 | #include <linux/etherdevice.h>
#include <linux/if_macvlan.h>
#include <linux/interrupt.h>
#include <linux/nsproxy.h>
#include <linux/compat.h>
#include <linux/if_tun.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/cdev.h>
#include <linux/idr.h>
#include <linux/fs.h>
#include <net/net_namespace.h>
#include <net/rtnetlink.h>
#include <net/sock.h>
#include <linux/virtio_net.h>
/*
* A macvtap queue is the central object of this driver, it connects
* an open character device to a macvlan interface. There can be
* multiple queues on one interface, which map back to queues
* implemented in hardware on the underlying device.
*
* macvtap_proto is used to allocate queues through the sock allocation
* mechanism.
*
* TODO: multiqueue support is currently not implemented, even though
* macvtap is basically prepared for that. We will need to add this
* here as well as in virtio-net and qemu to get line rate on 10gbit
* adapters from a guest.
*/
struct macvtap_queue {
struct sock sk;
struct socket sock;
struct socket_wq wq;
int vnet_hdr_sz;
struct macvlan_dev __rcu *vlan;
struct file *file;
unsigned int flags;
};
static struct proto macvtap_proto = {
.name = "macvtap",
.owner = THIS_MODULE,
.obj_size = sizeof (struct macvtap_queue),
};
/*
* Variables for dealing with macvtaps device numbers.
*/
static dev_t macvtap_major;
#define MACVTAP_NUM_DEVS (1U << MINORBITS)
static DEFINE_MUTEX(minor_lock);
static DEFINE_IDR(minor_idr);
#define GOODCOPY_LEN 128
static struct class *macvtap_class;
static struct cdev macvtap_cdev;
static const struct proto_ops macvtap_socket_ops;
/*
* RCU usage:
* The macvtap_queue and the macvlan_dev are loosely coupled, the
* pointers from one to the other can only be read while rcu_read_lock
* or macvtap_lock is held.
*
* Both the file and the macvlan_dev hold a reference on the macvtap_queue
* through sock_hold(&q->sk). When the macvlan_dev goes away first,
* q->vlan becomes inaccessible. When the files gets closed,
* macvtap_get_queue() fails.
*
* There may still be references to the struct sock inside of the
* queue from outbound SKBs, but these never reference back to the
* file or the dev. The data structure is freed through __sk_free
* when both our references and any pending SKBs are gone.
*/
static DEFINE_SPINLOCK(macvtap_lock);
/*
* get_slot: return a [unused/occupied] slot in vlan->taps[]:
* - if 'q' is NULL, return the first empty slot;
* - otherwise, return the slot this pointer occupies.
*/
static int get_slot(struct macvlan_dev *vlan, struct macvtap_queue *q)
{
int i;
for (i = 0; i < MAX_MACVTAP_QUEUES; i++) {
if (rcu_dereference(vlan->taps[i]) == q)
return i;
}
/* Should never happen */
BUG_ON(1);
}
static int macvtap_set_queue(struct net_device *dev, struct file *file,
struct macvtap_queue *q)
{
struct macvlan_dev *vlan = netdev_priv(dev);
int index;
int err = -EBUSY;
spin_lock(&macvtap_lock);
if (vlan->numvtaps == MAX_MACVTAP_QUEUES)
goto out;
err = 0;
index = get_slot(vlan, NULL);
rcu_assign_pointer(q->vlan, vlan);
rcu_assign_pointer(vlan->taps[index], q);
sock_hold(&q->sk);
q->file = file;
file->private_data = q;
vlan->numvtaps++;
out:
spin_unlock(&macvtap_lock);
return err;
}
/*
* The file owning the queue got closed, give up both
* the reference that the files holds as well as the
* one from the macvlan_dev if that still exists.
*
* Using the spinlock makes sure that we don't get
* to the queue again after destroying it.
*/
static void macvtap_put_queue(struct macvtap_queue *q)
{
struct macvlan_dev *vlan;
spin_lock(&macvtap_lock);
vlan = rcu_dereference_protected(q->vlan,
lockdep_is_held(&macvtap_lock));
if (vlan) {
int index = get_slot(vlan, q);
RCU_INIT_POINTER(vlan->taps[index], NULL);
RCU_INIT_POINTER(q->vlan, NULL);
sock_put(&q->sk);
--vlan->numvtaps;
}
spin_unlock(&macvtap_lock);
synchronize_rcu();
sock_put(&q->sk);
}
/*
* Select a queue based on the rxq of the device on which this packet
* arrived. If the incoming device is not mq, calculate a flow hash
* to select a queue. If all fails, find the first available queue.
* Cache vlan->numvtaps since it can become zero during the execution
* of this function.
*/
static struct macvtap_queue *macvtap_get_queue(struct net_device *dev,
struct sk_buff *skb)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct macvtap_queue *tap = NULL;
int numvtaps = vlan->numvtaps;
__u32 rxq;
if (!numvtaps)
goto out;
/* Check if we can use flow to select a queue */
rxq = skb_get_rxhash(skb);
if (rxq) {
tap = rcu_dereference(vlan->taps[rxq % numvtaps]);
if (tap)
goto out;
}
if (likely(skb_rx_queue_recorded(skb))) {
rxq = skb_get_rx_queue(skb);
while (unlikely(rxq >= numvtaps))
rxq -= numvtaps;
tap = rcu_dereference(vlan->taps[rxq]);
if (tap)
goto out;
}
/* Everything failed - find first available queue */
for (rxq = 0; rxq < MAX_MACVTAP_QUEUES; rxq++) {
tap = rcu_dereference(vlan->taps[rxq]);
if (tap)
break;
}
out:
return tap;
}
/*
* The net_device is going away, give up the reference
* that it holds on all queues and safely set the pointer
* from the queues to NULL.
*/
static void macvtap_del_queues(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct macvtap_queue *q, *qlist[MAX_MACVTAP_QUEUES];
int i, j = 0;
/* macvtap_put_queue can free some slots, so go through all slots */
spin_lock(&macvtap_lock);
for (i = 0; i < MAX_MACVTAP_QUEUES && vlan->numvtaps; i++) {
q = rcu_dereference_protected(vlan->taps[i],
lockdep_is_held(&macvtap_lock));
if (q) {
qlist[j++] = q;
RCU_INIT_POINTER(vlan->taps[i], NULL);
RCU_INIT_POINTER(q->vlan, NULL);
vlan->numvtaps--;
}
}
BUG_ON(vlan->numvtaps != 0);
/* guarantee that any future macvtap_set_queue will fail */
vlan->numvtaps = MAX_MACVTAP_QUEUES;
spin_unlock(&macvtap_lock);
synchronize_rcu();
for (--j; j >= 0; j--)
sock_put(&qlist[j]->sk);
}
/*
* Forward happens for data that gets sent from one macvlan
* endpoint to another one in bridge mode. We just take
* the skb and put it into the receive queue.
*/
static int macvtap_forward(struct net_device *dev, struct sk_buff *skb)
{
struct macvtap_queue *q = macvtap_get_queue(dev, skb);
if (!q)
goto drop;
if (skb_queue_len(&q->sk.sk_receive_queue) >= dev->tx_queue_len)
goto drop;
skb_queue_tail(&q->sk.sk_receive_queue, skb);
wake_up_interruptible_poll(sk_sleep(&q->sk), POLLIN | POLLRDNORM | POLLRDBAND);
return NET_RX_SUCCESS;
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
/*
* Receive is for data from the external interface (lowerdev),
* in case of macvtap, we can treat that the same way as
* forward, which macvlan cannot.
*/
static int macvtap_receive(struct sk_buff *skb)
{
skb_push(skb, ETH_HLEN);
return macvtap_forward(skb->dev, skb);
}
static int macvtap_get_minor(struct macvlan_dev *vlan)
{
int retval = -ENOMEM;
int id;
mutex_lock(&minor_lock);
if (idr_pre_get(&minor_idr, GFP_KERNEL) == 0)
goto exit;
retval = idr_get_new_above(&minor_idr, vlan, 1, &id);
if (retval < 0) {
if (retval == -EAGAIN)
retval = -ENOMEM;
goto exit;
}
if (id < MACVTAP_NUM_DEVS) {
vlan->minor = id;
} else {
printk(KERN_ERR "too many macvtap devices\n");
retval = -EINVAL;
idr_remove(&minor_idr, id);
}
exit:
mutex_unlock(&minor_lock);
return retval;
}
static void macvtap_free_minor(struct macvlan_dev *vlan)
{
mutex_lock(&minor_lock);
if (vlan->minor) {
idr_remove(&minor_idr, vlan->minor);
vlan->minor = 0;
}
mutex_unlock(&minor_lock);
}
static struct net_device *dev_get_by_macvtap_minor(int minor)
{
struct net_device *dev = NULL;
struct macvlan_dev *vlan;
mutex_lock(&minor_lock);
vlan = idr_find(&minor_idr, minor);
if (vlan) {
dev = vlan->dev;
dev_hold(dev);
}
mutex_unlock(&minor_lock);
return dev;
}
static int macvtap_newlink(struct net *src_net,
struct net_device *dev,
struct nlattr *tb[],
struct nlattr *data[])
{
/* Don't put anything that may fail after macvlan_common_newlink
* because we can't undo what it does.
*/
return macvlan_common_newlink(src_net, dev, tb, data,
macvtap_receive, macvtap_forward);
}
static void macvtap_dellink(struct net_device *dev,
struct list_head *head)
{
macvtap_del_queues(dev);
macvlan_dellink(dev, head);
}
static void macvtap_setup(struct net_device *dev)
{
macvlan_common_setup(dev);
dev->tx_queue_len = TUN_READQ_SIZE;
}
static struct rtnl_link_ops macvtap_link_ops __read_mostly = {
.kind = "macvtap",
.setup = macvtap_setup,
.newlink = macvtap_newlink,
.dellink = macvtap_dellink,
};
static void macvtap_sock_write_space(struct sock *sk)
{
wait_queue_head_t *wqueue;
if (!sock_writeable(sk) ||
!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
return;
wqueue = sk_sleep(sk);
if (wqueue && waitqueue_active(wqueue))
wake_up_interruptible_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND);
}
static void macvtap_sock_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_receive_queue);
}
static int macvtap_open(struct inode *inode, struct file *file)
{
struct net *net = current->nsproxy->net_ns;
struct net_device *dev = dev_get_by_macvtap_minor(iminor(inode));
struct macvtap_queue *q;
int err;
err = -ENODEV;
if (!dev)
goto out;
err = -ENOMEM;
q = (struct macvtap_queue *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
&macvtap_proto);
if (!q)
goto out;
q->sock.wq = &q->wq;
init_waitqueue_head(&q->wq.wait);
q->sock.type = SOCK_RAW;
q->sock.state = SS_CONNECTED;
q->sock.file = file;
q->sock.ops = &macvtap_socket_ops;
sock_init_data(&q->sock, &q->sk);
q->sk.sk_write_space = macvtap_sock_write_space;
q->sk.sk_destruct = macvtap_sock_destruct;
q->flags = IFF_VNET_HDR | IFF_NO_PI | IFF_TAP;
q->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
/*
* so far only KVM virtio_net uses macvtap, enable zero copy between
* guest kernel and host kernel when lower device supports zerocopy
*
* The macvlan supports zerocopy iff the lower device supports zero
* copy so we don't have to look at the lower device directly.
*/
if ((dev->features & NETIF_F_HIGHDMA) && (dev->features & NETIF_F_SG))
sock_set_flag(&q->sk, SOCK_ZEROCOPY);
err = macvtap_set_queue(dev, file, q);
if (err)
sock_put(&q->sk);
out:
if (dev)
dev_put(dev);
return err;
}
static int macvtap_release(struct inode *inode, struct file *file)
{
struct macvtap_queue *q = file->private_data;
macvtap_put_queue(q);
return 0;
}
static unsigned int macvtap_poll(struct file *file, poll_table * wait)
{
struct macvtap_queue *q = file->private_data;
unsigned int mask = POLLERR;
if (!q)
goto out;
mask = 0;
poll_wait(file, &q->wq.wait, wait);
if (!skb_queue_empty(&q->sk.sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
if (sock_writeable(&q->sk) ||
(!test_and_set_bit(SOCK_ASYNC_NOSPACE, &q->sock.flags) &&
sock_writeable(&q->sk)))
mask |= POLLOUT | POLLWRNORM;
out:
return mask;
}
static inline struct sk_buff *macvtap_alloc_skb(struct sock *sk, size_t prepad,
size_t len, size_t linear,
int noblock, int *err)
{
struct sk_buff *skb;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
err);
if (!skb)
return NULL;
skb_reserve(skb, prepad);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
/* set skb frags from iovec, this can move to core network code for reuse */
static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
int offset, size_t count)
{
int len = iov_length(from, count) - offset;
int copy = skb_headlen(skb);
int size, offset1 = 0;
int i = 0;
/* Skip over from offset */
while (count && (offset >= from->iov_len)) {
offset -= from->iov_len;
++from;
--count;
}
/* copy up to skb headlen */
while (count && (copy > 0)) {
size = min_t(unsigned int, copy, from->iov_len - offset);
if (copy_from_user(skb->data + offset1, from->iov_base + offset,
size))
return -EFAULT;
if (copy > size) {
++from;
--count;
offset = 0;
} else
offset += size;
copy -= size;
offset1 += size;
}
if (len == offset1)
return 0;
while (count--) {
struct page *page[MAX_SKB_FRAGS];
int num_pages;
unsigned long base;
unsigned long truesize;
len = from->iov_len - offset;
if (!len) {
offset = 0;
++from;
continue;
}
base = (unsigned long)from->iov_base + offset;
size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
num_pages = get_user_pages_fast(base, size, 0, &page[i]);
if ((num_pages != size) ||
(num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) {
for (i = 0; i < num_pages; i++)
put_page(page[i]);
return -EFAULT;
}
truesize = size * PAGE_SIZE;
skb->data_len += len;
skb->len += len;
skb->truesize += truesize;
atomic_add(truesize, &skb->sk->sk_wmem_alloc);
while (len) {
int off = base & ~PAGE_MASK;
int size = min_t(int, len, PAGE_SIZE - off);
__skb_fill_page_desc(skb, i, page[i], off, size);
skb_shinfo(skb)->nr_frags++;
/* increase sk_wmem_alloc */
base += size;
len -= size;
i++;
}
offset = 0;
++from;
}
return 0;
}
/*
* macvtap_skb_from_vnet_hdr and macvtap_skb_to_vnet_hdr should
* be shared with the tun/tap driver.
*/
static int macvtap_skb_from_vnet_hdr(struct sk_buff *skb,
struct virtio_net_hdr *vnet_hdr)
{
unsigned short gso_type = 0;
if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
switch (vnet_hdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
case VIRTIO_NET_HDR_GSO_TCPV4:
gso_type = SKB_GSO_TCPV4;
break;
case VIRTIO_NET_HDR_GSO_TCPV6:
gso_type = SKB_GSO_TCPV6;
break;
case VIRTIO_NET_HDR_GSO_UDP:
gso_type = SKB_GSO_UDP;
break;
default:
return -EINVAL;
}
if (vnet_hdr->gso_type & VIRTIO_NET_HDR_GSO_ECN)
gso_type |= SKB_GSO_TCP_ECN;
if (vnet_hdr->gso_size == 0)
return -EINVAL;
}
if (vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
if (!skb_partial_csum_set(skb, vnet_hdr->csum_start,
vnet_hdr->csum_offset))
return -EINVAL;
}
if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
skb_shinfo(skb)->gso_size = vnet_hdr->gso_size;
skb_shinfo(skb)->gso_type = gso_type;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
}
return 0;
}
static int macvtap_skb_to_vnet_hdr(const struct sk_buff *skb,
struct virtio_net_hdr *vnet_hdr)
{
memset(vnet_hdr, 0, sizeof(*vnet_hdr));
if (skb_is_gso(skb)) {
struct skb_shared_info *sinfo = skb_shinfo(skb);
/* This is a hint as to how much should be linear. */
vnet_hdr->hdr_len = skb_headlen(skb);
vnet_hdr->gso_size = sinfo->gso_size;
if (sinfo->gso_type & SKB_GSO_TCPV4)
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (sinfo->gso_type & SKB_GSO_TCPV6)
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (sinfo->gso_type & SKB_GSO_UDP)
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_UDP;
else
BUG();
if (sinfo->gso_type & SKB_GSO_TCP_ECN)
vnet_hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else
vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
vnet_hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
vnet_hdr->csum_start = skb_checksum_start_offset(skb);
vnet_hdr->csum_offset = skb->csum_offset;
} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
vnet_hdr->flags = VIRTIO_NET_HDR_F_DATA_VALID;
} /* else everything is zero */
return 0;
}
/* Get packet from user space buffer */
static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
const struct iovec *iv, unsigned long total_len,
size_t count, int noblock)
{
struct sk_buff *skb;
struct macvlan_dev *vlan;
unsigned long len = total_len;
int err;
struct virtio_net_hdr vnet_hdr = { 0 };
int vnet_hdr_len = 0;
int copylen;
bool zerocopy = false;
if (q->flags & IFF_VNET_HDR) {
vnet_hdr_len = q->vnet_hdr_sz;
err = -EINVAL;
if (len < vnet_hdr_len)
goto err;
len -= vnet_hdr_len;
err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,
sizeof(vnet_hdr));
if (err < 0)
goto err;
if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
vnet_hdr.hdr_len)
vnet_hdr.hdr_len = vnet_hdr.csum_start +
vnet_hdr.csum_offset + 2;
err = -EINVAL;
if (vnet_hdr.hdr_len > len)
goto err;
}
err = -EINVAL;
if (unlikely(len < ETH_HLEN))
goto err;
if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))
zerocopy = true;
if (zerocopy) {
/* There are 256 bytes to be copied in skb, so there is enough
* room for skb expand head in case it is used.
* The rest buffer is mapped from userspace.
*/
copylen = vnet_hdr.hdr_len;
if (!copylen)
copylen = GOODCOPY_LEN;
} else
copylen = len;
skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,
vnet_hdr.hdr_len, noblock, &err);
if (!skb)
goto err;
if (zerocopy)
err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);
else
err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,
len);
if (err)
goto err_kfree;
skb_set_network_header(skb, ETH_HLEN);
skb_reset_mac_header(skb);
skb->protocol = eth_hdr(skb)->h_proto;
if (vnet_hdr_len) {
err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);
if (err)
goto err_kfree;
}
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
/* copy skb_ubuf_info for callback when skb has no error */
if (zerocopy) {
skb_shinfo(skb)->destructor_arg = m->msg_control;
skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
}
if (vlan)
macvlan_start_xmit(skb, vlan->dev);
else
kfree_skb(skb);
rcu_read_unlock_bh();
return total_len;
err_kfree:
kfree_skb(skb);
err:
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
vlan->dev->stats.tx_dropped++;
rcu_read_unlock_bh();
return err;
}
static ssize_t macvtap_aio_write(struct kiocb *iocb, const struct iovec *iv,
unsigned long count, loff_t pos)
{
struct file *file = iocb->ki_filp;
ssize_t result = -ENOLINK;
struct macvtap_queue *q = file->private_data;
result = macvtap_get_user(q, NULL, iv, iov_length(iv, count), count,
file->f_flags & O_NONBLOCK);
return result;
}
/* Put packet to the user space buffer */
static ssize_t macvtap_put_user(struct macvtap_queue *q,
const struct sk_buff *skb,
const struct iovec *iv, int len)
{
struct macvlan_dev *vlan;
int ret;
int vnet_hdr_len = 0;
if (q->flags & IFF_VNET_HDR) {
struct virtio_net_hdr vnet_hdr;
vnet_hdr_len = q->vnet_hdr_sz;
if ((len -= vnet_hdr_len) < 0)
return -EINVAL;
ret = macvtap_skb_to_vnet_hdr(skb, &vnet_hdr);
if (ret)
return ret;
if (memcpy_toiovecend(iv, (void *)&vnet_hdr, 0, sizeof(vnet_hdr)))
return -EFAULT;
}
len = min_t(int, skb->len, len);
ret = skb_copy_datagram_const_iovec(skb, 0, iv, vnet_hdr_len, len);
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
macvlan_count_rx(vlan, len, ret == 0, 0);
rcu_read_unlock_bh();
return ret ? ret : (len + vnet_hdr_len);
}
static ssize_t macvtap_do_read(struct macvtap_queue *q, struct kiocb *iocb,
const struct iovec *iv, unsigned long len,
int noblock)
{
DECLARE_WAITQUEUE(wait, current);
struct sk_buff *skb;
ssize_t ret = 0;
add_wait_queue(sk_sleep(&q->sk), &wait);
while (len) {
current->state = TASK_INTERRUPTIBLE;
/* Read frames from the queue */
skb = skb_dequeue(&q->sk.sk_receive_queue);
if (!skb) {
if (noblock) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
/* Nothing to read, let's sleep */
schedule();
continue;
}
ret = macvtap_put_user(q, skb, iv, len);
kfree_skb(skb);
break;
}
current->state = TASK_RUNNING;
remove_wait_queue(sk_sleep(&q->sk), &wait);
return ret;
}
static ssize_t macvtap_aio_read(struct kiocb *iocb, const struct iovec *iv,
unsigned long count, loff_t pos)
{
struct file *file = iocb->ki_filp;
struct macvtap_queue *q = file->private_data;
ssize_t len, ret = 0;
len = iov_length(iv, count);
if (len < 0) {
ret = -EINVAL;
goto out;
}
ret = macvtap_do_read(q, iocb, iv, len, file->f_flags & O_NONBLOCK);
ret = min_t(ssize_t, ret, len); /* XXX copied from tun.c. Why? */
out:
return ret;
}
/*
* provide compatibility with generic tun/tap interface
*/
static long macvtap_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct macvtap_queue *q = file->private_data;
struct macvlan_dev *vlan;
void __user *argp = (void __user *)arg;
struct ifreq __user *ifr = argp;
unsigned int __user *up = argp;
unsigned int u;
int __user *sp = argp;
int s;
int ret;
switch (cmd) {
case TUNSETIFF:
/* ignore the name, just look at flags */
if (get_user(u, &ifr->ifr_flags))
return -EFAULT;
ret = 0;
if ((u & ~IFF_VNET_HDR) != (IFF_NO_PI | IFF_TAP))
ret = -EINVAL;
else
q->flags = u;
return ret;
case TUNGETIFF:
rcu_read_lock_bh();
vlan = rcu_dereference_bh(q->vlan);
if (vlan)
dev_hold(vlan->dev);
rcu_read_unlock_bh();
if (!vlan)
return -ENOLINK;
ret = 0;
if (copy_to_user(&ifr->ifr_name, vlan->dev->name, IFNAMSIZ) ||
put_user(q->flags, &ifr->ifr_flags))
ret = -EFAULT;
dev_put(vlan->dev);
return ret;
case TUNGETFEATURES:
if (put_user(IFF_TAP | IFF_NO_PI | IFF_VNET_HDR, up))
return -EFAULT;
return 0;
case TUNSETSNDBUF:
if (get_user(u, up))
return -EFAULT;
q->sk.sk_sndbuf = u;
return 0;
case TUNGETVNETHDRSZ:
s = q->vnet_hdr_sz;
if (put_user(s, sp))
return -EFAULT;
return 0;
case TUNSETVNETHDRSZ:
if (get_user(s, sp))
return -EFAULT;
if (s < (int)sizeof(struct virtio_net_hdr))
return -EINVAL;
q->vnet_hdr_sz = s;
return 0;
case TUNSETOFFLOAD:
/* let the user check for future flags */
if (arg & ~(TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 |
TUN_F_TSO_ECN | TUN_F_UFO))
return -EINVAL;
/* TODO: only accept frames with the features that
got enabled for forwarded frames */
if (!(q->flags & IFF_VNET_HDR))
return -EINVAL;
return 0;
default:
return -EINVAL;
}
}
#ifdef CONFIG_COMPAT
static long macvtap_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return macvtap_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
}
#endif
static const struct file_operations macvtap_fops = {
.owner = THIS_MODULE,
.open = macvtap_open,
.release = macvtap_release,
.aio_read = macvtap_aio_read,
.aio_write = macvtap_aio_write,
.poll = macvtap_poll,
.llseek = no_llseek,
.unlocked_ioctl = macvtap_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = macvtap_compat_ioctl,
#endif
};
static int macvtap_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
return macvtap_get_user(q, m, m->msg_iov, total_len, m->msg_iovlen,
m->msg_flags & MSG_DONTWAIT);
}
static int macvtap_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len,
int flags)
{
struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
int ret;
if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
return -EINVAL;
ret = macvtap_do_read(q, iocb, m->msg_iov, total_len,
flags & MSG_DONTWAIT);
if (ret > total_len) {
m->msg_flags |= MSG_TRUNC;
ret = flags & MSG_TRUNC ? ret : total_len;
}
return ret;
}
/* Ops structure to mimic raw sockets with tun */
static const struct proto_ops macvtap_socket_ops = {
.sendmsg = macvtap_sendmsg,
.recvmsg = macvtap_recvmsg,
};
/* Get an underlying socket object from tun file. Returns error unless file is
* attached to a device. The returned object works like a packet socket, it
* can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
* holding a reference to the file for as long as the socket is in use. */
struct socket *macvtap_get_socket(struct file *file)
{
struct macvtap_queue *q;
if (file->f_op != &macvtap_fops)
return ERR_PTR(-EINVAL);
q = file->private_data;
if (!q)
return ERR_PTR(-EBADFD);
return &q->sock;
}
EXPORT_SYMBOL_GPL(macvtap_get_socket);
static int macvtap_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct macvlan_dev *vlan;
struct device *classdev;
dev_t devt;
int err;
if (dev->rtnl_link_ops != &macvtap_link_ops)
return NOTIFY_DONE;
vlan = netdev_priv(dev);
switch (event) {
case NETDEV_REGISTER:
/* Create the device node here after the network device has
* been registered but before register_netdevice has
* finished running.
*/
err = macvtap_get_minor(vlan);
if (err)
return notifier_from_errno(err);
devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
classdev = device_create(macvtap_class, &dev->dev, devt,
dev, "tap%d", dev->ifindex);
if (IS_ERR(classdev)) {
macvtap_free_minor(vlan);
return notifier_from_errno(PTR_ERR(classdev));
}
break;
case NETDEV_UNREGISTER:
devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
device_destroy(macvtap_class, devt);
macvtap_free_minor(vlan);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block macvtap_notifier_block __read_mostly = {
.notifier_call = macvtap_device_event,
};
static int macvtap_init(void)
{
int err;
err = alloc_chrdev_region(&macvtap_major, 0,
MACVTAP_NUM_DEVS, "macvtap");
if (err)
goto out1;
cdev_init(&macvtap_cdev, &macvtap_fops);
err = cdev_add(&macvtap_cdev, macvtap_major, MACVTAP_NUM_DEVS);
if (err)
goto out2;
macvtap_class = class_create(THIS_MODULE, "macvtap");
if (IS_ERR(macvtap_class)) {
err = PTR_ERR(macvtap_class);
goto out3;
}
err = register_netdevice_notifier(&macvtap_notifier_block);
if (err)
goto out4;
err = macvlan_link_register(&macvtap_link_ops);
if (err)
goto out5;
return 0;
out5:
unregister_netdevice_notifier(&macvtap_notifier_block);
out4:
class_unregister(macvtap_class);
out3:
cdev_del(&macvtap_cdev);
out2:
unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
out1:
return err;
}
module_init(macvtap_init);
static void macvtap_exit(void)
{
rtnl_link_unregister(&macvtap_link_ops);
unregister_netdevice_notifier(&macvtap_notifier_block);
class_unregister(macvtap_class);
cdev_del(&macvtap_cdev);
unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
}
module_exit(macvtap_exit);
MODULE_ALIAS_RTNL_LINK("macvtap");
MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3635_0 |
crossvul-cpp_data_good_344_0 | /*
* card-cac.c: Support for CAC from NIST SP800-73
* card-default.c: Support for cards with no driver
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
* Copyright (C) 2016 - 2018, Red Hat, Inc.
*
* CAC driver author: Robert Relyea <rrelyea@redhat.com>
* Further work: Jakub Jelen <jjelen@redhat.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef ENABLE_OPENSSL
/* openssl only needed for card administration */
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#endif /* ENABLE_OPENSSL */
#include "internal.h"
#include "simpletlv.h"
#include "cardctl.h"
#ifdef ENABLE_ZLIB
#include "compression.h"
#endif
#include "iso7816.h"
#define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */
/*
* CAC hardware and APDU constants
*/
#define CAC_MAX_CHUNK_SIZE 240
#define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */
#define CAC_INS_READ_FILE 0x52 /* read a TL or V file */
#define CAC_INS_GET_ACR 0x4c
#define CAC_INS_GET_PROPERTIES 0x56
#define CAC_P1_STEP 0x80
#define CAC_P1_FINAL 0x00
#define CAC_FILE_TAG 1
#define CAC_FILE_VALUE 2
/* TAGS in a TL file */
#define CAC_TAG_CERTIFICATE 0x70
#define CAC_TAG_CERTINFO 0x71
#define CAC_TAG_MSCUID 0x72
#define CAC_TAG_CUID 0xF0
#define CAC_TAG_CC_VERSION_NUMBER 0xF1
#define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2
#define CAC_TAG_CARDURL 0xF3
#define CAC_TAG_PKCS15 0xF4
#define CAC_TAG_ACCESS_CONTROL 0xF6
#define CAC_TAG_DATA_MODEL 0xF5
#define CAC_TAG_CARD_APDU 0xF7
#define CAC_TAG_REDIRECTION 0xFA
#define CAC_TAG_CAPABILITY_TUPLES 0xFB
#define CAC_TAG_STATUS_TUPLES 0xFC
#define CAC_TAG_NEXT_CCC 0xFD
#define CAC_TAG_ERROR_CODES 0xFE
#define CAC_TAG_APPLET_FAMILY 0x01
#define CAC_TAG_NUMBER_APPLETS 0x94
#define CAC_TAG_APPLET_ENTRY 0x93
#define CAC_TAG_APPLET_AID 0x92
#define CAC_TAG_APPLET_INFORMATION 0x01
#define CAC_TAG_NUMBER_OF_OBJECTS 0x40
#define CAC_TAG_TV_BUFFER 0x50
#define CAC_TAG_PKI_OBJECT 0x51
#define CAC_TAG_OBJECT_ID 0x41
#define CAC_TAG_BUFFER_PROPERTIES 0x42
#define CAC_TAG_PKI_PROPERTIES 0x43
#define CAC_APP_TYPE_GENERAL 0x01
#define CAC_APP_TYPE_SKI 0x02
#define CAC_APP_TYPE_PKI 0x04
#define CAC_ACR_ACR 0x00
#define CAC_ACR_APPLET_OBJECT 0x10
#define CAC_ACR_AMP 0x20
#define CAC_ACR_SERVICE 0x21
/* hardware data structures (returned in the CCC) */
/* part of the card_url */
typedef struct cac_access_profile {
u8 GCACR_listID;
u8 GCACR_readTagListACRID;
u8 GCACR_updatevalueACRID;
u8 GCACR_readvalueACRID;
u8 GCACR_createACRID;
u8 GCACR_deleteACRID;
u8 CryptoACR_listID;
u8 CryptoACR_getChallengeACRID;
u8 CryptoACR_internalAuthenicateACRID;
u8 CryptoACR_pkiComputeACRID;
u8 CryptoACR_readTagListACRID;
u8 CryptoACR_updatevalueACRID;
u8 CryptoACR_readvalueACRID;
u8 CryptoACR_createACRID;
u8 CryptoACR_deleteACRID;
} cac_access_profile_t;
/* part of the card url */
typedef struct cac_access_key_info {
u8 keyFileID[2];
u8 keynumber;
} cac_access_key_info_t;
typedef struct cac_card_url {
u8 rid[5];
u8 cardApplicationType;
u8 objectID[2];
u8 applicationID[2];
cac_access_profile_t accessProfile;
u8 pinID; /* not used for VM cards */
cac_access_key_info_t accessKeyInfo; /* not used for VM cards */
u8 keyCryptoAlgorithm; /* not used for VM cards */
} cac_card_url_t;
typedef struct cac_cuid {
u8 gsc_rid[5];
u8 manufacturer_id;
u8 card_type;
u8 card_id;
} cac_cuid_t;
/* data structures to store meta data about CAC objects */
typedef struct cac_object {
const char *name;
int fd;
sc_path_t path;
} cac_object_t;
#define CAC_MAX_OBJECTS 16
typedef struct {
/* OID has two bytes */
unsigned char oid[2];
/* Format is NOT SimpleTLV? */
unsigned char simpletlv;
/* Is certificate object and private key is initialized */
unsigned char privatekey;
} cac_properties_object_t;
typedef struct {
unsigned int num_objects;
cac_properties_object_t objects[CAC_MAX_OBJECTS];
} cac_properties_t;
/*
* Flags for Current Selected Object Type
* CAC files are TLV files, with TL and V separated. For generic
* containers we reintegrate the TL anv V portions into a single
* file to read. Certs are also TLV files, but pkcs15 wants the
* actual certificate. At select time we know the patch which tells
* us what time of files we want to read. We remember that type
* so that read_binary can do the appropriate processing.
*/
#define CAC_OBJECT_TYPE_CERT 1
#define CAC_OBJECT_TYPE_TLV_FILE 4
#define CAC_OBJECT_TYPE_GENERIC 5
/*
* CAC private data per card state
*/
typedef struct cac_private_data {
int object_type; /* select set this so we know how to read the file */
int cert_next; /* index number for the next certificate found in the list */
u8 *cache_buf; /* cached version of the currently selected file */
size_t cache_buf_len; /* length of the cached selected file */
int cached; /* is the cached selected file valid */
cac_cuid_t cuid; /* card unique ID from the CCC */
u8 *cac_id; /* card serial number */
size_t cac_id_len; /* card serial number len */
list_t pki_list; /* list of pki containers */
cac_object_t *pki_current; /* current pki object _ctl function */
list_t general_list; /* list of general containers */
cac_object_t *general_current; /* current object for _ctl function */
sc_path_t *aca_path; /* ACA path to be selected before pin verification */
} cac_private_data_t;
#define CAC_DATA(card) ((cac_private_data_t*)card->drv_data)
int cac_list_compare_path(const void *a, const void *b)
{
if (a == NULL || b == NULL)
return 1;
return memcmp( &((cac_object_t *) a)->path,
&((cac_object_t *) b)->path, sizeof(sc_path_t));
}
/* For SimCList autocopy, we need to know the size of the data elements */
size_t cac_list_meter(const void *el) {
return sizeof(cac_object_t);
}
static cac_private_data_t *cac_new_private_data(void)
{
cac_private_data_t *priv;
priv = calloc(1, sizeof(cac_private_data_t));
if (!priv)
return NULL;
list_init(&priv->pki_list);
list_attributes_comparator(&priv->pki_list, cac_list_compare_path);
list_attributes_copy(&priv->pki_list, cac_list_meter, 1);
list_init(&priv->general_list);
list_attributes_comparator(&priv->general_list, cac_list_compare_path);
list_attributes_copy(&priv->general_list, cac_list_meter, 1);
/* set other fields as appropriate */
return priv;
}
static void cac_free_private_data(cac_private_data_t *priv)
{
free(priv->cac_id);
free(priv->cache_buf);
free(priv->aca_path);
list_destroy(&priv->pki_list);
list_destroy(&priv->general_list);
free(priv);
return;
}
static int cac_add_object_to_list(list_t *list, const cac_object_t *object)
{
if (list_append(list, object) < 0)
return SC_ERROR_UNKNOWN;
return SC_SUCCESS;
}
/*
* Set up the normal CAC paths
*/
#define CAC_TO_AID(x) x, sizeof(x)-1
#define CAC_2_RID "\xA0\x00\x00\x01\x16"
#define CAC_1_RID "\xA0\x00\x00\x00\x79"
static const sc_path_t cac_ACA_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x10\x00") }
};
static const sc_path_t cac_CCC_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_2_RID "\xDB\x00") }
};
#define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */
/* default certificate labels for the CAC card */
static const char *cac_labels[MAX_CAC_SLOTS] = {
"CAC ID Certificate",
"CAC Email Signature Certificate",
"CAC Email Encryption Certificate",
"CAC Cert 4",
"CAC Cert 5",
"CAC Cert 6",
"CAC Cert 7",
"CAC Cert 8",
"CAC Cert 9",
"CAC Cert 10",
"CAC Cert 11",
"CAC Cert 12",
"CAC Cert 13",
"CAC Cert 14",
"CAC Cert 15",
"CAC Cert 16"
};
/* template for a CAC pki object */
static const cac_object_t cac_cac_pki_obj = {
"CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x01\x00") } }
};
/* template for emulated cuid */
static const cac_cuid_t cac_cac_cuid = {
{ 0xa0, 0x00, 0x00, 0x00, 0x79 },
2, 2, 0
};
/*
* CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0.
* doubles as a source for CAC-2 labels.
*/
static const cac_object_t cac_objects[] = {
{ "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x00") }}},
{ "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x01") }}},
{ "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x02") }}},
{ "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x03") }}},
{ "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFD") }}},
{ "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFE") }}},
};
static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]);
/*
* use the object id to find our object info on the object in our CAC-1 list
*/
static const cac_object_t *cac_find_obj_by_id(unsigned short object_id)
{
int i;
for (i = 0; i < cac_object_count; i++) {
if (cac_objects[i].fd == object_id) {
return &cac_objects[i];
}
}
return NULL;
}
/*
* Lookup the path in the pki list to see if it is a cert path
*/
static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path)
{
cac_object_t test_obj;
test_obj.path = *in_path;
test_obj.path.index = 0;
test_obj.path.count = 0;
return (list_contains(&priv->pki_list, &test_obj) != 0);
}
/*
* Send a command and receive data.
*
* A caller may provide a buffer, and length to read. If not provided,
* an internal 4096 byte buffer is used, and a copy is returned to the
* caller. that need to be freed by the caller.
*
* modelled after a similar function in card-piv.c
*/
static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2,
const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf,
size_t * recvbuflen)
{
int r;
sc_apdu_t apdu;
u8 rbufinitbuf[CAC_MAX_SIZE];
u8 *rbuf;
size_t rbuflen;
unsigned int apdu_case = SC_APDU_CASE_1;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
ins, p1, p2, sendbuflen, card->max_send_size,
card->max_recv_size);
rbuf = rbufinitbuf;
rbuflen = sizeof(rbufinitbuf);
/* if caller provided a buffer and length */
if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
rbuf = *recvbuf;
rbuflen = *recvbuflen;
}
if (recvbuf) {
if (sendbuf)
apdu_case = SC_APDU_CASE_4_SHORT;
else
apdu_case = SC_APDU_CASE_2_SHORT;
} else if (sendbuf)
apdu_case = SC_APDU_CASE_3_SHORT;
sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
apdu.lc = sendbuflen;
apdu.datalen = sendbuflen;
apdu.data = sendbuf;
if (recvbuf) {
apdu.resp = rbuf;
apdu.le = (rbuflen > 255) ? 255 : rbuflen;
apdu.resplen = rbuflen;
} else {
apdu.resp = rbuf;
apdu.le = 0;
apdu.resplen = 0;
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
apdu.flags, apdu.le, apdu.resplen, apdu.resp);
/* with new adpu.c and chaining, this actually reads the whole object */
r = sc_transmit_apdu(card, &apdu);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
r, apdu.resplen, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error ");
goto err;
}
if (recvbuflen) {
if (recvbuf && *recvbuf == NULL) {
*recvbuf = malloc(apdu.resplen);
if (*recvbuf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*recvbuf, rbuf, apdu.resplen);
}
*recvbuflen = apdu.resplen;
r = *recvbuflen;
}
err:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Get ACR of currently ACA applet identified by the acr_type
* 5.3.3.5 Get ACR APDU
*/
static int
cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len)
{
u8 *out = NULL;
/* XXX assuming it will not be longer than 255 B */
size_t len = 256;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* for simplicity we support only ACR without arguments now */
if (acr_type != 0x00 && acr_type != 0x10
&& acr_type != 0x20 && acr_type != 0x21) {
return SC_ERROR_INVALID_ARGUMENTS;
}
r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out);
*out_len = len;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_buf = NULL;
*out_len = 0;
return r;
}
/*
* Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file
*/
#define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff)
#define LOW_BYTE_OF_SHORT(x) ((x) & 0xff)
static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len)
{
u8 params[2];
u8 count[2];
u8 *out = NULL;
u8 *out_ptr;
size_t offset = 0;
size_t size = 0;
size_t left = 0;
size_t len;
int r;
params[0] = file_type;
params[1] = 2;
/* get the size */
len = sizeof(count);
out_ptr = count;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, ¶ms[0], sizeof(params), &out_ptr, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
left = size = lebytes2ushort(count);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)",
len, out_ptr, &count, count[0], count[1], size, size);
out = out_ptr = malloc(size);
if (out == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto fail;
}
for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) {
len = MIN(left, CAC_MAX_CHUNK_SIZE);
params[1] = len;
r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset),
¶ms[0], sizeof(params), &out_ptr, &len);
/* if there is no data, assume there is no file */
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0) {
goto fail;
}
}
*out_len = size;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_len = 0;
return r;
}
/*
* Callers of this may be expecting a certificate,
* select file will have saved the object type for us
* as well as set that we want the cert from the object.
*/
static int cac_read_binary(sc_card_t *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
cac_private_data_t * priv = CAC_DATA(card);
int r = 0;
u8 *tl = NULL, *val = NULL;
u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start;
u8 *cert_ptr;
size_t tl_len, val_len, tlv_len;
size_t len, tl_head_len, cert_len;
u8 cert_type, tag;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* if we didn't return it all last time, return the remainder */
if (priv->cached) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (idx > priv->cache_buf_len) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED);
}
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len);
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
priv->cache_buf_len = 0;
}
if (priv->object_type <= 0)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0) {
goto done;
}
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
switch (priv->object_type) {
case CAC_OBJECT_TYPE_TLV_FILE:
tlv_len = tl_len + val_len;
priv->cache_buf = malloc(tlv_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = tlv_len;
for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
tl_len >= 2 && tlv_len > 0;
val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
/* get the tag and the length */
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = (tl_ptr - tl_start);
sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
tlv_len -= tl_head_len;
tl_len -= tl_head_len;
/* don't crash on bad data */
if (val_len < len) {
len = val_len;
}
/* if we run out of return space, truncate */
if (tlv_len < len) {
len = tlv_len;
}
memcpy(tlv_ptr, val_ptr, len);
}
break;
case CAC_OBJECT_TYPE_CERT:
/* read file */
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
" obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
val_len, val_len);
cert_len = 0;
cert_ptr = NULL;
cert_type = 0;
for (tl_ptr = tl, val_ptr = val; tl_len >= 2;
val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = tl_ptr - tl_start;
/* incomplete value */
if (val_len < len)
break;
if (tag == CAC_TAG_CERTIFICATE) {
cert_len = len;
cert_ptr = val_ptr;
}
if (tag == CAC_TAG_CERTINFO) {
if ((len >= 1) && (val_len >=1)) {
cert_type = *val_ptr;
}
}
if (tag == CAC_TAG_MSCUID) {
sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
}
if ((val_len < len) || (tl_len < tl_head_len)) {
break;
}
}
/* if the info byte is 1, then the cert is compressed, decompress it */
if ((cert_type & 0x3) == 1) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len,
cert_ptr, cert_len, COMPRESSION_AUTO);
#else
sc_log(card->ctx, "CAC compression not supported, no zlib");
r = SC_ERROR_NOT_SUPPORTED;
#endif
if (r)
goto done;
} else if (cert_len > 0) {
priv->cache_buf = malloc(cert_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = cert_len;
memcpy(priv->cache_buf, cert_ptr, cert_len);
} else {
sc_log(card->ctx, "Can't read zero-length certificate");
goto done;
}
break;
case CAC_OBJECT_TYPE_GENERIC:
/* TODO
* We have some two buffers in unknown encoding that we
* need to present in PKCS#15 layer.
*/
default:
/* Unknown object type */
sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
r = SC_ERROR_INTERNAL;
goto done;
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
priv->cached = 1;
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
r = len;
done:
if (tl)
free(tl);
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* CAC driver is read only */
static int cac_write_binary(sc_card_t *card, unsigned int idx,
const u8 *buf, size_t count, unsigned long flags)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
/* initialize getting a list and return the number of elements in the list */
static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp)
{
*countp = list_size(list);
list_iterator_start(list);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
/* finalize the list iterator */
static int cac_final_iterator(list_t *list)
{
list_iterator_stop(list);
return SC_SUCCESS;
}
/* fill in the obj_info for the current object on the list and advance to the next object */
static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info)
{
memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t));
if (*entry == NULL) {
return SC_ERROR_FILE_END_REACHED;
}
obj_info->path = (*entry)->path;
obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */
obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff;
obj_info->id.value[1] = (*entry)->fd & 0xff;
obj_info->id.len = 2;
strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, serial->len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (priv->aca_path) {
*path = *priv->aca_path;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
cac_private_data_t * priv = CAC_DATA(card);
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
if (priv == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
}
switch(cmd) {
case SC_CARDCTL_CAC_GET_ACA_PATH:
return cac_get_ACA_path(card, (sc_path_t *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS:
return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr);
case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS:
return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT:
return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT:
return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS:
return cac_final_iterator(&priv->general_list);
case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS:
return cac_final_iterator(&priv->pki_list);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
/* CAC requires 8 byte response */
u8 rbuf[8];
u8 *rbufp = &rbuf[0];
size_t out_len = sizeof rbuf;
int r;
LOG_FUNC_CALLED(card->ctx);
r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len);
LOG_TEST_RET(card->ctx, r, "Could not get challenge");
if (len < out_len) {
out_len = len;
}
memcpy(rnd, rbuf, out_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len);
}
static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
env->flags, env->operation, env->algorithm,
env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
env->key_ref_len);
if (env->algorithm != SC_ALGORITHM_RSA) {
r = SC_ERROR_NO_CARD_SUPPORT;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int cac_restore_security_env(sc_card_t *card, int se_num)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_rsa_op(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
u8 *outp, *rbuf;
size_t rbuflen, outplen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
datalen, outlen);
outp = out;
outplen = outlen;
/* Not strictly necessary. This code requires the caller to have selected the correct PKI container
* and authenticated to that container with the verifyPin command... All of this under the reader lock.
* The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just
* different sets of APDU's that need to be called), so this call is really a little bit of paranoia */
r = sc_lock(card);
if (r != SC_SUCCESS)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
rbuf = NULL;
rbuflen = 0;
for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) {
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0,
data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen);
if (r < 0) {
break;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
outp += n;
outplen -= n;
}
free(rbuf);
rbuf = NULL;
rbuflen = 0;
}
if (r < 0) {
goto err;
}
rbuf = NULL;
rbuflen = 0;
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen);
if (r < 0) {
goto err;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
/*outp += n; unused */
outplen -= n;
}
free(rbuf);
rbuf = NULL;
r = outlen-outplen;
err:
sc_unlock(card);
if (r < 0) {
sc_mem_clear(out, outlen);
}
if (rbuf) {
free(rbuf);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int cac_compute_signature(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_decipher(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_parse_properties_object(sc_card_t *card, u8 type,
u8 *data, size_t data_len, cac_properties_object_t *object)
{
size_t len;
u8 *val, *val_end, tag;
int parsed = 0;
if (data_len < 11)
return -1;
/* Initilize: non-PKI applet */
object->privatekey = 0;
val = data;
val_end = data + data_len;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_OBJECT_ID:
if (len != 2) {
sc_log(card->ctx, "TAG: Object ID: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]);
memcpy(&object->oid, val, 2);
parsed++;
break;
case CAC_TAG_BUFFER_PROPERTIES:
if (len != 5) {
sc_log(card->ctx, "TAG: Buffer Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* First byte is "Type of Tag Supported" */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Buffer Properties: Type of Tag Supported = 0x%02x",
val[0]);
object->simpletlv = val[0];
parsed++;
break;
case CAC_TAG_PKI_PROPERTIES:
/* 4th byte is "Private Key Initialized" */
if (len != 4) {
sc_log(card->ctx, "TAG: PKI Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
if (type != CAC_TAG_PKI_OBJECT) {
sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object");
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Properties: Private Key Initialized = 0x%02x",
val[2]);
object->privatekey = val[2];
parsed++;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)",tag );
break;
}
}
if (parsed < 2)
return SC_ERROR_INVALID_DATA;
return SC_SUCCESS;
}
static int cac_get_properties(sc_card_t *card, cac_properties_t *prop)
{
u8 *rbuf = NULL;
size_t rbuflen = 0, len;
u8 *val, *val_end, tag;
size_t i = 0;
int r;
prop->num_objects = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0,
&rbuf, &rbuflen);
if (r < 0)
return r;
val = rbuf;
val_end = val + rbuflen;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_INFORMATION:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%0x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_OF_OBJECTS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num objects: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num objects = %hhd", *val);
/* make sure we do not overrun buffer */
prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS);
break;
case CAC_TAG_TV_BUFFER:
if (len != 17) {
sc_log(card->ctx, "TAG: TV Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
case CAC_TAG_PKI_OBJECT:
if (len != 17) {
sc_log(card->ctx, "TAG: PKI Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
default:
/* ignore tags we don't understand */
sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%"
SC_FORMAT_LEN_SIZE_T"u", tag, len);
break;
}
}
free(rbuf);
/* sanity */
if (i != prop->num_objects)
sc_log(card->ctx, "The announced number of objects (%u) "
"did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)",
prop->num_objects, i);
prop->num_objects = i;
return SC_SUCCESS;
}
/*
* CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more
* of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead
* of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS
* if it doesn't like anything about the select, so we always 'request' FCI for CAC1
*
* The rest is just copied from iso7816_select_file
*/
static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type)
{
struct sc_context *ctx;
struct sc_apdu apdu;
unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen, pathtype;
struct sc_file *file = NULL;
cac_private_data_t * priv = CAC_DATA(card);
assert(card != NULL && in_path != NULL);
ctx = card->ctx;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
pathtype = in_path->type;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
in_path->aid.value[0], in_path->aid.value[1],
in_path->aid.value[2], in_path->aid.value[3],
in_path->aid.value[4], in_path->aid.value[5],
in_path->aid.value[6], in_path->aid.len, in_path->value[0],
in_path->value[1], in_path->value[2], in_path->value[3],
in_path->len, in_path->type, in_path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
file_out, in_path->index, in_path->count);
/* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override.
* we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file
* a flag that says 'no, really this path is fine'. We only need to do this for private keys */
if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
if (pathlen > 2) {
path += 2;
pathlen -= 2;
}
}
/* CAC has multiple different type of objects that aren't PKCS #15. When we read
* them we need convert them to something PKCS #15 would understand. Find the object
* and object type here:
*/
if (priv) { /* don't record anything if we haven't been initialized yet */
priv->object_type = CAC_OBJECT_TYPE_GENERIC;
if (cac_is_cert(priv, in_path)) {
priv->object_type = CAC_OBJECT_TYPE_CERT;
}
/* forget any old cached values */
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
}
priv->cache_buf_len = 0;
priv->cached = 0;
}
if (in_path->aid.len) {
if (!pathlen) {
memcpy(path, in_path->aid.value, in_path->aid.len);
pathlen = in_path->aid.len;
pathtype = SC_PATH_TYPE_DF_NAME;
} else {
/* First, select the application */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
apdu.data = in_path->aid.value;
apdu.datalen = in_path->aid.len;
apdu.lc = in_path->aid.len;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
switch (pathtype) {
/* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select.
* Unfortunately we'd also need to update the caching code as well. For now just
* use FILE_ID and change p1 here */
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 2;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
if (file_out != NULL) {
apdu.p2 = 0; /* first record, return FCI */
}
else {
apdu.p2 = 0x0C;
}
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
if (file_out == NULL) {
/* For some cards 'SELECT' can be only with request to return FCI/FCP. */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) {
apdu.p2 = 0x00;
apdu.resplen = sizeof(buf);
if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_FUNC_RETURN(ctx, r);
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
/* This needs to come after the applet selection */
if (priv && in_path->len >= 2) {
/* get applet properties to know if we can treat the
* buffer as SimpleLTV and if we have PKI applet.
*
* Do this only if we select applets for reading
* (not during driver initialization)
*/
cac_properties_t prop;
size_t i = -1;
r = cac_get_properties(card, &prop);
if (r == SC_SUCCESS) {
for (i = 0; i < prop.num_objects; i++) {
sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x",
prop.objects[i].oid[0], prop.objects[i].oid[1],
in_path->value[0], in_path->value[1]);
if (memcmp(prop.objects[i].oid,
in_path->value, 2) == 0)
break;
}
}
if (i < prop.num_objects) {
if (prop.objects[i].privatekey)
priv->object_type = CAC_OBJECT_TYPE_CERT;
else if (prop.objects[i].simpletlv == 0)
priv->object_type = CAC_OBJECT_TYPE_TLV_FILE;
}
}
/* CAC cards never return FCI, fake one */
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
*file_out = file;
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
return cac_select_file_by_type(card, in_path, file_out, card->type);
}
static int cac_finish(sc_card_t *card)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
cac_free_private_data(priv);
}
return SC_SUCCESS;
}
/* select the Card Capabilities Container on CAC-2 */
static int cac_select_CCC(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II);
}
/* Select ACA in non-standard location */
static int cac_select_ACA(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II);
}
static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len)
{
if (len < 10) {
return SC_ERROR_INVALID_DATA;
}
sc_mem_clear(path, sizeof(sc_path_t));
memcpy(path->aid.value, &val->rid, sizeof(val->rid));
memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID));
path->aid.len = sizeof(val->rid) + sizeof(val->applicationID);
memcpy(path->value, &val->objectID, sizeof(val->objectID));
path->len = sizeof(val->objectID);
path->type = SC_PATH_TYPE_FILE_ID;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
path->aid.value[0], path->aid.value[1], path->aid.value[2],
path->aid.value[3], path->aid.value[4], path->aid.value[5],
path->aid.value[6], path->aid.len, path->value[0],
path->value[1], path->len, path->type, path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u",
val->rid[0], val->rid[1], val->rid[2], val->rid[3],
val->rid[4], sizeof(val->rid), val->applicationID[0],
val->applicationID[1], sizeof(val->applicationID),
val->objectID[0], val->objectID[1], sizeof(val->objectID));
return SC_SUCCESS;
}
static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len)
{
cac_object_t new_object;
cac_properties_t prop;
size_t i;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Search for PKI applets (7 B). Ignore generic objects for now */
if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0
&& memcmp(aid, CAC_1_RID "\x00", 6) != 0))
return SC_SUCCESS;
sc_mem_clear(&new_object.path, sizeof(sc_path_t));
memcpy(new_object.path.aid.value, aid, aid_len);
new_object.path.aid.len = aid_len;
/* Call without OID set will just select the AID without subseqent
* OID selection, which we need to figure out just now
*/
cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II);
r = cac_get_properties(card, &prop);
if (r < 0)
return SC_ERROR_INTERNAL;
for (i = 0; i < prop.num_objects; i++) {
/* don't fail just because we have more certs than we can support */
if (priv->cert_next >= MAX_CAC_SLOTS)
return SC_SUCCESS;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"ACA: pki_object found, cert_next=%d (%s), privkey=%d",
priv->cert_next, cac_labels[priv->cert_next],
prop.objects[i].privatekey);
/* If the private key is not initialized, we can safely
* ignore this object here, but increase the pointer to follow
* the certificate labels
*/
if (!prop.objects[i].privatekey) {
priv->cert_next++;
continue;
}
/* OID here has always 2B */
memcpy(new_object.path.value, &prop.objects[i].oid, 2);
new_object.path.len = 2;
new_object.path.type = SC_PATH_TYPE_FILE_ID;
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
}
return SC_SUCCESS;
}
static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len)
{
cac_object_t new_object;
const cac_object_t *obj;
unsigned short object_id;
int r;
r = cac_path_from_cardurl(card, &new_object.path, val, len);
if (r != SC_SUCCESS) {
return r;
}
switch (val->cardApplicationType) {
case CAC_APP_TYPE_PKI:
/* we don't want to overflow the cac_label array. This test could
* go way if we create a label function that will create a unique label
* from a cert index.
*/
if (priv->cert_next >= MAX_CAC_SLOTS)
break; /* don't fail just because we have more certs than we can support */
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name);
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
break;
case CAC_APP_TYPE_GENERAL:
object_id = bebytes2ushort(val->objectID);
obj = cac_find_obj_by_id(object_id);
if (obj == NULL)
break; /* don't fail just because we don't recognize the object */
new_object.name = obj->name;
new_object.fd = 0;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name);
cac_add_object_to_list(&priv->general_list, &new_object);
break;
case CAC_APP_TYPE_SKI:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found");
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType);
/* don't fail just because there is an unknown object in the CCC */
break;
}
return SC_SUCCESS;
}
static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len)
{
size_t card_id_len;
if (len < sizeof(cac_cuid_t)) {
return SC_ERROR_INVALID_DATA;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid)));
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type);
card_id_len = len - (&val->card_id - (u8 *)val);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)",
sc_dump_hex(&val->card_id, card_id_len),
card_id_len);
priv->cuid = *val;
priv->cac_id = malloc(card_id_len);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
memcpy(priv->cac_id, &val->card_id, card_id_len);
priv->cac_id_len = card_id_len;
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv);
static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl,
size_t tl_len, u8 *val, size_t val_len)
{
size_t len = 0;
u8 *tl_end = tl + tl_len;
u8 *val_end = val + val_len;
sc_path_t new_path;
int r;
for (; (tl < tl_end) && (val< val_end); val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_CUID:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID");
r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len);
if (r < 0)
return r;
break;
case CAC_TAG_CC_VERSION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: CC Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: CC Version = 0x%02x", *val);
break;
case CAC_TAG_GRAMMAR_VERION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: Grammar Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Grammar Version = 0x%02x", *val);
break;
case CAC_TAG_CARDURL:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL");
r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len);
if (r < 0)
return r;
break;
/*
* The following are really for file systems cards. This code only cares about CAC VM cards
*/
case CAC_TAG_PKCS15:
if (len != 1) {
sc_log(card->ctx, "TAG: PKCS15: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* TODO should verify that this is '0'. If it's not
* zero, we should drop out of here and let the PKCS 15
* code handle this card */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val);
break;
case CAC_TAG_DATA_MODEL:
case CAC_TAG_CARD_APDU:
case CAC_TAG_CAPABILITY_TUPLES:
case CAC_TAG_STATUS_TUPLES:
case CAC_TAG_REDIRECTION:
case CAC_TAG_ERROR_CODES:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag);
break;
case CAC_TAG_ACCESS_CONTROL:
/* TODO handle access control later */
sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len);
break;
case CAC_TAG_NEXT_CCC:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC");
r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len);
if (r < 0)
return r;
r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II);
if (r < 0)
return r;
r = cac_process_CCC(card, priv);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag );
break;
}
}
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv)
{
u8 *tl = NULL, *val = NULL;
size_t tl_len, val_len;
int r;
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0)
goto done;
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len);
done:
if (tl)
free(tl);
if (val)
free(val);
return r;
}
/* Service Applet Table (Table 5-21) should list all the applets on the
* card, which is a good start if we don't have CCC
*/
static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv,
u8 *val, size_t val_len)
{
size_t len = 0;
u8 *val_end = val + val_len;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
for (; val < val_end; val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_FAMILY:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%02x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_APPLETS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num applets: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num applets = %hhd", *val);
break;
case CAC_TAG_APPLET_ENTRY:
/* Make sure we match the outer length */
if (len < 3 || val[2] != len - 3) {
sc_log(card->ctx, "TAG: Applet Entry: "
"bad length (%"SC_FORMAT_LEN_SIZE_T
"u) or length of internal buffer", len);
break;
}
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Entry: AID", &val[3], val[2]);
/* This is SimpleTLV prefixed with applet ID (1B) */
r = cac_parse_aid(card, priv, &val[3], val[2]);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)", tag);
break;
}
}
return SC_SUCCESS;
}
/* select a CAC pki applet by index */
static int cac_select_pki_applet(sc_card_t *card, int index)
{
sc_path_t applet_path = cac_cac_pki_obj.path;
applet_path.aid.value[applet_path.aid.len-1] = index;
return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II);
}
/*
* Find the first existing CAC applet. If none found, then this isn't a CAC
*/
static int cac_find_first_pki_applet(sc_card_t *card, int *index_out)
{
int r, i;
for (i = 0; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
/* Try to read first two bytes of the buffer to
* make sure it is not just malfunctioning card
*/
u8 params[2] = {CAC_FILE_TAG, 2};
u8 data[2], *out_ptr = data;
size_t len = 2;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0,
¶ms[0], sizeof(params), &out_ptr, &len);
if (r != 2)
continue;
*index_out = i;
return SC_SUCCESS;
}
}
return SC_ERROR_OBJECT_NOT_FOUND;
}
/*
* This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets
*/
static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv)
{
int r, i;
cac_object_t pki_obj = cac_cac_pki_obj;
u8 buf[100];
u8 *val;
size_t val_len;
/* populate PKI objects */
for (i = index; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
pki_obj.name = cac_labels[i];
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name);
pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
pki_obj.fd = i+1; /* don't use id of zero */
cac_add_object_to_list(&priv->pki_list, &pki_obj);
}
}
/* populate non-PKI objects */
for (i=0; i < cac_object_count; i++) {
r = cac_select_file_by_type(card, &cac_objects[i].path, NULL,
SC_CARD_TYPE_CAC_II);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: obj_object found, cert_next=%d (%s),",
i, cac_objects[i].name);
cac_add_object_to_list(&priv->general_list, &cac_objects[i]);
}
}
/*
* create a cuid to simulate the cac 2 cuid.
*/
priv->cuid = cac_cac_cuid;
/* create a serial number by hashing the first 100 bytes of the
* first certificate on the card */
r = cac_select_pki_applet(card, index);
if (r < 0) {
return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
}
val = buf;
val_len = cac_read_binary(card, 0, val, sizeof(buf), 0);
if (val_len > 0) {
priv->cac_id = malloc(20);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
#ifdef ENABLE_OPENSSL
SHA1(val, val_len, priv->cac_id);
priv->cac_id_len = 20;
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"cuid", priv->cac_id, priv->cac_id_len);
#else
sc_log(card->ctx, "OpenSSL Required");
return SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
}
return SC_SUCCESS;
}
static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv)
{
int r;
u8 *val = NULL;
size_t val_len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Assuming ACA is already selected */
r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_ACA_service(card, priv, val, val_len);
if (r == SC_SUCCESS) {
priv->aca_path = malloc(sizeof(sc_path_t));
if (!priv->aca_path) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t));
}
done:
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Look for a CAC card. If it exists, initialize our data structures
*/
static int cac_find_and_initialize(sc_card_t *card, int initialize)
{
int r, index;
cac_private_data_t *priv = NULL;
/* already initialized? */
if (card->drv_data) {
return SC_SUCCESS;
}
/* is this a CAC-2 specified in NIST Interagency Report 6887 -
* "Government Smart Card Interoperability Specification v2.1 July 2003" */
r = cac_select_CCC(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2");
if (!initialize) /* match card only */
return r;
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
r = cac_process_CCC(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* Even some ALT tokens can be missing CCC so we should try with ACA */
r = cac_select_ACA(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
r = cac_process_ACA(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* is this a CAC Alt token without any accompanying structures */
r = cac_find_first_pki_applet(card, &index);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
card->drv_data = priv; /* needed for the read_binary() */
r = cac_populate_cac_alt(card, index, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
return r;
}
card->drv_data = NULL; /* reset on failure */
}
if (priv) {
cac_free_private_data(priv);
}
return r;
}
/* NOTE: returns a bool, 1 card matches, 0 it does not */
static int cac_match_card(sc_card_t *card)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
r = cac_find_and_initialize(card, 0);
return (r == SC_SUCCESS); /* never match */
}
static int cac_init(sc_card_t *card)
{
int r;
unsigned long flags;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_find_and_initialize(card, 1);
if (r < 0) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD);
}
flags = SC_ALGORITHM_RSA_RAW;
_sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
_sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
_sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
/* CAC, like PIV needs Extra validation of (new) PIN during
* a PIN change request, to ensure it's not outside the
* FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2
* (6 character minimum) requirements.
*/
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (data->cmd == SC_PIN_CMD_CHANGE) {
int i = 0;
if (data->pin2.len < 6) {
return SC_ERROR_INVALID_PIN_LENGTH;
}
for(i=0; i < data->pin2.len; ++i) {
if (!isdigit(data->pin2.data[i])) {
return SC_ERROR_INVALID_DATA;
}
}
}
return iso_drv->ops->pin_cmd(card, data, tries_left);
}
static struct sc_card_operations cac_ops;
static struct sc_card_driver cac_drv = {
"Common Access Card (CAC)",
"cac",
&cac_ops,
NULL, 0, NULL
};
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
cac_ops = *iso_drv->ops;
cac_ops.match_card = cac_match_card;
cac_ops.init = cac_init;
cac_ops.finish = cac_finish;
cac_ops.select_file = cac_select_file; /* need to record object type */
cac_ops.get_challenge = cac_get_challenge;
cac_ops.read_binary = cac_read_binary;
cac_ops.write_binary = cac_write_binary;
cac_ops.set_security_env = cac_set_security_env;
cac_ops.restore_security_env = cac_restore_security_env;
cac_ops.compute_signature = cac_compute_signature;
cac_ops.decipher = cac_decipher;
cac_ops.card_ctl = cac_card_ctl;
cac_ops.pin_cmd = cac_pin_cmd;
return &cac_drv;
}
struct sc_card_driver * sc_get_cac_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_344_0 |
crossvul-cpp_data_good_2397_0 | /*****************************************************************************
* rtpfmt.c: RTP payload formats
*****************************************************************************
* Copyright (C) 2003-2004 VLC authors and VideoLAN
* Copyright © 2007 Rémi Denis-Courmont
* $Id$
*
* Authors: Laurent Aimar <fenrir@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_sout.h>
#include <vlc_block.h>
#include <vlc_strings.h>
#include "rtp.h"
#include "../demux/xiph.h"
#include <assert.h>
static int rtp_packetize_mpa (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_mpv (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_ac3 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_simple(sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_split(sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_pcm(sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_swab (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_mp4a (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_mp4a_latm (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_h263 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_h264 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_amr (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_spx (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_t140 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_g726_16 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_g726_24 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_g726_32 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_g726_40 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_xiph (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_vp8 (sout_stream_id_sys_t *, block_t *);
static int rtp_packetize_jpeg (sout_stream_id_sys_t *, block_t *);
#define XIPH_IDENT (0)
/* Helpers common to xiph codecs (vorbis and theora) */
static int rtp_xiph_pack_headers(size_t room, void *p_extra, size_t i_extra,
uint8_t **p_buffer, size_t *i_buffer,
uint8_t *theora_pixel_fmt)
{
unsigned packet_size[XIPH_MAX_HEADER_COUNT];
void *packet[XIPH_MAX_HEADER_COUNT];
unsigned packet_count;
if (xiph_SplitHeaders(packet_size, packet, &packet_count,
i_extra, p_extra))
return VLC_EGENERIC;;
if (packet_count < 3)
return VLC_EGENERIC;;
if (theora_pixel_fmt != NULL)
{
if (packet_size[0] < 42)
return VLC_EGENERIC;
*theora_pixel_fmt = (((uint8_t *)packet[0])[41] >> 3) & 0x03;
}
unsigned length_size[2] = { 0, 0 };
for (int i = 0; i < 2; i++)
{
unsigned size = packet_size[i];
while (size > 0)
{
length_size[i]++;
size >>= 7;
}
}
*i_buffer = room + 1 + length_size[0] + length_size[1]
+ packet_size[0] + packet_size[1] + packet_size[2];
*p_buffer = malloc(*i_buffer);
if (*p_buffer == NULL)
return VLC_ENOMEM;
uint8_t *p = *p_buffer + room;
/* Number of headers */
*p++ = 2;
for (int i = 0; i < 2; i++)
{
unsigned size = length_size[i];
while (size > 0)
{
*p = (packet_size[i] >> (7 * (size - 1))) & 0x7f;
if (--size > 0)
*p |= 0x80;
p++;
}
}
for (int i = 0; i < 3; i++)
{
memcpy(p, packet[i], packet_size[i]);
p += packet_size[i];
}
return VLC_SUCCESS;
}
static char *rtp_xiph_b64_oob_config(void *p_extra, size_t i_extra,
uint8_t *theora_pixel_fmt)
{
uint8_t *p_buffer;
size_t i_buffer;
if (rtp_xiph_pack_headers(9, p_extra, i_extra, &p_buffer, &i_buffer,
theora_pixel_fmt) != VLC_SUCCESS)
return NULL;
/* Number of packed headers */
SetDWBE(p_buffer, 1);
/* Ident */
uint32_t ident = XIPH_IDENT;
SetWBE(p_buffer + 4, ident >> 8);
p_buffer[6] = ident & 0xff;
/* Length field */
SetWBE(p_buffer + 7, i_buffer);
char *config = vlc_b64_encode_binary(p_buffer, i_buffer);
free(p_buffer);
return config;
}
static void sprintf_hexa( char *s, uint8_t *p_data, int i_data )
{
static const char hex[16] = "0123456789abcdef";
for( int i = 0; i < i_data; i++ )
{
s[2*i+0] = hex[(p_data[i]>>4)&0xf];
s[2*i+1] = hex[(p_data[i] )&0xf];
}
s[2*i_data] = '\0';
}
/* TODO: make this into something more clever than a big switch? */
int rtp_get_fmt( vlc_object_t *obj, es_format_t *p_fmt, const char *mux,
rtp_format_t *rtp_fmt )
{
assert( p_fmt != NULL || mux != NULL );
/* Dynamic payload type. Payload types are scoped to the RTP
* session, and we put each ES in its own session, so no risk of
* conflict. */
rtp_fmt->payload_type = 96;
rtp_fmt->cat = mux != NULL ? VIDEO_ES : p_fmt->i_cat;
if( rtp_fmt->cat == AUDIO_ES )
{
rtp_fmt->clock_rate = p_fmt->audio.i_rate;
rtp_fmt->channels = p_fmt->audio.i_channels;
}
else
rtp_fmt->clock_rate = 90000; /* most common case for video */
/* Stream bitrate in kbps */
rtp_fmt->bitrate = p_fmt != NULL ? p_fmt->i_bitrate/1000 : 0;
rtp_fmt->fmtp = NULL;
if( mux != NULL )
{
if( strncmp( mux, "ts", 2 ) == 0 )
{
rtp_fmt->payload_type = 33;
rtp_fmt->ptname = "MP2T";
}
else
rtp_fmt->ptname = "MP2P";
return VLC_SUCCESS;
}
switch( p_fmt->i_codec )
{
case VLC_CODEC_MULAW:
if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 )
rtp_fmt->payload_type = 0;
rtp_fmt->ptname = "PCMU";
rtp_fmt->pf_packetize = rtp_packetize_pcm;
break;
case VLC_CODEC_ALAW:
if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 8000 )
rtp_fmt->payload_type = 8;
rtp_fmt->ptname = "PCMA";
rtp_fmt->pf_packetize = rtp_packetize_pcm;
break;
case VLC_CODEC_S16B:
case VLC_CODEC_S16L:
if( p_fmt->audio.i_channels == 1 && p_fmt->audio.i_rate == 44100 )
{
rtp_fmt->payload_type = 11;
}
else if( p_fmt->audio.i_channels == 2 &&
p_fmt->audio.i_rate == 44100 )
{
rtp_fmt->payload_type = 10;
}
rtp_fmt->ptname = "L16";
if( p_fmt->i_codec == VLC_CODEC_S16B )
rtp_fmt->pf_packetize = rtp_packetize_pcm;
else
rtp_fmt->pf_packetize = rtp_packetize_swab;
break;
case VLC_CODEC_U8:
rtp_fmt->ptname = "L8";
rtp_fmt->pf_packetize = rtp_packetize_pcm;
break;
case VLC_CODEC_S24B:
rtp_fmt->ptname = "L24";
rtp_fmt->pf_packetize = rtp_packetize_pcm;
break;
case VLC_CODEC_MPGA:
rtp_fmt->payload_type = 14;
rtp_fmt->ptname = "MPA";
rtp_fmt->clock_rate = 90000; /* not 44100 */
rtp_fmt->pf_packetize = rtp_packetize_mpa;
break;
case VLC_CODEC_MPGV:
rtp_fmt->payload_type = 32;
rtp_fmt->ptname = "MPV";
rtp_fmt->pf_packetize = rtp_packetize_mpv;
break;
case VLC_CODEC_ADPCM_G726:
switch( p_fmt->i_bitrate / 1000 )
{
case 16:
rtp_fmt->ptname = "G726-16";
rtp_fmt->pf_packetize = rtp_packetize_g726_16;
break;
case 24:
rtp_fmt->ptname = "G726-24";
rtp_fmt->pf_packetize = rtp_packetize_g726_24;
break;
case 32:
rtp_fmt->ptname = "G726-32";
rtp_fmt->pf_packetize = rtp_packetize_g726_32;
break;
case 40:
rtp_fmt->ptname = "G726-40";
rtp_fmt->pf_packetize = rtp_packetize_g726_40;
break;
default:
msg_Err( obj, "cannot add this stream (unsupported "
"G.726 bit rate: %u)", p_fmt->i_bitrate );
return VLC_EGENERIC;
}
break;
case VLC_CODEC_A52:
rtp_fmt->ptname = "ac3";
rtp_fmt->pf_packetize = rtp_packetize_ac3;
break;
case VLC_CODEC_H263:
rtp_fmt->ptname = "H263-1998";
rtp_fmt->pf_packetize = rtp_packetize_h263;
break;
case VLC_CODEC_H264:
rtp_fmt->ptname = "H264";
rtp_fmt->pf_packetize = rtp_packetize_h264;
rtp_fmt->fmtp = NULL;
if( p_fmt->i_extra > 0 )
{
uint8_t *p_buffer = p_fmt->p_extra;
int i_buffer = p_fmt->i_extra;
char *p_64_sps = NULL;
char *p_64_pps = NULL;
char hexa[6+1];
while( i_buffer > 4 )
{
int i_offset = 0;
int i_size = 0;
while( p_buffer[0] != 0 || p_buffer[1] != 0 ||
p_buffer[2] != 1 )
{
p_buffer++;
i_buffer--;
if( i_buffer == 0 ) break;
}
if( i_buffer < 4 || memcmp(p_buffer, "\x00\x00\x01", 3 ) )
{
msg_Dbg( obj, "No startcode found..");
break;
}
p_buffer += 3;
i_buffer -= 3;
const int i_nal_type = p_buffer[0]&0x1f;
msg_Dbg( obj, "we found a startcode for NAL with TYPE:%d", i_nal_type );
i_size = i_buffer;
for( i_offset = 0; i_offset+2 < i_buffer ; i_offset++)
{
if( !memcmp(p_buffer + i_offset, "\x00\x00\x01", 3 ) )
{
/* we found another startcode */
while( i_offset > 0 && 0 == p_buffer[ i_offset - 1 ] )
i_offset--;
i_size = i_offset;
break;
}
}
if( i_size == 0 )
{
msg_Dbg( obj, "No-info found in nal ");
continue;
}
if( i_nal_type == 7 )
{
free( p_64_sps );
p_64_sps = vlc_b64_encode_binary( p_buffer, i_size );
/* XXX: nothing ensures that i_size >= 4 ?? */
sprintf_hexa( hexa, &p_buffer[1], 3 );
}
else if( i_nal_type == 8 )
{
free( p_64_pps );
p_64_pps = vlc_b64_encode_binary( p_buffer, i_size );
}
i_buffer -= i_size;
p_buffer += i_size;
}
/* */
if( p_64_sps && p_64_pps &&
( asprintf( &rtp_fmt->fmtp,
"packetization-mode=1;profile-level-id=%s;"
"sprop-parameter-sets=%s,%s;", hexa, p_64_sps,
p_64_pps ) == -1 ) )
rtp_fmt->fmtp = NULL;
free( p_64_sps );
free( p_64_pps );
}
if( rtp_fmt->fmtp == NULL )
rtp_fmt->fmtp = strdup( "packetization-mode=1" );
break;
case VLC_CODEC_MP4V:
{
rtp_fmt->ptname = "MP4V-ES";
rtp_fmt->pf_packetize = rtp_packetize_split;
if( p_fmt->i_extra > 0 )
{
char hexa[2*p_fmt->i_extra +1];
sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
if( asprintf( &rtp_fmt->fmtp,
"profile-level-id=3; config=%s;", hexa ) == -1 )
rtp_fmt->fmtp = NULL;
}
break;
}
case VLC_CODEC_MP4A:
{
if( ! var_InheritBool( obj, "sout-rtp-mp4a-latm" ) )
{
char hexa[2*p_fmt->i_extra +1];
rtp_fmt->ptname = "mpeg4-generic";
rtp_fmt->pf_packetize = rtp_packetize_mp4a;
sprintf_hexa( hexa, p_fmt->p_extra, p_fmt->i_extra );
if( asprintf( &rtp_fmt->fmtp,
"streamtype=5; profile-level-id=15; "
"mode=AAC-hbr; config=%s; SizeLength=13; "
"IndexLength=3; IndexDeltaLength=3; Profile=1;",
hexa ) == -1 )
rtp_fmt->fmtp = NULL;
}
else
{
char hexa[13];
int i;
unsigned char config[6];
unsigned int aacsrates[15] = {
96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
16000, 12000, 11025, 8000, 7350, 0, 0 };
for( i = 0; i < 15; i++ )
if( p_fmt->audio.i_rate == aacsrates[i] )
break;
config[0]=0x40;
config[1]=0;
config[2]=0x20|i;
config[3]=p_fmt->audio.i_channels<<4;
config[4]=0x3f;
config[5]=0xc0;
rtp_fmt->ptname = "MP4A-LATM";
rtp_fmt->pf_packetize = rtp_packetize_mp4a_latm;
sprintf_hexa( hexa, config, 6 );
if( asprintf( &rtp_fmt->fmtp, "profile-level-id=15; "
"object=2; cpresent=0; config=%s", hexa ) == -1 )
rtp_fmt->fmtp = NULL;
}
break;
}
case VLC_CODEC_AMR_NB:
rtp_fmt->ptname = "AMR";
rtp_fmt->fmtp = strdup( "octet-align=1" );
rtp_fmt->pf_packetize = rtp_packetize_amr;
break;
case VLC_CODEC_AMR_WB:
rtp_fmt->ptname = "AMR-WB";
rtp_fmt->fmtp = strdup( "octet-align=1" );
rtp_fmt->pf_packetize = rtp_packetize_amr;
break;
case VLC_CODEC_SPEEX:
rtp_fmt->ptname = "SPEEX";
rtp_fmt->pf_packetize = rtp_packetize_spx;
break;
case VLC_CODEC_VORBIS:
rtp_fmt->ptname = "vorbis";
rtp_fmt->pf_packetize = rtp_packetize_xiph;
if( p_fmt->i_extra > 0 )
{
rtp_fmt->fmtp = NULL;
char *config = rtp_xiph_b64_oob_config(p_fmt->p_extra,
p_fmt->i_extra, NULL);
if (config == NULL)
break;
if( asprintf( &rtp_fmt->fmtp,
"configuration=%s;", config ) == -1 )
rtp_fmt->fmtp = NULL;
free(config);
}
break;
case VLC_CODEC_THEORA:
rtp_fmt->ptname = "theora";
rtp_fmt->pf_packetize = rtp_packetize_xiph;
if( p_fmt->i_extra > 0 )
{
rtp_fmt->fmtp = NULL;
uint8_t pixel_fmt, c1, c2;
char *config = rtp_xiph_b64_oob_config(p_fmt->p_extra,
p_fmt->i_extra,
&pixel_fmt);
if (config == NULL)
break;
if (pixel_fmt == 1)
{
/* reserved */
free(config);
break;
}
switch (pixel_fmt)
{
case 0:
c1 = 2;
c2 = 0;
break;
case 2:
c1 = c2 = 2;
break;
case 3:
c1 = c2 = 4;
break;
default:
assert(0);
}
if( asprintf( &rtp_fmt->fmtp,
"sampling=YCbCr-4:%d:%d; width=%d; height=%d; "
"delivery-method=inline; configuration=%s; "
"delivery-method=in_band;", c1, c2,
p_fmt->video.i_width, p_fmt->video.i_height,
config ) == -1 )
rtp_fmt->fmtp = NULL;
free(config);
}
break;
case VLC_CODEC_ITU_T140:
rtp_fmt->ptname = "t140" ;
rtp_fmt->clock_rate = 1000;
rtp_fmt->pf_packetize = rtp_packetize_t140;
break;
case VLC_CODEC_GSM:
rtp_fmt->payload_type = 3;
rtp_fmt->ptname = "GSM";
rtp_fmt->pf_packetize = rtp_packetize_split;
break;
case VLC_CODEC_OPUS:
if (p_fmt->audio.i_channels > 2)
{
msg_Err( obj, "Multistream opus not supported in RTP"
" (having %d channels input)",
p_fmt->audio.i_channels );
return VLC_EGENERIC;
}
rtp_fmt->ptname = "opus";
rtp_fmt->pf_packetize = rtp_packetize_simple;
rtp_fmt->clock_rate = 48000;
rtp_fmt->channels = 2;
if (p_fmt->audio.i_channels == 2)
rtp_fmt->fmtp = strdup( "sprop-stereo=1" );
break;
case VLC_CODEC_VP8:
rtp_fmt->ptname = "VP8";
rtp_fmt->pf_packetize = rtp_packetize_vp8;
break;
case VLC_CODEC_MJPG:
case VLC_CODEC_JPEG:
rtp_fmt->ptname = "JPEG";
rtp_fmt->payload_type = 26;
rtp_fmt->pf_packetize = rtp_packetize_jpeg;
break;
default:
msg_Err( obj, "cannot add this stream (unsupported "
"codec: %4.4s)", (char*)&p_fmt->i_codec );
return VLC_EGENERIC;
}
return VLC_SUCCESS;
}
static int
rtp_packetize_h264_nal( sout_stream_id_sys_t *id,
const uint8_t *p_data, int i_data, int64_t i_pts,
int64_t i_dts, bool b_last, int64_t i_length );
int rtp_packetize_xiph_config( sout_stream_id_sys_t *id, const char *fmtp,
int64_t i_pts )
{
if (fmtp == NULL)
return VLC_EGENERIC;
/* extract base64 configuration from fmtp */
char *start = strstr(fmtp, "configuration=");
assert(start != NULL);
start += sizeof("configuration=") - 1;
char *end = strchr(start, ';');
assert(end != NULL);
size_t len = end - start;
char *b64 = malloc(len + 1);
if(!b64)
return VLC_EGENERIC;
memcpy(b64, start, len);
b64[len] = '\0';
int i_max = rtp_mtu (id) - 6; /* payload max in one packet */
uint8_t *p_orig, *p_data;
int i_data;
i_data = vlc_b64_decode_binary(&p_orig, b64);
free(b64);
if (i_data <= 9)
{
free(p_orig);
return VLC_EGENERIC;
}
p_data = p_orig + 9;
i_data -= 9;
int i_count = ( i_data + i_max - 1 ) / i_max;
for( int i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 18 + i_payload );
unsigned fragtype, numpkts;
if (i_count == 1)
{
fragtype = 0;
numpkts = 1;
}
else
{
numpkts = 0;
if (i == 0)
fragtype = 1;
else if (i == i_count - 1)
fragtype = 3;
else
fragtype = 2;
}
/* Ident:24, Fragment type:2, Vorbis/Theora Data Type:2, # of pkts:4 */
uint32_t header = ((XIPH_IDENT & 0xffffff) << 8) |
(fragtype << 6) | (1 << 4) | numpkts;
/* rtp common header */
rtp_packetize_common( id, out, 0, i_pts );
SetDWBE( out->p_buffer + 12, header);
SetWBE( out->p_buffer + 16, i_payload);
memcpy( &out->p_buffer[18], p_data, i_payload );
out->i_dts = i_pts;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
free(p_orig);
return VLC_SUCCESS;
}
/* rfc5215 */
static int rtp_packetize_xiph( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 6; /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
for( int i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 18 + i_payload );
unsigned fragtype, numpkts;
if (i_count == 1)
{
/* No fragmentation */
fragtype = 0;
numpkts = 1;
}
else
{
/* Fragmentation */
numpkts = 0;
if (i == 0)
fragtype = 1;
else if (i == i_count - 1)
fragtype = 3;
else
fragtype = 2;
}
/* Ident:24, Fragment type:2, Vorbis/Theora Data Type:2, # of pkts:4 */
uint32_t header = ((XIPH_IDENT & 0xffffff) << 8) |
(fragtype << 6) | (0 << 4) | numpkts;
/* rtp common header */
rtp_packetize_common( id, out, 0, in->i_pts);
SetDWBE( out->p_buffer + 12, header);
SetWBE( out->p_buffer + 16, i_payload);
memcpy( &out->p_buffer[18], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_mpa( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 4; /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 16 + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
/* mbz set to 0 */
SetWBE( out->p_buffer + 12, 0 );
/* fragment offset in the current frame */
SetWBE( out->p_buffer + 14, i * i_max );
memcpy( &out->p_buffer[16], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
/* rfc2250 */
static int rtp_packetize_mpv( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 4; /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
int b_sequence_start = 0;
int i_temporal_ref = 0;
int i_picture_coding_type = 0;
int i_fbv = 0, i_bfc = 0, i_ffv = 0, i_ffc = 0;
int b_start_slice = 0;
/* preparse this packet to get some info */
if( in->i_buffer > 4 )
{
uint8_t *p = p_data;
int i_rest = in->i_buffer;
for( ;; )
{
while( i_rest > 4 &&
( p[0] != 0x00 || p[1] != 0x00 || p[2] != 0x01 ) )
{
p++;
i_rest--;
}
if( i_rest <= 4 )
{
break;
}
p += 3;
i_rest -= 4;
if( *p == 0xb3 )
{
/* sequence start code */
b_sequence_start = 1;
}
else if( *p == 0x00 && i_rest >= 4 )
{
/* picture */
i_temporal_ref = ( p[1] << 2) |((p[2]>>6)&0x03);
i_picture_coding_type = (p[2] >> 3)&0x07;
if( i_rest >= 4 && ( i_picture_coding_type == 2 ||
i_picture_coding_type == 3 ) )
{
i_ffv = (p[3] >> 2)&0x01;
i_ffc = ((p[3]&0x03) << 1)|((p[4]>>7)&0x01);
if( i_rest > 4 && i_picture_coding_type == 3 )
{
i_fbv = (p[4]>>6)&0x01;
i_bfc = (p[4]>>3)&0x07;
}
}
}
else if( *p <= 0xaf )
{
b_start_slice = 1;
}
}
}
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 16 + i_payload );
/* MBZ:5 T:1 TR:10 AN:1 N:1 S:1 B:1 E:1 P:3 FBV:1 BFC:3 FFV:1 FFC:3 */
uint32_t h = ( i_temporal_ref << 16 )|
( b_sequence_start << 13 )|
( b_start_slice << 12 )|
( i == i_count - 1 ? 1 << 11 : 0 )|
( i_picture_coding_type << 8 )|
( i_fbv << 7 )|( i_bfc << 4 )|( i_ffv << 3 )|i_ffc;
/* rtp common header */
rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts );
SetDWBE( out->p_buffer + 12, h );
memcpy( &out->p_buffer[16], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_ac3( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 2; /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 14 + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, (i == i_count - 1)?1:0, in->i_pts );
/* unit count */
out->p_buffer[12] = 1;
/* unit header */
out->p_buffer[13] = 0x00;
/* data */
memcpy( &out->p_buffer[14], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_simple(sout_stream_id_sys_t *id, block_t *block)
{
bool marker = (block->i_flags & BLOCK_FLAG_DISCONTINUITY) != 0;
block = block_Realloc(block, 12, block->i_buffer);
if (unlikely(block == NULL))
return VLC_ENOMEM;
rtp_packetize_common(id, block, marker, block->i_pts);
rtp_packetize_send(id, block);
return VLC_SUCCESS;
}
static int rtp_packetize_split( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id); /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 12 + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, (i == i_count - 1),
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
memcpy( &out->p_buffer[12], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_pcm(sout_stream_id_sys_t *id, block_t *in)
{
unsigned max = rtp_mtu(id);
while (in->i_buffer > max)
{
unsigned duration = (in->i_length * max) / in->i_buffer;
bool marker = (in->i_flags & BLOCK_FLAG_DISCONTINUITY) != 0;
block_t *out = block_Alloc(12 + max);
if (unlikely(out == NULL))
{
block_Release(in);
return VLC_ENOMEM;
}
rtp_packetize_common(id, out, marker, in->i_pts);
memcpy(out->p_buffer + 12, in->p_buffer, max);
rtp_packetize_send(id, out);
in->p_buffer += max;
in->i_buffer -= max;
in->i_pts += duration;
in->i_length -= duration;
in->i_flags &= ~BLOCK_FLAG_DISCONTINUITY;
}
return rtp_packetize_simple(id, in); /* zero copy for the last frame */
}
/* split and convert from little endian to network byte order */
static int rtp_packetize_swab(sout_stream_id_sys_t *id, block_t *in)
{
unsigned max = rtp_mtu(id);
while (in->i_buffer > 0)
{
unsigned payload = (max < in->i_buffer) ? max : in->i_buffer;
unsigned duration = (in->i_length * payload) / in->i_buffer;
bool marker = (in->i_flags & BLOCK_FLAG_DISCONTINUITY) != 0;
block_t *out = block_Alloc(12 + payload);
if (unlikely(out == NULL))
{
block_Release(in);
return VLC_ENOMEM;
}
rtp_packetize_common(id, out, marker, in->i_pts);
swab(in->p_buffer, out->p_buffer + 12, payload);
rtp_packetize_send(id, out);
in->p_buffer += payload;
in->i_buffer -= payload;
in->i_pts += duration;
in->i_length -= duration;
in->i_flags &= ~BLOCK_FLAG_DISCONTINUITY;
}
block_Release(in);
return VLC_SUCCESS;
}
/* rfc3016 */
static int rtp_packetize_mp4a_latm( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 2; /* payload max in one packet */
int latmhdrsize = in->i_buffer / 0xff + 1;
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer, *p_header = NULL;
int i_data = in->i_buffer;
int i;
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out;
if( i != 0 )
latmhdrsize = 0;
out = block_Alloc( 12 + latmhdrsize + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, ((i == i_count - 1) ? 1 : 0),
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
if( i == 0 )
{
int tmp = in->i_buffer;
p_header=out->p_buffer+12;
while( tmp > 0xfe )
{
*p_header = 0xff;
p_header++;
tmp -= 0xff;
}
*p_header = tmp;
}
memcpy( &out->p_buffer[12+latmhdrsize], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_mp4a( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 4; /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 16 + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
/* AU headers */
/* AU headers length (bits) */
out->p_buffer[12] = 0;
out->p_buffer[13] = 2*8;
/* for each AU length 13 bits + idx 3bits, */
SetWBE( out->p_buffer + 14, (in->i_buffer << 3) | 0 );
memcpy( &out->p_buffer[16], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
/* rfc2429 */
#define RTP_H263_HEADER_SIZE (2) // plen = 0
#define RTP_H263_PAYLOAD_START (14) // plen = 0
static int rtp_packetize_h263( sout_stream_id_sys_t *id, block_t *in )
{
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
int i_max = rtp_mtu (id) - RTP_H263_HEADER_SIZE; /* payload max in one packet */
int i_count;
int b_p_bit;
int b_v_bit = 0; // no pesky error resilience
int i_plen = 0; // normally plen=0 for PSC packet
int i_pebit = 0; // because plen=0
uint16_t h;
if( i_data < 2 )
{
block_Release(in);
return VLC_EGENERIC;
}
if( p_data[0] || p_data[1] )
{
block_Release(in);
return VLC_EGENERIC;
}
/* remove 2 leading 0 bytes */
p_data += 2;
i_data -= 2;
i_count = ( i_data + i_max - 1 ) / i_max;
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( RTP_H263_PAYLOAD_START + i_payload );
b_p_bit = (i == 0) ? 1 : 0;
h = ( b_p_bit << 10 )|
( b_v_bit << 9 )|
( i_plen << 3 )|
i_pebit;
/* rtp common header */
//b_m_bit = 1; // always contains end of frame
rtp_packetize_common( id, out, (i == i_count - 1)?1:0,
in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts );
/* h263 header */
SetWBE( out->p_buffer + 12, h );
memcpy( &out->p_buffer[RTP_H263_PAYLOAD_START], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
/* rfc3984 */
static int
rtp_packetize_h264_nal( sout_stream_id_sys_t *id,
const uint8_t *p_data, int i_data, int64_t i_pts,
int64_t i_dts, bool b_last, int64_t i_length )
{
const int i_max = rtp_mtu (id); /* payload max in one packet */
int i_nal_hdr;
int i_nal_type;
if( i_data < 5 )
return VLC_SUCCESS;
i_nal_hdr = p_data[3];
i_nal_type = i_nal_hdr&0x1f;
/* Skip start code */
p_data += 3;
i_data -= 3;
/* */
if( i_data <= i_max )
{
/* Single NAL unit packet */
block_t *out = block_Alloc( 12 + i_data );
out->i_dts = i_dts;
out->i_length = i_length;
/* */
rtp_packetize_common( id, out, b_last, i_pts );
memcpy( &out->p_buffer[12], p_data, i_data );
rtp_packetize_send( id, out );
}
else
{
/* FU-A Fragmentation Unit without interleaving */
const int i_count = ( i_data-1 + i_max-2 - 1 ) / (i_max-2);
int i;
p_data++;
i_data--;
for( i = 0; i < i_count; i++ )
{
const int i_payload = __MIN( i_data, i_max-2 );
block_t *out = block_Alloc( 12 + 2 + i_payload );
out->i_dts = i_dts + i * i_length / i_count;
out->i_length = i_length / i_count;
/* */
rtp_packetize_common( id, out, (b_last && i_payload == i_data),
i_pts );
/* FU indicator */
out->p_buffer[12] = 0x00 | (i_nal_hdr & 0x60) | 28;
/* FU header */
out->p_buffer[13] = ( i == 0 ? 0x80 : 0x00 ) | ( (i == i_count-1) ? 0x40 : 0x00 ) | i_nal_type;
memcpy( &out->p_buffer[14], p_data, i_payload );
rtp_packetize_send( id, out );
i_data -= i_payload;
p_data += i_payload;
}
}
return VLC_SUCCESS;
}
static int rtp_packetize_h264( sout_stream_id_sys_t *id, block_t *in )
{
const uint8_t *p_buffer = in->p_buffer;
int i_buffer = in->i_buffer;
while( i_buffer > 4 && ( p_buffer[0] != 0 || p_buffer[1] != 0 || p_buffer[2] != 1 ) )
{
i_buffer--;
p_buffer++;
}
/* Split nal units */
while( i_buffer > 4 )
{
int i_offset;
int i_size = i_buffer;
int i_skip = i_buffer;
/* search nal end */
for( i_offset = 4; i_offset+2 < i_buffer ; i_offset++)
{
if( p_buffer[i_offset] == 0 && p_buffer[i_offset+1] == 0 && p_buffer[i_offset+2] == 1 )
{
/* we found another startcode */
i_size = i_offset - ( p_buffer[i_offset-1] == 0 ? 1 : 0);
i_skip = i_offset;
break;
}
}
/* TODO add STAP-A to remove a lot of overhead with small slice/sei/... */
rtp_packetize_h264_nal( id, p_buffer, i_size,
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts), in->i_dts,
(i_size >= i_buffer), in->i_length * i_size / in->i_buffer );
i_buffer -= i_skip;
p_buffer += i_skip;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_amr( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - 2; /* payload max in one packet */
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i;
/* Only supports octet-aligned mode */
for( i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 14 + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, ((i == i_count - 1)?1:0),
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
/* Payload header */
out->p_buffer[12] = 0xF0; /* CMR */
out->p_buffer[13] = p_data[0]&0x7C; /* ToC */ /* FIXME: frame type */
/* FIXME: are we fed multiple frames ? */
memcpy( &out->p_buffer[14], p_data+1, i_payload-1 );
out->i_buffer--; /* FIXME? */
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_t140( sout_stream_id_sys_t *id, block_t *in )
{
const size_t i_max = rtp_mtu (id);
const uint8_t *p_data = in->p_buffer;
size_t i_data = in->i_buffer;
for( unsigned i_packet = 0; i_data > 0; i_packet++ )
{
size_t i_payload = i_data;
/* Make sure we stop on an UTF-8 character boundary
* (assuming the input is valid UTF-8) */
if( i_data > i_max )
{
i_payload = i_max;
while( ( p_data[i_payload] & 0xC0 ) == 0x80 )
{
if( i_payload == 0 )
{
block_Release(in);
return VLC_SUCCESS; /* fishy input! */
}
i_payload--;
}
}
block_t *out = block_Alloc( 12 + i_payload );
if( out == NULL )
{
block_Release(in);
return VLC_SUCCESS;
}
rtp_packetize_common( id, out, 0, in->i_pts + i_packet );
memcpy( out->p_buffer + 12, p_data, i_payload );
out->i_dts = in->i_pts;
out->i_length = 0;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_spx( sout_stream_id_sys_t *id, block_t *in )
{
uint8_t *p_buffer = in->p_buffer;
int i_data_size, i_payload_size, i_payload_padding;
i_data_size = i_payload_size = in->i_buffer;
i_payload_padding = 0;
block_t *p_out;
if ( in->i_buffer > rtp_mtu (id) )
{
block_Release(in);
return VLC_SUCCESS;
}
/*
RFC for Speex in RTP says that each packet must end on an octet
boundary. So, we check to see if the number of bytes % 4 is zero.
If not, we have to add some padding.
This MAY be overkill since packetization is handled elsewhere and
appears to ensure the octet boundary. However, better safe than
sorry.
*/
if ( i_payload_size % 4 )
{
i_payload_padding = 4 - ( i_payload_size % 4 );
i_payload_size += i_payload_padding;
}
/*
Allocate a new RTP p_output block of the appropriate size.
Allow for 12 extra bytes of RTP header.
*/
p_out = block_Alloc( 12 + i_payload_size );
if ( i_payload_padding )
{
/*
The padding is required to be a zero followed by all 1s.
*/
char c_first_pad, c_remaining_pad;
c_first_pad = 0x7F;
c_remaining_pad = 0xFF;
/*
Allow for 12 bytes before the i_data_size because
of the expected RTP header added during
rtp_packetize_common.
*/
p_out->p_buffer[12 + i_data_size] = c_first_pad;
switch (i_payload_padding)
{
case 2:
p_out->p_buffer[12 + i_data_size + 1] = c_remaining_pad;
break;
case 3:
p_out->p_buffer[12 + i_data_size + 1] = c_remaining_pad;
p_out->p_buffer[12 + i_data_size + 2] = c_remaining_pad;
break;
}
}
/* Add the RTP header to our p_output buffer. */
rtp_packetize_common( id, p_out, 0,
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
/* Copy the Speex payload to the p_output buffer */
memcpy( &p_out->p_buffer[12], p_buffer, i_data_size );
p_out->i_dts = in->i_dts;
p_out->i_length = in->i_length;
block_Release(in);
/* Queue the buffer for actual transmission. */
rtp_packetize_send( id, p_out );
return VLC_SUCCESS;
}
static int rtp_packetize_g726( sout_stream_id_sys_t *id, block_t *in, int i_pad )
{
int i_max = (rtp_mtu( id )- 12 + i_pad - 1) & ~i_pad;
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
int i_packet = 0;
while( i_data > 0 )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( 12 + i_payload );
/* rtp common header */
rtp_packetize_common( id, out, 0,
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
memcpy( &out->p_buffer[12], p_data, i_payload );
out->i_dts = in->i_dts + i_packet++ * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_g726_16( sout_stream_id_sys_t *id, block_t *in )
{
return rtp_packetize_g726( id, in, 4 );
}
static int rtp_packetize_g726_24( sout_stream_id_sys_t *id, block_t *in )
{
return rtp_packetize_g726( id, in, 8 );
}
static int rtp_packetize_g726_32( sout_stream_id_sys_t *id, block_t *in )
{
return rtp_packetize_g726( id, in, 2 );
}
static int rtp_packetize_g726_40( sout_stream_id_sys_t *id, block_t *in )
{
return rtp_packetize_g726( id, in, 8 );
}
#define RTP_VP8_HEADER_SIZE 1
#define RTP_VP8_PAYLOAD_START (12 + RTP_VP8_HEADER_SIZE)
static int rtp_packetize_vp8( sout_stream_id_sys_t *id, block_t *in )
{
int i_max = rtp_mtu (id) - RTP_VP8_HEADER_SIZE;
int i_count = ( in->i_buffer + i_max - 1 ) / i_max;
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
if ( i_max <= 0 )
{
block_Release(in);
return VLC_EGENERIC;
}
for( int i = 0; i < i_count; i++ )
{
int i_payload = __MIN( i_max, i_data );
block_t *out = block_Alloc( RTP_VP8_PAYLOAD_START + i_payload );
if ( out == NULL )
{
block_Release(in);
return VLC_ENOMEM;
}
/* VP8 payload header */
/* All frames are marked as reference ones */
if (i == 0)
out->p_buffer[12] = 0x10; // partition start
else
out->p_buffer[12] = 0;
/* rtp common header */
rtp_packetize_common( id, out, (i == i_count - 1),
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
memcpy( &out->p_buffer[RTP_VP8_PAYLOAD_START], p_data, i_payload );
out->i_dts = in->i_dts + i * in->i_length / i_count;
out->i_length = in->i_length / i_count;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
}
block_Release(in);
return VLC_SUCCESS;
}
static int rtp_packetize_jpeg( sout_stream_id_sys_t *id, block_t *in )
{
uint8_t *p_data = in->p_buffer;
int i_data = in->i_buffer;
uint8_t *bufend = p_data + i_data;
const uint8_t *qtables = NULL;
int nb_qtables = 0;
int off = 0; // fragment offset in frame
int y_sampling_factor;
// type is set by pixel format (determined by y_sampling_factor):
// 0 for yuvj422p
// 1 for yuvj420p
// += 64 if DRI present
int type;
int w = 0; // Width in multiples of 8
int h = 0; // Height in multiples of 8
int restart_interval;
int dri_found = 0;
// Skip SOI
if (GetWBE(p_data) != 0xffd8)
goto error;
p_data += 2;
i_data -= 2;
/* parse the header to get necessary info */
int header_finished = 0;
while (!header_finished && p_data + 4 <= bufend) {
uint16_t marker = GetWBE(p_data);
uint8_t *section = p_data + 2;
int section_size = GetWBE(section);
uint8_t *section_body = p_data + 4;
if (section + section_size > bufend)
goto error;
assert((marker & 0xff00) == 0xff00);
switch (marker)
{
case 0xffdb /*DQT*/:
if (section_body[0])
goto error; // Only 8-bit precision is supported
/* a quantization table is 64 bytes long */
nb_qtables = section_size / 65;
qtables = section_body;
break;
case 0xffc0 /*SOF0*/:
{
int height = GetWBE(§ion_body[1]);
int width = GetWBE(§ion_body[3]);
if (width > 2040 || height > 2040)
{
// larger than limit supported by RFC 2435
goto error;
}
// Round up by 8, divide by 8
w = ((width+7)&~7) >> 3;
h = ((height+7)&~7) >> 3;
// Get components sampling to determine type
// Y has component ID 1
// Possible configurations of sampling factors:
// Y - 0x22, Cb - 0x11, Cr - 0x11 => yuvj420p
// Y - 0x21, Cb - 0x11, Cr - 0x11 => yuvj422p
// Only 3 components are supported by RFC 2435
if (section_body[5] != 3) // Number of components
goto error;
for (int j = 0; j < 3; j++)
{
if (section_body[6 + j * 3] == 1 /* Y */)
{
y_sampling_factor = section_body[6 + j * 3 + 1];
}
else if (section_body[6 + j * 3 + 1] != 0x11)
{
// Sampling factor is unsupported by RFC 2435
goto error;
}
}
break;
}
case 0xffdd /*DRI*/:
restart_interval = GetWBE(section_body);
dri_found = 1;
break;
case 0xffda /*SOS*/:
/* SOS is last marker in the header */
header_finished = 1;
break;
}
// Step over marker, 16bit length and section body
p_data += 2 + section_size;
i_data -= 2 + section_size;
}
if (!header_finished)
goto error;
if (!w || !h)
goto error;
switch (y_sampling_factor)
{
case 0x22: // yuvj420p
type = 1;
break;
case 0x21: // yuvj422p
type = 0;
break;
default:
goto error; // Sampling format unsupported by RFC 2435
}
if (dri_found)
type += 64;
while ( i_data )
{
int hdr_size = 8 + dri_found * 4;
if (off == 0 && nb_qtables)
hdr_size += 4 + 64 * nb_qtables;
int i_payload = __MIN( i_data, (int)(rtp_mtu (id) - hdr_size) );
if ( i_payload <= 0 )
return VLC_EGENERIC;
block_t *out = block_Alloc( 12 + hdr_size + i_payload );
if( out == NULL )
return VLC_ENOMEM;
uint8_t *p = out->p_buffer + 12;
/* set main header */
/* set type-specific=0, set offset in following 24 bits: */
SetDWBE(p, off & 0x00ffffff);
p += 4;
*p++ = type;
*p++ = 255; // Quant value
*p++ = w;
*p++ = h;
// Write restart_marker_hdr if needed
if (dri_found)
{
SetWBE(p, restart_interval);
p += 2;
// restart_count. Hardcoded same value as in gstreamer implementation
SetWBE(p, 0xffff);
p += 2;
}
if (off == 0 && nb_qtables)
{
/* set quantization tables header */
*p++ = 0;
*p++ = 0;
SetWBE (p, 64 * nb_qtables);
p += 2;
for (int i = 0; i < nb_qtables; i++)
{
memcpy (p, &qtables[65 * i + 1], 64);
p += 64;
}
}
/* rtp common header */
rtp_packetize_common( id, out, (i_payload == i_data),
(in->i_pts > VLC_TS_INVALID ? in->i_pts : in->i_dts) );
memcpy( p, p_data, i_payload );
out->i_dts = in->i_dts;
out->i_length = in->i_length;
rtp_packetize_send( id, out );
p_data += i_payload;
i_data -= i_payload;
off += i_payload;
}
block_Release(in);
return VLC_SUCCESS;
error:
block_Release(in);
return VLC_EGENERIC;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2397_0 |
crossvul-cpp_data_bad_5079_2 | /*
* Packet matching code.
*
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
* Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
* Copyright (c) 2006-2010 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/capability.h>
#include <linux/in.h>
#include <linux/skbuff.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/poison.h>
#include <linux/icmpv6.h>
#include <net/ipv6.h>
#include <net/compat.h>
#include <asm/uaccess.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/err.h>
#include <linux/cpumask.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter/x_tables.h>
#include <net/netfilter/nf_log.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
MODULE_DESCRIPTION("IPv6 packet filter");
/*#define DEBUG_IP_FIREWALL*/
/*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */
/*#define DEBUG_IP_FIREWALL_USER*/
#ifdef DEBUG_IP_FIREWALL
#define dprintf(format, args...) pr_info(format , ## args)
#else
#define dprintf(format, args...)
#endif
#ifdef DEBUG_IP_FIREWALL_USER
#define duprintf(format, args...) pr_info(format , ## args)
#else
#define duprintf(format, args...)
#endif
#ifdef CONFIG_NETFILTER_DEBUG
#define IP_NF_ASSERT(x) WARN_ON(!(x))
#else
#define IP_NF_ASSERT(x)
#endif
#if 0
/* All the better to debug you with... */
#define static
#define inline
#endif
void *ip6t_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(ip6t, IP6T);
}
EXPORT_SYMBOL_GPL(ip6t_alloc_initial_table);
/*
We keep a set of rules for each CPU, so we can avoid write-locking
them in the softirq when updating the counters and therefore
only need to read-lock in the softirq; doing a write_lock_bh() in user
context stops packets coming through and allows user context to read
the counters or update the rules.
Hence the start of any table is given by get_table() below. */
/* Returns whether matches rule or not. */
/* Performance critical - called for every packet */
static inline bool
ip6_packet_match(const struct sk_buff *skb,
const char *indev,
const char *outdev,
const struct ip6t_ip6 *ip6info,
unsigned int *protoff,
int *fragoff, bool *hotdrop)
{
unsigned long ret;
const struct ipv6hdr *ipv6 = ipv6_hdr(skb);
#define FWINV(bool, invflg) ((bool) ^ !!(ip6info->invflags & (invflg)))
if (FWINV(ipv6_masked_addr_cmp(&ipv6->saddr, &ip6info->smsk,
&ip6info->src), IP6T_INV_SRCIP) ||
FWINV(ipv6_masked_addr_cmp(&ipv6->daddr, &ip6info->dmsk,
&ip6info->dst), IP6T_INV_DSTIP)) {
dprintf("Source or dest mismatch.\n");
/*
dprintf("SRC: %u. Mask: %u. Target: %u.%s\n", ip->saddr,
ipinfo->smsk.s_addr, ipinfo->src.s_addr,
ipinfo->invflags & IP6T_INV_SRCIP ? " (INV)" : "");
dprintf("DST: %u. Mask: %u. Target: %u.%s\n", ip->daddr,
ipinfo->dmsk.s_addr, ipinfo->dst.s_addr,
ipinfo->invflags & IP6T_INV_DSTIP ? " (INV)" : "");*/
return false;
}
ret = ifname_compare_aligned(indev, ip6info->iniface, ip6info->iniface_mask);
if (FWINV(ret != 0, IP6T_INV_VIA_IN)) {
dprintf("VIA in mismatch (%s vs %s).%s\n",
indev, ip6info->iniface,
ip6info->invflags & IP6T_INV_VIA_IN ? " (INV)" : "");
return false;
}
ret = ifname_compare_aligned(outdev, ip6info->outiface, ip6info->outiface_mask);
if (FWINV(ret != 0, IP6T_INV_VIA_OUT)) {
dprintf("VIA out mismatch (%s vs %s).%s\n",
outdev, ip6info->outiface,
ip6info->invflags & IP6T_INV_VIA_OUT ? " (INV)" : "");
return false;
}
/* ... might want to do something with class and flowlabel here ... */
/* look for the desired protocol header */
if (ip6info->flags & IP6T_F_PROTO) {
int protohdr;
unsigned short _frag_off;
protohdr = ipv6_find_hdr(skb, protoff, -1, &_frag_off, NULL);
if (protohdr < 0) {
if (_frag_off == 0)
*hotdrop = true;
return false;
}
*fragoff = _frag_off;
dprintf("Packet protocol %hi ?= %s%hi.\n",
protohdr,
ip6info->invflags & IP6T_INV_PROTO ? "!":"",
ip6info->proto);
if (ip6info->proto == protohdr) {
if (ip6info->invflags & IP6T_INV_PROTO)
return false;
return true;
}
/* We need match for the '-p all', too! */
if ((ip6info->proto != 0) &&
!(ip6info->invflags & IP6T_INV_PROTO))
return false;
}
return true;
}
/* should be ip6 safe */
static bool
ip6_checkentry(const struct ip6t_ip6 *ipv6)
{
if (ipv6->flags & ~IP6T_F_MASK) {
duprintf("Unknown flag bits set: %08X\n",
ipv6->flags & ~IP6T_F_MASK);
return false;
}
if (ipv6->invflags & ~IP6T_INV_MASK) {
duprintf("Unknown invflag bits set: %08X\n",
ipv6->invflags & ~IP6T_INV_MASK);
return false;
}
return true;
}
static unsigned int
ip6t_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo);
return NF_DROP;
}
static inline struct ip6t_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct ip6t_entry *)(base + offset);
}
/* All zeroes == unconditional rule. */
/* Mildly perf critical (only if packet tracing is on) */
static inline bool unconditional(const struct ip6t_ip6 *ipv6)
{
static const struct ip6t_ip6 uncond;
return memcmp(ipv6, &uncond, sizeof(uncond)) == 0;
}
static inline const struct xt_entry_target *
ip6t_get_target_c(const struct ip6t_entry *e)
{
return ip6t_get_target((struct ip6t_entry *)e);
}
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* This cries for unification! */
static const char *const hooknames[] = {
[NF_INET_PRE_ROUTING] = "PREROUTING",
[NF_INET_LOCAL_IN] = "INPUT",
[NF_INET_FORWARD] = "FORWARD",
[NF_INET_LOCAL_OUT] = "OUTPUT",
[NF_INET_POST_ROUTING] = "POSTROUTING",
};
enum nf_ip_trace_comments {
NF_IP6_TRACE_COMMENT_RULE,
NF_IP6_TRACE_COMMENT_RETURN,
NF_IP6_TRACE_COMMENT_POLICY,
};
static const char *const comments[] = {
[NF_IP6_TRACE_COMMENT_RULE] = "rule",
[NF_IP6_TRACE_COMMENT_RETURN] = "return",
[NF_IP6_TRACE_COMMENT_POLICY] = "policy",
};
static struct nf_loginfo trace_loginfo = {
.type = NF_LOG_TYPE_LOG,
.u = {
.log = {
.level = LOGLEVEL_WARNING,
.logflags = NF_LOG_MASK,
},
},
};
/* Mildly perf critical (only if packet tracing is on) */
static inline int
get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ip6t_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (s->target_offset == sizeof(struct ip6t_entry) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0 &&
unconditional(&s->ipv6)) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP6_TRACE_COMMENT_POLICY]
: comments[NF_IP6_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
static void trace_packet(struct net *net,
const struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
const char *tablename,
const struct xt_table_info *private,
const struct ip6t_entry *e)
{
const struct ip6t_entry *root;
const char *hookname, *chainname, *comment;
const struct ip6t_entry *iter;
unsigned int rulenum = 0;
root = get_entry(private->entries, private->hook_entry[hook]);
hookname = chainname = hooknames[hook];
comment = comments[NF_IP6_TRACE_COMMENT_RULE];
xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
if (get_chainname_rulenum(iter, e, hookname,
&chainname, &comment, &rulenum) != 0)
break;
nf_log_trace(net, AF_INET6, hook, skb, in, out, &trace_loginfo,
"TRACE: %s:%s:%s:%u ",
tablename, chainname, comment, rulenum);
}
#endif
static inline struct ip6t_entry *
ip6t_next_entry(const struct ip6t_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Returns one of the generic firewall policies, like NF_ACCEPT. */
unsigned int
ip6t_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ip6t_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.hotdrop = false;
acpar.net = state->net;
acpar.in = state->in;
acpar.out = state->out;
acpar.family = NFPROTO_IPV6;
acpar.hooknum = hook;
IP_NF_ASSERT(table->valid_hooks & (1 << hook));
local_bh_disable();
addend = xt_write_recseq_begin();
private = table->private;
/*
* Ensure we load private-> members after we've fetched the base
* pointer.
*/
smp_read_barrier_depends();
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct ip6t_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
IP_NF_ASSERT(e);
acpar.thoff = 0;
if (!ip6_packet_match(skb, indev, outdev, &e->ipv6,
&acpar.thoff, &acpar.fragoff, &acpar.hotdrop)) {
no_match:
e = ip6t_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ip6t_get_target_c(e);
IP_NF_ASSERT(t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0)
e = get_entry(table_base,
private->underflow[hook]);
else
e = ip6t_next_entry(jumpstack[--stackidx]);
continue;
}
if (table_base + v != ip6t_next_entry(e) &&
!(e->ipv6.flags & IP6T_F_GOTO)) {
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE)
e = ip6t_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
#ifdef DEBUG_ALLOW_ALL
return NF_ACCEPT;
#else
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
#endif
}
/* Figures out from what hook each rule can be called: returns 0 if
there are loops. Puts hook bitmask in comefrom. */
static int
mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ip6t_entry *e = (struct ip6t_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ip6t_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct ip6t_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 &&
unconditional(&e->ipv6)) || visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ip6t_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ip6t_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ip6t_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ip6t_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
static void cleanup_match(struct xt_entry_match *m, struct net *net)
{
struct xt_mtdtor_param par;
par.net = net;
par.match = m->u.kernel.match;
par.matchinfo = m->data;
par.family = NFPROTO_IPV6;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
}
static int
check_entry(const struct ip6t_entry *e)
{
const struct xt_entry_target *t;
if (!ip6_checkentry(&e->ipv6))
return -EINVAL;
if (e->target_offset + sizeof(struct xt_entry_target) >
e->next_offset)
return -EINVAL;
t = ip6t_get_target_c(e);
if (e->target_offset + t->u.target_size > e->next_offset)
return -EINVAL;
return 0;
}
static int check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
const struct ip6t_ip6 *ipv6 = par->entryinfo;
int ret;
par->match = m->u.kernel.match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->u.match_size - sizeof(*m),
ipv6->proto, ipv6->invflags & IP6T_INV_PROTO);
if (ret < 0) {
duprintf("ip_tables: check failed for `%s'.\n",
par.match->name);
return ret;
}
return 0;
}
static int
find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
{
struct xt_match *match;
int ret;
match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("find_check_match: `%s' not found\n", m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
ret = check_match(m, par);
if (ret)
goto err;
return 0;
err:
module_put(m->u.kernel.match->me);
return ret;
}
static int check_target(struct ip6t_entry *e, struct net *net, const char *name)
{
struct xt_entry_target *t = ip6t_get_target(e);
struct xt_tgchk_param par = {
.net = net,
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_IPV6,
};
int ret;
t = ip6t_get_target(e);
ret = xt_check_target(&par, t->u.target_size - sizeof(*t),
e->ipv6.proto, e->ipv6.invflags & IP6T_INV_PROTO);
if (ret < 0) {
duprintf("ip_tables: check failed for `%s'.\n",
t->u.kernel.target->name);
return ret;
}
return 0;
}
static int
find_check_entry(struct ip6t_entry *e, struct net *net, const char *name,
unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
unsigned int j;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ipv6;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV6;
xt_ematch_foreach(ematch, e) {
ret = find_check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
t = ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
ret = PTR_ERR(target);
goto cleanup_matches;
}
t->u.kernel.target = target;
ret = check_target(e, net, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
static bool check_underflow(const struct ip6t_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->ipv6))
return false;
t = ip6t_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
static int
check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
static void cleanup_entry(struct ip6t_entry *e, struct net *net)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
cleanup_match(ematch, net);
t = ip6t_get_target(e);
par.net = net;
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_IPV6;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
xt_percpu_counter_free(e->counters.pcnt);
}
/* Checks and translates the user-supplied table segment (held in
newinfo) */
static int
translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0,
const struct ip6t_replace *repl)
{
struct ip6t_entry *iter;
unsigned int i;
int ret = 0;
newinfo->size = repl->size;
newinfo->number = repl->num_entries;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = 0xFFFFFFFF;
newinfo->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_table: size %u\n", newinfo->size);
i = 0;
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = check_entry_size_and_hooks(iter, newinfo, entry0,
entry0 + repl->size,
repl->hook_entry,
repl->underflow,
repl->valid_hooks);
if (ret != 0)
return ret;
++i;
if (strcmp(ip6t_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (i != repl->num_entries) {
duprintf("translate_table: %u not %u entries\n",
i, repl->num_entries);
return -EINVAL;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(repl->valid_hooks & (1 << i)))
continue;
if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, repl->hook_entry[i]);
return -EINVAL;
}
if (newinfo->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, repl->underflow[i]);
return -EINVAL;
}
}
if (!mark_source_chains(newinfo, repl->valid_hooks, entry0))
return -ELOOP;
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, net, repl->name, repl->size);
if (ret != 0)
break;
++i;
}
if (ret != 0) {
xt_entry_foreach(iter, entry0, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter, net);
}
return ret;
}
return ret;
}
static void
get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct ip6t_entry *iter;
unsigned int cpu;
unsigned int i;
for_each_possible_cpu(cpu) {
seqcount_t *s = &per_cpu(xt_recseq, cpu);
i = 0;
xt_entry_foreach(iter, t->entries, t->size) {
struct xt_counters *tmp;
u64 bcnt, pcnt;
unsigned int start;
tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
do {
start = read_seqcount_begin(s);
bcnt = tmp->bcnt;
pcnt = tmp->pcnt;
} while (read_seqcount_retry(s, start));
ADD_COUNTER(counters[i], bcnt, pcnt);
++i;
}
}
}
static struct xt_counters *alloc_counters(const struct xt_table *table)
{
unsigned int countersize;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
/* We need atomic snapshot of counters: rest doesn't change
(other than comefrom, which userspace doesn't care
about). */
countersize = sizeof(struct xt_counters) * private->number;
counters = vzalloc(countersize);
if (counters == NULL)
return ERR_PTR(-ENOMEM);
get_counters(private, counters);
return counters;
}
static int
copy_entries_to_user(unsigned int total_size,
const struct xt_table *table,
void __user *userptr)
{
unsigned int off, num;
const struct ip6t_entry *e;
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
int ret = 0;
const void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
loc_cpu_entry = private->entries;
if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
ret = -EFAULT;
goto free_counters;
}
/* FIXME: use iterator macros --RR */
/* ... then go back and fix counters and names */
for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
unsigned int i;
const struct xt_entry_match *m;
const struct xt_entry_target *t;
e = (struct ip6t_entry *)(loc_cpu_entry + off);
if (copy_to_user(userptr + off
+ offsetof(struct ip6t_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
for (i = sizeof(struct ip6t_entry);
i < e->target_offset;
i += m->u.match_size) {
m = (void *)e + i;
if (copy_to_user(userptr + off + i
+ offsetof(struct xt_entry_match,
u.user.name),
m->u.kernel.match->name,
strlen(m->u.kernel.match->name)+1)
!= 0) {
ret = -EFAULT;
goto free_counters;
}
}
t = ip6t_get_target_c(e);
if (copy_to_user(userptr + off + e->target_offset
+ offsetof(struct xt_entry_target,
u.user.name),
t->u.kernel.target->name,
strlen(t->u.kernel.target->name)+1) != 0) {
ret = -EFAULT;
goto free_counters;
}
}
free_counters:
vfree(counters);
return ret;
}
#ifdef CONFIG_COMPAT
static void compat_standard_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v > 0)
v += xt_compat_calc_jump(AF_INET6, v);
memcpy(dst, &v, sizeof(v));
}
static int compat_standard_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv > 0)
cv -= xt_compat_calc_jump(AF_INET6, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct ip6t_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_match *ematch;
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - base;
xt_ematch_foreach(ematch, e)
off += xt_compat_match_offset(ematch->u.kernel.match);
t = ip6t_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct ip6t_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct ip6t_entry *)(base + info->underflow[i])))
newinfo->underflow[i] -= off;
}
return 0;
}
static int compat_table_info(const struct xt_table_info *info,
struct xt_table_info *newinfo)
{
struct ip6t_entry *iter;
const void *loc_cpu_entry;
int ret;
if (!newinfo || !info)
return -EINVAL;
/* we dont care about newinfo->entries */
memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
newinfo->initial_entries = 0;
loc_cpu_entry = info->entries;
xt_compat_init_offsets(AF_INET6, info->number);
xt_entry_foreach(iter, loc_cpu_entry, info->size) {
ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
if (ret != 0)
return ret;
}
return 0;
}
#endif
static int get_info(struct net *net, void __user *user,
const int *len, int compat)
{
char name[XT_TABLE_MAXNAMELEN];
struct xt_table *t;
int ret;
if (*len != sizeof(struct ip6t_getinfo)) {
duprintf("length %u != %zu\n", *len,
sizeof(struct ip6t_getinfo));
return -EINVAL;
}
if (copy_from_user(name, user, sizeof(name)) != 0)
return -EFAULT;
name[XT_TABLE_MAXNAMELEN-1] = '\0';
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_lock(AF_INET6);
#endif
t = try_then_request_module(xt_find_table_lock(net, AF_INET6, name),
"ip6table_%s", name);
if (!IS_ERR_OR_NULL(t)) {
struct ip6t_getinfo info;
const struct xt_table_info *private = t->private;
#ifdef CONFIG_COMPAT
struct xt_table_info tmp;
if (compat) {
ret = compat_table_info(private, &tmp);
xt_compat_flush_offsets(AF_INET6);
private = &tmp;
}
#endif
memset(&info, 0, sizeof(info));
info.valid_hooks = t->valid_hooks;
memcpy(info.hook_entry, private->hook_entry,
sizeof(info.hook_entry));
memcpy(info.underflow, private->underflow,
sizeof(info.underflow));
info.num_entries = private->number;
info.size = private->size;
strcpy(info.name, name);
if (copy_to_user(user, &info, *len) != 0)
ret = -EFAULT;
else
ret = 0;
xt_table_unlock(t);
module_put(t->me);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
#ifdef CONFIG_COMPAT
if (compat)
xt_compat_unlock(AF_INET6);
#endif
return ret;
}
static int
get_entries(struct net *net, struct ip6t_get_entries __user *uptr,
const int *len)
{
int ret;
struct ip6t_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct ip6t_get_entries) + get.size) {
duprintf("get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
t = xt_find_table_lock(net, AF_INET6, get.name);
if (!IS_ERR_OR_NULL(t)) {
struct xt_table_info *private = t->private;
duprintf("t->private->number = %u\n", private->number);
if (get.size == private->size)
ret = copy_entries_to_user(private->size,
t, uptr->entrytable);
else {
duprintf("get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
return ret;
}
static int
__do_replace(struct net *net, const char *name, unsigned int valid_hooks,
struct xt_table_info *newinfo, unsigned int num_counters,
void __user *counters_ptr)
{
int ret;
struct xt_table *t;
struct xt_table_info *oldinfo;
struct xt_counters *counters;
struct ip6t_entry *iter;
ret = 0;
counters = vzalloc(num_counters * sizeof(struct xt_counters));
if (!counters) {
ret = -ENOMEM;
goto out;
}
t = try_then_request_module(xt_find_table_lock(net, AF_INET6, name),
"ip6table_%s", name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free_newinfo_counters_untrans;
}
/* You lied! */
if (valid_hooks != t->valid_hooks) {
duprintf("Valid hook crap: %08X vs %08X\n",
valid_hooks, t->valid_hooks);
ret = -EINVAL;
goto put_module;
}
oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
if (!oldinfo)
goto put_module;
/* Update module usage count based on number of rules */
duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
oldinfo->number, oldinfo->initial_entries, newinfo->number);
if ((oldinfo->number > oldinfo->initial_entries) ||
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
if ((oldinfo->number > oldinfo->initial_entries) &&
(newinfo->number <= oldinfo->initial_entries))
module_put(t->me);
/* Get the old counters, and synchronize with replace */
get_counters(oldinfo, counters);
/* Decrease module usage counts and free resource */
xt_entry_foreach(iter, oldinfo->entries, oldinfo->size)
cleanup_entry(iter, net);
xt_free_table_info(oldinfo);
if (copy_to_user(counters_ptr, counters,
sizeof(struct xt_counters) * num_counters) != 0) {
/* Silent error, can't fail, new table is already in place */
net_warn_ratelimited("ip6tables: counters copy to user failed while replacing table\n");
}
vfree(counters);
xt_table_unlock(t);
return ret;
put_module:
module_put(t->me);
xt_table_unlock(t);
free_newinfo_counters_untrans:
vfree(counters);
out:
return ret;
}
static int
do_replace(struct net *net, const void __user *user, unsigned int len)
{
int ret;
struct ip6t_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ip6t_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_table(net, newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
duprintf("ip_tables: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, tmp.counters);
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
do_add_counters(struct net *net, const void __user *user, unsigned int len,
int compat)
{
unsigned int i;
struct xt_counters_info tmp;
struct xt_counters *paddc;
unsigned int num_counters;
char *name;
int size;
void *ptmp;
struct xt_table *t;
const struct xt_table_info *private;
int ret = 0;
struct ip6t_entry *iter;
unsigned int addend;
#ifdef CONFIG_COMPAT
struct compat_xt_counters_info compat_tmp;
if (compat) {
ptmp = &compat_tmp;
size = sizeof(struct compat_xt_counters_info);
} else
#endif
{
ptmp = &tmp;
size = sizeof(struct xt_counters_info);
}
if (copy_from_user(ptmp, user, size) != 0)
return -EFAULT;
#ifdef CONFIG_COMPAT
if (compat) {
num_counters = compat_tmp.num_counters;
name = compat_tmp.name;
} else
#endif
{
num_counters = tmp.num_counters;
name = tmp.name;
}
if (len != size + num_counters * sizeof(struct xt_counters))
return -EINVAL;
paddc = vmalloc(len - size);
if (!paddc)
return -ENOMEM;
if (copy_from_user(paddc, user + size, len - size) != 0) {
ret = -EFAULT;
goto free;
}
t = xt_find_table_lock(net, AF_INET6, name);
if (IS_ERR_OR_NULL(t)) {
ret = t ? PTR_ERR(t) : -ENOENT;
goto free;
}
local_bh_disable();
private = t->private;
if (private->number != num_counters) {
ret = -EINVAL;
goto unlock_up_free;
}
i = 0;
addend = xt_write_recseq_begin();
xt_entry_foreach(iter, private->entries, private->size) {
struct xt_counters *tmp;
tmp = xt_get_this_cpu_counter(&iter->counters);
ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);
++i;
}
xt_write_recseq_end(addend);
unlock_up_free:
local_bh_enable();
xt_table_unlock(t);
module_put(t->me);
free:
vfree(paddc);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_ip6t_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_INET_NUMHOOKS];
u32 underflow[NF_INET_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters; /* struct xt_counters * */
struct compat_ip6t_entry entries[0];
};
static int
compat_copy_entry_to_user(struct ip6t_entry *e, void __user **dstptr,
unsigned int *size, struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_ip6t_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
const struct xt_entry_match *ematch;
int ret = 0;
origsize = *size;
ce = (struct compat_ip6t_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(struct ip6t_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_ip6t_entry);
*size -= sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_to_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
target_offset = e->target_offset - (origsize - *size);
t = ip6t_get_target(e);
ret = xt_compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(target_offset, &ce->target_offset) != 0 ||
put_user(next_offset, &ce->next_offset) != 0)
return -EFAULT;
return 0;
}
static int
compat_find_calc_match(struct xt_entry_match *m,
const char *name,
const struct ip6t_ip6 *ipv6,
int *size)
{
struct xt_match *match;
match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name,
m->u.user.revision);
if (IS_ERR(match)) {
duprintf("compat_check_calc_match: `%s' not found\n",
m->u.user.name);
return PTR_ERR(match);
}
m->u.kernel.match = match;
*size += xt_compat_match_offset(match);
return 0;
}
static void compat_release_entry(struct compat_ip6t_entry *e)
{
struct xt_entry_target *t;
struct xt_entry_match *ematch;
/* Cleanup all matches */
xt_ematch_foreach(ematch, e)
module_put(ematch->u.kernel.match->me);
t = compat_ip6t_get_target(e);
module_put(t->u.kernel.target->me);
}
static int
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ip6t_entry *)e);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
static int
compat_copy_entry_from_user(struct compat_ip6t_entry *e, void **dstptr,
unsigned int *size, const char *name,
struct xt_table_info *newinfo, unsigned char *base)
{
struct xt_entry_target *t;
struct ip6t_entry *de;
unsigned int origsize;
int ret, h;
struct xt_entry_match *ematch;
ret = 0;
origsize = *size;
de = (struct ip6t_entry *)*dstptr;
memcpy(de, e, sizeof(struct ip6t_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct ip6t_entry);
*size += sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
xt_ematch_foreach(ematch, e) {
ret = xt_compat_match_from_user(ematch, dstptr, size);
if (ret != 0)
return ret;
}
de->target_offset = e->target_offset - (origsize - *size);
t = compat_ip6t_get_target(e);
xt_compat_target_from_user(t, dstptr, size);
de->next_offset = e->next_offset - (origsize - *size);
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)de - base < newinfo->hook_entry[h])
newinfo->hook_entry[h] -= origsize - *size;
if ((unsigned char *)de - base < newinfo->underflow[h])
newinfo->underflow[h] -= origsize - *size;
}
return ret;
}
static int compat_check_entry(struct ip6t_entry *e, struct net *net,
const char *name)
{
unsigned int j;
int ret = 0;
struct xt_mtchk_param mtpar;
struct xt_entry_match *ematch;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
j = 0;
mtpar.net = net;
mtpar.table = name;
mtpar.entryinfo = &e->ipv6;
mtpar.hook_mask = e->comefrom;
mtpar.family = NFPROTO_IPV6;
xt_ematch_foreach(ematch, e) {
ret = check_match(ematch, &mtpar);
if (ret != 0)
goto cleanup_matches;
++j;
}
ret = check_target(e, net, name);
if (ret)
goto cleanup_matches;
return 0;
cleanup_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
cleanup_match(ematch, net);
}
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
static int
translate_compat_table(struct net *net,
const char *name,
unsigned int valid_hooks,
struct xt_table_info **pinfo,
void **pentry0,
unsigned int total_size,
unsigned int number,
unsigned int *hook_entries,
unsigned int *underflows)
{
unsigned int i, j;
struct xt_table_info *newinfo, *info;
void *pos, *entry0, *entry1;
struct compat_ip6t_entry *iter0;
struct ip6t_entry *iter1;
unsigned int size;
int ret = 0;
info = *pinfo;
entry0 = *pentry0;
size = total_size;
info->number = number;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
info->hook_entry[i] = 0xFFFFFFFF;
info->underflow[i] = 0xFFFFFFFF;
}
duprintf("translate_compat_table: size %u\n", info->size);
j = 0;
xt_compat_lock(AF_INET6);
xt_compat_init_offsets(AF_INET6, number);
/* Walk through entries, checking offsets. */
xt_entry_foreach(iter0, entry0, total_size) {
ret = check_compat_entry_size_and_hooks(iter0, info, &size,
entry0,
entry0 + total_size,
hook_entries,
underflows,
name);
if (ret != 0)
goto out_unlock;
++j;
}
ret = -EINVAL;
if (j != number) {
duprintf("translate_compat_table: %u not %u entries\n",
j, number);
goto out_unlock;
}
/* Check hooks all assigned */
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
/* Only hooks which are valid */
if (!(valid_hooks & (1 << i)))
continue;
if (info->hook_entry[i] == 0xFFFFFFFF) {
duprintf("Invalid hook entry %u %u\n",
i, hook_entries[i]);
goto out_unlock;
}
if (info->underflow[i] == 0xFFFFFFFF) {
duprintf("Invalid underflow %u %u\n",
i, underflows[i]);
goto out_unlock;
}
}
ret = -ENOMEM;
newinfo = xt_alloc_table_info(size);
if (!newinfo)
goto out_unlock;
newinfo->number = number;
for (i = 0; i < NF_INET_NUMHOOKS; i++) {
newinfo->hook_entry[i] = info->hook_entry[i];
newinfo->underflow[i] = info->underflow[i];
}
entry1 = newinfo->entries;
pos = entry1;
size = total_size;
xt_entry_foreach(iter0, entry0, total_size) {
ret = compat_copy_entry_from_user(iter0, &pos, &size,
name, newinfo, entry1);
if (ret != 0)
break;
}
xt_compat_flush_offsets(AF_INET6);
xt_compat_unlock(AF_INET6);
if (ret)
goto free_newinfo;
ret = -ELOOP;
if (!mark_source_chains(newinfo, valid_hooks, entry1))
goto free_newinfo;
i = 0;
xt_entry_foreach(iter1, entry1, newinfo->size) {
ret = compat_check_entry(iter1, net, name);
if (ret != 0)
break;
++i;
if (strcmp(ip6t_get_target(iter1)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
if (ret) {
/*
* The first i matches need cleanup_entry (calls ->destroy)
* because they had called ->check already. The other j-i
* entries need only release.
*/
int skip = i;
j -= i;
xt_entry_foreach(iter0, entry0, newinfo->size) {
if (skip-- > 0)
continue;
if (j-- == 0)
break;
compat_release_entry(iter0);
}
xt_entry_foreach(iter1, entry1, newinfo->size) {
if (i-- == 0)
break;
cleanup_entry(iter1, net);
}
xt_free_table_info(newinfo);
return ret;
}
*pinfo = newinfo;
*pentry0 = entry1;
xt_free_table_info(info);
return 0;
free_newinfo:
xt_free_table_info(newinfo);
out:
xt_entry_foreach(iter0, entry0, total_size) {
if (j-- == 0)
break;
compat_release_entry(iter0);
}
return ret;
out_unlock:
xt_compat_flush_offsets(AF_INET6);
xt_compat_unlock(AF_INET6);
goto out;
}
static int
compat_do_replace(struct net *net, void __user *user, unsigned int len)
{
int ret;
struct compat_ip6t_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct ip6t_entry *iter;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
/* overflow check */
if (tmp.size >= INT_MAX / num_possible_cpus())
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
return -ENOMEM;
if (tmp.num_counters == 0)
return -EINVAL;
tmp.name[sizeof(tmp.name)-1] = 0;
newinfo = xt_alloc_table_info(tmp.size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
tmp.size) != 0) {
ret = -EFAULT;
goto free_newinfo;
}
ret = translate_compat_table(net, tmp.name, tmp.valid_hooks,
&newinfo, &loc_cpu_entry, tmp.size,
tmp.num_entries, tmp.hook_entry,
tmp.underflow);
if (ret != 0)
goto free_newinfo;
duprintf("compat_do_replace: Translated table\n");
ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
tmp.num_counters, compat_ptr(tmp.counters));
if (ret)
goto free_newinfo_untrans;
return 0;
free_newinfo_untrans:
xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
cleanup_entry(iter, net);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int
compat_do_ip6t_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case IP6T_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
duprintf("do_ip6t_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
struct compat_ip6t_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_ip6t_entry entrytable[0];
};
static int
compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
unsigned int i = 0;
struct ip6t_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
pos = userptr;
size = total_size;
xt_entry_foreach(iter, private->entries, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
static int
compat_get_entries(struct net *net, struct compat_ip6t_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_ip6t_get_entries get;
struct xt_table *t;
if (*len < sizeof(get)) {
duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get));
return -EINVAL;
}
if (copy_from_user(&get, uptr, sizeof(get)) != 0)
return -EFAULT;
if (*len != sizeof(struct compat_ip6t_get_entries) + get.size) {
duprintf("compat_get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
xt_compat_lock(AF_INET6);
t = xt_find_table_lock(net, AF_INET6, get.name);
if (!IS_ERR_OR_NULL(t)) {
const struct xt_table_info *private = t->private;
struct xt_table_info info;
duprintf("t->private->number = %u\n", private->number);
ret = compat_table_info(private, &info);
if (!ret && get.size == info.size) {
ret = compat_copy_entries_to_user(private->size,
t, uptr->entrytable);
} else if (!ret) {
duprintf("compat_get_entries: I've got %u not %u!\n",
private->size, get.size);
ret = -EAGAIN;
}
xt_compat_flush_offsets(AF_INET6);
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
xt_compat_unlock(AF_INET6);
return ret;
}
static int do_ip6t_get_ctl(struct sock *, int, void __user *, int *);
static int
compat_do_ip6t_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case IP6T_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_ip6t_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int
do_ip6t_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case IP6T_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
duprintf("do_ip6t_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int
do_ip6t_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IP6T_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case IP6T_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case IP6T_SO_GET_REVISION_MATCH:
case IP6T_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
int target;
if (*len != sizeof(rev)) {
ret = -EINVAL;
break;
}
if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
ret = -EFAULT;
break;
}
rev.name[sizeof(rev.name)-1] = 0;
if (cmd == IP6T_SO_GET_REVISION_TARGET)
target = 1;
else
target = 0;
try_then_request_module(xt_find_revision(AF_INET6, rev.name,
rev.revision,
target, &ret),
"ip6t_%s", rev.name);
break;
}
default:
duprintf("do_ip6t_get_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static void __ip6t_unregister_table(struct net *net, struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct ip6t_entry *iter;
private = xt_unregister_table(table);
/* Decrease module usage counts and free resources */
loc_cpu_entry = private->entries;
xt_entry_foreach(iter, loc_cpu_entry, private->size)
cleanup_entry(iter, net);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
int ip6t_register_table(struct net *net, const struct xt_table *table,
const struct ip6t_replace *repl,
const struct nf_hook_ops *ops,
struct xt_table **res)
{
int ret;
struct xt_table_info *newinfo;
struct xt_table_info bootstrap = {0};
void *loc_cpu_entry;
struct xt_table *new_table;
newinfo = xt_alloc_table_info(repl->size);
if (!newinfo)
return -ENOMEM;
loc_cpu_entry = newinfo->entries;
memcpy(loc_cpu_entry, repl->entries, repl->size);
ret = translate_table(net, newinfo, loc_cpu_entry, repl);
if (ret != 0)
goto out_free;
new_table = xt_register_table(net, table, &bootstrap, newinfo);
if (IS_ERR(new_table)) {
ret = PTR_ERR(new_table);
goto out_free;
}
/* set res now, will see skbs right after nf_register_net_hooks */
WRITE_ONCE(*res, new_table);
ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks));
if (ret != 0) {
__ip6t_unregister_table(net, new_table);
*res = NULL;
}
return ret;
out_free:
xt_free_table_info(newinfo);
return ret;
}
void ip6t_unregister_table(struct net *net, struct xt_table *table,
const struct nf_hook_ops *ops)
{
nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks));
__ip6t_unregister_table(net, table);
}
/* Returns 1 if the type and code is matched by the range, 0 otherwise */
static inline bool
icmp6_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code,
u_int8_t type, u_int8_t code,
bool invert)
{
return (type == test_type && code >= min_code && code <= max_code)
^ invert;
}
static bool
icmp6_match(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct icmp6hdr *ic;
struct icmp6hdr _icmph;
const struct ip6t_icmp *icmpinfo = par->matchinfo;
/* Must not be a fragment. */
if (par->fragoff != 0)
return false;
ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph);
if (ic == NULL) {
/* We've been asked to examine this packet, and we
* can't. Hence, no choice but to drop.
*/
duprintf("Dropping evil ICMP tinygram.\n");
par->hotdrop = true;
return false;
}
return icmp6_type_code_match(icmpinfo->type,
icmpinfo->code[0],
icmpinfo->code[1],
ic->icmp6_type, ic->icmp6_code,
!!(icmpinfo->invflags&IP6T_ICMP_INV));
}
/* Called when user tries to insert an entry of this type. */
static int icmp6_checkentry(const struct xt_mtchk_param *par)
{
const struct ip6t_icmp *icmpinfo = par->matchinfo;
/* Must specify no unknown invflags */
return (icmpinfo->invflags & ~IP6T_ICMP_INV) ? -EINVAL : 0;
}
/* The built-in targets: standard (NULL) and error. */
static struct xt_target ip6t_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_IPV6,
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = compat_standard_from_user,
.compat_to_user = compat_standard_to_user,
#endif
},
{
.name = XT_ERROR_TARGET,
.target = ip6t_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_IPV6,
},
};
static struct nf_sockopt_ops ip6t_sockopts = {
.pf = PF_INET6,
.set_optmin = IP6T_BASE_CTL,
.set_optmax = IP6T_SO_SET_MAX+1,
.set = do_ip6t_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ip6t_set_ctl,
#endif
.get_optmin = IP6T_BASE_CTL,
.get_optmax = IP6T_SO_GET_MAX+1,
.get = do_ip6t_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ip6t_get_ctl,
#endif
.owner = THIS_MODULE,
};
static struct xt_match ip6t_builtin_mt[] __read_mostly = {
{
.name = "icmp6",
.match = icmp6_match,
.matchsize = sizeof(struct ip6t_icmp),
.checkentry = icmp6_checkentry,
.proto = IPPROTO_ICMPV6,
.family = NFPROTO_IPV6,
},
};
static int __net_init ip6_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_IPV6);
}
static void __net_exit ip6_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_IPV6);
}
static struct pernet_operations ip6_tables_net_ops = {
.init = ip6_tables_net_init,
.exit = ip6_tables_net_exit,
};
static int __init ip6_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&ip6_tables_net_ops);
if (ret < 0)
goto err1;
/* No one else will be downing sem now, so we won't sleep */
ret = xt_register_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg));
if (ret < 0)
goto err2;
ret = xt_register_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt));
if (ret < 0)
goto err4;
/* Register setsockopt */
ret = nf_register_sockopt(&ip6t_sockopts);
if (ret < 0)
goto err5;
pr_info("(C) 2000-2006 Netfilter Core Team\n");
return 0;
err5:
xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt));
err4:
xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg));
err2:
unregister_pernet_subsys(&ip6_tables_net_ops);
err1:
return ret;
}
static void __exit ip6_tables_fini(void)
{
nf_unregister_sockopt(&ip6t_sockopts);
xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt));
xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg));
unregister_pernet_subsys(&ip6_tables_net_ops);
}
EXPORT_SYMBOL(ip6t_register_table);
EXPORT_SYMBOL(ip6t_unregister_table);
EXPORT_SYMBOL(ip6t_do_table);
module_init(ip6_tables_init);
module_exit(ip6_tables_fini);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5079_2 |
crossvul-cpp_data_good_340_10 | /*
* util.c: utility functions used by OpenSC command line tools.
*
* Copyright (C) 2011 OpenSC Project developers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <conio.h>
#endif
#include <ctype.h>
#include "util.h"
#include "ui/notify.h"
int
is_string_valid_atr(const char *atr_str)
{
unsigned char atr[SC_MAX_ATR_SIZE];
size_t atr_len = sizeof(atr);
if (sc_hex_to_bin(atr_str, atr, &atr_len))
return 0;
if (atr_len < 2)
return 0;
if (atr[0] != 0x3B && atr[0] != 0x3F)
return 0;
return 1;
}
int
util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int do_lock, int verbose)
{
struct sc_reader *reader = NULL, *found = NULL;
struct sc_card *card = NULL;
int r;
sc_notify_init();
if (do_wait) {
unsigned int event;
if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "Waiting for a reader to be attached...\n");
r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r));
return 3;
}
r = sc_ctx_detect_readers(ctx);
if (r < 0) {
fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r));
return 3;
}
}
fprintf(stderr, "Waiting for a card to be inserted...\n");
r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r));
return 3;
}
reader = found;
}
else if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "No smart card readers found.\n");
return 1;
}
else {
if (!reader_id) {
unsigned int i;
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
reader = sc_ctx_get_reader(ctx, i);
if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) {
fprintf(stderr, "Using reader with a card: %s\n", reader->name);
goto autofound;
}
}
/* If no reader had a card, default to the first reader */
reader = sc_ctx_get_reader(ctx, 0);
}
else {
/* If the reader identifier looks like an ATR, try to find the reader with that card */
if (is_string_valid_atr(reader_id)) {
unsigned char atr_buf[SC_MAX_ATR_SIZE];
size_t atr_buf_len = sizeof(atr_buf);
unsigned int i;
sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len);
/* Loop readers, looking for a card with ATR */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
struct sc_reader *rdr = sc_ctx_get_reader(ctx, i);
if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT))
continue;
else if (rdr->atr.len != atr_buf_len)
continue;
else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len))
continue;
fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name);
reader = rdr;
goto autofound;
}
}
else {
char *endptr = NULL;
unsigned int num;
errno = 0;
num = strtol(reader_id, &endptr, 0);
if (!errno && endptr && *endptr == '\0')
reader = sc_ctx_get_reader(ctx, num);
else
reader = sc_ctx_get_reader_by_name(ctx, reader_id);
}
}
autofound:
if (!reader) {
fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n",
reader_id, sc_ctx_get_reader_count(ctx));
return 1;
}
if (sc_detect_card_presence(reader) <= 0) {
fprintf(stderr, "Card not present.\n");
return 3;
}
}
if (verbose)
printf("Connecting to card in reader %s...\n", reader->name);
r = sc_connect_card(reader, &card);
if (r < 0) {
fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Using card driver %s.\n", card->driver->name);
if (do_lock) {
r = sc_lock(card);
if (r < 0) {
fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r));
sc_disconnect_card(card);
return 1;
}
}
*cardp = card;
return 0;
}
int
util_connect_card(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int verbose)
{
return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose);
}
void util_print_binary(FILE *f, const u8 *buf, int count)
{
int i;
for (i = 0; i < count; i++) {
unsigned char c = buf[i];
const char *format;
if (!isprint(c))
format = "\\x%02X";
else
format = "%c";
fprintf(f, format, c);
}
(void) fflush(f);
}
void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep)
{
int i;
for (i = 0; i < len; i++) {
if (sep != NULL && i)
fprintf(f, "%s", sep);
fprintf(f, "%02X", in[i]);
}
}
void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr)
{
int lines = 0;
while (count) {
char ascbuf[17];
size_t i;
if (addr >= 0) {
fprintf(f, "%08X: ", addr);
addr += 16;
}
for (i = 0; i < count && i < 16; i++) {
fprintf(f, "%02X ", *in);
if (isprint(*in))
ascbuf[i] = *in;
else
ascbuf[i] = '.';
in++;
}
count -= i;
ascbuf[i] = 0;
for (; i < 16 && lines; i++)
fprintf(f, " ");
fprintf(f, "%s\n", ascbuf);
lines++;
}
}
NORETURN void
util_print_usage_and_die(const char *app_name, const struct option options[],
const char *option_help[], const char *args)
{
int i;
int header_shown = 0;
if (args)
printf("Usage: %s [OPTIONS] %s\n", app_name, args);
else
printf("Usage: %s [OPTIONS]\n", app_name);
for (i = 0; options[i].name; i++) {
char buf[40];
const char *arg_str;
/* Skip "hidden" options */
if (option_help[i] == NULL)
continue;
if (!header_shown++)
printf("Options:\n");
switch (options[i].has_arg) {
case 1:
arg_str = " <arg>";
break;
case 2:
arg_str = " [arg]";
break;
default:
arg_str = "";
break;
}
if (isascii(options[i].val) &&
isprint(options[i].val) && !isspace(options[i].val))
sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str);
else
sprintf(buf, " --%s%s", options[i].name, arg_str);
/* print the line - wrap if necessary */
if (strlen(buf) > 28) {
printf(" %s\n", buf);
buf[0] = '\0';
}
printf(" %-28s %s\n", buf, option_help[i]);
}
exit(2);
}
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strncat(line, buf, sizeof line);
strncat(line, " ", sizeof line);
e = e->next;
}
line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
NORETURN void
util_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\nAborting.\n");
va_end(ap);
sc_notify_close();
exit(1);
}
void
util_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void
util_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "warning: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int
util_getpass (char **lineptr, size_t *len, FILE *stream)
{
#define MAX_PASS_SIZE 128
char *buf;
size_t i;
int ch = 0;
#ifndef _WIN32
struct termios old, new;
fflush(stdout);
if (tcgetattr (fileno (stdout), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0)
return -1;
#endif
buf = calloc(1, MAX_PASS_SIZE);
if (!buf)
return -1;
for (i = 0; i < MAX_PASS_SIZE - 1; i++) {
#ifndef _WIN32
ch = getchar();
#else
ch = _getch();
#endif
if (ch == 0 || ch == 3)
break;
if (ch == '\n' || ch == '\r')
break;
buf[i] = (char) ch;
}
#ifndef _WIN32
tcsetattr (fileno (stdout), TCSAFLUSH, &old);
fputs("\n", stdout);
#endif
if (ch == 0 || ch == 3) {
free(buf);
return -1;
}
if (*lineptr && (!len || *len < i+1)) {
free(*lineptr);
*lineptr = NULL;
}
if (*lineptr) {
memcpy(*lineptr,buf,i+1);
memset(buf, 0, MAX_PASS_SIZE);
free(buf);
} else {
*lineptr = buf;
if (len)
*len = MAX_PASS_SIZE;
}
return i;
}
size_t
util_get_pin(const char *input, const char **pin)
{
size_t inputlen = strlen(input);
size_t pinlen = 0;
if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) {
// Get a PIN from a environment variable
*pin = getenv(input + 4);
pinlen = *pin ? strlen(*pin) : 0;
} else {
//Just use the input
*pin = input;
pinlen = inputlen;
}
return pinlen;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_340_10 |
crossvul-cpp_data_bad_346_8 | /*
* cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff
*
* Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "libopensc/sc-ossl-compat.h"
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include "libopensc/pkcs15.h"
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "util.h"
static const char *app_name = "cryptoflex-tool";
static char * opt_reader = NULL;
static int opt_wait = 0;
static int opt_key_num = 1, opt_pin_num = -1;
static int verbose = 0;
static int opt_exponent = 3;
static int opt_mod_length = 1024;
static int opt_key_count = 1;
static int opt_pin_attempts = 10;
static int opt_puk_attempts = 10;
static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL;
static u8 *pincode = NULL;
static const struct option options[] = {
{ "list-keys", 0, NULL, 'l' },
{ "create-key-files", 1, NULL, 'c' },
{ "create-pin-file", 1, NULL, 'P' },
{ "generate-key", 0, NULL, 'g' },
{ "read-key", 0, NULL, 'R' },
{ "verify-pin", 0, NULL, 'V' },
{ "key-num", 1, NULL, 'k' },
{ "app-df", 1, NULL, 'a' },
{ "prkey-file", 1, NULL, 'p' },
{ "pubkey-file", 1, NULL, 'u' },
{ "exponent", 1, NULL, 'e' },
{ "modulus-length", 1, NULL, 'm' },
{ "reader", 1, NULL, 'r' },
{ "wait", 0, NULL, 'w' },
{ "verbose", 0, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
static const char *option_help[] = {
"Lists all keys in a public key file",
"Creates new RSA key files for <arg> keys",
"Creates a new CHV<arg> file",
"Generates a new RSA key pair",
"Reads a public key from the card",
"Verifies CHV1 before issuing commands",
"Selects which key number to operate on [1]",
"Selects the DF to operate in",
"Private key file",
"Public key file",
"The RSA exponent to use in key generation [3]",
"Modulus length to use in key generation [1024]",
"Uses reader <arg>",
"Wait for card insertion",
"Verbose operation. Use several times to enable debug output.",
};
static sc_context_t *ctx = NULL;
static sc_card_t *card = NULL;
static char *getpin(const char *prompt)
{
char *buf, pass[20];
int i;
printf("%s", prompt);
fflush(stdout);
if (fgets(pass, 20, stdin) == NULL)
return NULL;
for (i = 0; i < 20; i++)
if (pass[i] == '\n')
pass[i] = 0;
if (strlen(pass) == 0)
return NULL;
buf = malloc(8);
if (buf == NULL)
return NULL;
if (strlen(pass) > 8) {
fprintf(stderr, "PIN code too long.\n");
free(buf);
return NULL;
}
memset(buf, 0, 8);
strlcpy(buf, pass, 8);
return buf;
}
static int verify_pin(int pin)
{
char prompt[50];
int r, tries_left = -1;
if (pincode == NULL) {
sprintf(prompt, "Please enter CHV%d: ", pin);
pincode = (u8 *) getpin(prompt);
if (pincode == NULL || strlen((char *) pincode) == 0)
return -1;
}
if (pin != 1 && pin != 2)
return -3;
r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left);
if (r) {
memset(pincode, 0, 8);
free(pincode);
pincode = NULL;
fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r));
return -1;
}
return 0;
}
static int select_app_df(void)
{
sc_path_t path;
sc_file_t *file;
char str[80];
int r;
strcpy(str, "3F00");
if (opt_appdf != NULL)
strlcat(str, opt_appdf, sizeof str);
sc_format_path(str, &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r));
return -1;
}
if (file->type != SC_FILE_TYPE_DF) {
fprintf(stderr, "Selected application DF is not a DF.\n");
return -1;
}
sc_file_free(file);
if (opt_pin_num >= 0)
return verify_pin(opt_pin_num);
else
return 0;
}
static void invert_buf(u8 *dest, const u8 *src, size_t c)
{
size_t i;
for (i = 0; i < c; i++)
dest[i] = src[c-1-i];
}
static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num)
{
u8 tmp[512];
invert_buf(tmp, buf, bufsize);
return BN_bin2bn(tmp, bufsize, num);
}
static int bn2cf(const BIGNUM *num, u8 *buf)
{
u8 tmp[512];
int r;
r = BN_bn2bin(num, tmp);
if (r <= 0)
return r;
invert_buf(buf, tmp, r);
return r;
}
static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *n, *e;
int base;
base = (keysize - 7) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid public key.\n");
return -1;
}
p += 3;
n = BN_new();
if (n == NULL)
return -1;
cf2bn(p, 2 * base, n);
p += 2 * base;
p += base;
p += 2 * base;
e = BN_new();
if (e == NULL)
return -1;
cf2bn(p, 4, e);
if (RSA_set0_key(rsa, n, e, NULL) != 1)
return -1;
return 0;
}
static int gen_d(RSA *rsa)
{
BN_CTX *bnctx;
BIGNUM *r0, *r1, *r2;
const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d;
BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new;
bnctx = BN_CTX_new();
if (bnctx == NULL)
return -1;
BN_CTX_start(bnctx);
r0 = BN_CTX_get(bnctx);
r1 = BN_CTX_get(bnctx);
r2 = BN_CTX_get(bnctx);
RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d);
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
BN_sub(r1, rsa_p, BN_value_one());
BN_sub(r2, rsa_q, BN_value_one());
BN_mul(r0, r1, r2, bnctx);
if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) {
fprintf(stderr, "BN_mod_inverse() failed.\n");
return -1;
}
/* RSA_set0_key will free previous value, and replace with new value
* Thus the need to copy the contents of rsa_n and rsa_e
*/
rsa_n_new = BN_dup(rsa_n);
rsa_e_new = BN_dup(rsa_e);
if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1)
return -1;
BN_CTX_end(bnctx);
BN_CTX_free(bnctx);
return 0;
}
static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa)
{
const u8 *p = key;
BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp;
int base;
base = (keysize - 3) / 5;
if (base != 32 && base != 48 && base != 64 && base != 128) {
fprintf(stderr, "Invalid private key.\n");
return -1;
}
p += 3;
bn_p = BN_new();
if (bn_p == NULL)
return -1;
cf2bn(p, base, bn_p);
p += base;
q = BN_new();
if (q == NULL)
return -1;
cf2bn(p, base, q);
p += base;
iqmp = BN_new();
if (iqmp == NULL)
return -1;
cf2bn(p, base, iqmp);
p += base;
dmp1 = BN_new();
if (dmp1 == NULL)
return -1;
cf2bn(p, base, dmp1);
p += base;
dmq1 = BN_new();
if (dmq1 == NULL)
return -1;
cf2bn(p, base, dmq1);
p += base;
if (RSA_set0_factors(rsa, bn_p, q) != 1)
return -1;
if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1)
return -1;
if (gen_d(rsa))
return -1;
return 0;
}
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
static int read_private_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
const sc_acl_entry_t *e;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
e = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (e == NULL || e->method == SC_AC_NEVER)
return 10;
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_private_key(p, keysize, rsa);
}
static int read_key(void)
{
RSA *rsa = RSA_new();
u8 buf[1024], *p = buf;
u8 b64buf[2048];
int r;
if (rsa == NULL)
return -1;
r = read_public_key(rsa);
if (r)
return r;
r = i2d_RSA_PUBKEY(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding public key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf);
r = read_private_key(rsa);
if (r == 10)
return 0;
else if (r)
return r;
p = buf;
r = i2d_RSAPrivateKey(rsa, &p);
if (r <= 0) {
fprintf(stderr, "Error encoding private key.\n");
return -1;
}
r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64);
if (r < 0) {
fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r));
return -1;
}
printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf);
return 0;
}
static int list_keys(void)
{
int r, idx = 0;
sc_path_t path;
u8 buf[2048], *p = buf;
size_t keysize, i;
int mod_lens[] = { 512, 768, 1024, 2048 };
size_t sizes[] = { 167, 247, 327, 647 };
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
do {
int mod_len = -1;
r = sc_read_binary(card, idx, buf, 3, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
idx += keysize;
for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++)
if (sizes[i] == keysize)
mod_len = mod_lens[i];
if (mod_len < 0)
printf("Key %d -- unknown modulus length\n", p[2] & 0x0F);
else
printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len);
} while (1);
return 0;
}
static int generate_key(void)
{
sc_apdu_t apdu;
u8 sbuf[4];
u8 p2;
int r;
switch (opt_mod_length) {
case 512:
p2 = 0x40;
break;
case 768:
p2 = 0x60;
break;
case 1024:
p2 = 0x80;
break;
case 2048:
p2 = 0x00;
break;
default:
fprintf(stderr, "Invalid modulus length.\n");
return 2;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2);
apdu.cla = 0xF0;
apdu.lc = 4;
apdu.datalen = 4;
apdu.data = sbuf;
sbuf[0] = opt_exponent & 0xFF;
sbuf[1] = (opt_exponent >> 8) & 0xFF;
sbuf[2] = (opt_exponent >> 16) & 0xFF;
sbuf[3] = (opt_exponent >> 24) & 0xFF;
r = select_app_df();
if (r)
return 1;
if (verbose)
printf("Generating key...\n");
r = sc_transmit_apdu(card, &apdu);
if (r) {
fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r));
if (r == SC_ERROR_TRANSMIT_FAILED)
fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n"
"succeeded.\n");
return 1;
}
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
printf("Key generation successful.\n");
return 0;
}
if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82)
fprintf(stderr, "CHV1 not verified or invalid exponent value.\n");
else
fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2);
return 1;
}
static int create_key_files(void)
{
sc_file_t *file;
int mod_lens[] = { 512, 768, 1024, 2048 };
int sizes[] = { 163, 243, 323, 643 };
int size = -1;
int r;
size_t i;
for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++)
if (mod_lens[i] == opt_mod_length) {
size = sizes[i];
break;
}
if (size == -1) {
fprintf(stderr, "Invalid modulus length.\n");
return 1;
}
if (verbose)
printf("Creating key files for %d keys.\n", opt_key_count);
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x0012;
file->size = opt_key_count * size + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r));
return 1;
}
file = sc_file_new();
if (!file) {
fprintf(stderr, "out of memory.\n");
return 1;
}
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
file->id = 0x1012;
file->size = opt_key_count * (size + 4) + 3;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1);
if (select_app_df()) {
sc_file_free(file);
return 1;
}
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Key files generated successfully.\n");
return 0;
}
static int read_rsa_privkey(RSA **rsa_out)
{
RSA *rsa = NULL;
BIO *in = NULL;
int r;
in = BIO_new(BIO_s_file());
if (opt_prkeyf == NULL) {
fprintf(stderr, "Private key file must be set.\n");
return 2;
}
r = BIO_read_filename(in, opt_prkeyf);
if (r <= 0) {
perror(opt_prkeyf);
return 2;
}
rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL);
if (rsa == NULL) {
fprintf(stderr, "Unable to load private key.\n");
return 2;
}
BIO_free(in);
*rsa_out = rsa;
return 0;
}
static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 3) >> 8;
*p++ = (5 * base + 3) & 0xFF;
*p++ = opt_key_num;
RSA_get0_factors(rsa, &rsa_p, &rsa_q);
r = bn2cf(rsa_p, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_q, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp);
r = bn2cf(rsa_iqmp, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmp1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
r = bn2cf(rsa_dmq1, bnbuf);
if (r != base) {
fprintf(stderr, "Invalid private key.\n");
return 2;
}
memcpy(p, bnbuf, base);
p += base;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize)
{
u8 buf[1024], *p = buf;
u8 bnbuf[256];
int base = 0;
int r;
const BIGNUM *rsa_n, *rsa_e;
switch (RSA_bits(rsa)) {
case 512:
base = 32;
break;
case 768:
base = 48;
break;
case 1024:
base = 64;
break;
case 2048:
base = 128;
break;
}
if (base == 0) {
fprintf(stderr, "Key length invalid.\n");
return 2;
}
*p++ = (5 * base + 7) >> 8;
*p++ = (5 * base + 7) & 0xFF;
*p++ = opt_key_num;
RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL);
r = bn2cf(rsa_n, bnbuf);
if (r != 2*base) {
fprintf(stderr, "Invalid public key.\n");
return 2;
}
memcpy(p, bnbuf, 2*base);
p += 2*base;
memset(p, 0, base);
p += base;
memset(bnbuf, 0, 2*base);
memcpy(p, bnbuf, 2*base);
p += 2*base;
r = bn2cf(rsa_e, bnbuf);
memcpy(p, bnbuf, 4);
p += 4;
memcpy(key, buf, p - buf);
*keysize = p - buf;
return 0;
}
static int update_public_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int update_private_key(const u8 *key, size_t keysize)
{
int r, idx = 0;
sc_path_t path;
r = select_app_df();
if (r)
return 1;
sc_format_path("I0012", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r));
return 2;
}
idx = keysize * (opt_key_num-1);
r = sc_update_binary(card, idx, key, keysize, 0);
if (r < 0) {
fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r));
return 2;
}
return 0;
}
static int store_key(void)
{
u8 prv[1024], pub[1024];
size_t prvsize, pubsize;
int r;
RSA *rsa;
r = read_rsa_privkey(&rsa);
if (r)
return r;
r = encode_private_key(rsa, prv, &prvsize);
if (r)
return r;
r = encode_public_key(rsa, pub, &pubsize);
if (r)
return r;
if (verbose)
printf("Storing private key...\n");
r = select_app_df();
if (r)
return r;
r = update_private_key(prv, prvsize);
if (r)
return r;
if (verbose)
printf("Storing public key...\n");
r = select_app_df();
if (r)
return r;
r = update_public_key(pub, pubsize);
if (r)
return r;
return 0;
}
static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id)
{
char prompt[40], *pin, *puk;
char buf[30], *p = buf;
sc_path_t file_id, path;
sc_file_t *file;
size_t len;
int r;
file_id = *inpath;
if (file_id.len < 2)
return -1;
if (chv == 1)
sc_format_path("I0000", &file_id);
else if (chv == 2)
sc_format_path("I0100", &file_id);
else
return -1;
r = sc_select_file(card, inpath, NULL);
if (r)
return -1;
r = sc_select_file(card, &file_id, NULL);
if (r == 0)
return 0;
sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id);
pin = getpin(prompt);
if (pin == NULL)
return -1;
sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id);
puk = getpin(prompt);
if (puk == NULL) {
free(pin);
return -1;
}
memset(p, 0xFF, 3);
p += 3;
memcpy(p, pin, 8);
p += 8;
*p++ = opt_pin_attempts;
*p++ = opt_pin_attempts;
memcpy(p, puk, 8);
p += 8;
*p++ = opt_puk_attempts;
*p++ = opt_puk_attempts;
len = p - buf;
free(pin);
free(puk);
file = sc_file_new();
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE);
if (inpath->len == 2 && inpath->value[0] == 0x3F &&
inpath->value[1] == 0x00)
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1);
else
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1);
file->size = len;
file->id = (file_id.value[0] << 8) | file_id.value[1];
r = sc_create_file(card, file);
sc_file_free(file);
if (r) {
fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r));
return r;
}
path = *inpath;
sc_append_path(&path, &file_id);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r));
return r;
}
r = sc_update_binary(card, 0, (const u8 *) buf, len, 0);
if (r < 0) {
fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r));
return r;
}
return 0;
}
static int create_pin(void)
{
sc_path_t path;
char buf[80];
if (opt_pin_num != 1 && opt_pin_num != 2) {
fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n");
return 2;
}
strcpy(buf, "3F00");
if (opt_appdf != NULL)
strlcat(buf, opt_appdf, sizeof buf);
sc_format_path(buf, &path);
return create_pin_file(&path, opt_pin_num, "");
}
int main(int argc, char *argv[])
{
int err = 0, r, c, long_optind = 0;
int action_count = 0;
int do_read_key = 0;
int do_generate_key = 0;
int do_create_key_files = 0;
int do_list_keys = 0;
int do_store_key = 0;
int do_create_pin_file = 0;
sc_context_param_t ctx_param;
while (1) {
c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind);
if (c == -1)
break;
if (c == '?')
util_print_usage_and_die(app_name, options, option_help, NULL);
switch (c) {
case 'l':
do_list_keys = 1;
action_count++;
break;
case 'P':
do_create_pin_file = 1;
opt_pin_num = atoi(optarg);
action_count++;
break;
case 'R':
do_read_key = 1;
action_count++;
break;
case 'g':
do_generate_key = 1;
action_count++;
break;
case 'c':
do_create_key_files = 1;
opt_key_count = atoi(optarg);
action_count++;
break;
case 's':
do_store_key = 1;
action_count++;
break;
case 'k':
opt_key_num = atoi(optarg);
if (opt_key_num < 1 || opt_key_num > 15) {
fprintf(stderr, "Key number invalid.\n");
exit(2);
}
break;
case 'V':
opt_pin_num = 1;
break;
case 'e':
opt_exponent = atoi(optarg);
break;
case 'm':
opt_mod_length = atoi(optarg);
break;
case 'p':
opt_prkeyf = optarg;
break;
case 'u':
opt_pubkeyf = optarg;
break;
case 'r':
opt_reader = optarg;
break;
case 'v':
verbose++;
break;
case 'w':
opt_wait = 1;
break;
case 'a':
opt_appdf = optarg;
break;
}
}
if (action_count == 0)
util_print_usage_and_die(app_name, options, option_help, NULL);
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
ctx_param.app_name = app_name;
r = sc_context_create(&ctx, &ctx_param);
if (r) {
fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
return 1;
}
if (verbose > 1) {
ctx->debug = verbose;
sc_ctx_log_to_file(ctx, "stderr");
}
err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose);
printf("Using card driver: %s\n", card->driver->name);
if (do_create_pin_file) {
if ((err = create_pin()) != 0)
goto end;
action_count--;
}
if (do_create_key_files) {
if ((err = create_key_files()) != 0)
goto end;
action_count--;
}
if (do_generate_key) {
if ((err = generate_key()) != 0)
goto end;
action_count--;
}
if (do_store_key) {
if ((err = store_key()) != 0)
goto end;
action_count--;
}
if (do_list_keys) {
if ((err = list_keys()) != 0)
goto end;
action_count--;
}
if (do_read_key) {
if ((err = read_key()) != 0)
goto end;
action_count--;
}
if (pincode != NULL) {
memset(pincode, 0, 8);
free(pincode);
}
end:
if (card) {
sc_unlock(card);
sc_disconnect_card(card);
}
if (ctx)
sc_release_context(ctx);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_346_8 |
crossvul-cpp_data_bad_730_0 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2014, STMicroelectronics International N.V.
*/
#include <assert.h>
#include <crypto/crypto.h>
#include <kernel/tee_ta_manager.h>
#include <mm/tee_mmu.h>
#include <string_ext.h>
#include <string.h>
#include <sys/queue.h>
#include <tee_api_types.h>
#include <tee/tee_cryp_utl.h>
#include <tee/tee_obj.h>
#include <tee/tee_svc_cryp.h>
#include <tee/tee_svc.h>
#include <trace.h>
#include <utee_defines.h>
#include <util.h>
#include <tee_api_defines_extensions.h>
#if defined(CFG_CRYPTO_HKDF)
#include <tee/tee_cryp_hkdf.h>
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
#include <tee/tee_cryp_concat_kdf.h>
#endif
#if defined(CFG_CRYPTO_PBKDF2)
#include <tee/tee_cryp_pbkdf2.h>
#endif
typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo);
struct tee_cryp_state {
TAILQ_ENTRY(tee_cryp_state) link;
uint32_t algo;
uint32_t mode;
vaddr_t key1;
vaddr_t key2;
void *ctx;
tee_cryp_ctx_finalize_func_t ctx_finalize;
};
struct tee_cryp_obj_secret {
uint32_t key_size;
uint32_t alloc_size;
/*
* Pseudo code visualize layout of structure
* Next follows data, such as:
* uint8_t data[alloc_size]
* key_size must never exceed alloc_size
*/
};
#define TEE_TYPE_ATTR_OPTIONAL 0x0
#define TEE_TYPE_ATTR_REQUIRED 0x1
#define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2
#define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4
#define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8
#define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10
/* Handle storing of generic secret keys of varying lengths */
#define ATTR_OPS_INDEX_SECRET 0
/* Convert to/from big-endian byte array and provider-specific bignum */
#define ATTR_OPS_INDEX_BIGNUM 1
/* Convert to/from value attribute depending on direction */
#define ATTR_OPS_INDEX_VALUE 2
struct tee_cryp_obj_type_attrs {
uint32_t attr_id;
uint16_t flags;
uint16_t ops_index;
uint16_t raw_offs;
uint16_t raw_size;
};
#define RAW_DATA(_x, _y) \
.raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_secret_value_attrs[] = {
{
.attr_id = TEE_ATTR_SECRET_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = {
{
.attr_id = TEE_ATTR_RSA_MODULUS,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_public_key, n)
},
{
.attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_public_key, e)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_RSA_MODULUS,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, n)
},
{
.attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, e)
},
{
.attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, d)
},
{
.attr_id = TEE_ATTR_RSA_PRIME1,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, p)
},
{
.attr_id = TEE_ATTR_RSA_PRIME2,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, q)
},
{
.attr_id = TEE_ATTR_RSA_EXPONENT1,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, dp)
},
{
.attr_id = TEE_ATTR_RSA_EXPONENT2,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, dq)
},
{
.attr_id = TEE_ATTR_RSA_COEFFICIENT,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct rsa_keypair, qp)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = {
{
.attr_id = TEE_ATTR_DSA_PRIME,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, p)
},
{
.attr_id = TEE_ATTR_DSA_SUBPRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, q)
},
{
.attr_id = TEE_ATTR_DSA_BASE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, g)
},
{
.attr_id = TEE_ATTR_DSA_PUBLIC_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_public_key, y)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_DSA_PRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, p)
},
{
.attr_id = TEE_ATTR_DSA_SUBPRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR |
TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, q)
},
{
.attr_id = TEE_ATTR_DSA_BASE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, g)
},
{
.attr_id = TEE_ATTR_DSA_PRIVATE_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, x)
},
{
.attr_id = TEE_ATTR_DSA_PUBLIC_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dsa_keypair, y)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_DH_PRIME,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR |
TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, p)
},
{
.attr_id = TEE_ATTR_DH_BASE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, g)
},
{
.attr_id = TEE_ATTR_DH_PUBLIC_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, y)
},
{
.attr_id = TEE_ATTR_DH_PRIVATE_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, x)
},
{
.attr_id = TEE_ATTR_DH_SUBPRIME,
.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct dh_keypair, q)
},
{
.attr_id = TEE_ATTR_DH_X_BITS,
.flags = TEE_TYPE_ATTR_GEN_KEY_OPT,
.ops_index = ATTR_OPS_INDEX_VALUE,
RAW_DATA(struct dh_keypair, xbits)
},
};
#if defined(CFG_CRYPTO_HKDF)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_hkdf_ikm_attrs[] = {
{
.attr_id = TEE_ATTR_HKDF_IKM,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_concat_kdf_z_attrs[] = {
{
.attr_id = TEE_ATTR_CONCAT_KDF_Z,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
#endif
#if defined(CFG_CRYPTO_PBKDF2)
static const struct tee_cryp_obj_type_attrs
tee_cryp_obj_pbkdf2_passwd_attrs[] = {
{
.attr_id = TEE_ATTR_PBKDF2_PASSWORD,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_SECRET,
.raw_offs = 0,
.raw_size = 0
},
};
#endif
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = {
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_public_key, x)
},
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_public_key, y)
},
{
.attr_id = TEE_ATTR_ECC_CURVE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_VALUE,
RAW_DATA(struct ecc_public_key, curve)
},
};
static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = {
{
.attr_id = TEE_ATTR_ECC_PRIVATE_VALUE,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_keypair, d)
},
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_keypair, x)
},
{
.attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y,
.flags = TEE_TYPE_ATTR_REQUIRED,
.ops_index = ATTR_OPS_INDEX_BIGNUM,
RAW_DATA(struct ecc_keypair, y)
},
{
.attr_id = TEE_ATTR_ECC_CURVE,
.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
.ops_index = ATTR_OPS_INDEX_VALUE,
RAW_DATA(struct ecc_keypair, curve)
},
};
struct tee_cryp_obj_type_props {
TEE_ObjectType obj_type;
uint16_t min_size; /* may not be smaller than this */
uint16_t max_size; /* may not be larger than this */
uint16_t alloc_size; /* this many bytes are allocated to hold data */
uint8_t quanta; /* may only be an multiple of this */
uint8_t num_type_attrs;
const struct tee_cryp_obj_type_attrs *type_attrs;
};
#define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \
{ (obj_type), (min_size), (max_size), (alloc_size), (quanta), \
ARRAY_SIZE(type_attrs), (type_attrs) }
static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = {
PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */
256 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_DES, 56, 56, 56,
/*
* Valid size 56 without parity, note that we still allocate
* for 64 bits since the key is supplied with parity.
*/
64 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_DES3, 56, 112, 168,
/*
* Valid sizes 112, 168 without parity, note that we still
* allocate for with space for the parity since the key is
* supplied with parity.
*/
192 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512,
512 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512,
512 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512,
512 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024,
1024 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024,
1024 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024,
1024 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_secret_value_attrs),
#if defined(CFG_CRYPTO_HKDF)
PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_hkdf_ikm_attrs),
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_concat_kdf_z_attrs),
#endif
#if defined(CFG_CRYPTO_PBKDF2)
PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096,
4096 / 8 + sizeof(struct tee_cryp_obj_secret),
tee_cryp_obj_pbkdf2_passwd_attrs),
#endif
PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS,
sizeof(struct rsa_public_key),
tee_cryp_obj_rsa_pub_key_attrs),
PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS,
sizeof(struct rsa_keypair),
tee_cryp_obj_rsa_keypair_attrs),
PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072,
sizeof(struct dsa_public_key),
tee_cryp_obj_dsa_pub_key_attrs),
PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072,
sizeof(struct dsa_keypair),
tee_cryp_obj_dsa_keypair_attrs),
PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048,
sizeof(struct dh_keypair),
tee_cryp_obj_dh_keypair_attrs),
PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521,
sizeof(struct ecc_public_key),
tee_cryp_obj_ecc_pub_key_attrs),
PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521,
sizeof(struct ecc_keypair),
tee_cryp_obj_ecc_keypair_attrs),
PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521,
sizeof(struct ecc_public_key),
tee_cryp_obj_ecc_pub_key_attrs),
PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521,
sizeof(struct ecc_keypair),
tee_cryp_obj_ecc_keypair_attrs),
};
struct attr_ops {
TEE_Result (*from_user)(void *attr, const void *buffer, size_t size);
TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess,
void *buffer, uint64_t *size);
TEE_Result (*to_binary)(void *attr, void *data, size_t data_len,
size_t *offs);
bool (*from_binary)(void *attr, const void *data, size_t data_len,
size_t *offs);
TEE_Result (*from_obj)(void *attr, void *src_attr);
void (*free)(void *attr);
void (*clear)(void *attr);
};
static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data,
size_t data_len, size_t *offs)
{
uint32_t field;
size_t next_offs;
if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs))
return TEE_ERROR_OVERFLOW;
if (data && next_offs <= data_len) {
field = TEE_U32_TO_BIG_ENDIAN(v);
memcpy(data + *offs, &field, sizeof(field));
}
(*offs) = next_offs;
return TEE_SUCCESS;
}
static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data,
size_t data_len, size_t *offs)
{
uint32_t field;
if (!data || (*offs + sizeof(field)) > data_len)
return false;
memcpy(&field, data + *offs, sizeof(field));
*v = TEE_U32_FROM_BIG_ENDIAN(field);
(*offs) += sizeof(field);
return true;
}
static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer,
size_t size)
{
struct tee_cryp_obj_secret *key = attr;
/* Data size has to fit in allocated buffer */
if (size > key->alloc_size)
return TEE_ERROR_SECURITY;
memcpy(key + 1, buffer, size);
key->key_size = size;
return TEE_SUCCESS;
}
static TEE_Result op_attr_secret_value_to_user(void *attr,
struct tee_ta_session *sess __unused,
void *buffer, uint64_t *size)
{
TEE_Result res;
struct tee_cryp_obj_secret *key = attr;
uint64_t s;
uint64_t key_size;
res = tee_svc_copy_from_user(&s, size, sizeof(s));
if (res != TEE_SUCCESS)
return res;
key_size = key->key_size;
res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size));
if (res != TEE_SUCCESS)
return res;
if (s < key->key_size || !buffer)
return TEE_ERROR_SHORT_BUFFER;
return tee_svc_copy_to_user(buffer, key + 1, key->key_size);
}
static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data,
size_t data_len, size_t *offs)
{
TEE_Result res;
struct tee_cryp_obj_secret *key = attr;
size_t next_offs;
res = op_u32_to_binary_helper(key->key_size, data, data_len, offs);
if (res != TEE_SUCCESS)
return res;
if (ADD_OVERFLOW(*offs, key->key_size, &next_offs))
return TEE_ERROR_OVERFLOW;
if (data && next_offs <= data_len)
memcpy((uint8_t *)data + *offs, key + 1, key->key_size);
(*offs) = next_offs;
return TEE_SUCCESS;
}
static bool op_attr_secret_value_from_binary(void *attr, const void *data,
size_t data_len, size_t *offs)
{
struct tee_cryp_obj_secret *key = attr;
uint32_t s;
if (!op_u32_from_binary_helper(&s, data, data_len, offs))
return false;
if ((*offs + s) > data_len)
return false;
/* Data size has to fit in allocated buffer */
if (s > key->alloc_size)
return false;
key->key_size = s;
memcpy(key + 1, (const uint8_t *)data + *offs, s);
(*offs) += s;
return true;
}
static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr)
{
struct tee_cryp_obj_secret *key = attr;
struct tee_cryp_obj_secret *src_key = src_attr;
if (src_key->key_size > key->alloc_size)
return TEE_ERROR_BAD_STATE;
memcpy(key + 1, src_key + 1, src_key->key_size);
key->key_size = src_key->key_size;
return TEE_SUCCESS;
}
static void op_attr_secret_value_clear(void *attr)
{
struct tee_cryp_obj_secret *key = attr;
key->key_size = 0;
memset(key + 1, 0, key->alloc_size);
}
static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer,
size_t size)
{
struct bignum **bn = attr;
return crypto_bignum_bin2bn(buffer, size, *bn);
}
static TEE_Result op_attr_bignum_to_user(void *attr,
struct tee_ta_session *sess,
void *buffer, uint64_t *size)
{
TEE_Result res;
struct bignum **bn = attr;
uint64_t req_size;
uint64_t s;
res = tee_svc_copy_from_user(&s, size, sizeof(s));
if (res != TEE_SUCCESS)
return res;
req_size = crypto_bignum_num_bytes(*bn);
res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size));
if (res != TEE_SUCCESS)
return res;
if (!req_size)
return TEE_SUCCESS;
if (s < req_size || !buffer)
return TEE_ERROR_SHORT_BUFFER;
/* Check we can access data using supplied user mode pointer */
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)buffer, req_size);
if (res != TEE_SUCCESS)
return res;
/*
* Write the bignum (wich raw data points to) into an array of
* bytes (stored in buffer)
*/
crypto_bignum_bn2bin(*bn, buffer);
return TEE_SUCCESS;
}
static TEE_Result op_attr_bignum_to_binary(void *attr, void *data,
size_t data_len, size_t *offs)
{
TEE_Result res;
struct bignum **bn = attr;
uint32_t n = crypto_bignum_num_bytes(*bn);
size_t next_offs;
res = op_u32_to_binary_helper(n, data, data_len, offs);
if (res != TEE_SUCCESS)
return res;
if (ADD_OVERFLOW(*offs, n, &next_offs))
return TEE_ERROR_OVERFLOW;
if (data && next_offs <= data_len)
crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs);
(*offs) = next_offs;
return TEE_SUCCESS;
}
static bool op_attr_bignum_from_binary(void *attr, const void *data,
size_t data_len, size_t *offs)
{
struct bignum **bn = attr;
uint32_t n;
if (!op_u32_from_binary_helper(&n, data, data_len, offs))
return false;
if ((*offs + n) > data_len)
return false;
if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn))
return false;
(*offs) += n;
return true;
}
static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr)
{
struct bignum **bn = attr;
struct bignum **src_bn = src_attr;
crypto_bignum_copy(*bn, *src_bn);
return TEE_SUCCESS;
}
static void op_attr_bignum_clear(void *attr)
{
struct bignum **bn = attr;
crypto_bignum_clear(*bn);
}
static void op_attr_bignum_free(void *attr)
{
struct bignum **bn = attr;
crypto_bignum_free(*bn);
*bn = NULL;
}
static TEE_Result op_attr_value_from_user(void *attr, const void *buffer,
size_t size)
{
uint32_t *v = attr;
if (size != sizeof(uint32_t) * 2)
return TEE_ERROR_GENERIC; /* "can't happen */
/* Note that only the first value is copied */
memcpy(v, buffer, sizeof(uint32_t));
return TEE_SUCCESS;
}
static TEE_Result op_attr_value_to_user(void *attr,
struct tee_ta_session *sess __unused,
void *buffer, uint64_t *size)
{
TEE_Result res;
uint32_t *v = attr;
uint64_t s;
uint32_t value[2] = { *v };
uint64_t req_size = sizeof(value);
res = tee_svc_copy_from_user(&s, size, sizeof(s));
if (res != TEE_SUCCESS)
return res;
if (s < req_size || !buffer)
return TEE_ERROR_SHORT_BUFFER;
return tee_svc_copy_to_user(buffer, value, req_size);
}
static TEE_Result op_attr_value_to_binary(void *attr, void *data,
size_t data_len, size_t *offs)
{
uint32_t *v = attr;
return op_u32_to_binary_helper(*v, data, data_len, offs);
}
static bool op_attr_value_from_binary(void *attr, const void *data,
size_t data_len, size_t *offs)
{
uint32_t *v = attr;
return op_u32_from_binary_helper(v, data, data_len, offs);
}
static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr)
{
uint32_t *v = attr;
uint32_t *src_v = src_attr;
*v = *src_v;
return TEE_SUCCESS;
}
static void op_attr_value_clear(void *attr)
{
uint32_t *v = attr;
*v = 0;
}
static const struct attr_ops attr_ops[] = {
[ATTR_OPS_INDEX_SECRET] = {
.from_user = op_attr_secret_value_from_user,
.to_user = op_attr_secret_value_to_user,
.to_binary = op_attr_secret_value_to_binary,
.from_binary = op_attr_secret_value_from_binary,
.from_obj = op_attr_secret_value_from_obj,
.free = op_attr_secret_value_clear, /* not a typo */
.clear = op_attr_secret_value_clear,
},
[ATTR_OPS_INDEX_BIGNUM] = {
.from_user = op_attr_bignum_from_user,
.to_user = op_attr_bignum_to_user,
.to_binary = op_attr_bignum_to_binary,
.from_binary = op_attr_bignum_from_binary,
.from_obj = op_attr_bignum_from_obj,
.free = op_attr_bignum_free,
.clear = op_attr_bignum_clear,
},
[ATTR_OPS_INDEX_VALUE] = {
.from_user = op_attr_value_from_user,
.to_user = op_attr_value_to_user,
.to_binary = op_attr_value_to_binary,
.from_binary = op_attr_value_from_binary,
.from_obj = op_attr_value_from_obj,
.free = op_attr_value_clear, /* not a typo */
.clear = op_attr_value_clear,
},
};
TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
goto exit;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
goto exit;
res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info));
exit:
return res;
}
TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj,
unsigned long usage)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
goto exit;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
goto exit;
o->info.objectUsage &= usage;
exit:
return res;
}
static int tee_svc_cryp_obj_find_type_attr_idx(
uint32_t attr_id,
const struct tee_cryp_obj_type_props *type_props)
{
size_t n;
for (n = 0; n < type_props->num_type_attrs; n++) {
if (attr_id == type_props->type_attrs[n].attr_id)
return n;
}
return -1;
}
static const struct tee_cryp_obj_type_props *tee_svc_find_type_props(
TEE_ObjectType obj_type)
{
size_t n;
for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) {
if (tee_cryp_obj_props[n].obj_type == obj_type)
return tee_cryp_obj_props + n;
}
return NULL;
}
/* Set an attribute on an object */
static void set_attribute(struct tee_obj *o,
const struct tee_cryp_obj_type_props *props,
uint32_t attr)
{
int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props);
if (idx < 0)
return;
o->have_attrs |= BIT(idx);
}
/* Get an attribute on an object */
static uint32_t get_attribute(const struct tee_obj *o,
const struct tee_cryp_obj_type_props *props,
uint32_t attr)
{
int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props);
if (idx < 0)
return 0;
return o->have_attrs & BIT(idx);
}
TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id,
void *buffer, uint64_t *size)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
int idx;
const struct attr_ops *ops;
void *attr;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return TEE_ERROR_ITEM_NOT_FOUND;
/* Check that the object is initialized */
if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED))
return TEE_ERROR_BAD_PARAMETERS;
/* Check that getting the attribute is allowed */
if (!(attr_id & TEE_ATTR_BIT_PROTECTED) &&
!(o->info.objectUsage & TEE_USAGE_EXTRACTABLE))
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props) {
/* Unknown object type, "can't happen" */
return TEE_ERROR_BAD_STATE;
}
idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props);
if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0))
return TEE_ERROR_ITEM_NOT_FOUND;
ops = attr_ops + type_props->type_attrs[idx].ops_index;
attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs;
return ops->to_user(attr, sess, buffer, size);
}
void tee_obj_attr_free(struct tee_obj *o)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
if (!o->attr)
return;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs);
}
}
void tee_obj_attr_clear(struct tee_obj *o)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
if (!o->attr)
return;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
attr_ops[ta->ops_index].clear((uint8_t *)o->attr +
ta->raw_offs);
}
}
TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data,
size_t *data_len)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
size_t offs = 0;
size_t len = data ? *data_len : 0;
TEE_Result res;
if (o->info.objectType == TEE_TYPE_DATA) {
*data_len = 0;
return TEE_SUCCESS; /* pure data object */
}
if (!o->attr)
return TEE_ERROR_BAD_STATE;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return TEE_ERROR_BAD_STATE;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
void *attr = (uint8_t *)o->attr + ta->raw_offs;
res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs);
if (res != TEE_SUCCESS)
return res;
}
*data_len = offs;
if (data && offs > len)
return TEE_ERROR_SHORT_BUFFER;
return TEE_SUCCESS;
}
TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data,
size_t data_len)
{
const struct tee_cryp_obj_type_props *tp;
size_t n;
size_t offs = 0;
if (o->info.objectType == TEE_TYPE_DATA)
return TEE_SUCCESS; /* pure data object */
if (!o->attr)
return TEE_ERROR_BAD_STATE;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return TEE_ERROR_BAD_STATE;
for (n = 0; n < tp->num_type_attrs; n++) {
const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n;
void *attr = (uint8_t *)o->attr + ta->raw_offs;
if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len,
&offs))
return TEE_ERROR_CORRUPT_OBJECT;
}
return TEE_SUCCESS;
}
TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src)
{
TEE_Result res;
const struct tee_cryp_obj_type_props *tp;
const struct tee_cryp_obj_type_attrs *ta;
size_t n;
uint32_t have_attrs = 0;
void *attr;
void *src_attr;
if (o->info.objectType == TEE_TYPE_DATA)
return TEE_SUCCESS; /* pure data object */
if (!o->attr)
return TEE_ERROR_BAD_STATE;
tp = tee_svc_find_type_props(o->info.objectType);
if (!tp)
return TEE_ERROR_BAD_STATE;
if (o->info.objectType == src->info.objectType) {
have_attrs = src->have_attrs;
for (n = 0; n < tp->num_type_attrs; n++) {
ta = tp->type_attrs + n;
attr = (uint8_t *)o->attr + ta->raw_offs;
src_attr = (uint8_t *)src->attr + ta->raw_offs;
res = attr_ops[ta->ops_index].from_obj(attr, src_attr);
if (res != TEE_SUCCESS)
return res;
}
} else {
const struct tee_cryp_obj_type_props *tp_src;
int idx;
if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) {
if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR)
return TEE_ERROR_BAD_PARAMETERS;
} else {
return TEE_ERROR_BAD_PARAMETERS;
}
tp_src = tee_svc_find_type_props(src->info.objectType);
if (!tp_src)
return TEE_ERROR_BAD_STATE;
have_attrs = BIT32(tp->num_type_attrs) - 1;
for (n = 0; n < tp->num_type_attrs; n++) {
ta = tp->type_attrs + n;
idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id,
tp_src);
if (idx < 0)
return TEE_ERROR_BAD_STATE;
attr = (uint8_t *)o->attr + ta->raw_offs;
src_attr = (uint8_t *)src->attr +
tp_src->type_attrs[idx].raw_offs;
res = attr_ops[ta->ops_index].from_obj(attr, src_attr);
if (res != TEE_SUCCESS)
return res;
}
}
o->have_attrs = have_attrs;
return TEE_SUCCESS;
}
TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type,
size_t max_key_size)
{
TEE_Result res = TEE_SUCCESS;
const struct tee_cryp_obj_type_props *type_props;
/* Can only set type for newly allocated objs */
if (o->attr)
return TEE_ERROR_BAD_STATE;
/*
* Verify that maxKeySize is supported and find out how
* much should be allocated.
*/
if (obj_type == TEE_TYPE_DATA) {
if (max_key_size)
return TEE_ERROR_NOT_SUPPORTED;
} else {
/* Find description of object */
type_props = tee_svc_find_type_props(obj_type);
if (!type_props)
return TEE_ERROR_NOT_SUPPORTED;
/* Check that maxKeySize follows restrictions */
if (max_key_size % type_props->quanta != 0)
return TEE_ERROR_NOT_SUPPORTED;
if (max_key_size < type_props->min_size)
return TEE_ERROR_NOT_SUPPORTED;
if (max_key_size > type_props->max_size)
return TEE_ERROR_NOT_SUPPORTED;
o->attr = calloc(1, type_props->alloc_size);
if (!o->attr)
return TEE_ERROR_OUT_OF_MEMORY;
}
/* If we have a key structure, pre-allocate the bignums inside */
switch (obj_type) {
case TEE_TYPE_RSA_PUBLIC_KEY:
res = crypto_acipher_alloc_rsa_public_key(o->attr,
max_key_size);
break;
case TEE_TYPE_RSA_KEYPAIR:
res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size);
break;
case TEE_TYPE_DSA_PUBLIC_KEY:
res = crypto_acipher_alloc_dsa_public_key(o->attr,
max_key_size);
break;
case TEE_TYPE_DSA_KEYPAIR:
res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size);
break;
case TEE_TYPE_DH_KEYPAIR:
res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size);
break;
case TEE_TYPE_ECDSA_PUBLIC_KEY:
case TEE_TYPE_ECDH_PUBLIC_KEY:
res = crypto_acipher_alloc_ecc_public_key(o->attr,
max_key_size);
break;
case TEE_TYPE_ECDSA_KEYPAIR:
case TEE_TYPE_ECDH_KEYPAIR:
res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size);
break;
default:
if (obj_type != TEE_TYPE_DATA) {
struct tee_cryp_obj_secret *key = o->attr;
key->alloc_size = type_props->alloc_size -
sizeof(*key);
}
break;
}
if (res != TEE_SUCCESS)
return res;
o->info.objectType = obj_type;
o->info.maxKeySize = max_key_size;
o->info.objectUsage = TEE_USAGE_DEFAULT;
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type,
unsigned long max_key_size, uint32_t *obj)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
if (obj_type == TEE_TYPE_DATA)
return TEE_ERROR_NOT_SUPPORTED;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
o = tee_obj_alloc();
if (!o)
return TEE_ERROR_OUT_OF_MEMORY;
res = tee_obj_set_type(o, obj_type, max_key_size);
if (res != TEE_SUCCESS) {
tee_obj_free(o);
return res;
}
tee_obj_add(to_user_ta_ctx(sess->ctx), o);
res = tee_svc_copy_kaddr_to_uref(obj, o);
if (res != TEE_SUCCESS)
tee_obj_close(to_user_ta_ctx(sess->ctx), o);
return res;
}
TEE_Result syscall_cryp_obj_close(unsigned long obj)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/*
* If it's busy it's used by an operation, a client should never have
* this handle.
*/
if (o->busy)
return TEE_ERROR_ITEM_NOT_FOUND;
tee_obj_close(to_user_ta_ctx(sess->ctx), o);
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_obj_reset(unsigned long obj)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) {
tee_obj_attr_clear(o);
o->info.keySize = 0;
o->info.objectUsage = TEE_USAGE_DEFAULT;
} else {
return TEE_ERROR_BAD_PARAMETERS;
}
/* the object is no more initialized */
o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED;
return TEE_SUCCESS;
}
static TEE_Result copy_in_attrs(struct user_ta_ctx *utc,
const struct utee_attribute *usr_attrs,
uint32_t attr_count, TEE_Attribute *attrs)
{
TEE_Result res;
uint32_t n;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)usr_attrs,
attr_count * sizeof(struct utee_attribute));
if (res != TEE_SUCCESS)
return res;
for (n = 0; n < attr_count; n++) {
attrs[n].attributeID = usr_attrs[n].attribute_id;
if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) {
attrs[n].content.value.a = usr_attrs[n].a;
attrs[n].content.value.b = usr_attrs[n].b;
} else {
uintptr_t buf = usr_attrs[n].a;
size_t len = usr_attrs[n].b;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER, buf, len);
if (res != TEE_SUCCESS)
return res;
attrs[n].content.ref.buffer = (void *)buf;
attrs[n].content.ref.length = len;
}
}
return TEE_SUCCESS;
}
enum attr_usage {
ATTR_USAGE_POPULATE,
ATTR_USAGE_GENERATE_KEY
};
static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage,
const struct tee_cryp_obj_type_props
*type_props,
const TEE_Attribute *attrs,
uint32_t attr_count)
{
uint32_t required_flag;
uint32_t opt_flag;
bool all_opt_needed;
uint32_t req_attrs = 0;
uint32_t opt_grp_attrs = 0;
uint32_t attrs_found = 0;
size_t n;
uint32_t bit;
uint32_t flags;
int idx;
if (usage == ATTR_USAGE_POPULATE) {
required_flag = TEE_TYPE_ATTR_REQUIRED;
opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP;
all_opt_needed = true;
} else {
required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ;
opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT;
all_opt_needed = false;
}
/*
* First find out which attributes are required and which belong to
* the optional group
*/
for (n = 0; n < type_props->num_type_attrs; n++) {
bit = 1 << n;
flags = type_props->type_attrs[n].flags;
if (flags & required_flag)
req_attrs |= bit;
else if (flags & opt_flag)
opt_grp_attrs |= bit;
}
/*
* Verify that all required attributes are in place and
* that the same attribute isn't repeated.
*/
for (n = 0; n < attr_count; n++) {
idx = tee_svc_cryp_obj_find_type_attr_idx(
attrs[n].attributeID,
type_props);
/* attribute not defined in current object type */
if (idx < 0)
return TEE_ERROR_ITEM_NOT_FOUND;
bit = 1 << idx;
/* attribute not repeated */
if ((attrs_found & bit) != 0)
return TEE_ERROR_ITEM_NOT_FOUND;
attrs_found |= bit;
}
/* Required attribute missing */
if ((attrs_found & req_attrs) != req_attrs)
return TEE_ERROR_ITEM_NOT_FOUND;
/*
* If the flag says that "if one of the optional attributes are included
* all of them has to be included" this must be checked.
*/
if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 &&
(attrs_found & opt_grp_attrs) != opt_grp_attrs)
return TEE_ERROR_ITEM_NOT_FOUND;
return TEE_SUCCESS;
}
static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size)
{
switch (curve) {
case TEE_ECC_CURVE_NIST_P192:
*key_size = 192;
break;
case TEE_ECC_CURVE_NIST_P224:
*key_size = 224;
break;
case TEE_ECC_CURVE_NIST_P256:
*key_size = 256;
break;
case TEE_ECC_CURVE_NIST_P384:
*key_size = 384;
break;
case TEE_ECC_CURVE_NIST_P521:
*key_size = 521;
break;
default:
return TEE_ERROR_NOT_SUPPORTED;
}
return TEE_SUCCESS;
}
static TEE_Result tee_svc_cryp_obj_populate_type(
struct tee_obj *o,
const struct tee_cryp_obj_type_props *type_props,
const TEE_Attribute *attrs,
uint32_t attr_count)
{
TEE_Result res;
uint32_t have_attrs = 0;
size_t obj_size = 0;
size_t n;
int idx;
const struct attr_ops *ops;
void *attr;
for (n = 0; n < attr_count; n++) {
idx = tee_svc_cryp_obj_find_type_attr_idx(
attrs[n].attributeID,
type_props);
/* attribute not defined in current object type */
if (idx < 0)
return TEE_ERROR_ITEM_NOT_FOUND;
have_attrs |= BIT32(idx);
ops = attr_ops + type_props->type_attrs[idx].ops_index;
attr = (uint8_t *)o->attr +
type_props->type_attrs[idx].raw_offs;
if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE)
res = ops->from_user(attr, &attrs[n].content.value,
sizeof(attrs[n].content.value));
else
res = ops->from_user(attr, attrs[n].content.ref.buffer,
attrs[n].content.ref.length);
if (res != TEE_SUCCESS)
return res;
/*
* First attr_idx signifies the attribute that gives the size
* of the object
*/
if (type_props->type_attrs[idx].flags &
TEE_TYPE_ATTR_SIZE_INDICATOR) {
/*
* For ECDSA/ECDH we need to translate curve into
* object size
*/
if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) {
res = get_ec_key_size(attrs[n].content.value.a,
&obj_size);
if (res != TEE_SUCCESS)
return res;
} else {
obj_size += (attrs[n].content.ref.length * 8);
}
}
}
/*
* We have to do it like this because the parity bits aren't counted
* when telling the size of the key in bits.
*/
if (o->info.objectType == TEE_TYPE_DES ||
o->info.objectType == TEE_TYPE_DES3)
obj_size -= obj_size / 8; /* Exclude parity in size of key */
o->have_attrs = have_attrs;
o->info.keySize = obj_size;
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_obj_populate(unsigned long obj,
struct utee_attribute *usr_attrs,
unsigned long attr_count)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *o;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *attrs = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_IMPLEMENTED;
attrs = malloc(sizeof(TEE_Attribute) * attr_count);
if (!attrs)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count,
attrs);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
attrs, attr_count);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
if (res == TEE_SUCCESS)
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
out:
free(attrs);
return res;
}
TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src)
{
TEE_Result res;
struct tee_ta_session *sess;
struct tee_obj *dst_o;
struct tee_obj *src_o;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(dst), &dst_o);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(src), &src_o);
if (res != TEE_SUCCESS)
return res;
if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_PARAMETERS;
if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_obj_attr_copy_from(dst_o, src_o);
if (res != TEE_SUCCESS)
return res;
dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
dst_o->info.keySize = src_o->info.keySize;
dst_o->info.objectUsage = src_o->info.objectUsage;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_rsa(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size,
const TEE_Attribute *params, uint32_t param_count)
{
TEE_Result res;
struct rsa_keypair *key = o->attr;
uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537);
/* Copy the present attributes into the obj before starting */
res = tee_svc_cryp_obj_populate_type(o, type_props, params,
param_count);
if (res != TEE_SUCCESS)
return res;
if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT))
crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e);
res = crypto_acipher_gen_rsa_key(key, key_size);
if (res != TEE_SUCCESS)
return res;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_dsa(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size)
{
TEE_Result res;
res = crypto_acipher_gen_dsa_key(o->attr, key_size);
if (res != TEE_SUCCESS)
return res;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_dh(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size __unused,
const TEE_Attribute *params, uint32_t param_count)
{
TEE_Result res;
struct dh_keypair *tee_dh_key;
struct bignum *dh_q = NULL;
uint32_t dh_xbits = 0;
/* Copy the present attributes into the obj before starting */
res = tee_svc_cryp_obj_populate_type(o, type_props, params,
param_count);
if (res != TEE_SUCCESS)
return res;
tee_dh_key = (struct dh_keypair *)o->attr;
if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME))
dh_q = tee_dh_key->q;
if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS))
dh_xbits = tee_dh_key->xbits;
res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits);
if (res != TEE_SUCCESS)
return res;
/* Set bits for the generated public and private key */
set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE);
set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE);
set_attribute(o, type_props, TEE_ATTR_DH_X_BITS);
return TEE_SUCCESS;
}
static TEE_Result tee_svc_obj_generate_key_ecc(
struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
uint32_t key_size __unused,
const TEE_Attribute *params, uint32_t param_count)
{
TEE_Result res;
struct ecc_keypair *tee_ecc_key;
/* Copy the present attributes into the obj before starting */
res = tee_svc_cryp_obj_populate_type(o, type_props, params,
param_count);
if (res != TEE_SUCCESS)
return res;
tee_ecc_key = (struct ecc_keypair *)o->attr;
res = crypto_acipher_gen_ecc_key(tee_ecc_key);
if (res != TEE_SUCCESS)
return res;
/* Set bits for the generated public and private key */
set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE);
set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X);
set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y);
set_attribute(o, type_props, TEE_ATTR_ECC_CURVE);
return TEE_SUCCESS;
}
TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size,
const struct utee_attribute *usr_params,
unsigned long param_count)
{
TEE_Result res;
struct tee_ta_session *sess;
const struct tee_cryp_obj_type_props *type_props;
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
size_t byte_size;
TEE_Attribute *params = NULL;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
tee_svc_uref_to_vaddr(obj), &o);
if (res != TEE_SUCCESS)
return res;
/* Must be a transient object */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
return TEE_ERROR_BAD_STATE;
/* Must not be initialized already */
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
return TEE_ERROR_BAD_STATE;
/* Find description of object */
type_props = tee_svc_find_type_props(o->info.objectType);
if (!type_props)
return TEE_ERROR_NOT_SUPPORTED;
/* Check that maxKeySize follows restrictions */
if (key_size % type_props->quanta != 0)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size < type_props->min_size)
return TEE_ERROR_NOT_SUPPORTED;
if (key_size > type_props->max_size)
return TEE_ERROR_NOT_SUPPORTED;
params = malloc(sizeof(TEE_Attribute) * param_count);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count,
params);
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
switch (o->info.objectType) {
case TEE_TYPE_AES:
case TEE_TYPE_DES:
case TEE_TYPE_DES3:
case TEE_TYPE_HMAC_MD5:
case TEE_TYPE_HMAC_SHA1:
case TEE_TYPE_HMAC_SHA224:
case TEE_TYPE_HMAC_SHA256:
case TEE_TYPE_HMAC_SHA384:
case TEE_TYPE_HMAC_SHA512:
case TEE_TYPE_GENERIC_SECRET:
byte_size = key_size / 8;
/*
* We have to do it like this because the parity bits aren't
* counted when telling the size of the key in bits.
*/
if (o->info.objectType == TEE_TYPE_DES ||
o->info.objectType == TEE_TYPE_DES3) {
byte_size = (key_size + key_size / 7) / 8;
}
key = (struct tee_cryp_obj_secret *)o->attr;
if (byte_size > key->alloc_size) {
res = TEE_ERROR_EXCESS_DATA;
goto out;
}
res = crypto_rng_read((void *)(key + 1), byte_size);
if (res != TEE_SUCCESS)
goto out;
key->key_size = byte_size;
/* Set bits for all known attributes for this object type */
o->have_attrs = (1 << type_props->num_type_attrs) - 1;
break;
case TEE_TYPE_RSA_KEYPAIR:
res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DSA_KEYPAIR:
res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_DH_KEYPAIR:
res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
case TEE_TYPE_ECDSA_KEYPAIR:
case TEE_TYPE_ECDH_KEYPAIR:
res = tee_svc_obj_generate_key_ecc(o, type_props, key_size,
params, param_count);
if (res != TEE_SUCCESS)
goto out;
break;
default:
res = TEE_ERROR_BAD_FORMAT;
}
out:
free(params);
if (res == TEE_SUCCESS) {
o->info.keySize = key_size;
o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
}
return res;
}
static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess,
uint32_t state_id,
struct tee_cryp_state **state)
{
struct tee_cryp_state *s;
struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
TAILQ_FOREACH(s, &utc->cryp_states, link) {
if (state_id == (vaddr_t)s) {
*state = s;
return TEE_SUCCESS;
}
}
return TEE_ERROR_BAD_PARAMETERS;
}
static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs)
{
struct tee_obj *o;
if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS)
tee_obj_close(utc, o);
if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS)
tee_obj_close(utc, o);
TAILQ_REMOVE(&utc->cryp_states, cs, link);
if (cs->ctx_finalize != NULL)
cs->ctx_finalize(cs->ctx, cs->algo);
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_CIPHER:
crypto_cipher_free_ctx(cs->ctx, cs->algo);
break;
case TEE_OPERATION_AE:
crypto_authenc_free_ctx(cs->ctx, cs->algo);
break;
case TEE_OPERATION_DIGEST:
crypto_hash_free_ctx(cs->ctx, cs->algo);
break;
case TEE_OPERATION_MAC:
crypto_mac_free_ctx(cs->ctx, cs->algo);
break;
default:
assert(!cs->ctx);
}
free(cs);
}
static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o,
uint32_t algo,
TEE_OperationMode mode)
{
uint32_t req_key_type;
uint32_t req_key_type2 = 0;
switch (TEE_ALG_GET_MAIN_ALG(algo)) {
case TEE_MAIN_ALGO_MD5:
req_key_type = TEE_TYPE_HMAC_MD5;
break;
case TEE_MAIN_ALGO_SHA1:
req_key_type = TEE_TYPE_HMAC_SHA1;
break;
case TEE_MAIN_ALGO_SHA224:
req_key_type = TEE_TYPE_HMAC_SHA224;
break;
case TEE_MAIN_ALGO_SHA256:
req_key_type = TEE_TYPE_HMAC_SHA256;
break;
case TEE_MAIN_ALGO_SHA384:
req_key_type = TEE_TYPE_HMAC_SHA384;
break;
case TEE_MAIN_ALGO_SHA512:
req_key_type = TEE_TYPE_HMAC_SHA512;
break;
case TEE_MAIN_ALGO_AES:
req_key_type = TEE_TYPE_AES;
break;
case TEE_MAIN_ALGO_DES:
req_key_type = TEE_TYPE_DES;
break;
case TEE_MAIN_ALGO_DES3:
req_key_type = TEE_TYPE_DES3;
break;
case TEE_MAIN_ALGO_RSA:
req_key_type = TEE_TYPE_RSA_KEYPAIR;
if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY;
break;
case TEE_MAIN_ALGO_DSA:
req_key_type = TEE_TYPE_DSA_KEYPAIR;
if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY;
break;
case TEE_MAIN_ALGO_DH:
req_key_type = TEE_TYPE_DH_KEYPAIR;
break;
case TEE_MAIN_ALGO_ECDSA:
req_key_type = TEE_TYPE_ECDSA_KEYPAIR;
if (mode == TEE_MODE_VERIFY)
req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY;
break;
case TEE_MAIN_ALGO_ECDH:
req_key_type = TEE_TYPE_ECDH_KEYPAIR;
break;
#if defined(CFG_CRYPTO_HKDF)
case TEE_MAIN_ALGO_HKDF:
req_key_type = TEE_TYPE_HKDF_IKM;
break;
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
case TEE_MAIN_ALGO_CONCAT_KDF:
req_key_type = TEE_TYPE_CONCAT_KDF_Z;
break;
#endif
#if defined(CFG_CRYPTO_PBKDF2)
case TEE_MAIN_ALGO_PBKDF2:
req_key_type = TEE_TYPE_PBKDF2_PASSWORD;
break;
#endif
default:
return TEE_ERROR_BAD_PARAMETERS;
}
if (req_key_type != o->info.objectType &&
req_key_type2 != o->info.objectType)
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode,
unsigned long key1, unsigned long key2,
uint32_t *state)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o1 = NULL;
struct tee_obj *o2 = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
if (key1 != 0) {
res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1);
if (res != TEE_SUCCESS)
return res;
if (o1->busy)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_svc_cryp_check_key_type(o1, algo, mode);
if (res != TEE_SUCCESS)
return res;
}
if (key2 != 0) {
res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2);
if (res != TEE_SUCCESS)
return res;
if (o2->busy)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_svc_cryp_check_key_type(o2, algo, mode);
if (res != TEE_SUCCESS)
return res;
}
cs = calloc(1, sizeof(struct tee_cryp_state));
if (!cs)
return TEE_ERROR_OUT_OF_MEMORY;
TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link);
cs->algo = algo;
cs->mode = mode;
switch (TEE_ALG_GET_CLASS(algo)) {
case TEE_OPERATION_EXTENSION:
#ifdef CFG_CRYPTO_RSASSA_NA1
if (algo == TEE_ALG_RSASSA_PKCS1_V1_5)
goto rsassa_na1;
#endif
res = TEE_ERROR_NOT_SUPPORTED;
break;
case TEE_OPERATION_CIPHER:
if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) ||
(algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_cipher_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_AE:
if (key1 == 0 || key2 != 0) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_authenc_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_MAC:
if (key1 == 0 || key2 != 0) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_mac_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_DIGEST:
if (key1 != 0 || key2 != 0) {
res = TEE_ERROR_BAD_PARAMETERS;
} else {
res = crypto_hash_alloc_ctx(&cs->ctx, algo);
if (res != TEE_SUCCESS)
break;
}
break;
case TEE_OPERATION_ASYMMETRIC_CIPHER:
case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
rsassa_na1: __maybe_unused
if (key1 == 0 || key2 != 0)
res = TEE_ERROR_BAD_PARAMETERS;
break;
case TEE_OPERATION_KEY_DERIVATION:
if (key1 == 0 || key2 != 0)
res = TEE_ERROR_BAD_PARAMETERS;
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
break;
}
if (res != TEE_SUCCESS)
goto out;
res = tee_svc_copy_kaddr_to_uref(state, cs);
if (res != TEE_SUCCESS)
goto out;
/* Register keys */
if (o1 != NULL) {
o1->busy = true;
cs->key1 = (vaddr_t)o1;
}
if (o2 != NULL) {
o2->busy = true;
cs->key2 = (vaddr_t)o2;
}
out:
if (res != TEE_SUCCESS)
cryp_state_free(utc, cs);
return res;
}
TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src)
{
TEE_Result res;
struct tee_cryp_state *cs_dst;
struct tee_cryp_state *cs_src;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src);
if (res != TEE_SUCCESS)
return res;
if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
return TEE_ERROR_BAD_PARAMETERS;
switch (TEE_ALG_GET_CLASS(cs_src->algo)) {
case TEE_OPERATION_CIPHER:
crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx,
cs_src->algo);
break;
case TEE_OPERATION_AE:
crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx,
cs_src->algo);
break;
case TEE_OPERATION_DIGEST:
crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo);
break;
case TEE_OPERATION_MAC:
crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo);
break;
default:
return TEE_ERROR_BAD_STATE;
}
return TEE_SUCCESS;
}
void tee_svc_cryp_free_states(struct user_ta_ctx *utc)
{
struct tee_cryp_state_head *states = &utc->cryp_states;
while (!TAILQ_EMPTY(states))
cryp_state_free(utc, TAILQ_FIRST(states));
}
TEE_Result syscall_cryp_state_free(unsigned long state)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
cryp_state_free(to_user_ta_ctx(sess->ctx), cs);
return TEE_SUCCESS;
}
TEE_Result syscall_hash_init(unsigned long state,
const void *iv __maybe_unused,
size_t iv_len __maybe_unused)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_DIGEST:
res = crypto_hash_init(cs->ctx, cs->algo);
if (res != TEE_SUCCESS)
return res;
break;
case TEE_OPERATION_MAC:
{
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
res = tee_obj_get(to_user_ta_ctx(sess->ctx),
cs->key1, &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags &
TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
key = (struct tee_cryp_obj_secret *)o->attr;
res = crypto_mac_init(cs->ctx, cs->algo,
(void *)(key + 1), key->key_size);
if (res != TEE_SUCCESS)
return res;
break;
}
default:
return TEE_ERROR_BAD_PARAMETERS;
}
return TEE_SUCCESS;
}
TEE_Result syscall_hash_update(unsigned long state, const void *chunk,
size_t chunk_size)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
/* No data, but size provided isn't valid parameters. */
if (!chunk && chunk_size)
return TEE_ERROR_BAD_PARAMETERS;
/* Zero length hash is valid, but nothing we need to do. */
if (!chunk_size)
return TEE_SUCCESS;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_DIGEST:
res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
break;
case TEE_OPERATION_MAC:
res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
break;
default:
return TEE_ERROR_BAD_PARAMETERS;
}
return TEE_SUCCESS;
}
TEE_Result syscall_hash_final(unsigned long state, const void *chunk,
size_t chunk_size, void *hash, uint64_t *hash_len)
{
TEE_Result res, res2;
size_t hash_size;
uint64_t hlen;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
/* No data, but size provided isn't valid parameters. */
if (!chunk && chunk_size)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)chunk, chunk_size);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)hash, hlen);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
switch (TEE_ALG_GET_CLASS(cs->algo)) {
case TEE_OPERATION_DIGEST:
res = tee_hash_get_digest_size(cs->algo, &hash_size);
if (res != TEE_SUCCESS)
return res;
if (*hash_len < hash_size) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
if (chunk_size) {
res = crypto_hash_update(cs->ctx, cs->algo, chunk,
chunk_size);
if (res != TEE_SUCCESS)
return res;
}
res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size);
if (res != TEE_SUCCESS)
return res;
break;
case TEE_OPERATION_MAC:
res = tee_mac_get_digest_size(cs->algo, &hash_size);
if (res != TEE_SUCCESS)
return res;
if (*hash_len < hash_size) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
if (chunk_size) {
res = crypto_mac_update(cs->ctx, cs->algo, chunk,
chunk_size);
if (res != TEE_SUCCESS)
return res;
}
res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size);
if (res != TEE_SUCCESS)
return res;
break;
default:
return TEE_ERROR_BAD_PARAMETERS;
}
out:
hlen = hash_size;
res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len));
if (res2 != TEE_SUCCESS)
return res2;
return res;
}
TEE_Result syscall_cipher_init(unsigned long state, const void *iv,
size_t iv_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
struct tee_cryp_obj_secret *key1;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) iv, iv_len);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
key1 = o->attr;
if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) {
struct tee_cryp_obj_secret *key2 = o->attr;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode,
(uint8_t *)(key1 + 1), key1->key_size,
(uint8_t *)(key2 + 1), key2->key_size,
iv, iv_len);
} else {
res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode,
(uint8_t *)(key1 + 1), key1->key_size,
NULL, 0, iv, iv_len);
}
if (res != TEE_SUCCESS)
return res;
cs->ctx_finalize = crypto_cipher_final;
return TEE_SUCCESS;
}
static TEE_Result tee_svc_cipher_update_helper(unsigned long state,
bool last_block, const void *src, size_t src_len,
void *dst, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)src, src_len);
if (res != TEE_SUCCESS)
return res;
if (!dst_len) {
dlen = 0;
} else {
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst, dlen);
if (res != TEE_SUCCESS)
return res;
}
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
if (src_len > 0) {
/* Permit src_len == 0 to finalize the operation */
res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
last_block, src, src_len, dst);
}
if (last_block && cs->ctx_finalize != NULL) {
cs->ctx_finalize(cs->ctx, cs->algo);
cs->ctx_finalize = NULL;
}
out:
if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
dst_len != NULL) {
TEE_Result res2;
dlen = src_len;
res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
res = res2;
}
return res;
}
TEE_Result syscall_cipher_update(unsigned long state, const void *src,
size_t src_len, void *dst, uint64_t *dst_len)
{
return tee_svc_cipher_update_helper(state, false /* last_block */,
src, src_len, dst, dst_len);
}
TEE_Result syscall_cipher_final(unsigned long state, const void *src,
size_t src_len, void *dst, uint64_t *dst_len)
{
return tee_svc_cipher_update_helper(state, true /* last_block */,
src, src_len, dst, dst_len);
}
#if defined(CFG_CRYPTO_HKDF)
static TEE_Result get_hkdf_params(const TEE_Attribute *params,
uint32_t param_count,
void **salt, size_t *salt_len, void **info,
size_t *info_len, size_t *okm_len)
{
size_t n;
enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
uint8_t found = 0;
*salt = *info = NULL;
*salt_len = *info_len = *okm_len = 0;
for (n = 0; n < param_count; n++) {
switch (params[n].attributeID) {
case TEE_ATTR_HKDF_SALT:
if (!(found & SALT)) {
*salt = params[n].content.ref.buffer;
*salt_len = params[n].content.ref.length;
found |= SALT;
}
break;
case TEE_ATTR_HKDF_OKM_LENGTH:
if (!(found & LENGTH)) {
*okm_len = params[n].content.value.a;
found |= LENGTH;
}
break;
case TEE_ATTR_HKDF_INFO:
if (!(found & INFO)) {
*info = params[n].content.ref.buffer;
*info_len = params[n].content.ref.length;
found |= INFO;
}
break;
default:
/* Unexpected attribute */
return TEE_ERROR_BAD_PARAMETERS;
}
}
if (!(found & LENGTH))
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
uint32_t param_count,
void **other_info,
size_t *other_info_len,
size_t *derived_key_len)
{
size_t n;
enum { LENGTH = 0x1, INFO = 0x2 };
uint8_t found = 0;
*other_info = NULL;
*other_info_len = *derived_key_len = 0;
for (n = 0; n < param_count; n++) {
switch (params[n].attributeID) {
case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
if (!(found & INFO)) {
*other_info = params[n].content.ref.buffer;
*other_info_len = params[n].content.ref.length;
found |= INFO;
}
break;
case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
if (!(found & LENGTH)) {
*derived_key_len = params[n].content.value.a;
found |= LENGTH;
}
break;
default:
/* Unexpected attribute */
return TEE_ERROR_BAD_PARAMETERS;
}
}
if (!(found & LENGTH))
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
#endif
#if defined(CFG_CRYPTO_PBKDF2)
static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
uint32_t param_count, void **salt,
size_t *salt_len, size_t *derived_key_len,
size_t *iteration_count)
{
size_t n;
enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
uint8_t found = 0;
*salt = NULL;
*salt_len = *derived_key_len = *iteration_count = 0;
for (n = 0; n < param_count; n++) {
switch (params[n].attributeID) {
case TEE_ATTR_PBKDF2_SALT:
if (!(found & SALT)) {
*salt = params[n].content.ref.buffer;
*salt_len = params[n].content.ref.length;
found |= SALT;
}
break;
case TEE_ATTR_PBKDF2_DKM_LENGTH:
if (!(found & LENGTH)) {
*derived_key_len = params[n].content.value.a;
found |= LENGTH;
}
break;
case TEE_ATTR_PBKDF2_ITERATION_COUNT:
if (!(found & COUNT)) {
*iteration_count = params[n].content.value.a;
found |= COUNT;
}
break;
default:
/* Unexpected attribute */
return TEE_ERROR_BAD_PARAMETERS;
}
}
if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
return TEE_ERROR_BAD_PARAMETERS;
return TEE_SUCCESS;
}
#endif
TEE_Result syscall_cryp_derive_key(unsigned long state,
const struct utee_attribute *usr_params,
unsigned long param_count, unsigned long derived_key)
{
TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
struct tee_ta_session *sess;
struct tee_obj *ko;
struct tee_obj *so;
struct tee_cryp_state *cs;
struct tee_cryp_obj_secret *sk;
const struct tee_cryp_obj_type_props *type_props;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * param_count);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, param_count, params);
if (res != TEE_SUCCESS)
goto out;
/* Get key set in operation */
res = tee_obj_get(utc, cs->key1, &ko);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so);
if (res != TEE_SUCCESS)
goto out;
/* Find information needed about the object to initialize */
sk = so->attr;
/* Find description of object */
type_props = tee_svc_find_type_props(so->info.objectType);
if (!type_props) {
res = TEE_ERROR_NOT_SUPPORTED;
goto out;
}
if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
size_t alloc_size;
struct bignum *pub;
struct bignum *ss;
if (param_count != 1 ||
params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
alloc_size = params[0].content.ref.length * 8;
pub = crypto_bignum_allocate(alloc_size);
ss = crypto_bignum_allocate(alloc_size);
if (pub && ss) {
crypto_bignum_bin2bn(params[0].content.ref.buffer,
params[0].content.ref.length, pub);
res = crypto_acipher_dh_shared_secret(ko->attr,
pub, ss);
if (res == TEE_SUCCESS) {
sk->key_size = crypto_bignum_num_bytes(ss);
crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1));
so->info.handleFlags |=
TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props,
TEE_ATTR_SECRET_VALUE);
}
} else {
res = TEE_ERROR_OUT_OF_MEMORY;
}
crypto_bignum_free(pub);
crypto_bignum_free(ss);
} else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) {
size_t alloc_size;
struct ecc_public_key key_public;
uint8_t *pt_secret;
unsigned long pt_secret_len;
if (param_count != 2 ||
params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X ||
params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (cs->algo) {
case TEE_ALG_ECDH_P192:
alloc_size = 192;
break;
case TEE_ALG_ECDH_P224:
alloc_size = 224;
break;
case TEE_ALG_ECDH_P256:
alloc_size = 256;
break;
case TEE_ALG_ECDH_P384:
alloc_size = 384;
break;
case TEE_ALG_ECDH_P521:
alloc_size = 521;
break;
default:
res = TEE_ERROR_NOT_IMPLEMENTED;
goto out;
}
/* Create the public key */
res = crypto_acipher_alloc_ecc_public_key(&key_public,
alloc_size);
if (res != TEE_SUCCESS)
goto out;
key_public.curve = ((struct ecc_keypair *)ko->attr)->curve;
crypto_bignum_bin2bn(params[0].content.ref.buffer,
params[0].content.ref.length,
key_public.x);
crypto_bignum_bin2bn(params[1].content.ref.buffer,
params[1].content.ref.length,
key_public.y);
pt_secret = (uint8_t *)(sk + 1);
pt_secret_len = sk->alloc_size;
res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public,
pt_secret,
&pt_secret_len);
if (res == TEE_SUCCESS) {
sk->key_size = pt_secret_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
/* free the public key */
crypto_acipher_free_ecc_public_key(&key_public);
}
#if defined(CFG_CRYPTO_HKDF)
else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
void *salt, *info;
size_t salt_len, info_len, okm_len;
uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
struct tee_cryp_obj_secret *ik = ko->attr;
const uint8_t *ikm = (const uint8_t *)(ik + 1);
res = get_hkdf_params(params, param_count, &salt, &salt_len,
&info, &info_len, &okm_len);
if (res != TEE_SUCCESS)
goto out;
/* Requested size must fit into the output object's buffer */
if (okm_len > ik->alloc_size) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
info, info_len, (uint8_t *)(sk + 1),
okm_len);
if (res == TEE_SUCCESS) {
sk->key_size = okm_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
}
#endif
#if defined(CFG_CRYPTO_CONCAT_KDF)
else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
void *info;
size_t info_len, derived_key_len;
uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
struct tee_cryp_obj_secret *ss = ko->attr;
const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
res = get_concat_kdf_params(params, param_count, &info,
&info_len, &derived_key_len);
if (res != TEE_SUCCESS)
goto out;
/* Requested size must fit into the output object's buffer */
if (derived_key_len > ss->alloc_size) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
info, info_len, (uint8_t *)(sk + 1),
derived_key_len);
if (res == TEE_SUCCESS) {
sk->key_size = derived_key_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
}
#endif
#if defined(CFG_CRYPTO_PBKDF2)
else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
void *salt;
size_t salt_len, iteration_count, derived_key_len;
uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
struct tee_cryp_obj_secret *ss = ko->attr;
const uint8_t *password = (const uint8_t *)(ss + 1);
res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
&derived_key_len, &iteration_count);
if (res != TEE_SUCCESS)
goto out;
/* Requested size must fit into the output object's buffer */
if (derived_key_len > ss->alloc_size) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
salt_len, iteration_count,
(uint8_t *)(sk + 1), derived_key_len);
if (res == TEE_SUCCESS) {
sk->key_size = derived_key_len;
so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
}
}
#endif
else
res = TEE_ERROR_NOT_SUPPORTED;
out:
free(params);
return res;
}
TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen)
{
TEE_Result res;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)buf, blen);
if (res != TEE_SUCCESS)
return res;
res = crypto_rng_read(buf, blen);
if (res != TEE_SUCCESS)
return res;
return res;
}
TEE_Result syscall_authenc_init(unsigned long state, const void *nonce,
size_t nonce_len, size_t tag_len,
size_t aad_len, size_t payload_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
struct tee_cryp_obj_secret *key;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o);
if (res != TEE_SUCCESS)
return res;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
return TEE_ERROR_BAD_PARAMETERS;
key = o->attr;
res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode,
(uint8_t *)(key + 1), key->key_size,
nonce, nonce_len, tag_len, aad_len,
payload_len);
if (res != TEE_SUCCESS)
return res;
cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final;
return TEE_SUCCESS;
}
TEE_Result syscall_authenc_update_aad(unsigned long state,
const void *aad_data, size_t aad_data_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) aad_data,
aad_data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode,
aad_data, aad_data_len);
if (res != TEE_SUCCESS)
return res;
return TEE_SUCCESS;
}
TEE_Result syscall_authenc_update_payload(unsigned long state,
const void *src_data, size_t src_len, void *dst_data,
uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
size_t tmp_dlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
tmp_dlen = dlen;
res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode,
src_data, src_len, dst_data,
&tmp_dlen);
dlen = tmp_dlen;
out:
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen,
sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
res = res2;
}
return res;
}
TEE_Result syscall_authenc_enc_final(unsigned long state,
const void *src_data, size_t src_len, void *dst_data,
uint64_t *dst_len, void *tag, uint64_t *tag_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
uint64_t tlen = 0;
size_t tmp_dlen;
size_t tmp_tlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_ENCRYPT)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)src_data, src_len);
if (res != TEE_SUCCESS)
return res;
if (!dst_len) {
dlen = 0;
} else {
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
}
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)tag, tlen);
if (res != TEE_SUCCESS)
return res;
tmp_dlen = dlen;
tmp_tlen = tlen;
res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data,
src_len, dst_data, &tmp_dlen, tag,
&tmp_tlen);
dlen = tmp_dlen;
tlen = tmp_tlen;
out:
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
if (dst_len != NULL) {
res2 = tee_svc_copy_to_user(dst_len, &dlen,
sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
TEE_Result syscall_authenc_dec_final(unsigned long state,
const void *src_data, size_t src_len, void *dst_data,
uint64_t *dst_len, const void *tag, size_t tag_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen;
size_t tmp_dlen;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_DECRYPT)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)src_data, src_len);
if (res != TEE_SUCCESS)
return res;
if (!dst_len) {
dlen = 0;
} else {
res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen));
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
}
if (dlen < src_len) {
res = TEE_ERROR_SHORT_BUFFER;
goto out;
}
res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx),
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)tag, tag_len);
if (res != TEE_SUCCESS)
return res;
tmp_dlen = dlen;
res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len,
dst_data, &tmp_dlen, tag, tag_len);
dlen = tmp_dlen;
out:
if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
dst_len != NULL) {
TEE_Result res2;
res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params,
size_t default_len)
{
size_t n;
assert(default_len < INT_MAX);
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
if (params[n].content.value.a < INT_MAX)
return params[n].content.value.a;
break;
}
}
/*
* If salt length isn't provided use the default value which is
* the length of the digest.
*/
return default_len;
}
TEE_Result syscall_asymm_operate(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *src_data, size_t src_len,
void *dst_data, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen64;
size_t dlen;
struct tee_obj *o;
void *label = NULL;
size_t label_len = 0;
size_t n;
int salt_len;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64));
if (res != TEE_SUCCESS)
return res;
dlen = dlen64;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_GENERIC;
goto out;
}
switch (cs->algo) {
case TEE_ALG_RSA_NOPAD:
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else {
/*
* We will panic because "the mode is not compatible
* with the function"
*/
res = TEE_ERROR_GENERIC;
}
break;
case TEE_ALG_RSAES_PKCS1_V1_5:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
label = params[n].content.ref.buffer;
label_len = params[n].content.ref.length;
break;
}
}
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
label, label_len,
src_data, src_len,
dst_data, &dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsaes_decrypt(
cs->algo, o->attr, label, label_len,
src_data, src_len, dst_data, &dlen);
} else {
res = TEE_ERROR_BAD_PARAMETERS;
}
break;
#if defined(CFG_CRYPTO_RSASSA_NA1)
case TEE_ALG_RSASSA_PKCS1_V1_5:
#endif
case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
if (cs->mode != TEE_MODE_SIGN) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params, src_len);
res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
src_data, src_len, dst_data,
&dlen);
break;
case TEE_ALG_DSA_SHA1:
case TEE_ALG_DSA_SHA224:
case TEE_ALG_DSA_SHA256:
res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
case TEE_ALG_ECDSA_P192:
case TEE_ALG_ECDSA_P224:
case TEE_ALG_ECDSA_P256:
case TEE_ALG_ECDSA_P384:
case TEE_ALG_ECDSA_P521:
res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
default:
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
out:
free(params);
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
dlen64 = dlen;
res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
TEE_Result syscall_asymm_verify(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *data, size_t data_len,
const void *sig, size_t sig_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
size_t hash_size;
int salt_len = 0;
TEE_Attribute *params = NULL;
uint32_t hash_algo;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_VERIFY)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)data, data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)sig, sig_len);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
case TEE_MAIN_ALGO_RSA:
if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
if (data_len != hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params,
hash_size);
}
res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
data, data_len, sig,
sig_len);
break;
case TEE_MAIN_ALGO_DSA:
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
/*
* Depending on the DSA algorithm (NIST), the digital signature
* output size may be truncated to the size of a key pair
* (Q prime size). Q prime size must be less or equal than the
* hash output length of the hash algorithm involved.
*/
if (data_len > hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
case TEE_MAIN_ALGO_ECDSA:
res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
}
out:
free(params);
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_730_0 |
crossvul-cpp_data_bad_2384_0 | /*
** Copyright (C) 2001-2014 Erik de Castro Lopo <erikd@mega-nerd.com>
** Copyright (C) 2004 Paavo Jumppanen
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
** The sd2 support implemented in this file was partially sponsored
** (financially) by Paavo Jumppanen.
*/
/*
** Documentation on the Mac resource fork was obtained here :
** http://developer.apple.com/documentation/mac/MoreToolbox/MoreToolbox-99.html
*/
#include "sfconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "sndfile.h"
#include "sfendian.h"
#include "common.h"
/*------------------------------------------------------------------------------
* Markers.
*/
#define Sd2f_MARKER MAKE_MARKER ('S', 'd', '2', 'f')
#define Sd2a_MARKER MAKE_MARKER ('S', 'd', '2', 'a')
#define ALCH_MARKER MAKE_MARKER ('A', 'L', 'C', 'H')
#define lsf1_MARKER MAKE_MARKER ('l', 's', 'f', '1')
#define STR_MARKER MAKE_MARKER ('S', 'T', 'R', ' ')
#define sdML_MARKER MAKE_MARKER ('s', 'd', 'M', 'L')
enum
{ RSRC_STR = 111,
RSRC_BIN
} ;
typedef struct
{ unsigned char * rsrc_data ;
int rsrc_len ;
int need_to_free_rsrc_data ;
int data_offset, data_length ;
int map_offset, map_length ;
int type_count, type_offset ;
int item_offset ;
int str_index, str_count ;
int string_offset ;
/* All the above just to get these three. */
int sample_size, sample_rate, channels ;
} SD2_RSRC ;
typedef struct
{ int type ;
int id ;
char name [32] ;
char value [32] ;
int value_len ;
} STR_RSRC ;
/*------------------------------------------------------------------------------
* Private static functions.
*/
static int sd2_close (SF_PRIVATE *psf) ;
static int sd2_parse_rsrc_fork (SF_PRIVATE *psf) ;
static int parse_str_rsrc (SF_PRIVATE *psf, SD2_RSRC * rsrc) ;
static int sd2_write_rsrc_fork (SF_PRIVATE *psf, int calc_length) ;
/*------------------------------------------------------------------------------
** Public functions.
*/
int
sd2_open (SF_PRIVATE *psf)
{ int subformat, error = 0, valid ;
/* SD2 is always big endian. */
psf->endian = SF_ENDIAN_BIG ;
if (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->rsrclength > 0))
{ psf_use_rsrc (psf, SF_TRUE) ;
valid = psf_file_valid (psf) ;
psf_use_rsrc (psf, SF_FALSE) ;
if (! valid)
{ psf_log_printf (psf, "sd2_open : psf->rsrc.filedes < 0\n") ;
return SFE_SD2_BAD_RSRC ;
} ;
error = sd2_parse_rsrc_fork (psf) ;
if (error)
goto error_cleanup ;
} ;
if ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_SD2)
{ error = SFE_BAD_OPEN_FORMAT ;
goto error_cleanup ;
} ;
subformat = SF_CODEC (psf->sf.format) ;
psf->dataoffset = 0 ;
/* Only open and write the resource in RDWR mode is its current length is zero. */
if (psf->file.mode == SFM_WRITE || (psf->file.mode == SFM_RDWR && psf->rsrclength == 0))
{ psf->rsrc.mode = psf->file.mode ;
psf_open_rsrc (psf) ;
error = sd2_write_rsrc_fork (psf, SF_FALSE) ;
if (error)
goto error_cleanup ;
/* Not needed. */
psf->write_header = NULL ;
} ;
psf->container_close = sd2_close ;
psf->blockwidth = psf->bytewidth * psf->sf.channels ;
switch (subformat)
{ case SF_FORMAT_PCM_S8 : /* 8-bit linear PCM. */
case SF_FORMAT_PCM_16 : /* 16-bit linear PCM. */
case SF_FORMAT_PCM_24 : /* 24-bit linear PCM */
case SF_FORMAT_PCM_32 : /* 32-bit linear PCM */
error = pcm_init (psf) ;
break ;
default :
error = SFE_UNIMPLEMENTED ;
break ;
} ;
psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
error_cleanup:
/* Close the resource fork regardless. We won't need it again. */
psf_close_rsrc (psf) ;
return error ;
} /* sd2_open */
/*------------------------------------------------------------------------------
*/
static int
sd2_close (SF_PRIVATE *psf)
{
if (psf->file.mode == SFM_WRITE)
{ /* Now we know for certain the audio_length of the file we can re-write
** correct values for the FORM, 8SVX and BODY chunks.
*/
} ;
return 0 ;
} /* sd2_close */
/*------------------------------------------------------------------------------
*/
static inline void
write_char (unsigned char * data, int offset, char value)
{ data [offset] = value ;
} /* write_char */
static inline void
write_short (unsigned char * data, int offset, short value)
{ data [offset] = value >> 8 ;
data [offset + 1] = value ;
} /* write_char */
static inline void
write_int (unsigned char * data, int offset, int value)
{ data [offset] = value >> 24 ;
data [offset + 1] = value >> 16 ;
data [offset + 2] = value >> 8 ;
data [offset + 3] = value ;
} /* write_int */
static inline void
write_marker (unsigned char * data, int offset, int value)
{
if (CPU_IS_BIG_ENDIAN)
{ data [offset] = value >> 24 ;
data [offset + 1] = value >> 16 ;
data [offset + 2] = value >> 8 ;
data [offset + 3] = value ;
}
else
{ data [offset] = value ;
data [offset + 1] = value >> 8 ;
data [offset + 2] = value >> 16 ;
data [offset + 3] = value >> 24 ;
} ;
} /* write_marker */
static void
write_str (unsigned char * data, int offset, const char * buffer, int buffer_len)
{ memcpy (data + offset, buffer, buffer_len) ;
} /* write_str */
static int
sd2_write_rsrc_fork (SF_PRIVATE *psf, int UNUSED (calc_length))
{ SD2_RSRC rsrc ;
STR_RSRC str_rsrc [] =
{ { RSRC_STR, 1000, "_sample-size", "", 0 },
{ RSRC_STR, 1001, "_sample-rate", "", 0 },
{ RSRC_STR, 1002, "_channels", "", 0 },
{ RSRC_BIN, 1000, "_Markers", "", 8 }
} ;
int k, str_offset, data_offset, next_str ;
psf_use_rsrc (psf, SF_TRUE) ;
memset (&rsrc, 0, sizeof (rsrc)) ;
rsrc.sample_rate = psf->sf.samplerate ;
rsrc.sample_size = psf->bytewidth ;
rsrc.channels = psf->sf.channels ;
rsrc.rsrc_data = psf->header ;
rsrc.rsrc_len = sizeof (psf->header) ;
memset (rsrc.rsrc_data, 0xea, rsrc.rsrc_len) ;
snprintf (str_rsrc [0].value, sizeof (str_rsrc [0].value), "_%d", rsrc.sample_size) ;
snprintf (str_rsrc [1].value, sizeof (str_rsrc [1].value), "_%d.000000", rsrc.sample_rate) ;
snprintf (str_rsrc [2].value, sizeof (str_rsrc [2].value), "_%d", rsrc.channels) ;
for (k = 0 ; k < ARRAY_LEN (str_rsrc) ; k++)
{ if (str_rsrc [k].value_len == 0)
{ str_rsrc [k].value_len = strlen (str_rsrc [k].value) ;
str_rsrc [k].value [0] = str_rsrc [k].value_len - 1 ;
} ;
/* Turn name string into a pascal string. */
str_rsrc [k].name [0] = strlen (str_rsrc [k].name) - 1 ;
} ;
rsrc.data_offset = 0x100 ;
/*
** Calculate data length :
** length of strings, plus the length of the sdML chunk.
*/
rsrc.data_length = 0 ;
for (k = 0 ; k < ARRAY_LEN (str_rsrc) ; k++)
rsrc.data_length += str_rsrc [k].value_len + 4 ;
rsrc.map_offset = rsrc.data_offset + rsrc.data_length ;
/* Very start of resource fork. */
write_int (rsrc.rsrc_data, 0, rsrc.data_offset) ;
write_int (rsrc.rsrc_data, 4, rsrc.map_offset) ;
write_int (rsrc.rsrc_data, 8, rsrc.data_length) ;
write_char (rsrc.rsrc_data, 0x30, strlen (psf->file.name.c)) ;
write_str (rsrc.rsrc_data, 0x31, psf->file.name.c, strlen (psf->file.name.c)) ;
write_short (rsrc.rsrc_data, 0x50, 0) ;
write_marker (rsrc.rsrc_data, 0x52, Sd2f_MARKER) ;
write_marker (rsrc.rsrc_data, 0x56, lsf1_MARKER) ;
/* Very start of resource map. */
write_int (rsrc.rsrc_data, rsrc.map_offset + 0, rsrc.data_offset) ;
write_int (rsrc.rsrc_data, rsrc.map_offset + 4, rsrc.map_offset) ;
write_int (rsrc.rsrc_data, rsrc.map_offset + 8, rsrc.data_length) ;
/* These I don't currently understand. */
if (1)
{ write_char (rsrc.rsrc_data, rsrc.map_offset+ 16, 1) ;
/* Next resource map. */
write_int (rsrc.rsrc_data, rsrc.map_offset + 17, 0x12345678) ;
/* File ref number. */
write_short (rsrc.rsrc_data, rsrc.map_offset + 21, 0xabcd) ;
/* Fork attributes. */
write_short (rsrc.rsrc_data, rsrc.map_offset + 23, 0) ;
} ;
/* Resource type offset. */
rsrc.type_offset = rsrc.map_offset + 30 ;
write_short (rsrc.rsrc_data, rsrc.map_offset + 24, rsrc.type_offset - rsrc.map_offset - 2) ;
/* Type index max. */
rsrc.type_count = 2 ;
write_short (rsrc.rsrc_data, rsrc.map_offset + 28, rsrc.type_count - 1) ;
rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ;
rsrc.str_count = ARRAY_LEN (str_rsrc) ;
rsrc.string_offset = rsrc.item_offset + (rsrc.str_count + 1) * 12 - rsrc.map_offset ;
write_short (rsrc.rsrc_data, rsrc.map_offset + 26, rsrc.string_offset) ;
/* Write 'STR ' resource type. */
rsrc.str_count = 3 ;
write_marker (rsrc.rsrc_data, rsrc.type_offset, STR_MARKER) ;
write_short (rsrc.rsrc_data, rsrc.type_offset + 4, rsrc.str_count - 1) ;
write_short (rsrc.rsrc_data, rsrc.type_offset + 6, 0x12) ;
/* Write 'sdML' resource type. */
write_marker (rsrc.rsrc_data, rsrc.type_offset + 8, sdML_MARKER) ;
write_short (rsrc.rsrc_data, rsrc.type_offset + 12, 0) ;
write_short (rsrc.rsrc_data, rsrc.type_offset + 14, 0x36) ;
str_offset = rsrc.map_offset + rsrc.string_offset ;
next_str = 0 ;
data_offset = rsrc.data_offset ;
for (k = 0 ; k < ARRAY_LEN (str_rsrc) ; k++)
{ write_str (rsrc.rsrc_data, str_offset, str_rsrc [k].name, strlen (str_rsrc [k].name)) ;
write_short (rsrc.rsrc_data, rsrc.item_offset + k * 12, str_rsrc [k].id) ;
write_short (rsrc.rsrc_data, rsrc.item_offset + k * 12 + 2, next_str) ;
str_offset += strlen (str_rsrc [k].name) ;
next_str += strlen (str_rsrc [k].name) ;
write_int (rsrc.rsrc_data, rsrc.item_offset + k * 12 + 4, data_offset - rsrc.data_offset) ;
write_int (rsrc.rsrc_data, data_offset, str_rsrc [k].value_len) ;
write_str (rsrc.rsrc_data, data_offset + 4, str_rsrc [k].value, str_rsrc [k].value_len) ;
data_offset += 4 + str_rsrc [k].value_len ;
} ;
/* Finally, calculate and set map length. */
rsrc.map_length = str_offset - rsrc.map_offset ;
write_int (rsrc.rsrc_data, 12, rsrc.map_length) ;
write_int (rsrc.rsrc_data, rsrc.map_offset + 12, rsrc.map_length) ;
rsrc.rsrc_len = rsrc.map_offset + rsrc.map_length ;
psf_fwrite (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ;
psf_use_rsrc (psf, SF_FALSE) ;
if (psf->error)
return psf->error ;
return 0 ;
} /* sd2_write_rsrc_fork */
/*------------------------------------------------------------------------------
*/
static inline int
read_rsrc_char (const SD2_RSRC *prsrc, int offset)
{ const unsigned char * data = prsrc->rsrc_data ;
if (offset < 0 || offset >= prsrc->rsrc_len)
return 0 ;
return data [offset] ;
} /* read_rsrc_char */
static inline int
read_rsrc_short (const SD2_RSRC *prsrc, int offset)
{ const unsigned char * data = prsrc->rsrc_data ;
if (offset < 0 || offset + 1 >= prsrc->rsrc_len)
return 0 ;
return (data [offset] << 8) + data [offset + 1] ;
} /* read_rsrc_short */
static inline int
read_rsrc_int (const SD2_RSRC *prsrc, int offset)
{ const unsigned char * data = prsrc->rsrc_data ;
if (offset < 0 || offset + 3 >= prsrc->rsrc_len)
return 0 ;
return (((uint32_t) data [offset]) << 24) + (data [offset + 1] << 16) + (data [offset + 2] << 8) + data [offset + 3] ;
} /* read_rsrc_int */
static inline int
read_rsrc_marker (const SD2_RSRC *prsrc, int offset)
{ const unsigned char * data = prsrc->rsrc_data ;
if (offset < 0 || offset + 3 >= prsrc->rsrc_len)
return 0 ;
if (CPU_IS_BIG_ENDIAN)
return (((uint32_t) data [offset]) << 24) + (data [offset + 1] << 16) + (data [offset + 2] << 8) + data [offset + 3] ;
if (CPU_IS_LITTLE_ENDIAN)
return data [offset] + (data [offset + 1] << 8) + (data [offset + 2] << 16) + (((uint32_t) data [offset + 3]) << 24) ;
return 0 ;
} /* read_rsrc_marker */
static void
read_rsrc_str (const SD2_RSRC *prsrc, int offset, char * buffer, int buffer_len)
{ const unsigned char * data = prsrc->rsrc_data ;
int k ;
memset (buffer, 0, buffer_len) ;
if (offset < 0 || offset + buffer_len >= prsrc->rsrc_len)
return ;
for (k = 0 ; k < buffer_len - 1 ; k++)
{ if (psf_isprint (data [offset + k]) == 0)
return ;
buffer [k] = data [offset + k] ;
} ;
return ;
} /* read_rsrc_str */
static int
sd2_parse_rsrc_fork (SF_PRIVATE *psf)
{ SD2_RSRC rsrc ;
int k, marker, error = 0 ;
psf_use_rsrc (psf, SF_TRUE) ;
memset (&rsrc, 0, sizeof (rsrc)) ;
rsrc.rsrc_len = psf_get_filelen (psf) ;
psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ;
if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header))
{ rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ;
rsrc.need_to_free_rsrc_data = SF_TRUE ;
}
else
{
rsrc.rsrc_data = psf->header ;
rsrc.need_to_free_rsrc_data = SF_FALSE ;
} ;
/* Read in the whole lot. */
psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ;
/* Reset the header storage because we have changed to the rsrcdes. */
psf->headindex = psf->headend = rsrc.rsrc_len ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0) ;
rsrc.map_offset = read_rsrc_int (&rsrc, 4) ;
rsrc.data_length = read_rsrc_int (&rsrc, 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 12) ;
if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000)
{ psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ;
rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ;
rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ;
} ;
psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n"
" data length : 0x%04X\n map length : 0x%04X\n",
rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ;
if (rsrc.data_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ;
error = SFE_SD2_BAD_DATA_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ;
error = SFE_SD2_BAD_MAP_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_length > len\n") ;
error = SFE_SD2_BAD_DATA_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_length > len\n") ;
error = SFE_SD2_BAD_MAP_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset + 28 >= rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ;
if (rsrc.string_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.type_offset = rsrc.map_offset + 30 ;
rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ;
if (rsrc.type_count < 1)
{ psf_log_printf (psf, "Bad type count.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ;
if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.str_index = -1 ;
for (k = 0 ; k < rsrc.type_count ; k ++)
{ marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ;
if (marker == STR_MARKER)
{ rsrc.str_index = k ;
rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ;
error = parse_str_rsrc (psf, &rsrc) ;
goto parse_rsrc_fork_cleanup ;
} ;
} ;
psf_log_printf (psf, "No 'STR ' resource.\n") ;
error = SFE_SD2_BAD_RSRC ;
parse_rsrc_fork_cleanup :
psf_use_rsrc (psf, SF_FALSE) ;
if (rsrc.need_to_free_rsrc_data)
free (rsrc.rsrc_data) ;
return error ;
} /* sd2_parse_rsrc_fork */
static int
parse_str_rsrc (SF_PRIVATE *psf, SD2_RSRC * rsrc)
{ char name [32], value [32] ;
int k, str_offset, rsrc_id, data_offset = 0, data_len = 0 ;
psf_log_printf (psf, "Finding parameters :\n") ;
str_offset = rsrc->string_offset ;
psf_log_printf (psf, " Offset RsrcId dlen slen Value\n") ;
for (k = 0 ; data_offset + data_len < rsrc->rsrc_len ; k++)
{ int slen ;
slen = read_rsrc_char (rsrc, str_offset) ;
read_rsrc_str (rsrc, str_offset + 1, name, SF_MIN (SIGNED_SIZEOF (name), slen + 1)) ;
str_offset += slen + 1 ;
rsrc_id = read_rsrc_short (rsrc, rsrc->item_offset + k * 12) ;
data_offset = rsrc->data_offset + read_rsrc_int (rsrc, rsrc->item_offset + k * 12 + 4) ;
if (data_offset < 0 || data_offset > rsrc->rsrc_len)
{ psf_log_printf (psf, "Exiting parser on data offset of %d.\n", data_offset) ;
break ;
} ;
data_len = read_rsrc_int (rsrc, data_offset) ;
if (data_len < 0 || data_len > rsrc->rsrc_len)
{ psf_log_printf (psf, "Exiting parser on data length of %d.\n", data_len) ;
break ;
} ;
slen = read_rsrc_char (rsrc, data_offset + 4) ;
read_rsrc_str (rsrc, data_offset + 5, value, SF_MIN (SIGNED_SIZEOF (value), slen + 1)) ;
psf_log_printf (psf, " 0x%04x %4d %4d %3d '%s'\n", data_offset, rsrc_id, data_len, slen, value) ;
if (rsrc_id == 1000 && rsrc->sample_size == 0)
rsrc->sample_size = strtol (value, NULL, 10) ;
else if (rsrc_id == 1001 && rsrc->sample_rate == 0)
rsrc->sample_rate = strtol (value, NULL, 10) ;
else if (rsrc_id == 1002 && rsrc->channels == 0)
rsrc->channels = strtol (value, NULL, 10) ;
} ;
psf_log_printf (psf, "Found Parameters :\n") ;
psf_log_printf (psf, " sample-size : %d\n", rsrc->sample_size) ;
psf_log_printf (psf, " sample-rate : %d\n", rsrc->sample_rate) ;
psf_log_printf (psf, " channels : %d\n", rsrc->channels) ;
if (rsrc->sample_rate <= 4 && rsrc->sample_size > 4)
{ int temp ;
psf_log_printf (psf, "Geez!! Looks like sample rate and sample size got switched.\nCorrecting this screw up.\n") ;
temp = rsrc->sample_rate ;
rsrc->sample_rate = rsrc->sample_size ;
rsrc->sample_size = temp ;
} ;
if (rsrc->sample_rate < 0)
{ psf_log_printf (psf, "Bad sample rate (%d)\n", rsrc->sample_rate) ;
return SFE_SD2_BAD_RSRC ;
} ;
if (rsrc->channels < 0)
{ psf_log_printf (psf, "Bad channel count (%d)\n", rsrc->channels) ;
return SFE_SD2_BAD_RSRC ;
} ;
psf->sf.samplerate = rsrc->sample_rate ;
psf->sf.channels = rsrc->channels ;
psf->bytewidth = rsrc->sample_size ;
switch (rsrc->sample_size)
{ case 1 :
psf->sf.format = SF_FORMAT_SD2 | SF_FORMAT_PCM_S8 ;
break ;
case 2 :
psf->sf.format = SF_FORMAT_SD2 | SF_FORMAT_PCM_16 ;
break ;
case 3 :
psf->sf.format = SF_FORMAT_SD2 | SF_FORMAT_PCM_24 ;
break ;
case 4 :
psf->sf.format = SF_FORMAT_SD2 | SF_FORMAT_PCM_32 ;
break ;
default :
psf_log_printf (psf, "Bad sample size (%d)\n", rsrc->sample_size) ;
return SFE_SD2_BAD_SAMPLE_SIZE ;
} ;
psf_log_printf (psf, "ok\n") ;
return 0 ;
} /* parse_str_rsrc */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2384_0 |
crossvul-cpp_data_bad_1655_0 | /* A network driver using virtio.
*
* Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
*
* 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/>.
*/
//#define DEBUG
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/module.h>
#include <linux/virtio.h>
#include <linux/virtio_net.h>
#include <linux/scatterlist.h>
#include <linux/if_vlan.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/average.h>
#include <net/busy_poll.h>
static int napi_weight = NAPI_POLL_WEIGHT;
module_param(napi_weight, int, 0444);
static bool csum = true, gso = true;
module_param(csum, bool, 0444);
module_param(gso, bool, 0444);
/* FIXME: MTU in config. */
#define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
#define GOOD_COPY_LEN 128
/* Weight used for the RX packet size EWMA. The average packet size is used to
* determine the packet buffer size when refilling RX rings. As the entire RX
* ring may be refilled at once, the weight is chosen so that the EWMA will be
* insensitive to short-term, transient changes in packet size.
*/
#define RECEIVE_AVG_WEIGHT 64
/* Minimum alignment for mergeable packet buffers. */
#define MERGEABLE_BUFFER_ALIGN max(L1_CACHE_BYTES, 256)
#define VIRTNET_DRIVER_VERSION "1.0.0"
struct virtnet_stats {
struct u64_stats_sync tx_syncp;
struct u64_stats_sync rx_syncp;
u64 tx_bytes;
u64 tx_packets;
u64 rx_bytes;
u64 rx_packets;
};
/* Internal representation of a send virtqueue */
struct send_queue {
/* Virtqueue associated with this send _queue */
struct virtqueue *vq;
/* TX: fragments + linear part + virtio header */
struct scatterlist sg[MAX_SKB_FRAGS + 2];
/* Name of the send queue: output.$index */
char name[40];
};
/* Internal representation of a receive virtqueue */
struct receive_queue {
/* Virtqueue associated with this receive_queue */
struct virtqueue *vq;
struct napi_struct napi;
/* Chain pages by the private ptr. */
struct page *pages;
/* Average packet length for mergeable receive buffers. */
struct ewma mrg_avg_pkt_len;
/* Page frag for packet buffer allocation. */
struct page_frag alloc_frag;
/* RX: fragments + linear part + virtio header */
struct scatterlist sg[MAX_SKB_FRAGS + 2];
/* Name of this receive queue: input.$index */
char name[40];
};
struct virtnet_info {
struct virtio_device *vdev;
struct virtqueue *cvq;
struct net_device *dev;
struct send_queue *sq;
struct receive_queue *rq;
unsigned int status;
/* Max # of queue pairs supported by the device */
u16 max_queue_pairs;
/* # of queue pairs currently used by the driver */
u16 curr_queue_pairs;
/* I like... big packets and I cannot lie! */
bool big_packets;
/* Host will merge rx buffers for big packets (shake it! shake it!) */
bool mergeable_rx_bufs;
/* Has control virtqueue */
bool has_cvq;
/* Host can handle any s/g split between our header and packet data */
bool any_header_sg;
/* Packet virtio header size */
u8 hdr_len;
/* Active statistics */
struct virtnet_stats __percpu *stats;
/* Work struct for refilling if we run low on memory. */
struct delayed_work refill;
/* Work struct for config space updates */
struct work_struct config_work;
/* Does the affinity hint is set for virtqueues? */
bool affinity_hint_set;
/* CPU hot plug notifier */
struct notifier_block nb;
};
struct padded_vnet_hdr {
struct virtio_net_hdr_mrg_rxbuf hdr;
/*
* hdr is in a separate sg buffer, and data sg buffer shares same page
* with this header sg. This padding makes next sg 16 byte aligned
* after the header.
*/
char padding[4];
};
/* Converting between virtqueue no. and kernel tx/rx queue no.
* 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
*/
static int vq2txq(struct virtqueue *vq)
{
return (vq->index - 1) / 2;
}
static int txq2vq(int txq)
{
return txq * 2 + 1;
}
static int vq2rxq(struct virtqueue *vq)
{
return vq->index / 2;
}
static int rxq2vq(int rxq)
{
return rxq * 2;
}
static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
{
return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
}
/*
* private is used to chain pages for big packets, put the whole
* most recent used list in the beginning for reuse
*/
static void give_pages(struct receive_queue *rq, struct page *page)
{
struct page *end;
/* Find end of list, sew whole thing into vi->rq.pages. */
for (end = page; end->private; end = (struct page *)end->private);
end->private = (unsigned long)rq->pages;
rq->pages = page;
}
static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
{
struct page *p = rq->pages;
if (p) {
rq->pages = (struct page *)p->private;
/* clear private here, it is used to chain pages */
p->private = 0;
} else
p = alloc_page(gfp_mask);
return p;
}
static void skb_xmit_done(struct virtqueue *vq)
{
struct virtnet_info *vi = vq->vdev->priv;
/* Suppress further interrupts. */
virtqueue_disable_cb(vq);
/* We were probably waiting for more output buffers. */
netif_wake_subqueue(vi->dev, vq2txq(vq));
}
static unsigned int mergeable_ctx_to_buf_truesize(unsigned long mrg_ctx)
{
unsigned int truesize = mrg_ctx & (MERGEABLE_BUFFER_ALIGN - 1);
return (truesize + 1) * MERGEABLE_BUFFER_ALIGN;
}
static void *mergeable_ctx_to_buf_address(unsigned long mrg_ctx)
{
return (void *)(mrg_ctx & -MERGEABLE_BUFFER_ALIGN);
}
static unsigned long mergeable_buf_to_ctx(void *buf, unsigned int truesize)
{
unsigned int size = truesize / MERGEABLE_BUFFER_ALIGN;
return (unsigned long)buf | (size - 1);
}
/* Called from bottom half context */
static struct sk_buff *page_to_skb(struct virtnet_info *vi,
struct receive_queue *rq,
struct page *page, unsigned int offset,
unsigned int len, unsigned int truesize)
{
struct sk_buff *skb;
struct virtio_net_hdr_mrg_rxbuf *hdr;
unsigned int copy, hdr_len, hdr_padded_len;
char *p;
p = page_address(page) + offset;
/* copy small packet so we can reuse these pages for small data */
skb = netdev_alloc_skb_ip_align(vi->dev, GOOD_COPY_LEN);
if (unlikely(!skb))
return NULL;
hdr = skb_vnet_hdr(skb);
hdr_len = vi->hdr_len;
if (vi->mergeable_rx_bufs)
hdr_padded_len = sizeof *hdr;
else
hdr_padded_len = sizeof(struct padded_vnet_hdr);
memcpy(hdr, p, hdr_len);
len -= hdr_len;
offset += hdr_padded_len;
p += hdr_padded_len;
copy = len;
if (copy > skb_tailroom(skb))
copy = skb_tailroom(skb);
memcpy(skb_put(skb, copy), p, copy);
len -= copy;
offset += copy;
if (vi->mergeable_rx_bufs) {
if (len)
skb_add_rx_frag(skb, 0, page, offset, len, truesize);
else
put_page(page);
return skb;
}
/*
* Verify that we can indeed put this data into a skb.
* This is here to handle cases when the device erroneously
* tries to receive more than is possible. This is usually
* the case of a broken device.
*/
if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
dev_kfree_skb(skb);
return NULL;
}
BUG_ON(offset >= PAGE_SIZE);
while (len) {
unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
frag_size, truesize);
len -= frag_size;
page = (struct page *)page->private;
offset = 0;
}
if (page)
give_pages(rq, page);
return skb;
}
static struct sk_buff *receive_small(struct virtnet_info *vi, void *buf, unsigned int len)
{
struct sk_buff * skb = buf;
len -= vi->hdr_len;
skb_trim(skb, len);
return skb;
}
static struct sk_buff *receive_big(struct net_device *dev,
struct virtnet_info *vi,
struct receive_queue *rq,
void *buf,
unsigned int len)
{
struct page *page = buf;
struct sk_buff *skb = page_to_skb(vi, rq, page, 0, len, PAGE_SIZE);
if (unlikely(!skb))
goto err;
return skb;
err:
dev->stats.rx_dropped++;
give_pages(rq, page);
return NULL;
}
static struct sk_buff *receive_mergeable(struct net_device *dev,
struct virtnet_info *vi,
struct receive_queue *rq,
unsigned long ctx,
unsigned int len)
{
void *buf = mergeable_ctx_to_buf_address(ctx);
struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
struct page *page = virt_to_head_page(buf);
int offset = buf - page_address(page);
unsigned int truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
struct sk_buff *head_skb = page_to_skb(vi, rq, page, offset, len,
truesize);
struct sk_buff *curr_skb = head_skb;
if (unlikely(!curr_skb))
goto err_skb;
while (--num_buf) {
int num_skb_frags;
ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
if (unlikely(!ctx)) {
pr_debug("%s: rx error: %d buffers out of %d missing\n",
dev->name, num_buf,
virtio16_to_cpu(vi->vdev,
hdr->num_buffers));
dev->stats.rx_length_errors++;
goto err_buf;
}
buf = mergeable_ctx_to_buf_address(ctx);
page = virt_to_head_page(buf);
num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
if (unlikely(!nskb))
goto err_skb;
if (curr_skb == head_skb)
skb_shinfo(curr_skb)->frag_list = nskb;
else
curr_skb->next = nskb;
curr_skb = nskb;
head_skb->truesize += nskb->truesize;
num_skb_frags = 0;
}
truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
if (curr_skb != head_skb) {
head_skb->data_len += len;
head_skb->len += len;
head_skb->truesize += truesize;
}
offset = buf - page_address(page);
if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
put_page(page);
skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
len, truesize);
} else {
skb_add_rx_frag(curr_skb, num_skb_frags, page,
offset, len, truesize);
}
}
ewma_add(&rq->mrg_avg_pkt_len, head_skb->len);
return head_skb;
err_skb:
put_page(page);
while (--num_buf) {
ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
if (unlikely(!ctx)) {
pr_debug("%s: rx error: %d buffers missing\n",
dev->name, num_buf);
dev->stats.rx_length_errors++;
break;
}
page = virt_to_head_page(mergeable_ctx_to_buf_address(ctx));
put_page(page);
}
err_buf:
dev->stats.rx_dropped++;
dev_kfree_skb(head_skb);
return NULL;
}
static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
void *buf, unsigned int len)
{
struct net_device *dev = vi->dev;
struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
struct sk_buff *skb;
struct virtio_net_hdr_mrg_rxbuf *hdr;
if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
pr_debug("%s: short packet %i\n", dev->name, len);
dev->stats.rx_length_errors++;
if (vi->mergeable_rx_bufs) {
unsigned long ctx = (unsigned long)buf;
void *base = mergeable_ctx_to_buf_address(ctx);
put_page(virt_to_head_page(base));
} else if (vi->big_packets) {
give_pages(rq, buf);
} else {
dev_kfree_skb(buf);
}
return;
}
if (vi->mergeable_rx_bufs)
skb = receive_mergeable(dev, vi, rq, (unsigned long)buf, len);
else if (vi->big_packets)
skb = receive_big(dev, vi, rq, buf, len);
else
skb = receive_small(vi, buf, len);
if (unlikely(!skb))
return;
hdr = skb_vnet_hdr(skb);
u64_stats_update_begin(&stats->rx_syncp);
stats->rx_bytes += skb->len;
stats->rx_packets++;
u64_stats_update_end(&stats->rx_syncp);
if (hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
pr_debug("Needs csum!\n");
if (!skb_partial_csum_set(skb,
virtio16_to_cpu(vi->vdev, hdr->hdr.csum_start),
virtio16_to_cpu(vi->vdev, hdr->hdr.csum_offset)))
goto frame_err;
} else if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
skb->protocol = eth_type_trans(skb, dev);
pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
ntohs(skb->protocol), skb->len, skb->pkt_type);
if (hdr->hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
pr_debug("GSO!\n");
switch (hdr->hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
case VIRTIO_NET_HDR_GSO_TCPV4:
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
break;
case VIRTIO_NET_HDR_GSO_UDP:
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
break;
case VIRTIO_NET_HDR_GSO_TCPV6:
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
break;
default:
net_warn_ratelimited("%s: bad gso type %u.\n",
dev->name, hdr->hdr.gso_type);
goto frame_err;
}
if (hdr->hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
skb_shinfo(skb)->gso_size = virtio16_to_cpu(vi->vdev,
hdr->hdr.gso_size);
if (skb_shinfo(skb)->gso_size == 0) {
net_warn_ratelimited("%s: zero gso size.\n", dev->name);
goto frame_err;
}
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
}
skb_mark_napi_id(skb, &rq->napi);
netif_receive_skb(skb);
return;
frame_err:
dev->stats.rx_frame_errors++;
dev_kfree_skb(skb);
}
static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
gfp_t gfp)
{
struct sk_buff *skb;
struct virtio_net_hdr_mrg_rxbuf *hdr;
int err;
skb = __netdev_alloc_skb_ip_align(vi->dev, GOOD_PACKET_LEN, gfp);
if (unlikely(!skb))
return -ENOMEM;
skb_put(skb, GOOD_PACKET_LEN);
hdr = skb_vnet_hdr(skb);
sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
sg_set_buf(rq->sg, hdr, vi->hdr_len);
skb_to_sgvec(skb, rq->sg + 1, 0, skb->len);
err = virtqueue_add_inbuf(rq->vq, rq->sg, 2, skb, gfp);
if (err < 0)
dev_kfree_skb(skb);
return err;
}
static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
gfp_t gfp)
{
struct page *first, *list = NULL;
char *p;
int i, err, offset;
sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
/* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
first = get_a_page(rq, gfp);
if (!first) {
if (list)
give_pages(rq, list);
return -ENOMEM;
}
sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
/* chain new page in list head to match sg */
first->private = (unsigned long)list;
list = first;
}
first = get_a_page(rq, gfp);
if (!first) {
give_pages(rq, list);
return -ENOMEM;
}
p = page_address(first);
/* rq->sg[0], rq->sg[1] share the same page */
/* a separated rq->sg[0] for header - required in case !any_header_sg */
sg_set_buf(&rq->sg[0], p, vi->hdr_len);
/* rq->sg[1] for data packet, from offset */
offset = sizeof(struct padded_vnet_hdr);
sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
/* chain first in list head */
first->private = (unsigned long)list;
err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
first, gfp);
if (err < 0)
give_pages(rq, first);
return err;
}
static unsigned int get_mergeable_buf_len(struct ewma *avg_pkt_len)
{
const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
unsigned int len;
len = hdr_len + clamp_t(unsigned int, ewma_read(avg_pkt_len),
GOOD_PACKET_LEN, PAGE_SIZE - hdr_len);
return ALIGN(len, MERGEABLE_BUFFER_ALIGN);
}
static int add_recvbuf_mergeable(struct receive_queue *rq, gfp_t gfp)
{
struct page_frag *alloc_frag = &rq->alloc_frag;
char *buf;
unsigned long ctx;
int err;
unsigned int len, hole;
len = get_mergeable_buf_len(&rq->mrg_avg_pkt_len);
if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
return -ENOMEM;
buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
ctx = mergeable_buf_to_ctx(buf, len);
get_page(alloc_frag->page);
alloc_frag->offset += len;
hole = alloc_frag->size - alloc_frag->offset;
if (hole < len) {
/* To avoid internal fragmentation, if there is very likely not
* enough space for another buffer, add the remaining space to
* the current buffer. This extra space is not included in
* the truesize stored in ctx.
*/
len += hole;
alloc_frag->offset += hole;
}
sg_init_one(rq->sg, buf, len);
err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, (void *)ctx, gfp);
if (err < 0)
put_page(virt_to_head_page(buf));
return err;
}
/*
* Returns false if we couldn't fill entirely (OOM).
*
* Normally run in the receive path, but can also be run from ndo_open
* before we're receiving packets, or from refill_work which is
* careful to disable receiving (using napi_disable).
*/
static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
gfp_t gfp)
{
int err;
bool oom;
gfp |= __GFP_COLD;
do {
if (vi->mergeable_rx_bufs)
err = add_recvbuf_mergeable(rq, gfp);
else if (vi->big_packets)
err = add_recvbuf_big(vi, rq, gfp);
else
err = add_recvbuf_small(vi, rq, gfp);
oom = err == -ENOMEM;
if (err)
break;
} while (rq->vq->num_free);
virtqueue_kick(rq->vq);
return !oom;
}
static void skb_recv_done(struct virtqueue *rvq)
{
struct virtnet_info *vi = rvq->vdev->priv;
struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
/* Schedule NAPI, Suppress further interrupts if successful. */
if (napi_schedule_prep(&rq->napi)) {
virtqueue_disable_cb(rvq);
__napi_schedule(&rq->napi);
}
}
static void virtnet_napi_enable(struct receive_queue *rq)
{
napi_enable(&rq->napi);
/* If all buffers were filled by other side before we napi_enabled, we
* won't get another interrupt, so process any outstanding packets
* now. virtnet_poll wants re-enable the queue, so we disable here.
* We synchronize against interrupts via NAPI_STATE_SCHED */
if (napi_schedule_prep(&rq->napi)) {
virtqueue_disable_cb(rq->vq);
local_bh_disable();
__napi_schedule(&rq->napi);
local_bh_enable();
}
}
static void refill_work(struct work_struct *work)
{
struct virtnet_info *vi =
container_of(work, struct virtnet_info, refill.work);
bool still_empty;
int i;
for (i = 0; i < vi->curr_queue_pairs; i++) {
struct receive_queue *rq = &vi->rq[i];
napi_disable(&rq->napi);
still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
virtnet_napi_enable(rq);
/* In theory, this can happen: if we don't get any buffers in
* we will *never* try to fill again.
*/
if (still_empty)
schedule_delayed_work(&vi->refill, HZ/2);
}
}
static int virtnet_receive(struct receive_queue *rq, int budget)
{
struct virtnet_info *vi = rq->vq->vdev->priv;
unsigned int len, received = 0;
void *buf;
while (received < budget &&
(buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
receive_buf(vi, rq, buf, len);
received++;
}
if (rq->vq->num_free > virtqueue_get_vring_size(rq->vq) / 2) {
if (!try_fill_recv(vi, rq, GFP_ATOMIC))
schedule_delayed_work(&vi->refill, 0);
}
return received;
}
static int virtnet_poll(struct napi_struct *napi, int budget)
{
struct receive_queue *rq =
container_of(napi, struct receive_queue, napi);
unsigned int r, received;
received = virtnet_receive(rq, budget);
/* Out of packets? */
if (received < budget) {
r = virtqueue_enable_cb_prepare(rq->vq);
napi_complete(napi);
if (unlikely(virtqueue_poll(rq->vq, r)) &&
napi_schedule_prep(napi)) {
virtqueue_disable_cb(rq->vq);
__napi_schedule(napi);
}
}
return received;
}
#ifdef CONFIG_NET_RX_BUSY_POLL
/* must be called with local_bh_disable()d */
static int virtnet_busy_poll(struct napi_struct *napi)
{
struct receive_queue *rq =
container_of(napi, struct receive_queue, napi);
struct virtnet_info *vi = rq->vq->vdev->priv;
int r, received = 0, budget = 4;
if (!(vi->status & VIRTIO_NET_S_LINK_UP))
return LL_FLUSH_FAILED;
if (!napi_schedule_prep(napi))
return LL_FLUSH_BUSY;
virtqueue_disable_cb(rq->vq);
again:
received += virtnet_receive(rq, budget);
r = virtqueue_enable_cb_prepare(rq->vq);
clear_bit(NAPI_STATE_SCHED, &napi->state);
if (unlikely(virtqueue_poll(rq->vq, r)) &&
napi_schedule_prep(napi)) {
virtqueue_disable_cb(rq->vq);
if (received < budget) {
budget -= received;
goto again;
} else {
__napi_schedule(napi);
}
}
return received;
}
#endif /* CONFIG_NET_RX_BUSY_POLL */
static int virtnet_open(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
int i;
for (i = 0; i < vi->max_queue_pairs; i++) {
if (i < vi->curr_queue_pairs)
/* Make sure we have some buffers: if oom use wq. */
if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
schedule_delayed_work(&vi->refill, 0);
virtnet_napi_enable(&vi->rq[i]);
}
return 0;
}
static void free_old_xmit_skbs(struct send_queue *sq)
{
struct sk_buff *skb;
unsigned int len;
struct virtnet_info *vi = sq->vq->vdev->priv;
struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
while ((skb = virtqueue_get_buf(sq->vq, &len)) != NULL) {
pr_debug("Sent skb %p\n", skb);
u64_stats_update_begin(&stats->tx_syncp);
stats->tx_bytes += skb->len;
stats->tx_packets++;
u64_stats_update_end(&stats->tx_syncp);
dev_kfree_skb_any(skb);
}
}
static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
{
struct virtio_net_hdr_mrg_rxbuf *hdr;
const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
struct virtnet_info *vi = sq->vq->vdev->priv;
unsigned num_sg;
unsigned hdr_len = vi->hdr_len;
bool can_push;
pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
can_push = vi->any_header_sg &&
!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
/* Even if we can, don't push here yet as this would skew
* csum_start offset below. */
if (can_push)
hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
else
hdr = skb_vnet_hdr(skb);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
hdr->hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
hdr->hdr.csum_start = cpu_to_virtio16(vi->vdev,
skb_checksum_start_offset(skb));
hdr->hdr.csum_offset = cpu_to_virtio16(vi->vdev,
skb->csum_offset);
} else {
hdr->hdr.flags = 0;
hdr->hdr.csum_offset = hdr->hdr.csum_start = 0;
}
if (skb_is_gso(skb)) {
hdr->hdr.hdr_len = cpu_to_virtio16(vi->vdev, skb_headlen(skb));
hdr->hdr.gso_size = cpu_to_virtio16(vi->vdev,
skb_shinfo(skb)->gso_size);
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4)
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
else
BUG();
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN)
hdr->hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else {
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
hdr->hdr.gso_size = hdr->hdr.hdr_len = 0;
}
if (vi->mergeable_rx_bufs)
hdr->num_buffers = 0;
sg_init_table(sq->sg, MAX_SKB_FRAGS + 2);
if (can_push) {
__skb_push(skb, hdr_len);
num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
/* Pull header back to avoid skew in tx bytes calculations. */
__skb_pull(skb, hdr_len);
} else {
sg_set_buf(sq->sg, hdr, hdr_len);
num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1;
}
return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
}
static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
int qnum = skb_get_queue_mapping(skb);
struct send_queue *sq = &vi->sq[qnum];
int err;
struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
bool kick = !skb->xmit_more;
/* Free up any pending old buffers before queueing new ones. */
free_old_xmit_skbs(sq);
/* timestamp packet in software */
skb_tx_timestamp(skb);
/* Try to transmit */
err = xmit_skb(sq, skb);
/* This should not happen! */
if (unlikely(err)) {
dev->stats.tx_fifo_errors++;
if (net_ratelimit())
dev_warn(&dev->dev,
"Unexpected TXQ (%d) queue failure: %d\n", qnum, err);
dev->stats.tx_dropped++;
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* Don't wait up for transmitted skbs to be freed. */
skb_orphan(skb);
nf_reset(skb);
/* If running out of space, stop queue to avoid getting packets that we
* are then unable to transmit.
* An alternative would be to force queuing layer to requeue the skb by
* returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
* returned in a normal path of operation: it means that driver is not
* maintaining the TX queue stop/start state properly, and causes
* the stack to do a non-trivial amount of useless work.
* Since most packets only take 1 or 2 ring slots, stopping the queue
* early means 16 slots are typically wasted.
*/
if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
netif_stop_subqueue(dev, qnum);
if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
/* More just got used, free them then recheck. */
free_old_xmit_skbs(sq);
if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
netif_start_subqueue(dev, qnum);
virtqueue_disable_cb(sq->vq);
}
}
}
if (kick || netif_xmit_stopped(txq))
virtqueue_kick(sq->vq);
return NETDEV_TX_OK;
}
/*
* Send command via the control virtqueue and check status. Commands
* supported by the hypervisor, as indicated by feature bits, should
* never fail unless improperly formatted.
*/
static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
struct scatterlist *out)
{
struct scatterlist *sgs[4], hdr, stat;
struct virtio_net_ctrl_hdr ctrl;
virtio_net_ctrl_ack status = ~0;
unsigned out_num = 0, tmp;
/* Caller should know better */
BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
ctrl.class = class;
ctrl.cmd = cmd;
/* Add header */
sg_init_one(&hdr, &ctrl, sizeof(ctrl));
sgs[out_num++] = &hdr;
if (out)
sgs[out_num++] = out;
/* Add return status. */
sg_init_one(&stat, &status, sizeof(status));
sgs[out_num] = &stat;
BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
if (unlikely(!virtqueue_kick(vi->cvq)))
return status == VIRTIO_NET_OK;
/* Spin for a response, the kick causes an ioport write, trapping
* into the hypervisor, so the request should be handled immediately.
*/
while (!virtqueue_get_buf(vi->cvq, &tmp) &&
!virtqueue_is_broken(vi->cvq))
cpu_relax();
return status == VIRTIO_NET_OK;
}
static int virtnet_set_mac_address(struct net_device *dev, void *p)
{
struct virtnet_info *vi = netdev_priv(dev);
struct virtio_device *vdev = vi->vdev;
int ret;
struct sockaddr *addr = p;
struct scatterlist sg;
ret = eth_prepare_mac_addr_change(dev, p);
if (ret)
return ret;
if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
sg_init_one(&sg, addr->sa_data, dev->addr_len);
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
dev_warn(&vdev->dev,
"Failed to set mac address by vq command.\n");
return -EINVAL;
}
} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
!virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
unsigned int i;
/* Naturally, this has an atomicity problem. */
for (i = 0; i < dev->addr_len; i++)
virtio_cwrite8(vdev,
offsetof(struct virtio_net_config, mac) +
i, addr->sa_data[i]);
}
eth_commit_mac_addr_change(dev, p);
return 0;
}
static struct rtnl_link_stats64 *virtnet_stats(struct net_device *dev,
struct rtnl_link_stats64 *tot)
{
struct virtnet_info *vi = netdev_priv(dev);
int cpu;
unsigned int start;
for_each_possible_cpu(cpu) {
struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
u64 tpackets, tbytes, rpackets, rbytes;
do {
start = u64_stats_fetch_begin_irq(&stats->tx_syncp);
tpackets = stats->tx_packets;
tbytes = stats->tx_bytes;
} while (u64_stats_fetch_retry_irq(&stats->tx_syncp, start));
do {
start = u64_stats_fetch_begin_irq(&stats->rx_syncp);
rpackets = stats->rx_packets;
rbytes = stats->rx_bytes;
} while (u64_stats_fetch_retry_irq(&stats->rx_syncp, start));
tot->rx_packets += rpackets;
tot->tx_packets += tpackets;
tot->rx_bytes += rbytes;
tot->tx_bytes += tbytes;
}
tot->tx_dropped = dev->stats.tx_dropped;
tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
tot->rx_dropped = dev->stats.rx_dropped;
tot->rx_length_errors = dev->stats.rx_length_errors;
tot->rx_frame_errors = dev->stats.rx_frame_errors;
return tot;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void virtnet_netpoll(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
int i;
for (i = 0; i < vi->curr_queue_pairs; i++)
napi_schedule(&vi->rq[i].napi);
}
#endif
static void virtnet_ack_link_announce(struct virtnet_info *vi)
{
rtnl_lock();
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
rtnl_unlock();
}
static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
{
struct scatterlist sg;
struct virtio_net_ctrl_mq s;
struct net_device *dev = vi->dev;
if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
return 0;
s.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
sg_init_one(&sg, &s, sizeof(s));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
queue_pairs);
return -EINVAL;
} else {
vi->curr_queue_pairs = queue_pairs;
/* virtnet_open() will refill when device is going to up. */
if (dev->flags & IFF_UP)
schedule_delayed_work(&vi->refill, 0);
}
return 0;
}
static int virtnet_close(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
int i;
/* Make sure refill_work doesn't re-enable napi! */
cancel_delayed_work_sync(&vi->refill);
for (i = 0; i < vi->max_queue_pairs; i++)
napi_disable(&vi->rq[i].napi);
return 0;
}
static void virtnet_set_rx_mode(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
struct scatterlist sg[2];
u8 promisc, allmulti;
struct virtio_net_ctrl_mac *mac_data;
struct netdev_hw_addr *ha;
int uc_count;
int mc_count;
void *buf;
int i;
/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
return;
promisc = ((dev->flags & IFF_PROMISC) != 0);
allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
sg_init_one(sg, &promisc, sizeof(promisc));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
VIRTIO_NET_CTRL_RX_PROMISC, sg))
dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
promisc ? "en" : "dis");
sg_init_one(sg, &allmulti, sizeof(allmulti));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
allmulti ? "en" : "dis");
uc_count = netdev_uc_count(dev);
mc_count = netdev_mc_count(dev);
/* MAC filter - use one buffer for both lists */
buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
(2 * sizeof(mac_data->entries)), GFP_ATOMIC);
mac_data = buf;
if (!buf)
return;
sg_init_table(sg, 2);
/* Store the unicast list and count in the front of the buffer */
mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
i = 0;
netdev_for_each_uc_addr(ha, dev)
memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
sg_set_buf(&sg[0], mac_data,
sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
/* multicast list and count fill the end */
mac_data = (void *)&mac_data->macs[uc_count][0];
mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
i = 0;
netdev_for_each_mc_addr(ha, dev)
memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
sg_set_buf(&sg[1], mac_data,
sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
kfree(buf);
}
static int virtnet_vlan_rx_add_vid(struct net_device *dev,
__be16 proto, u16 vid)
{
struct virtnet_info *vi = netdev_priv(dev);
struct scatterlist sg;
sg_init_one(&sg, &vid, sizeof(vid));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
VIRTIO_NET_CTRL_VLAN_ADD, &sg))
dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
return 0;
}
static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
__be16 proto, u16 vid)
{
struct virtnet_info *vi = netdev_priv(dev);
struct scatterlist sg;
sg_init_one(&sg, &vid, sizeof(vid));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
VIRTIO_NET_CTRL_VLAN_DEL, &sg))
dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
return 0;
}
static void virtnet_clean_affinity(struct virtnet_info *vi, long hcpu)
{
int i;
if (vi->affinity_hint_set) {
for (i = 0; i < vi->max_queue_pairs; i++) {
virtqueue_set_affinity(vi->rq[i].vq, -1);
virtqueue_set_affinity(vi->sq[i].vq, -1);
}
vi->affinity_hint_set = false;
}
}
static void virtnet_set_affinity(struct virtnet_info *vi)
{
int i;
int cpu;
/* In multiqueue mode, when the number of cpu is equal to the number of
* queue pairs, we let the queue pairs to be private to one cpu by
* setting the affinity hint to eliminate the contention.
*/
if (vi->curr_queue_pairs == 1 ||
vi->max_queue_pairs != num_online_cpus()) {
virtnet_clean_affinity(vi, -1);
return;
}
i = 0;
for_each_online_cpu(cpu) {
virtqueue_set_affinity(vi->rq[i].vq, cpu);
virtqueue_set_affinity(vi->sq[i].vq, cpu);
netif_set_xps_queue(vi->dev, cpumask_of(cpu), i);
i++;
}
vi->affinity_hint_set = true;
}
static int virtnet_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
struct virtnet_info *vi = container_of(nfb, struct virtnet_info, nb);
switch(action & ~CPU_TASKS_FROZEN) {
case CPU_ONLINE:
case CPU_DOWN_FAILED:
case CPU_DEAD:
virtnet_set_affinity(vi);
break;
case CPU_DOWN_PREPARE:
virtnet_clean_affinity(vi, (long)hcpu);
break;
default:
break;
}
return NOTIFY_OK;
}
static void virtnet_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *ring)
{
struct virtnet_info *vi = netdev_priv(dev);
ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
ring->rx_pending = ring->rx_max_pending;
ring->tx_pending = ring->tx_max_pending;
}
static void virtnet_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct virtnet_info *vi = netdev_priv(dev);
struct virtio_device *vdev = vi->vdev;
strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
}
/* TODO: Eliminate OOO packets during switching */
static int virtnet_set_channels(struct net_device *dev,
struct ethtool_channels *channels)
{
struct virtnet_info *vi = netdev_priv(dev);
u16 queue_pairs = channels->combined_count;
int err;
/* We don't support separate rx/tx channels.
* We don't allow setting 'other' channels.
*/
if (channels->rx_count || channels->tx_count || channels->other_count)
return -EINVAL;
if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
return -EINVAL;
get_online_cpus();
err = virtnet_set_queues(vi, queue_pairs);
if (!err) {
netif_set_real_num_tx_queues(dev, queue_pairs);
netif_set_real_num_rx_queues(dev, queue_pairs);
virtnet_set_affinity(vi);
}
put_online_cpus();
return err;
}
static void virtnet_get_channels(struct net_device *dev,
struct ethtool_channels *channels)
{
struct virtnet_info *vi = netdev_priv(dev);
channels->combined_count = vi->curr_queue_pairs;
channels->max_combined = vi->max_queue_pairs;
channels->max_other = 0;
channels->rx_count = 0;
channels->tx_count = 0;
channels->other_count = 0;
}
static const struct ethtool_ops virtnet_ethtool_ops = {
.get_drvinfo = virtnet_get_drvinfo,
.get_link = ethtool_op_get_link,
.get_ringparam = virtnet_get_ringparam,
.set_channels = virtnet_set_channels,
.get_channels = virtnet_get_channels,
.get_ts_info = ethtool_op_get_ts_info,
};
#define MIN_MTU 68
#define MAX_MTU 65535
static int virtnet_change_mtu(struct net_device *dev, int new_mtu)
{
if (new_mtu < MIN_MTU || new_mtu > MAX_MTU)
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
static const struct net_device_ops virtnet_netdev = {
.ndo_open = virtnet_open,
.ndo_stop = virtnet_close,
.ndo_start_xmit = start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = virtnet_set_mac_address,
.ndo_set_rx_mode = virtnet_set_rx_mode,
.ndo_change_mtu = virtnet_change_mtu,
.ndo_get_stats64 = virtnet_stats,
.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = virtnet_netpoll,
#endif
#ifdef CONFIG_NET_RX_BUSY_POLL
.ndo_busy_poll = virtnet_busy_poll,
#endif
};
static void virtnet_config_changed_work(struct work_struct *work)
{
struct virtnet_info *vi =
container_of(work, struct virtnet_info, config_work);
u16 v;
if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
struct virtio_net_config, status, &v) < 0)
return;
if (v & VIRTIO_NET_S_ANNOUNCE) {
netdev_notify_peers(vi->dev);
virtnet_ack_link_announce(vi);
}
/* Ignore unknown (future) status bits */
v &= VIRTIO_NET_S_LINK_UP;
if (vi->status == v)
return;
vi->status = v;
if (vi->status & VIRTIO_NET_S_LINK_UP) {
netif_carrier_on(vi->dev);
netif_tx_wake_all_queues(vi->dev);
} else {
netif_carrier_off(vi->dev);
netif_tx_stop_all_queues(vi->dev);
}
}
static void virtnet_config_changed(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
schedule_work(&vi->config_work);
}
static void virtnet_free_queues(struct virtnet_info *vi)
{
int i;
for (i = 0; i < vi->max_queue_pairs; i++) {
napi_hash_del(&vi->rq[i].napi);
netif_napi_del(&vi->rq[i].napi);
}
kfree(vi->rq);
kfree(vi->sq);
}
static void free_receive_bufs(struct virtnet_info *vi)
{
int i;
for (i = 0; i < vi->max_queue_pairs; i++) {
while (vi->rq[i].pages)
__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
}
}
static void free_receive_page_frags(struct virtnet_info *vi)
{
int i;
for (i = 0; i < vi->max_queue_pairs; i++)
if (vi->rq[i].alloc_frag.page)
put_page(vi->rq[i].alloc_frag.page);
}
static void free_unused_bufs(struct virtnet_info *vi)
{
void *buf;
int i;
for (i = 0; i < vi->max_queue_pairs; i++) {
struct virtqueue *vq = vi->sq[i].vq;
while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
dev_kfree_skb(buf);
}
for (i = 0; i < vi->max_queue_pairs; i++) {
struct virtqueue *vq = vi->rq[i].vq;
while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
if (vi->mergeable_rx_bufs) {
unsigned long ctx = (unsigned long)buf;
void *base = mergeable_ctx_to_buf_address(ctx);
put_page(virt_to_head_page(base));
} else if (vi->big_packets) {
give_pages(&vi->rq[i], buf);
} else {
dev_kfree_skb(buf);
}
}
}
}
static void virtnet_del_vqs(struct virtnet_info *vi)
{
struct virtio_device *vdev = vi->vdev;
virtnet_clean_affinity(vi, -1);
vdev->config->del_vqs(vdev);
virtnet_free_queues(vi);
}
static int virtnet_find_vqs(struct virtnet_info *vi)
{
vq_callback_t **callbacks;
struct virtqueue **vqs;
int ret = -ENOMEM;
int i, total_vqs;
const char **names;
/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
* possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
* possible control vq.
*/
total_vqs = vi->max_queue_pairs * 2 +
virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
/* Allocate space for find_vqs parameters */
vqs = kzalloc(total_vqs * sizeof(*vqs), GFP_KERNEL);
if (!vqs)
goto err_vq;
callbacks = kmalloc(total_vqs * sizeof(*callbacks), GFP_KERNEL);
if (!callbacks)
goto err_callback;
names = kmalloc(total_vqs * sizeof(*names), GFP_KERNEL);
if (!names)
goto err_names;
/* Parameters for control virtqueue, if any */
if (vi->has_cvq) {
callbacks[total_vqs - 1] = NULL;
names[total_vqs - 1] = "control";
}
/* Allocate/initialize parameters for send/receive virtqueues */
for (i = 0; i < vi->max_queue_pairs; i++) {
callbacks[rxq2vq(i)] = skb_recv_done;
callbacks[txq2vq(i)] = skb_xmit_done;
sprintf(vi->rq[i].name, "input.%d", i);
sprintf(vi->sq[i].name, "output.%d", i);
names[rxq2vq(i)] = vi->rq[i].name;
names[txq2vq(i)] = vi->sq[i].name;
}
ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
names);
if (ret)
goto err_find;
if (vi->has_cvq) {
vi->cvq = vqs[total_vqs - 1];
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
}
for (i = 0; i < vi->max_queue_pairs; i++) {
vi->rq[i].vq = vqs[rxq2vq(i)];
vi->sq[i].vq = vqs[txq2vq(i)];
}
kfree(names);
kfree(callbacks);
kfree(vqs);
return 0;
err_find:
kfree(names);
err_names:
kfree(callbacks);
err_callback:
kfree(vqs);
err_vq:
return ret;
}
static int virtnet_alloc_queues(struct virtnet_info *vi)
{
int i;
vi->sq = kzalloc(sizeof(*vi->sq) * vi->max_queue_pairs, GFP_KERNEL);
if (!vi->sq)
goto err_sq;
vi->rq = kzalloc(sizeof(*vi->rq) * vi->max_queue_pairs, GFP_KERNEL);
if (!vi->rq)
goto err_rq;
INIT_DELAYED_WORK(&vi->refill, refill_work);
for (i = 0; i < vi->max_queue_pairs; i++) {
vi->rq[i].pages = NULL;
netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
napi_weight);
napi_hash_add(&vi->rq[i].napi);
sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
ewma_init(&vi->rq[i].mrg_avg_pkt_len, 1, RECEIVE_AVG_WEIGHT);
sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
}
return 0;
err_rq:
kfree(vi->sq);
err_sq:
return -ENOMEM;
}
static int init_vqs(struct virtnet_info *vi)
{
int ret;
/* Allocate send & receive queues */
ret = virtnet_alloc_queues(vi);
if (ret)
goto err;
ret = virtnet_find_vqs(vi);
if (ret)
goto err_free;
get_online_cpus();
virtnet_set_affinity(vi);
put_online_cpus();
return 0;
err_free:
virtnet_free_queues(vi);
err:
return ret;
}
#ifdef CONFIG_SYSFS
static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
struct rx_queue_attribute *attribute, char *buf)
{
struct virtnet_info *vi = netdev_priv(queue->dev);
unsigned int queue_index = get_netdev_rx_queue_index(queue);
struct ewma *avg;
BUG_ON(queue_index >= vi->max_queue_pairs);
avg = &vi->rq[queue_index].mrg_avg_pkt_len;
return sprintf(buf, "%u\n", get_mergeable_buf_len(avg));
}
static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
__ATTR_RO(mergeable_rx_buffer_size);
static struct attribute *virtio_net_mrg_rx_attrs[] = {
&mergeable_rx_buffer_size_attribute.attr,
NULL
};
static const struct attribute_group virtio_net_mrg_rx_group = {
.name = "virtio_net",
.attrs = virtio_net_mrg_rx_attrs
};
#endif
static bool virtnet_fail_on_feature(struct virtio_device *vdev,
unsigned int fbit,
const char *fname, const char *dname)
{
if (!virtio_has_feature(vdev, fbit))
return false;
dev_err(&vdev->dev, "device advertises feature %s but not %s",
fname, dname);
return true;
}
#define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
static bool virtnet_validate_features(struct virtio_device *vdev)
{
if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
(VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
"VIRTIO_NET_F_CTRL_VQ") ||
VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
"VIRTIO_NET_F_CTRL_VQ") ||
VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
"VIRTIO_NET_F_CTRL_VQ") ||
VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
"VIRTIO_NET_F_CTRL_VQ"))) {
return false;
}
return true;
}
static int virtnet_probe(struct virtio_device *vdev)
{
int i, err;
struct net_device *dev;
struct virtnet_info *vi;
u16 max_queue_pairs;
if (!vdev->config->get) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
if (!virtnet_validate_features(vdev))
return -EINVAL;
/* Find if host supports multiqueue virtio_net device */
err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
struct virtio_net_config,
max_virtqueue_pairs, &max_queue_pairs);
/* We need at least 2 queue's */
if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
max_queue_pairs = 1;
/* Allocate ourselves a network device with room for our info */
dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
if (!dev)
return -ENOMEM;
/* Set up network device as normal. */
dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
dev->netdev_ops = &virtnet_netdev;
dev->features = NETIF_F_HIGHDMA;
dev->ethtool_ops = &virtnet_ethtool_ops;
SET_NETDEV_DEV(dev, &vdev->dev);
/* Do we support "hardware" checksums? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
/* This opens up the world of extra features. */
dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (csum)
dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
| NETIF_F_TSO_ECN | NETIF_F_TSO6;
}
/* Individual feature bits: what can host handle? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
dev->hw_features |= NETIF_F_TSO;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
dev->hw_features |= NETIF_F_TSO6;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
dev->hw_features |= NETIF_F_TSO_ECN;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
dev->hw_features |= NETIF_F_UFO;
dev->features |= NETIF_F_GSO_ROBUST;
if (gso)
dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
/* (!csum && gso) case will be fixed by register_netdev() */
}
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
dev->features |= NETIF_F_RXCSUM;
dev->vlan_features = dev->features;
/* Configuration may specify what MAC to use. Otherwise random. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
virtio_cread_bytes(vdev,
offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len);
else
eth_hw_addr_random(dev);
/* Set up our device-specific information */
vi = netdev_priv(dev);
vi->dev = dev;
vi->vdev = vdev;
vdev->priv = vi;
vi->stats = alloc_percpu(struct virtnet_stats);
err = -ENOMEM;
if (vi->stats == NULL)
goto free;
for_each_possible_cpu(i) {
struct virtnet_stats *virtnet_stats;
virtnet_stats = per_cpu_ptr(vi->stats, i);
u64_stats_init(&virtnet_stats->tx_syncp);
u64_stats_init(&virtnet_stats->rx_syncp);
}
INIT_WORK(&vi->config_work, virtnet_config_changed_work);
/* If we can receive ANY GSO packets, we must allocate large ones. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
vi->big_packets = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
vi->mergeable_rx_bufs = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
else
vi->hdr_len = sizeof(struct virtio_net_hdr);
if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->any_header_sg = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
vi->has_cvq = true;
if (vi->any_header_sg)
dev->needed_headroom = vi->hdr_len;
/* Use single tx/rx queue pair as default */
vi->curr_queue_pairs = 1;
vi->max_queue_pairs = max_queue_pairs;
/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
err = init_vqs(vi);
if (err)
goto free_stats;
#ifdef CONFIG_SYSFS
if (vi->mergeable_rx_bufs)
dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
#endif
netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
err = register_netdev(dev);
if (err) {
pr_debug("virtio_net: registering device failed\n");
goto free_vqs;
}
virtio_device_ready(vdev);
/* Last of all, set up some receive buffers. */
for (i = 0; i < vi->curr_queue_pairs; i++) {
try_fill_recv(vi, &vi->rq[i], GFP_KERNEL);
/* If we didn't even get one input buffer, we're useless. */
if (vi->rq[i].vq->num_free ==
virtqueue_get_vring_size(vi->rq[i].vq)) {
free_unused_bufs(vi);
err = -ENOMEM;
goto free_recv_bufs;
}
}
vi->nb.notifier_call = &virtnet_cpu_callback;
err = register_hotcpu_notifier(&vi->nb);
if (err) {
pr_debug("virtio_net: registering cpu notifier failed\n");
goto free_recv_bufs;
}
/* Assume link up if device can't report link status,
otherwise get link status from config. */
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
netif_carrier_off(dev);
schedule_work(&vi->config_work);
} else {
vi->status = VIRTIO_NET_S_LINK_UP;
netif_carrier_on(dev);
}
pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
dev->name, max_queue_pairs);
return 0;
free_recv_bufs:
vi->vdev->config->reset(vdev);
free_receive_bufs(vi);
unregister_netdev(dev);
free_vqs:
cancel_delayed_work_sync(&vi->refill);
free_receive_page_frags(vi);
virtnet_del_vqs(vi);
free_stats:
free_percpu(vi->stats);
free:
free_netdev(dev);
return err;
}
static void remove_vq_common(struct virtnet_info *vi)
{
vi->vdev->config->reset(vi->vdev);
/* Free unused buffers in both send and recv, if any. */
free_unused_bufs(vi);
free_receive_bufs(vi);
free_receive_page_frags(vi);
virtnet_del_vqs(vi);
}
static void virtnet_remove(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
unregister_hotcpu_notifier(&vi->nb);
/* Make sure no work handler is accessing the device. */
flush_work(&vi->config_work);
unregister_netdev(vi->dev);
remove_vq_common(vi);
free_percpu(vi->stats);
free_netdev(vi->dev);
}
#ifdef CONFIG_PM_SLEEP
static int virtnet_freeze(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
int i;
unregister_hotcpu_notifier(&vi->nb);
/* Make sure no work handler is accessing the device */
flush_work(&vi->config_work);
netif_device_detach(vi->dev);
cancel_delayed_work_sync(&vi->refill);
if (netif_running(vi->dev)) {
for (i = 0; i < vi->max_queue_pairs; i++)
napi_disable(&vi->rq[i].napi);
}
remove_vq_common(vi);
return 0;
}
static int virtnet_restore(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
int err, i;
err = init_vqs(vi);
if (err)
return err;
virtio_device_ready(vdev);
if (netif_running(vi->dev)) {
for (i = 0; i < vi->curr_queue_pairs; i++)
if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
schedule_delayed_work(&vi->refill, 0);
for (i = 0; i < vi->max_queue_pairs; i++)
virtnet_napi_enable(&vi->rq[i]);
}
netif_device_attach(vi->dev);
rtnl_lock();
virtnet_set_queues(vi, vi->curr_queue_pairs);
rtnl_unlock();
err = register_hotcpu_notifier(&vi->nb);
if (err)
return err;
return 0;
}
#endif
static struct virtio_device_id id_table[] = {
{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
{ 0 },
};
static unsigned int features[] = {
VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM,
VIRTIO_NET_F_GSO, VIRTIO_NET_F_MAC,
VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6,
VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6,
VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO,
VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ,
VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN,
VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ,
VIRTIO_NET_F_CTRL_MAC_ADDR,
VIRTIO_F_ANY_LAYOUT,
};
static struct virtio_driver virtio_net_driver = {
.feature_table = features,
.feature_table_size = ARRAY_SIZE(features),
.driver.name = KBUILD_MODNAME,
.driver.owner = THIS_MODULE,
.id_table = id_table,
.probe = virtnet_probe,
.remove = virtnet_remove,
.config_changed = virtnet_config_changed,
#ifdef CONFIG_PM_SLEEP
.freeze = virtnet_freeze,
.restore = virtnet_restore,
#endif
};
module_virtio_driver(virtio_net_driver);
MODULE_DEVICE_TABLE(virtio, id_table);
MODULE_DESCRIPTION("Virtio network driver");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1655_0 |
crossvul-cpp_data_good_344_10 | /*
* util.c: utility functions used by OpenSC command line tools.
*
* Copyright (C) 2011 OpenSC Project developers
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _WIN32
#include <termios.h>
#else
#include <conio.h>
#endif
#include <ctype.h>
#include "util.h"
#include "ui/notify.h"
int
is_string_valid_atr(const char *atr_str)
{
unsigned char atr[SC_MAX_ATR_SIZE];
size_t atr_len = sizeof(atr);
if (sc_hex_to_bin(atr_str, atr, &atr_len))
return 0;
if (atr_len < 2)
return 0;
if (atr[0] != 0x3B && atr[0] != 0x3F)
return 0;
return 1;
}
int
util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int do_lock, int verbose)
{
struct sc_reader *reader = NULL, *found = NULL;
struct sc_card *card = NULL;
int r;
sc_notify_init();
if (do_wait) {
unsigned int event;
if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "Waiting for a reader to be attached...\n");
r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r));
return 3;
}
r = sc_ctx_detect_readers(ctx);
if (r < 0) {
fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r));
return 3;
}
}
fprintf(stderr, "Waiting for a card to be inserted...\n");
r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL);
if (r < 0) {
fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r));
return 3;
}
reader = found;
}
else if (sc_ctx_get_reader_count(ctx) == 0) {
fprintf(stderr, "No smart card readers found.\n");
return 1;
}
else {
if (!reader_id) {
unsigned int i;
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
reader = sc_ctx_get_reader(ctx, i);
if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) {
fprintf(stderr, "Using reader with a card: %s\n", reader->name);
goto autofound;
}
}
/* If no reader had a card, default to the first reader */
reader = sc_ctx_get_reader(ctx, 0);
}
else {
/* If the reader identifier looks like an ATR, try to find the reader with that card */
if (is_string_valid_atr(reader_id)) {
unsigned char atr_buf[SC_MAX_ATR_SIZE];
size_t atr_buf_len = sizeof(atr_buf);
unsigned int i;
sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len);
/* Loop readers, looking for a card with ATR */
for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) {
struct sc_reader *rdr = sc_ctx_get_reader(ctx, i);
if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT))
continue;
else if (rdr->atr.len != atr_buf_len)
continue;
else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len))
continue;
fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name);
reader = rdr;
goto autofound;
}
}
else {
char *endptr = NULL;
unsigned int num;
errno = 0;
num = strtol(reader_id, &endptr, 0);
if (!errno && endptr && *endptr == '\0')
reader = sc_ctx_get_reader(ctx, num);
else
reader = sc_ctx_get_reader_by_name(ctx, reader_id);
}
}
autofound:
if (!reader) {
fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n",
reader_id, sc_ctx_get_reader_count(ctx));
return 1;
}
if (sc_detect_card_presence(reader) <= 0) {
fprintf(stderr, "Card not present.\n");
return 3;
}
}
if (verbose)
printf("Connecting to card in reader %s...\n", reader->name);
r = sc_connect_card(reader, &card);
if (r < 0) {
fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
return 1;
}
if (verbose)
printf("Using card driver %s.\n", card->driver->name);
if (do_lock) {
r = sc_lock(card);
if (r < 0) {
fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r));
sc_disconnect_card(card);
return 1;
}
}
*cardp = card;
return 0;
}
int
util_connect_card(sc_context_t *ctx, sc_card_t **cardp,
const char *reader_id, int do_wait, int verbose)
{
return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose);
}
void util_print_binary(FILE *f, const u8 *buf, int count)
{
int i;
for (i = 0; i < count; i++) {
unsigned char c = buf[i];
const char *format;
if (!isprint(c))
format = "\\x%02X";
else
format = "%c";
fprintf(f, format, c);
}
(void) fflush(f);
}
void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep)
{
int i;
for (i = 0; i < len; i++) {
if (sep != NULL && i)
fprintf(f, "%s", sep);
fprintf(f, "%02X", in[i]);
}
}
void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr)
{
int lines = 0;
while (count) {
char ascbuf[17];
size_t i;
if (addr >= 0) {
fprintf(f, "%08X: ", addr);
addr += 16;
}
for (i = 0; i < count && i < 16; i++) {
fprintf(f, "%02X ", *in);
if (isprint(*in))
ascbuf[i] = *in;
else
ascbuf[i] = '.';
in++;
}
count -= i;
ascbuf[i] = 0;
for (; i < 16 && lines; i++)
fprintf(f, " ");
fprintf(f, "%s\n", ascbuf);
lines++;
}
}
NORETURN void
util_print_usage_and_die(const char *app_name, const struct option options[],
const char *option_help[], const char *args)
{
int i;
int header_shown = 0;
if (args)
printf("Usage: %s [OPTIONS] %s\n", app_name, args);
else
printf("Usage: %s [OPTIONS]\n", app_name);
for (i = 0; options[i].name; i++) {
char buf[40];
const char *arg_str;
/* Skip "hidden" options */
if (option_help[i] == NULL)
continue;
if (!header_shown++)
printf("Options:\n");
switch (options[i].has_arg) {
case 1:
arg_str = " <arg>";
break;
case 2:
arg_str = " [arg]";
break;
default:
arg_str = "";
break;
}
if (isascii(options[i].val) &&
isprint(options[i].val) && !isspace(options[i].val))
sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str);
else
sprintf(buf, " --%s%s", options[i].name, arg_str);
/* print the line - wrap if necessary */
if (strlen(buf) > 28) {
printf(" %s\n", buf);
buf[0] = '\0';
}
printf(" %-28s %s\n", buf, option_help[i]);
}
exit(2);
}
const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strncat(line, buf, sizeof line);
strncat(line, " ", sizeof line);
e = e->next;
}
line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
NORETURN void
util_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\nAborting.\n");
va_end(ap);
sc_notify_close();
exit(1);
}
void
util_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void
util_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "warning: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
int
util_getpass (char **lineptr, size_t *len, FILE *stream)
{
#define MAX_PASS_SIZE 128
char *buf;
size_t i;
int ch = 0;
#ifndef _WIN32
struct termios old, new;
fflush(stdout);
if (tcgetattr (fileno (stdout), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0)
return -1;
#endif
buf = calloc(1, MAX_PASS_SIZE);
if (!buf)
return -1;
for (i = 0; i < MAX_PASS_SIZE - 1; i++) {
#ifndef _WIN32
ch = getchar();
#else
ch = _getch();
#endif
if (ch == 0 || ch == 3)
break;
if (ch == '\n' || ch == '\r')
break;
buf[i] = (char) ch;
}
#ifndef _WIN32
tcsetattr (fileno (stdout), TCSAFLUSH, &old);
fputs("\n", stdout);
#endif
if (ch == 0 || ch == 3) {
free(buf);
return -1;
}
if (*lineptr && (!len || *len < i+1)) {
free(*lineptr);
*lineptr = NULL;
}
if (*lineptr) {
memcpy(*lineptr,buf,i+1);
memset(buf, 0, MAX_PASS_SIZE);
free(buf);
} else {
*lineptr = buf;
if (len)
*len = MAX_PASS_SIZE;
}
return i;
}
size_t
util_get_pin(const char *input, const char **pin)
{
size_t inputlen = strlen(input);
size_t pinlen = 0;
if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) {
// Get a PIN from a environment variable
*pin = getenv(input + 4);
pinlen = *pin ? strlen(*pin) : 0;
} else {
//Just use the input
*pin = input;
pinlen = inputlen;
}
return pinlen;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_344_10 |
crossvul-cpp_data_good_5056_0 | /*
* videobuf2-v4l2.c - V4L2 driver helper framework
*
* Copyright (C) 2010 Samsung Electronics
*
* Author: Pawel Osciak <pawel@osciak.com>
* Marek Szyprowski <m.szyprowski@samsung.com>
*
* The vb2_thread implementation was based on code from videobuf-dvb.c:
* (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SUSE Labs]
*
* 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.
*/
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include <media/v4l2-common.h>
#include <media/videobuf2-v4l2.h>
static int debug;
module_param(debug, int, 0644);
#define dprintk(level, fmt, arg...) \
do { \
if (debug >= level) \
pr_info("vb2-v4l2: %s: " fmt, __func__, ## arg); \
} while (0)
/* Flags that are set by the vb2 core */
#define V4L2_BUFFER_MASK_FLAGS (V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_QUEUED | \
V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_ERROR | \
V4L2_BUF_FLAG_PREPARED | \
V4L2_BUF_FLAG_TIMESTAMP_MASK)
/* Output buffer flags that should be passed on to the driver */
#define V4L2_BUFFER_OUT_FLAGS (V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | \
V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_TIMECODE)
/**
* __verify_planes_array() - verify that the planes array passed in struct
* v4l2_buffer from userspace can be safely used
*/
static int __verify_planes_array(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
if (!V4L2_TYPE_IS_MULTIPLANAR(b->type))
return 0;
/* Is memory for copying plane information present? */
if (b->m.planes == NULL) {
dprintk(1, "multi-planar buffer passed but "
"planes array not provided\n");
return -EINVAL;
}
if (b->length < vb->num_planes || b->length > VB2_MAX_PLANES) {
dprintk(1, "incorrect planes array length, "
"expected %d, got %d\n", vb->num_planes, b->length);
return -EINVAL;
}
return 0;
}
static int __verify_planes_array_core(struct vb2_buffer *vb, const void *pb)
{
return __verify_planes_array(vb, pb);
}
/**
* __verify_length() - Verify that the bytesused value for each plane fits in
* the plane length and that the data offset doesn't exceed the bytesused value.
*/
static int __verify_length(struct vb2_buffer *vb, const struct v4l2_buffer *b)
{
unsigned int length;
unsigned int bytesused;
unsigned int plane;
if (!V4L2_TYPE_IS_OUTPUT(b->type))
return 0;
if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
for (plane = 0; plane < vb->num_planes; ++plane) {
length = (b->memory == VB2_MEMORY_USERPTR ||
b->memory == VB2_MEMORY_DMABUF)
? b->m.planes[plane].length
: vb->planes[plane].length;
bytesused = b->m.planes[plane].bytesused
? b->m.planes[plane].bytesused : length;
if (b->m.planes[plane].bytesused > length)
return -EINVAL;
if (b->m.planes[plane].data_offset > 0 &&
b->m.planes[plane].data_offset >= bytesused)
return -EINVAL;
}
} else {
length = (b->memory == VB2_MEMORY_USERPTR)
? b->length : vb->planes[0].length;
if (b->bytesused > length)
return -EINVAL;
}
return 0;
}
static void __copy_timestamp(struct vb2_buffer *vb, const void *pb)
{
const struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct vb2_queue *q = vb->vb2_queue;
if (q->is_output) {
/*
* For output buffers copy the timestamp if needed,
* and the timecode field and flag if needed.
*/
if (q->copy_timestamp)
vb->timestamp = timeval_to_ns(&b->timestamp);
vbuf->flags |= b->flags & V4L2_BUF_FLAG_TIMECODE;
if (b->flags & V4L2_BUF_FLAG_TIMECODE)
vbuf->timecode = b->timecode;
}
};
static void vb2_warn_zero_bytesused(struct vb2_buffer *vb)
{
static bool check_once;
if (check_once)
return;
check_once = true;
WARN_ON(1);
pr_warn("use of bytesused == 0 is deprecated and will be removed in the future,\n");
if (vb->vb2_queue->allow_zero_bytesused)
pr_warn("use VIDIOC_DECODER_CMD(V4L2_DEC_CMD_STOP) instead.\n");
else
pr_warn("use the actual size instead.\n");
}
static int vb2_queue_or_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b,
const char *opname)
{
if (b->type != q->type) {
dprintk(1, "%s: invalid buffer type\n", opname);
return -EINVAL;
}
if (b->index >= q->num_buffers) {
dprintk(1, "%s: buffer index out of range\n", opname);
return -EINVAL;
}
if (q->bufs[b->index] == NULL) {
/* Should never happen */
dprintk(1, "%s: buffer is NULL\n", opname);
return -EINVAL;
}
if (b->memory != q->memory) {
dprintk(1, "%s: invalid memory type\n", opname);
return -EINVAL;
}
return __verify_planes_array(q->bufs[b->index], b);
}
/**
* __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
* returned to userspace
*/
static void __fill_v4l2_buffer(struct vb2_buffer *vb, void *pb)
{
struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct vb2_queue *q = vb->vb2_queue;
unsigned int plane;
/* Copy back data such as timestamp, flags, etc. */
b->index = vb->index;
b->type = vb->type;
b->memory = vb->memory;
b->bytesused = 0;
b->flags = vbuf->flags;
b->field = vbuf->field;
b->timestamp = ns_to_timeval(vb->timestamp);
b->timecode = vbuf->timecode;
b->sequence = vbuf->sequence;
b->reserved2 = 0;
b->reserved = 0;
if (q->is_multiplanar) {
/*
* Fill in plane-related data if userspace provided an array
* for it. The caller has already verified memory and size.
*/
b->length = vb->num_planes;
for (plane = 0; plane < vb->num_planes; ++plane) {
struct v4l2_plane *pdst = &b->m.planes[plane];
struct vb2_plane *psrc = &vb->planes[plane];
pdst->bytesused = psrc->bytesused;
pdst->length = psrc->length;
if (q->memory == VB2_MEMORY_MMAP)
pdst->m.mem_offset = psrc->m.offset;
else if (q->memory == VB2_MEMORY_USERPTR)
pdst->m.userptr = psrc->m.userptr;
else if (q->memory == VB2_MEMORY_DMABUF)
pdst->m.fd = psrc->m.fd;
pdst->data_offset = psrc->data_offset;
memset(pdst->reserved, 0, sizeof(pdst->reserved));
}
} else {
/*
* We use length and offset in v4l2_planes array even for
* single-planar buffers, but userspace does not.
*/
b->length = vb->planes[0].length;
b->bytesused = vb->planes[0].bytesused;
if (q->memory == VB2_MEMORY_MMAP)
b->m.offset = vb->planes[0].m.offset;
else if (q->memory == VB2_MEMORY_USERPTR)
b->m.userptr = vb->planes[0].m.userptr;
else if (q->memory == VB2_MEMORY_DMABUF)
b->m.fd = vb->planes[0].m.fd;
}
/*
* Clear any buffer state related flags.
*/
b->flags &= ~V4L2_BUFFER_MASK_FLAGS;
b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK;
if (!q->copy_timestamp) {
/*
* For non-COPY timestamps, drop timestamp source bits
* and obtain the timestamp source from the queue.
*/
b->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
b->flags |= q->timestamp_flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
}
switch (vb->state) {
case VB2_BUF_STATE_QUEUED:
case VB2_BUF_STATE_ACTIVE:
b->flags |= V4L2_BUF_FLAG_QUEUED;
break;
case VB2_BUF_STATE_ERROR:
b->flags |= V4L2_BUF_FLAG_ERROR;
/* fall through */
case VB2_BUF_STATE_DONE:
b->flags |= V4L2_BUF_FLAG_DONE;
break;
case VB2_BUF_STATE_PREPARED:
b->flags |= V4L2_BUF_FLAG_PREPARED;
break;
case VB2_BUF_STATE_PREPARING:
case VB2_BUF_STATE_DEQUEUED:
case VB2_BUF_STATE_REQUEUEING:
/* nothing */
break;
}
if (vb2_buffer_in_use(q, vb))
b->flags |= V4L2_BUF_FLAG_MAPPED;
if (!q->is_output &&
b->flags & V4L2_BUF_FLAG_DONE &&
b->flags & V4L2_BUF_FLAG_LAST)
q->last_buffer_dequeued = true;
}
/**
* __fill_vb2_buffer() - fill a vb2_buffer with information provided in a
* v4l2_buffer by the userspace. It also verifies that struct
* v4l2_buffer has a valid number of planes.
*/
static int __fill_vb2_buffer(struct vb2_buffer *vb,
const void *pb, struct vb2_plane *planes)
{
struct vb2_queue *q = vb->vb2_queue;
const struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
unsigned int plane;
int ret;
ret = __verify_length(vb, b);
if (ret < 0) {
dprintk(1, "plane parameters verification failed: %d\n", ret);
return ret;
}
if (b->field == V4L2_FIELD_ALTERNATE && q->is_output) {
/*
* If the format's field is ALTERNATE, then the buffer's field
* should be either TOP or BOTTOM, not ALTERNATE since that
* makes no sense. The driver has to know whether the
* buffer represents a top or a bottom field in order to
* program any DMA correctly. Using ALTERNATE is wrong, since
* that just says that it is either a top or a bottom field,
* but not which of the two it is.
*/
dprintk(1, "the field is incorrectly set to ALTERNATE "
"for an output buffer\n");
return -EINVAL;
}
vb->timestamp = 0;
vbuf->sequence = 0;
if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
if (b->memory == VB2_MEMORY_USERPTR) {
for (plane = 0; plane < vb->num_planes; ++plane) {
planes[plane].m.userptr =
b->m.planes[plane].m.userptr;
planes[plane].length =
b->m.planes[plane].length;
}
}
if (b->memory == VB2_MEMORY_DMABUF) {
for (plane = 0; plane < vb->num_planes; ++plane) {
planes[plane].m.fd =
b->m.planes[plane].m.fd;
planes[plane].length =
b->m.planes[plane].length;
}
}
/* Fill in driver-provided information for OUTPUT types */
if (V4L2_TYPE_IS_OUTPUT(b->type)) {
/*
* Will have to go up to b->length when API starts
* accepting variable number of planes.
*
* If bytesused == 0 for the output buffer, then fall
* back to the full buffer size. In that case
* userspace clearly never bothered to set it and
* it's a safe assumption that they really meant to
* use the full plane sizes.
*
* Some drivers, e.g. old codec drivers, use bytesused == 0
* as a way to indicate that streaming is finished.
* In that case, the driver should use the
* allow_zero_bytesused flag to keep old userspace
* applications working.
*/
for (plane = 0; plane < vb->num_planes; ++plane) {
struct vb2_plane *pdst = &planes[plane];
struct v4l2_plane *psrc = &b->m.planes[plane];
if (psrc->bytesused == 0)
vb2_warn_zero_bytesused(vb);
if (vb->vb2_queue->allow_zero_bytesused)
pdst->bytesused = psrc->bytesused;
else
pdst->bytesused = psrc->bytesused ?
psrc->bytesused : pdst->length;
pdst->data_offset = psrc->data_offset;
}
}
} else {
/*
* Single-planar buffers do not use planes array,
* so fill in relevant v4l2_buffer struct fields instead.
* In videobuf we use our internal V4l2_planes struct for
* single-planar buffers as well, for simplicity.
*
* If bytesused == 0 for the output buffer, then fall back
* to the full buffer size as that's a sensible default.
*
* Some drivers, e.g. old codec drivers, use bytesused == 0 as
* a way to indicate that streaming is finished. In that case,
* the driver should use the allow_zero_bytesused flag to keep
* old userspace applications working.
*/
if (b->memory == VB2_MEMORY_USERPTR) {
planes[0].m.userptr = b->m.userptr;
planes[0].length = b->length;
}
if (b->memory == VB2_MEMORY_DMABUF) {
planes[0].m.fd = b->m.fd;
planes[0].length = b->length;
}
if (V4L2_TYPE_IS_OUTPUT(b->type)) {
if (b->bytesused == 0)
vb2_warn_zero_bytesused(vb);
if (vb->vb2_queue->allow_zero_bytesused)
planes[0].bytesused = b->bytesused;
else
planes[0].bytesused = b->bytesused ?
b->bytesused : planes[0].length;
} else
planes[0].bytesused = 0;
}
/* Zero flags that the vb2 core handles */
vbuf->flags = b->flags & ~V4L2_BUFFER_MASK_FLAGS;
if (!vb->vb2_queue->copy_timestamp || !V4L2_TYPE_IS_OUTPUT(b->type)) {
/*
* Non-COPY timestamps and non-OUTPUT queues will get
* their timestamp and timestamp source flags from the
* queue.
*/
vbuf->flags &= ~V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
}
if (V4L2_TYPE_IS_OUTPUT(b->type)) {
/*
* For output buffers mask out the timecode flag:
* this will be handled later in vb2_internal_qbuf().
* The 'field' is valid metadata for this output buffer
* and so that needs to be copied here.
*/
vbuf->flags &= ~V4L2_BUF_FLAG_TIMECODE;
vbuf->field = b->field;
} else {
/* Zero any output buffer flags as this is a capture buffer */
vbuf->flags &= ~V4L2_BUFFER_OUT_FLAGS;
}
return 0;
}
static const struct vb2_buf_ops v4l2_buf_ops = {
.verify_planes_array = __verify_planes_array_core,
.fill_user_buffer = __fill_v4l2_buffer,
.fill_vb2_buffer = __fill_vb2_buffer,
.copy_timestamp = __copy_timestamp,
};
/**
* vb2_querybuf() - query video buffer information
* @q: videobuf queue
* @b: buffer struct passed from userspace to vidioc_querybuf handler
* in driver
*
* Should be called from vidioc_querybuf ioctl handler in driver.
* This function will verify the passed v4l2_buffer structure and fill the
* relevant information for the userspace.
*
* The return values from this function are intended to be directly returned
* from vidioc_querybuf handler in driver.
*/
int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
struct vb2_buffer *vb;
int ret;
if (b->type != q->type) {
dprintk(1, "wrong buffer type\n");
return -EINVAL;
}
if (b->index >= q->num_buffers) {
dprintk(1, "buffer index out of range\n");
return -EINVAL;
}
vb = q->bufs[b->index];
ret = __verify_planes_array(vb, b);
if (!ret)
vb2_core_querybuf(q, b->index, b);
return ret;
}
EXPORT_SYMBOL(vb2_querybuf);
/**
* vb2_reqbufs() - Wrapper for vb2_core_reqbufs() that also verifies
* the memory and type values.
* @q: videobuf2 queue
* @req: struct passed from userspace to vidioc_reqbufs handler
* in driver
*/
int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
{
int ret = vb2_verify_memory_type(q, req->memory, req->type);
return ret ? ret : vb2_core_reqbufs(q, req->memory, &req->count);
}
EXPORT_SYMBOL_GPL(vb2_reqbufs);
/**
* vb2_prepare_buf() - Pass ownership of a buffer from userspace to the kernel
* @q: videobuf2 queue
* @b: buffer structure passed from userspace to vidioc_prepare_buf
* handler in driver
*
* Should be called from vidioc_prepare_buf ioctl handler of a driver.
* This function:
* 1) verifies the passed buffer,
* 2) calls buf_prepare callback in the driver (if provided), in which
* driver-specific buffer initialization can be performed,
*
* The return values from this function are intended to be directly returned
* from vidioc_prepare_buf handler in driver.
*/
int vb2_prepare_buf(struct vb2_queue *q, struct v4l2_buffer *b)
{
int ret;
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
ret = vb2_queue_or_prepare_buf(q, b, "prepare_buf");
return ret ? ret : vb2_core_prepare_buf(q, b->index, b);
}
EXPORT_SYMBOL_GPL(vb2_prepare_buf);
/**
* vb2_create_bufs() - Wrapper for vb2_core_create_bufs() that also verifies
* the memory and type values.
* @q: videobuf2 queue
* @create: creation parameters, passed from userspace to vidioc_create_bufs
* handler in driver
*/
int vb2_create_bufs(struct vb2_queue *q, struct v4l2_create_buffers *create)
{
unsigned requested_planes = 1;
unsigned requested_sizes[VIDEO_MAX_PLANES];
struct v4l2_format *f = &create->format;
int ret = vb2_verify_memory_type(q, create->memory, f->type);
unsigned i;
create->index = q->num_buffers;
if (create->count == 0)
return ret != -EBUSY ? ret : 0;
switch (f->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
requested_planes = f->fmt.pix_mp.num_planes;
if (requested_planes == 0 ||
requested_planes > VIDEO_MAX_PLANES)
return -EINVAL;
for (i = 0; i < requested_planes; i++)
requested_sizes[i] =
f->fmt.pix_mp.plane_fmt[i].sizeimage;
break;
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
requested_sizes[0] = f->fmt.pix.sizeimage;
break;
case V4L2_BUF_TYPE_VBI_CAPTURE:
case V4L2_BUF_TYPE_VBI_OUTPUT:
requested_sizes[0] = f->fmt.vbi.samples_per_line *
(f->fmt.vbi.count[0] + f->fmt.vbi.count[1]);
break;
case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
requested_sizes[0] = f->fmt.sliced.io_size;
break;
case V4L2_BUF_TYPE_SDR_CAPTURE:
case V4L2_BUF_TYPE_SDR_OUTPUT:
requested_sizes[0] = f->fmt.sdr.buffersize;
break;
default:
return -EINVAL;
}
for (i = 0; i < requested_planes; i++)
if (requested_sizes[i] == 0)
return -EINVAL;
return ret ? ret : vb2_core_create_bufs(q, create->memory,
&create->count, requested_planes, requested_sizes);
}
EXPORT_SYMBOL_GPL(vb2_create_bufs);
static int vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
int ret = vb2_queue_or_prepare_buf(q, b, "qbuf");
return ret ? ret : vb2_core_qbuf(q, b->index, b);
}
/**
* vb2_qbuf() - Queue a buffer from userspace
* @q: videobuf2 queue
* @b: buffer structure passed from userspace to vidioc_qbuf handler
* in driver
*
* Should be called from vidioc_qbuf ioctl handler of a driver.
* This function:
* 1) verifies the passed buffer,
* 2) if necessary, calls buf_prepare callback in the driver (if provided), in
* which driver-specific buffer initialization can be performed,
* 3) if streaming is on, queues the buffer in driver by the means of buf_queue
* callback for processing.
*
* The return values from this function are intended to be directly returned
* from vidioc_qbuf handler in driver.
*/
int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_internal_qbuf(q, b);
}
EXPORT_SYMBOL_GPL(vb2_qbuf);
static int vb2_internal_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b,
bool nonblocking)
{
int ret;
if (b->type != q->type) {
dprintk(1, "invalid buffer type\n");
return -EINVAL;
}
ret = vb2_core_dqbuf(q, NULL, b, nonblocking);
return ret;
}
/**
* vb2_dqbuf() - Dequeue a buffer to the userspace
* @q: videobuf2 queue
* @b: buffer structure passed from userspace to vidioc_dqbuf handler
* in driver
* @nonblocking: if true, this call will not sleep waiting for a buffer if no
* buffers ready for dequeuing are present. Normally the driver
* would be passing (file->f_flags & O_NONBLOCK) here
*
* Should be called from vidioc_dqbuf ioctl handler of a driver.
* This function:
* 1) verifies the passed buffer,
* 2) calls buf_finish callback in the driver (if provided), in which
* driver can perform any additional operations that may be required before
* returning the buffer to userspace, such as cache sync,
* 3) the buffer struct members are filled with relevant information for
* the userspace.
*
* The return values from this function are intended to be directly returned
* from vidioc_dqbuf handler in driver.
*/
int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_internal_dqbuf(q, b, nonblocking);
}
EXPORT_SYMBOL_GPL(vb2_dqbuf);
/**
* vb2_streamon - start streaming
* @q: videobuf2 queue
* @type: type argument passed from userspace to vidioc_streamon handler
*
* Should be called from vidioc_streamon handler of a driver.
* This function:
* 1) verifies current state
* 2) passes any previously queued buffers to the driver and starts streaming
*
* The return values from this function are intended to be directly returned
* from vidioc_streamon handler in the driver.
*/
int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_core_streamon(q, type);
}
EXPORT_SYMBOL_GPL(vb2_streamon);
/**
* vb2_streamoff - stop streaming
* @q: videobuf2 queue
* @type: type argument passed from userspace to vidioc_streamoff handler
*
* Should be called from vidioc_streamoff handler of a driver.
* This function:
* 1) verifies current state,
* 2) stop streaming and dequeues any queued buffers, including those previously
* passed to the driver (after waiting for the driver to finish).
*
* This call can be used for pausing playback.
* The return values from this function are intended to be directly returned
* from vidioc_streamoff handler in the driver
*/
int vb2_streamoff(struct vb2_queue *q, enum v4l2_buf_type type)
{
if (vb2_fileio_is_active(q)) {
dprintk(1, "file io in progress\n");
return -EBUSY;
}
return vb2_core_streamoff(q, type);
}
EXPORT_SYMBOL_GPL(vb2_streamoff);
/**
* vb2_expbuf() - Export a buffer as a file descriptor
* @q: videobuf2 queue
* @eb: export buffer structure passed from userspace to vidioc_expbuf
* handler in driver
*
* The return values from this function are intended to be directly returned
* from vidioc_expbuf handler in driver.
*/
int vb2_expbuf(struct vb2_queue *q, struct v4l2_exportbuffer *eb)
{
return vb2_core_expbuf(q, &eb->fd, eb->type, eb->index,
eb->plane, eb->flags);
}
EXPORT_SYMBOL_GPL(vb2_expbuf);
/**
* vb2_queue_init() - initialize a videobuf2 queue
* @q: videobuf2 queue; this structure should be allocated in driver
*
* The vb2_queue structure should be allocated by the driver. The driver is
* responsible of clearing it's content and setting initial values for some
* required entries before calling this function.
* q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
* to the struct vb2_queue description in include/media/videobuf2-core.h
* for more information.
*/
int vb2_queue_init(struct vb2_queue *q)
{
/*
* Sanity check
*/
if (WARN_ON(!q) ||
WARN_ON(q->timestamp_flags &
~(V4L2_BUF_FLAG_TIMESTAMP_MASK |
V4L2_BUF_FLAG_TSTAMP_SRC_MASK)))
return -EINVAL;
/* Warn that the driver should choose an appropriate timestamp type */
WARN_ON((q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN);
/* Warn that vb2_memory should match with v4l2_memory */
if (WARN_ON(VB2_MEMORY_MMAP != (int)V4L2_MEMORY_MMAP)
|| WARN_ON(VB2_MEMORY_USERPTR != (int)V4L2_MEMORY_USERPTR)
|| WARN_ON(VB2_MEMORY_DMABUF != (int)V4L2_MEMORY_DMABUF))
return -EINVAL;
if (q->buf_struct_size == 0)
q->buf_struct_size = sizeof(struct vb2_v4l2_buffer);
q->buf_ops = &v4l2_buf_ops;
q->is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(q->type);
q->is_output = V4L2_TYPE_IS_OUTPUT(q->type);
q->copy_timestamp = (q->timestamp_flags & V4L2_BUF_FLAG_TIMESTAMP_MASK)
== V4L2_BUF_FLAG_TIMESTAMP_COPY;
return vb2_core_queue_init(q);
}
EXPORT_SYMBOL_GPL(vb2_queue_init);
/**
* vb2_queue_release() - stop streaming, release the queue and free memory
* @q: videobuf2 queue
*
* This function stops streaming and performs necessary clean ups, including
* freeing video buffer memory. The driver is responsible for freeing
* the vb2_queue structure itself.
*/
void vb2_queue_release(struct vb2_queue *q)
{
vb2_core_queue_release(q);
}
EXPORT_SYMBOL_GPL(vb2_queue_release);
/**
* vb2_poll() - implements poll userspace operation
* @q: videobuf2 queue
* @file: file argument passed to the poll file operation handler
* @wait: wait argument passed to the poll file operation handler
*
* This function implements poll file operation handler for a driver.
* For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
* be informed that the file descriptor of a video device is available for
* reading.
* For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
* will be reported as available for writing.
*
* If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
* pending events.
*
* The return values from this function are intended to be directly returned
* from poll handler in driver.
*/
unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
{
struct video_device *vfd = video_devdata(file);
unsigned long req_events = poll_requested_events(wait);
unsigned int res = 0;
if (test_bit(V4L2_FL_USES_V4L2_FH, &vfd->flags)) {
struct v4l2_fh *fh = file->private_data;
if (v4l2_event_pending(fh))
res = POLLPRI;
else if (req_events & POLLPRI)
poll_wait(file, &fh->wait, wait);
}
/*
* For compatibility with vb1: if QBUF hasn't been called yet, then
* return POLLERR as well. This only affects capture queues, output
* queues will always initialize waiting_for_buffers to false.
*/
if (q->waiting_for_buffers && (req_events & (POLLIN | POLLRDNORM)))
return POLLERR;
return res | vb2_core_poll(q, file, wait);
}
EXPORT_SYMBOL_GPL(vb2_poll);
/*
* The following functions are not part of the vb2 core API, but are helper
* functions that plug into struct v4l2_ioctl_ops, struct v4l2_file_operations
* and struct vb2_ops.
* They contain boilerplate code that most if not all drivers have to do
* and so they simplify the driver code.
*/
/* The queue is busy if there is a owner and you are not that owner. */
static inline bool vb2_queue_is_busy(struct video_device *vdev, struct file *file)
{
return vdev->queue->owner && vdev->queue->owner != file->private_data;
}
/* vb2 ioctl helpers */
int vb2_ioctl_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct video_device *vdev = video_devdata(file);
int res = vb2_verify_memory_type(vdev->queue, p->memory, p->type);
if (res)
return res;
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
res = vb2_core_reqbufs(vdev->queue, p->memory, &p->count);
/* If count == 0, then the owner has released all buffers and he
is no longer owner of the queue. Otherwise we have a new owner. */
if (res == 0)
vdev->queue->owner = p->count ? file->private_data : NULL;
return res;
}
EXPORT_SYMBOL_GPL(vb2_ioctl_reqbufs);
int vb2_ioctl_create_bufs(struct file *file, void *priv,
struct v4l2_create_buffers *p)
{
struct video_device *vdev = video_devdata(file);
int res = vb2_verify_memory_type(vdev->queue, p->memory,
p->format.type);
p->index = vdev->queue->num_buffers;
/*
* If count == 0, then just check if memory and type are valid.
* Any -EBUSY result from vb2_verify_memory_type can be mapped to 0.
*/
if (p->count == 0)
return res != -EBUSY ? res : 0;
if (res)
return res;
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
res = vb2_create_bufs(vdev->queue, p);
if (res == 0)
vdev->queue->owner = file->private_data;
return res;
}
EXPORT_SYMBOL_GPL(vb2_ioctl_create_bufs);
int vb2_ioctl_prepare_buf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_prepare_buf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_prepare_buf);
int vb2_ioctl_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
/* No need to call vb2_queue_is_busy(), anyone can query buffers. */
return vb2_querybuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf);
int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_qbuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf);
int vb2_ioctl_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_dqbuf(vdev->queue, p, file->f_flags & O_NONBLOCK);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_dqbuf);
int vb2_ioctl_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_streamon(vdev->queue, i);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_streamon);
int vb2_ioctl_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_streamoff(vdev->queue, i);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_streamoff);
int vb2_ioctl_expbuf(struct file *file, void *priv, struct v4l2_exportbuffer *p)
{
struct video_device *vdev = video_devdata(file);
if (vb2_queue_is_busy(vdev, file))
return -EBUSY;
return vb2_expbuf(vdev->queue, p);
}
EXPORT_SYMBOL_GPL(vb2_ioctl_expbuf);
/* v4l2_file_operations helpers */
int vb2_fop_mmap(struct file *file, struct vm_area_struct *vma)
{
struct video_device *vdev = video_devdata(file);
return vb2_mmap(vdev->queue, vma);
}
EXPORT_SYMBOL_GPL(vb2_fop_mmap);
int _vb2_fop_release(struct file *file, struct mutex *lock)
{
struct video_device *vdev = video_devdata(file);
if (lock)
mutex_lock(lock);
if (file->private_data == vdev->queue->owner) {
vb2_queue_release(vdev->queue);
vdev->queue->owner = NULL;
}
if (lock)
mutex_unlock(lock);
return v4l2_fh_release(file);
}
EXPORT_SYMBOL_GPL(_vb2_fop_release);
int vb2_fop_release(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
return _vb2_fop_release(file, lock);
}
EXPORT_SYMBOL_GPL(vb2_fop_release);
ssize_t vb2_fop_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct video_device *vdev = video_devdata(file);
struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
int err = -EBUSY;
if (!(vdev->queue->io_modes & VB2_WRITE))
return -EINVAL;
if (lock && mutex_lock_interruptible(lock))
return -ERESTARTSYS;
if (vb2_queue_is_busy(vdev, file))
goto exit;
err = vb2_write(vdev->queue, buf, count, ppos,
file->f_flags & O_NONBLOCK);
if (vdev->queue->fileio)
vdev->queue->owner = file->private_data;
exit:
if (lock)
mutex_unlock(lock);
return err;
}
EXPORT_SYMBOL_GPL(vb2_fop_write);
ssize_t vb2_fop_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct video_device *vdev = video_devdata(file);
struct mutex *lock = vdev->queue->lock ? vdev->queue->lock : vdev->lock;
int err = -EBUSY;
if (!(vdev->queue->io_modes & VB2_READ))
return -EINVAL;
if (lock && mutex_lock_interruptible(lock))
return -ERESTARTSYS;
if (vb2_queue_is_busy(vdev, file))
goto exit;
err = vb2_read(vdev->queue, buf, count, ppos,
file->f_flags & O_NONBLOCK);
if (vdev->queue->fileio)
vdev->queue->owner = file->private_data;
exit:
if (lock)
mutex_unlock(lock);
return err;
}
EXPORT_SYMBOL_GPL(vb2_fop_read);
unsigned int vb2_fop_poll(struct file *file, poll_table *wait)
{
struct video_device *vdev = video_devdata(file);
struct vb2_queue *q = vdev->queue;
struct mutex *lock = q->lock ? q->lock : vdev->lock;
unsigned res;
void *fileio;
/*
* If this helper doesn't know how to lock, then you shouldn't be using
* it but you should write your own.
*/
WARN_ON(!lock);
if (lock && mutex_lock_interruptible(lock))
return POLLERR;
fileio = q->fileio;
res = vb2_poll(vdev->queue, file, wait);
/* If fileio was started, then we have a new queue owner. */
if (!fileio && q->fileio)
q->owner = file->private_data;
if (lock)
mutex_unlock(lock);
return res;
}
EXPORT_SYMBOL_GPL(vb2_fop_poll);
#ifndef CONFIG_MMU
unsigned long vb2_fop_get_unmapped_area(struct file *file, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
struct video_device *vdev = video_devdata(file);
return vb2_get_unmapped_area(vdev->queue, addr, len, pgoff, flags);
}
EXPORT_SYMBOL_GPL(vb2_fop_get_unmapped_area);
#endif
/* vb2_ops helpers. Only use if vq->lock is non-NULL. */
void vb2_ops_wait_prepare(struct vb2_queue *vq)
{
mutex_unlock(vq->lock);
}
EXPORT_SYMBOL_GPL(vb2_ops_wait_prepare);
void vb2_ops_wait_finish(struct vb2_queue *vq)
{
mutex_lock(vq->lock);
}
EXPORT_SYMBOL_GPL(vb2_ops_wait_finish);
MODULE_DESCRIPTION("Driver helper framework for Video for Linux 2");
MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>, Marek Szyprowski");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5056_0 |
crossvul-cpp_data_bad_395_5 | /*
Copyright 1996-2014 Han The Thanh <thanh@pdftex.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, see <http://www.gnu.org/licenses/>. */
#include "ptexlib.h"
#include <stdarg.h>
#include <string.h>
#define t1_log(str) tex_printf("%s",str)
#define get_length1() t1_length1 = t1_offset() - t1_save_offset
#define get_length2() t1_length2 = t1_offset() - t1_save_offset
#define get_length3() t1_length3 = fixedcontent? t1_offset() - t1_save_offset : 0
#define save_offset() t1_save_offset = t1_offset()
#define t1_open() open_input(&t1_file, kpse_type1_format, FOPEN_RBIN_MODE)
#define t1_close() xfclose(t1_file, cur_file_name)
#define t1_getchar() getc(t1_file)
#define t1_putchar fb_putchar
#define t1_offset fb_offset
#define t1_ungetchar(c) ungetc(c, t1_file)
#define t1_eof() feof(t1_file)
#define t1_prefix(s) str_prefix(t1_line_array, s)
#define t1_buf_prefix(s) str_prefix(t1_buf_array, s)
#define t1_suffix(s) str_suffix(t1_line_array, t1_line_ptr, s)
#define t1_buf_suffix(s) str_suffix(t1_buf_array, t1_buf_ptr, s)
#define t1_charstrings() strstr(t1_line_array, charstringname)
#define t1_subrs() t1_prefix("/Subrs")
#define t1_end_eexec() t1_suffix("mark currentfile closefile")
#define t1_cleartomark() t1_prefix("cleartomark")
#define enc_open() open_input(&enc_file, kpse_enc_format, FOPEN_RBIN_MODE)
#define enc_close() xfclose(enc_file, cur_file_name)
#define enc_getchar() getc(enc_file)
#define enc_eof() feof(enc_file)
#define valid_code(c) (c >= 0 && c < 256)
#define fixedcontent false /* false for pdfTeX, true for dvips */
static const char *standard_glyph_names[256] = {
/* 0x00 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0x10 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0x20 */
"space", "exclam", "quotedbl", "numbersign", "dollar", "percent",
"ampersand", "quoteright", "parenleft", "parenright", "asterisk",
"plus", "comma", "hyphen", "period", "slash",
/* 0x30 */
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "colon", "semicolon", "less", "equal", "greater", "question",
/* 0x40 */
"at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O",
/* 0x50 */
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft",
"backslash", "bracketright", "asciicircum", "underscore",
/* 0x60 */
"quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o",
/* 0x70 */
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar",
"braceright", "asciitilde", notdef,
/* 0x80 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0x90 */
notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0xa0 */
notdef, "exclamdown", "cent", "sterling", "fraction", "yen", "florin",
"section", "currency", "quotesingle", "quotedblleft", "guillemotleft",
"guilsinglleft", "guilsinglright", "fi", "fl",
/* 0xb0 */
notdef, "endash", "dagger", "daggerdbl", "periodcentered", notdef,
"paragraph", "bullet", "quotesinglbase", "quotedblbase",
"quotedblright", "guillemotright", "ellipsis", "perthousand", notdef,
"questiondown",
/* 0xc0 */
notdef, "grave", "acute", "circumflex", "tilde", "macron", "breve",
"dotaccent", "dieresis", notdef,
"ring", "cedilla", notdef, "hungarumlaut", "ogonek", "caron",
/* 0xd0 */
"emdash", notdef, notdef, notdef, notdef, notdef, notdef, notdef, notdef,
notdef, notdef, notdef, notdef, notdef, notdef, notdef,
/* 0xe0 */
notdef, "AE", notdef, "ordfeminine", notdef, notdef, notdef, notdef,
"Lslash", "Oslash", "OE", "ordmasculine", notdef, notdef, notdef,
notdef,
/* 0xf0 */
notdef, "ae", notdef, notdef, notdef, "dotlessi", notdef, notdef, "lslash",
"oslash", "oe", "germandbls", notdef, notdef, notdef, notdef
};
integer t1_length1, t1_length2, t1_length3;
static integer t1_save_offset;
static integer t1_fontname_offset;
static fd_entry *fd_cur;
static char charstringname[] = "/CharStrings";
enum { ENC_STANDARD, ENC_BUILTIN } t1_encoding;
#define T1_BUF_SIZE 0x10
#define ENC_BUF_SIZE 0x1000
#define CS_HSTEM 1
#define CS_VSTEM 3
#define CS_VMOVETO 4
#define CS_RLINETO 5
#define CS_HLINETO 6
#define CS_VLINETO 7
#define CS_RRCURVETO 8
#define CS_CLOSEPATH 9
#define CS_CALLSUBR 10
#define CS_RETURN 11
#define CS_ESCAPE 12
#define CS_HSBW 13
#define CS_ENDCHAR 14
#define CS_RMOVETO 21
#define CS_HMOVETO 22
#define CS_VHCURVETO 30
#define CS_HVCURVETO 31
#define CS_1BYTE_MAX (CS_HVCURVETO + 1)
#define CS_DOTSECTION CS_1BYTE_MAX + 0
#define CS_VSTEM3 CS_1BYTE_MAX + 1
#define CS_HSTEM3 CS_1BYTE_MAX + 2
#define CS_SEAC CS_1BYTE_MAX + 6
#define CS_SBW CS_1BYTE_MAX + 7
#define CS_DIV CS_1BYTE_MAX + 12
#define CS_CALLOTHERSUBR CS_1BYTE_MAX + 16
#define CS_POP CS_1BYTE_MAX + 17
#define CS_SETCURRENTPOINT CS_1BYTE_MAX + 33
#define CS_2BYTE_MAX (CS_SETCURRENTPOINT + 1)
#define CS_MAX CS_2BYTE_MAX
typedef unsigned char byte;
typedef struct {
byte nargs; /* number of arguments */
boolean bottom; /* take arguments from bottom of stack? */
boolean clear; /* clear stack? */
boolean valid;
} cc_entry; /* CharString Command */
typedef struct {
char *name; /* glyph name (or notdef for Subrs entry) */
byte *data;
unsigned short len; /* length of the whole string */
unsigned short cslen; /* length of the encoded part of the string */
boolean used;
boolean valid;
} cs_entry;
static unsigned short t1_dr, t1_er;
static const unsigned short t1_c1 = 52845, t1_c2 = 22719;
static unsigned short t1_cslen;
static short t1_lenIV;
static char enc_line[ENC_BUF_SIZE];
/* define t1_line_ptr, t1_line_array & t1_line_limit */
typedef char t1_line_entry;
define_array(t1_line);
/* define t1_buf_ptr, t1_buf_array & t1_buf_limit */
typedef char t1_buf_entry;
define_array(t1_buf);
static int cs_start;
static cs_entry *cs_tab, *cs_ptr, *cs_notdef;
static char *cs_dict_start, *cs_dict_end;
static int cs_count, cs_size, cs_size_pos;
static cs_entry *subr_tab;
static char *subr_array_start, *subr_array_end;
static int subr_max, subr_size, subr_size_pos;
/* This list contains the begin/end tokens commonly used in the */
/* /Subrs array of a Type 1 font. */
static const char *cs_token_pairs_list[][2] = {
{" RD", "NP"},
{" -|", "|"},
{" RD", "noaccess put"},
{" -|", "noaccess put"},
{NULL, NULL}
};
static const char **cs_token_pair;
static boolean t1_pfa, t1_cs, t1_scan, t1_eexec_encrypt, t1_synthetic;
static int t1_in_eexec; /* 0 before eexec-encrypted, 1 during, 2 after */
static long t1_block_length;
static int last_hexbyte;
static FILE *t1_file;
static FILE *enc_file;
static void enc_getline(void)
{
char *p;
int c;
restart:
if (enc_eof())
pdftex_fail("unexpected end of file");
p = enc_line;
do {
c = enc_getchar();
append_char_to_buf(c, p, enc_line, ENC_BUF_SIZE);
} while (c != 10);
append_eol(p, enc_line, ENC_BUF_SIZE);
if (p - enc_line < 2 || *enc_line == '%')
goto restart;
}
/* read encoding from .enc file, return glyph_names array, or pdffail() */
char **load_enc_file(char *enc_name)
{
char buf[ENC_BUF_SIZE], *p, *r;
int i, names_count;
char **glyph_names;
set_cur_file_name(enc_name);
if (!enc_open()) {
pdftex_fail("cannot open encoding file for reading");
}
glyph_names = xtalloc(256, char *);
for (i = 0; i < 256; i++)
glyph_names[i] = notdef;
t1_log("{");
t1_log(cur_file_name = (char *) nameoffile + 1);
enc_getline();
if (*enc_line != '/' || (r = strchr(enc_line, '[')) == NULL) {
remove_eol(r, enc_line);
pdftex_fail
("invalid encoding vector (a name or `[' missing): `%s'", enc_line);
}
names_count = 0;
r++; /* skip '[' */
skip(r, ' ');
for (;;) {
while (*r == '/') {
for (p = buf, r++;
*r != ' ' && *r != 10 && *r != ']' && *r != '/'; *p++ = *r++);
*p = 0;
skip(r, ' ');
if (names_count > 255)
pdftex_fail("encoding vector contains more than 256 names");
if (strcmp(buf, notdef) != 0)
glyph_names[names_count] = xstrdup(buf);
names_count++;
}
if (*r != 10 && *r != '%') {
if (str_prefix(r, "] def"))
goto done;
else {
remove_eol(r, enc_line);
pdftex_fail
("invalid encoding vector: a name or `] def' expected: `%s'", enc_line);
}
}
enc_getline();
r = enc_line;
}
done:
enc_close();
t1_log("}");
cur_file_name = NULL;
return glyph_names;
}
static void t1_check_pfa(void)
{
const int c = t1_getchar();
t1_pfa = (c != 128) ? true : false;
t1_ungetchar(c);
}
static int t1_getbyte(void)
{
int c = t1_getchar();
if (t1_pfa)
return c;
if (t1_block_length == 0) {
if (c != 128)
pdftex_fail("invalid marker");
c = t1_getchar();
if (c == 3) {
while (!t1_eof())
t1_getchar();
return EOF;
}
t1_block_length = t1_getchar() & 0xff;
t1_block_length |= (t1_getchar() & 0xff) << 8;
t1_block_length |= (t1_getchar() & 0xff) << 16;
t1_block_length |= (t1_getchar() & 0xff) << 24;
c = t1_getchar();
}
t1_block_length--;
return c;
}
static int hexval(int c)
{
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
else if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
else if (c >= '0' && c <= '9')
return c - '0';
else
return -1;
}
static byte edecrypt(byte cipher)
{
byte plain;
if (t1_pfa) {
while (cipher == 10 || cipher == 13)
cipher = t1_getbyte();
last_hexbyte = cipher = (hexval(cipher) << 4) + hexval(t1_getbyte());
}
plain = (cipher ^ (t1_dr >> 8));
t1_dr = (cipher + t1_dr) * t1_c1 + t1_c2;
return plain;
}
static byte cdecrypt(byte cipher, unsigned short *cr)
{
const byte plain = (cipher ^ (*cr >> 8));
*cr = (cipher + *cr) * t1_c1 + t1_c2;
return plain;
}
static byte eencrypt(byte plain)
{
const byte cipher = (plain ^ (t1_er >> 8));
t1_er = (cipher + t1_er) * t1_c1 + t1_c2;
return cipher;
}
static byte cencrypt(byte plain, unsigned short *cr)
{
const byte cipher = (plain ^ (*cr >> 8));
*cr = (cipher + *cr) * t1_c1 + t1_c2;
return cipher;
}
static char *eol(char *s)
{
char *p = strend(s);
if (p - s > 1 && p[-1] != 10) {
*p++ = 10;
*p = 0;
}
return p;
}
static float t1_scan_num(char *p, char **r)
{
float f;
skip(p, ' ');
if (sscanf(p, "%g", &f) != 1) {
remove_eol(p, t1_line_array);
pdftex_fail("a number expected: `%s'", t1_line_array);
}
if (r != NULL) {
for (; isdigit((unsigned char)*p) || *p == '.' ||
*p == 'e' || *p == 'E' || *p == '+' || *p == '-'; p++);
*r = p;
}
return f;
}
static boolean str_suffix(const char *begin_buf, const char *end_buf,
const char *s)
{
const char *s1 = end_buf - 1, *s2 = strend(s) - 1;
if (*s1 == 10)
s1--;
while (s1 >= begin_buf && s2 >= s) {
if (*s1-- != *s2--)
return false;
}
return s2 < s;
}
static void t1_getline(void)
{
int c, l, eexec_scan;
char *p;
static const char eexec_str[] = "currentfile eexec";
static int eexec_len = 17; /* strlen(eexec_str) */
restart:
if (t1_eof())
pdftex_fail("unexpected end of file");
t1_line_ptr = t1_line_array;
alloc_array(t1_line, 1, T1_BUF_SIZE);
t1_cslen = 0;
eexec_scan = 0;
c = t1_getbyte();
if (c == EOF)
goto exit;
while (!t1_eof()) {
if (t1_in_eexec == 1)
c = edecrypt((byte)c);
alloc_array(t1_line, 1, T1_BUF_SIZE);
append_char_to_buf(c, t1_line_ptr, t1_line_array, t1_line_limit);
if (t1_in_eexec == 0 && eexec_scan >= 0 && eexec_scan < eexec_len) {
if (t1_line_array[eexec_scan] == eexec_str[eexec_scan])
eexec_scan++;
else
eexec_scan = -1;
}
if (c == 10 || (t1_pfa && eexec_scan == eexec_len && c == 32))
break;
if (t1_cs && t1_cslen == 0 && (t1_line_ptr - t1_line_array > 4) &&
(t1_suffix(" RD ") || t1_suffix(" -| "))) {
p = t1_line_ptr - 5;
while (*p != ' ')
p--;
t1_cslen = l = t1_scan_num(p + 1, 0);
cs_start = t1_line_ptr - t1_line_array; /* cs_start is an index now */
alloc_array(t1_line, l, T1_BUF_SIZE);
while (l-- > 0)
*t1_line_ptr++ = edecrypt((byte)t1_getbyte());
}
c = t1_getbyte();
}
alloc_array(t1_line, 2, T1_BUF_SIZE); /* append_eol can append 2 chars */
append_eol(t1_line_ptr, t1_line_array, t1_line_limit);
if (t1_line_ptr - t1_line_array < 2)
goto restart;
if (eexec_scan == eexec_len)
t1_in_eexec = 1;
exit:
/* ensure that t1_buf_array has as much room as t1_line_array */
t1_buf_ptr = t1_buf_array;
alloc_array(t1_buf, t1_line_limit, t1_line_limit);
}
static void t1_putline(void)
{
char *p = t1_line_array;
if (t1_line_ptr - t1_line_array <= 1)
return;
if (t1_eexec_encrypt) {
while (p < t1_line_ptr)
t1_putchar(eencrypt(*p++));
} else
while (p < t1_line_ptr)
t1_putchar(*p++);
}
static void t1_puts(const char *s)
{
if (s != t1_line_array)
strcpy(t1_line_array, s);
t1_line_ptr = strend(t1_line_array);
t1_putline();
}
__attribute__ ((format(printf, 1, 2)))
static void t1_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsprintf(t1_line_array, fmt, args);
t1_puts(t1_line_array);
va_end(args);
}
static void t1_init_params(const char *open_name_prefix)
{
t1_log(open_name_prefix);
t1_log(cur_file_name);
t1_lenIV = 4;
t1_dr = 55665;
t1_er = 55665;
t1_in_eexec = 0;
t1_cs = false;
t1_scan = true;
t1_synthetic = false;
t1_eexec_encrypt = false;
t1_block_length = 0;
t1_check_pfa();
}
static void t1_close_font_file(const char *close_name_suffix)
{
t1_log(close_name_suffix);
t1_close();
cur_file_name = NULL;
}
static void t1_check_block_len(boolean decrypt)
{
int l, c;
if (t1_block_length == 0)
return;
c = t1_getbyte();
if (decrypt)
c = edecrypt((byte)c);
l = t1_block_length;
if (!(l == 0 && (c == 10 || c == 13))) {
pdftex_fail("%i bytes more than expected", l + 1);
}
}
static void t1_start_eexec(void)
{
int i;
assert(is_included(fd_cur->fm));
get_length1();
save_offset();
if (!t1_pfa)
t1_check_block_len(false);
for (t1_line_ptr = t1_line_array, i = 0; i < 4; i++) {
edecrypt((byte)t1_getbyte());
*t1_line_ptr++ = 0;
}
t1_eexec_encrypt = true;
t1_putline(); /* to put the first four bytes */
}
static void t1_stop_eexec(void)
{
int c;
assert(is_included(fd_cur->fm));
get_length2();
save_offset();
t1_eexec_encrypt = false;
if (!t1_pfa)
t1_check_block_len(true);
else {
c = edecrypt((byte)t1_getbyte());
if (!(c == 10 || c == 13)) {
if (last_hexbyte == 0)
t1_puts("00");
else
pdftex_fail("unexpected data after eexec");
}
}
t1_cs = false;
t1_in_eexec = 2;
}
/* macros for various transforms; currently only slant and extend are used */
#define do_xshift(x,a) {x[4]+=a;}
#define do_yshift(x,a) {x[5]+=a;}
#define do_xscale(x,a) {x[0]*=a; x[2]*=a; x[4]*=a;}
#define do_yscale(x,a) {x[1]*=a; x[3]*=a; x[5]*=a;}
#define do_extend(x,a) {do_xscale(x,a);}
#define do_scale(x,a) {do_xscale(x,a); do_yscale(x,a);}
#define do_slant(x,a) {x[0]+=x[1]*(a); x[2]+=x[3]*(a); x[4]+=x[5]*(a);}
#define do_shear(x,a) {x[1]+=x[0]*(a); x[3]+=x[2]*(a); x[5]+=x[4]*(a);}
#define do_rotate(x,a) \
{float t, u=cos(a), v=sin(a); \
t =x[0]*u+x[1]*-v; \
x[1] =x[0]*v+x[1]* u; x[0]=t; \
t =x[2]*u+x[3]*-v; \
x[3] =x[2]*v+x[3]* u; x[2]=t; \
t =x[4]*u+x[5]*-v; \
x[5] =x[4]*v+x[5]* u; x[4]=t;}
static void t1_modify_fm(void)
{
/*
* font matrix is given as six numbers a0..a5, which stands for the matrix
*
* a0 a1 0
* M = a2 a3 0
* a4 a5 1
*
* ExtendFont is given as
*
* e 0 0
* E = 0 1 0
* 0 0 1
*
* SlantFont is given as
*
* 1 0 0
* S = s 1 0
* 0 0 1
*
* The slant transform must be done _before_ the extend transform
* for compatibility!
*/
float a[6];
int i, c;
char *p, *q, *r;
if ((p = strchr(t1_line_array, '[')) == 0)
if ((p = strchr(t1_line_array, '{')) == 0) {
remove_eol(p, t1_line_array);
pdftex_fail("FontMatrix: an array expected: `%s'", t1_line_array);
}
c = *p++; /* save the character '[' resp. '{' */
strncpy(t1_buf_array, t1_line_array, (size_t) (p - t1_line_array));
r = t1_buf_array + (p - t1_line_array);
for (i = 0; i < 6; i++) {
a[i] = t1_scan_num(p, &q);
p = q;
}
if (fm_slant(fd_cur->fm) != 0)
do_slant(a, fm_slant(fd_cur->fm) * 1E-3);
if (fm_extend(fd_cur->fm) != 0)
do_extend(a, fm_extend(fd_cur->fm) * 1E-3);
for (i = 0; i < 6; i++) {
sprintf(r, "%g ", a[i]);
r = strend(r);
}
if (c == '[') {
while (*p != ']' && *p != 0)
p++;
} else {
while (*p != '}' && *p != 0)
p++;
}
if (*p == 0) {
remove_eol(p, t1_line_array);
pdftex_fail
("FontMatrix: cannot find the corresponding character to '%c': `%s'",
c, t1_line_array);
}
strcpy(r, p);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
static void t1_modify_italic(void)
{
float a;
char *p, *r;
if (fm_slant(fd_cur->fm) == 0)
return;
p = strchr(t1_line_array, ' ');
strncpy(t1_buf_array, t1_line_array, (size_t) (p - t1_line_array + 1));
a = t1_scan_num(p + 1, &r);
a -= atan(fm_slant(fd_cur->fm) * 1E-3) * (180 / M_PI);
sprintf(t1_buf_array + (p - t1_line_array + 1), "%g", a);
strcpy(strend(t1_buf_array), r);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
fd_cur->font_dim[ITALIC_ANGLE_CODE].val = round(a);
fd_cur->font_dim[ITALIC_ANGLE_CODE].set = true;
}
static void t1_scan_keys(void)
{
int i, k;
char *p, *q, *r;
const key_entry *key;
if (fm_extend(fd_cur->fm) != 0 || fm_slant(fd_cur->fm) != 0) {
if (t1_prefix("/FontMatrix")) {
t1_modify_fm();
return;
}
if (t1_prefix("/ItalicAngle")) {
t1_modify_italic();
return;
}
}
if (t1_prefix("/FontType")) {
p = t1_line_array + strlen("FontType") + 1;
if ((i = t1_scan_num(p, 0)) != 1)
pdftex_fail("Type%d fonts unsupported by pdfTeX", i);
return;
}
for (key = font_key; key - font_key < FONT_KEYS_NUM; key++) {
if (key->t1name[0] != '\0' &&
str_prefix(t1_line_array + 1, key->t1name))
break;
}
if (key - font_key == FONT_KEYS_NUM)
return;
p = t1_line_array + strlen(key->t1name) + 1;
skip(p, ' ');
if ((k = key - font_key) == FONTNAME_CODE) {
if (*p != '/') {
remove_eol(p, t1_line_array);
pdftex_fail("a name expected: `%s'", t1_line_array);
}
r = ++p; /* skip the slash */
for (q = t1_buf_array; *p != ' ' && *p != 10; *q++ = *p++);
*q = 0;
if (fm_slant(fd_cur->fm) != 0) {
sprintf(q, "-Slant_%i", (int) fm_slant(fd_cur->fm));
q = strend(q);
}
if (fm_extend(fd_cur->fm) != 0) {
sprintf(q, "-Extend_%i", (int) fm_extend(fd_cur->fm));
}
xfree(fd_cur->fontname);
fd_cur->fontname = xstrdup(t1_buf_array);
/* at this moment we cannot call make_subset_tag() yet, as the encoding
* is not read; thus we mark the offset of the subset tag and write it
* later */
if (is_subsetted(fd_cur->fm)) {
assert(is_included(fd_cur->fm));
t1_fontname_offset = t1_offset() + (r - t1_line_array);
strcpy(t1_buf_array, p);
sprintf(r, "ABCDEF+%s%s", fd_cur->fontname, t1_buf_array);
t1_line_ptr = eol(r);
}
return;
}
if ((k == STEMV_CODE || k == FONTBBOX1_CODE)
&& (*p == '[' || *p == '{'))
p++;
if (k == FONTBBOX1_CODE) {
for (i = 0; i < 4; i++, k++) {
fd_cur->font_dim[k].val = t1_scan_num(p, &r);
fd_cur->font_dim[k].set = true;
p = r;
}
return;
}
fd_cur->font_dim[k].val = t1_scan_num(p, 0);
fd_cur->font_dim[k].set = true;
}
static void t1_scan_param(void)
{
static const char *lenIV = "/lenIV";
if (!t1_scan || *t1_line_array != '/')
return;
if (t1_prefix(lenIV)) {
t1_lenIV = t1_scan_num(t1_line_array + strlen(lenIV), 0);
if (t1_lenIV < 0)
pdftex_fail("negative value of lenIV is not supported");
return;
}
t1_scan_keys();
}
static void copy_glyph_names(char **glyph_names, int a, int b)
{
if (glyph_names[b] != notdef) {
xfree(glyph_names[b]);
glyph_names[b] = notdef;
}
if (glyph_names[a] != notdef) {
glyph_names[b] = xstrdup(glyph_names[a]);
}
}
/* read encoding from Type1 font file, return glyph_names array, or pdffail() */
static char **t1_builtin_enc(void)
{
int i, a, b, c, counter = 0;
char *r, *p, **glyph_names;
/* At this moment "/Encoding" is the prefix of t1_line_array */
glyph_names = xtalloc(256, char *);
for (i = 0; i < 256; i++)
glyph_names[i] = notdef;
if (t1_suffix("def")) { /* predefined encoding */
if (sscanf(t1_line_array + strlen("/Encoding"), "%255s", t1_buf_array) == 1
&& strcmp(t1_buf_array, "StandardEncoding") == 0) {
t1_encoding = ENC_STANDARD;
for (i = 0; i < 256; i++) {
if (standard_glyph_names[i] != notdef)
glyph_names[i] = xstrdup(standard_glyph_names[i]);
}
return glyph_names;
}
pdftex_fail("cannot subset font (unknown predefined encoding `%s')",
t1_buf_array);
}
/* At this moment "/Encoding" is the prefix of t1_line_array, and the encoding is
* not a predefined encoding.
*
* We have two possible forms of Encoding vector. The first case is
*
* /Encoding [/a /b /c...] readonly def
*
* and the second case can look like
*
* /Encoding 256 array 0 1 255 {1 index exch /.notdef put} for
* dup 0 /x put
* dup 1 /y put
* ...
* readonly def
*/
t1_encoding = ENC_BUILTIN;
if (t1_prefix("/Encoding [") || t1_prefix("/Encoding[")) { /* the first case */
r = strchr(t1_line_array, '[') + 1;
skip(r, ' ');
for (;;) {
while (*r == '/') {
for (p = t1_buf_array, r++;
*r != 32 && *r != 10 && *r != ']' && *r != '/';
*p++ = *r++);
*p = 0;
skip(r, ' ');
if (counter > 255)
pdftex_fail("encoding vector contains more than 256 names");
if (strcmp(t1_buf_array, notdef) != 0)
glyph_names[counter] = xstrdup(t1_buf_array);
counter++;
}
if (*r != 10 && *r != '%') {
if (str_prefix(r, "] def") || str_prefix(r, "] readonly def"))
break;
else {
remove_eol(r, t1_line_array);
pdftex_fail
("a name or `] def' or `] readonly def' expected: `%s'", t1_line_array);
}
}
t1_getline();
r = t1_line_array;
}
} else { /* the second case */
p = strchr(t1_line_array, 10);
for (;;) {
if (*p == 10) {
t1_getline();
p = t1_line_array;
}
/*
check for `dup <index> <glyph> put'
*/
if (sscanf(p, "dup %i%255s put", &i, t1_buf_array) == 2 &&
*t1_buf_array == '/' && valid_code(i)) {
if (strcmp(t1_buf_array + 1, notdef) != 0)
glyph_names[i] = xstrdup(t1_buf_array + 1);
p = strstr(p, " put") + strlen(" put");
skip(p, ' ');
}
/*
check for `dup dup <to> exch <from> get put'
*/
else if (sscanf(p, "dup dup %i exch %i get put", &b, &a) == 2
&& valid_code(a) && valid_code(b)) {
copy_glyph_names(glyph_names, a, b);
p = strstr(p, " get put") + strlen(" get put");
skip(p, ' ');
}
/*
check for `dup dup <from> <size> getinterval <to> exch putinterval'
*/
else if (sscanf(p, "dup dup %i %i getinterval %i exch putinterval",
&a, &c, &b) == 3
&& valid_code(a) && valid_code(b) && valid_code(c)) {
for (i = 0; i < c; i++)
copy_glyph_names(glyph_names, a + i, b + i);
p = strstr(p, " putinterval") + strlen(" putinterval");
skip(p, ' ');
}
/*
check for `def' or `readonly def'
*/
else if ((p == t1_line_array || (p > t1_line_array && p[-1] == ' '))
&& strcmp(p, "def\n") == 0)
return glyph_names;
/*
skip an unrecognizable word
*/
else {
while (*p != ' ' && *p != 10)
p++;
skip(p, ' ');
}
}
}
return glyph_names;
}
static void t1_check_end(void)
{
if (t1_eof())
return;
t1_getline();
if (t1_prefix("{restore}"))
t1_putline();
}
static boolean t1_open_fontfile(const char *open_name_prefix)
{
ff_entry *ff;
ff = check_ff_exist(fd_cur->fm->ff_name, is_truetype(fd_cur->fm));
if (ff->ff_path != NULL) {
t1_file = xfopen(cur_file_name = ff->ff_path, FOPEN_RBIN_MODE);
recorder_record_input(ff->ff_path);
} else {
set_cur_file_name(fd_cur->fm->ff_name);
pdftex_fail("cannot open Type 1 font file for reading");
}
t1_init_params(open_name_prefix);
return true; /* font file found */
}
static void t1_include(void)
{
do {
t1_getline();
t1_scan_param();
t1_putline();
} while (t1_in_eexec == 0);
t1_start_eexec();
do {
t1_getline();
t1_scan_param();
t1_putline();
} while (!(t1_charstrings() || t1_subrs()));
t1_cs = true;
do {
t1_getline();
t1_putline();
} while (!t1_end_eexec());
t1_stop_eexec();
if (fixedcontent) { /* copy 512 zeros (not needed for PDF) */
do {
t1_getline();
t1_putline();
} while (!t1_cleartomark());
t1_check_end(); /* write "{restore}if" if found */
}
get_length3();
}
#define check_subr(subr) \
if (subr >= subr_size || subr < 0) \
pdftex_fail("Subrs array: entry index out of range (%i)", subr);
static const char **check_cs_token_pair(void)
{
const char **p = (const char **) cs_token_pairs_list;
for (; p[0] != NULL; ++p)
if (t1_buf_prefix(p[0]) && t1_buf_suffix(p[1]))
return p;
return NULL;
}
static void cs_store(boolean is_subr)
{
char *p;
cs_entry *ptr;
int subr;
for (p = t1_line_array, t1_buf_ptr = t1_buf_array; *p != ' ';
*t1_buf_ptr++ = *p++);
*t1_buf_ptr = 0;
if (is_subr) {
subr = t1_scan_num(p + 1, 0);
check_subr(subr);
ptr = subr_tab + subr;
} else {
ptr = cs_ptr++;
if (cs_ptr - cs_tab > cs_size)
pdftex_fail
("CharStrings dict: more entries than dict size (%i)", cs_size);
if (strcmp(t1_buf_array + 1, notdef) == 0) /* skip the slash */
ptr->name = notdef;
else
ptr->name = xstrdup(t1_buf_array + 1);
}
/* copy " RD " + cs data to t1_buf_array */
memcpy(t1_buf_array, t1_line_array + cs_start - 4,
(unsigned) (t1_cslen + 4));
/* copy the end of cs data to t1_buf_array */
for (p = t1_line_array + cs_start + t1_cslen,
t1_buf_ptr = t1_buf_array + t1_cslen + 4;
*p != 10; *t1_buf_ptr++ = *p++);
*t1_buf_ptr++ = 10;
if (is_subr && cs_token_pair == NULL)
cs_token_pair = check_cs_token_pair();
ptr->len = t1_buf_ptr - t1_buf_array;
ptr->cslen = t1_cslen;
ptr->data = xtalloc(ptr->len, byte);
memcpy(ptr->data, t1_buf_array, ptr->len);
ptr->valid = true;
}
#define store_subr() cs_store(true)
#define store_cs() cs_store(false)
#define CC_STACK_SIZE 24
static integer cc_stack[CC_STACK_SIZE], *stack_ptr = cc_stack;
static cc_entry cc_tab[CS_MAX];
static boolean is_cc_init = false;
#define cc_pop(N) \
if (stack_ptr - cc_stack < (N)) \
stack_error(N); \
stack_ptr -= N
#define stack_error(N) { \
pdftex_fail("CharString: invalid access (%i) to stack (%i entries)", \
(int) N, (int)(stack_ptr - cc_stack)); \
goto cs_error; \
}
/*
static integer cc_get(integer index)
{
if (index < 0) {
if (stack_ptr + index < cc_stack )
stack_error(stack_ptr - cc_stack + index);
return *(stack_ptr + index);
}
else {
if (cc_stack + index >= stack_ptr)
stack_error(index);
return cc_stack[index];
}
}
*/
#define cc_get(N) ((N) < 0 ? *(stack_ptr + (N)) : *(cc_stack + (N)))
#define cc_push(V) *stack_ptr++ = V
#define cc_clear() stack_ptr = cc_stack
#define set_cc(N, B, A, C) \
cc_tab[N].nargs = A; \
cc_tab[N].bottom = B; \
cc_tab[N].clear = C; \
cc_tab[N].valid = true
static void cc_init(void)
{
int i;
if (is_cc_init)
return;
for (i = 0; i < CS_MAX; i++)
cc_tab[i].valid = false;
set_cc(CS_HSTEM, true, 2, true);
set_cc(CS_VSTEM, true, 2, true);
set_cc(CS_VMOVETO, true, 1, true);
set_cc(CS_RLINETO, true, 2, true);
set_cc(CS_HLINETO, true, 1, true);
set_cc(CS_VLINETO, true, 1, true);
set_cc(CS_RRCURVETO, true, 6, true);
set_cc(CS_CLOSEPATH, false, 0, true);
set_cc(CS_CALLSUBR, false, 1, false);
set_cc(CS_RETURN, false, 0, false);
/*
set_cc(CS_ESCAPE, false, 0, false);
*/
set_cc(CS_HSBW, true, 2, true);
set_cc(CS_ENDCHAR, false, 0, true);
set_cc(CS_RMOVETO, true, 2, true);
set_cc(CS_HMOVETO, true, 1, true);
set_cc(CS_VHCURVETO, true, 4, true);
set_cc(CS_HVCURVETO, true, 4, true);
set_cc(CS_DOTSECTION, false, 0, true);
set_cc(CS_VSTEM3, true, 6, true);
set_cc(CS_HSTEM3, true, 6, true);
set_cc(CS_SEAC, true, 5, true);
set_cc(CS_SBW, true, 4, true);
set_cc(CS_DIV, false, 2, false);
set_cc(CS_CALLOTHERSUBR, false, 0, false);
set_cc(CS_POP, false, 0, false);
set_cc(CS_SETCURRENTPOINT, true, 2, true);
is_cc_init = true;
}
#define cs_getchar() cdecrypt(*data++, &cr)
#define mark_subr(n) cs_mark(0, n)
#define mark_cs(s) cs_mark(s, 0)
__attribute__ ((format(printf, 3, 4)))
static void cs_fail(const char *cs_name, int subr, const char *fmt, ...)
{
char buf[SMALL_BUF_SIZE];
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
if (cs_name == NULL)
pdftex_fail("Subr (%i): %s", (int) subr, buf);
else
pdftex_fail("CharString (/%s): %s", cs_name, buf);
}
/* fix a return-less subr by appending CS_RETURN */
static void append_cs_return(cs_entry *ptr)
{
unsigned short cr;
int i;
byte *p, *q, *data, *new_data;
assert(ptr != NULL && ptr->valid && ptr->used);
/* decrypt the cs data to t1_buf_array, append CS_RETURN */
p = (byte *) t1_buf_array;
data = ptr->data + 4;
cr = 4330;
for (i = 0; i < ptr->cslen; i++)
*p++ = cs_getchar();
*p = CS_RETURN;
/* encrypt the new cs data to new_data */
new_data = xtalloc(ptr->len + 1, byte);
memcpy(new_data, ptr->data, 4);
p = new_data + 4;
q = (byte *) t1_buf_array;
cr = 4330;
for (i = 0; i < ptr->cslen + 1; i++)
*p++ = cencrypt(*q++, &cr);
memcpy(p, ptr->data + 4 + ptr->cslen, ptr->len - ptr->cslen - 4);
/* update *ptr */
xfree(ptr->data);
ptr->data = new_data;
ptr->len++;
ptr->cslen++;
}
static void cs_mark(const char *cs_name, int subr)
{
byte *data;
int i, b, cs_len;
int last_cmd = 0;
integer a, a1, a2;
unsigned short cr;
static integer lastargOtherSubr3 = 3; /* the argument of last call to
OtherSubrs[3] */
cs_entry *ptr;
cc_entry *cc;
if (cs_name == NULL) {
check_subr(subr);
ptr = subr_tab + subr;
if (!ptr->valid)
return;
} else {
if (cs_notdef != NULL &&
(cs_name == notdef || strcmp(cs_name, notdef) == 0))
ptr = cs_notdef;
else {
for (ptr = cs_tab; ptr < cs_ptr; ptr++)
if (strcmp(ptr->name, cs_name) == 0)
break;
if (ptr == cs_ptr) {
pdftex_warn("glyph `%s' undefined", cs_name);
return;
}
if (ptr->name == notdef)
cs_notdef = ptr;
}
}
/* only marked CharString entries and invalid entries can be skipped;
valid marked subrs must be parsed to keep the stack in sync */
if (!ptr->valid || (ptr->used && cs_name != NULL))
return;
ptr->used = true;
cr = 4330;
cs_len = ptr->cslen;
data = ptr->data + 4;
for (i = 0; i < t1_lenIV; i++, cs_len--)
cs_getchar();
while (cs_len > 0) {
--cs_len;
b = cs_getchar();
if (b >= 32) {
if (b <= 246)
a = b - 139;
else if (b <= 250) {
--cs_len;
a = ((b - 247) << 8) + 108 + cs_getchar();
} else if (b <= 254) {
--cs_len;
a = -((b - 251) << 8) - 108 - cs_getchar();
} else {
cs_len -= 4;
a = (cs_getchar() & 0xff) << 24;
a |= (cs_getchar() & 0xff) << 16;
a |= (cs_getchar() & 0xff) << 8;
a |= (cs_getchar() & 0xff) << 0;
if (sizeof(integer) > 4 && (a & 0x80000000))
a |= ~0x7FFFFFFF;
}
cc_push(a);
} else {
if (b == CS_ESCAPE) {
b = cs_getchar() + CS_1BYTE_MAX;
cs_len--;
}
if (b >= CS_MAX) {
cs_fail(cs_name, subr, "command value out of range: %i",
(int) b);
goto cs_error;
}
cc = cc_tab + b;
if (!cc->valid) {
cs_fail(cs_name, subr, "command not valid: %i", (int) b);
goto cs_error;
}
if (cc->bottom) {
if (stack_ptr - cc_stack < cc->nargs)
cs_fail(cs_name, subr,
"less arguments on stack (%i) than required (%i)",
(int) (stack_ptr - cc_stack), (int) cc->nargs);
else if (stack_ptr - cc_stack > cc->nargs)
cs_fail(cs_name, subr,
"more arguments on stack (%i) than required (%i)",
(int) (stack_ptr - cc_stack), (int) cc->nargs);
}
last_cmd = b;
switch (cc - cc_tab) {
case CS_CALLSUBR:
a1 = cc_get(-1);
cc_pop(1);
mark_subr(a1);
if (!subr_tab[a1].valid) {
cs_fail(cs_name, subr, "cannot call subr (%i)", (int) a1);
goto cs_error;
}
break;
case CS_DIV:
cc_pop(2);
cc_push(0);
break;
case CS_CALLOTHERSUBR:
if (cc_get(-1) == 3)
lastargOtherSubr3 = cc_get(-3);
a1 = cc_get(-2) + 2;
cc_pop(a1);
break;
case CS_POP:
cc_push(lastargOtherSubr3);
/* the only case when we care about the value being pushed onto
stack is when POP follows CALLOTHERSUBR (changing hints by
OtherSubrs[3])
*/
break;
case CS_SEAC:
a1 = cc_get(3);
a2 = cc_get(4);
cc_clear();
mark_cs(standard_glyph_names[a1]);
mark_cs(standard_glyph_names[a2]);
break;
default:
if (cc->clear)
cc_clear();
}
}
}
if (cs_name == NULL && last_cmd != CS_RETURN) {
pdftex_warn("last command in subr `%i' is not a RETURN; "
"I will add it now but please consider fixing the font",
(int) subr);
append_cs_return(ptr);
}
return;
cs_error: /* an error occured during parsing */
cc_clear();
ptr->valid = false;
ptr->used = false;
}
/**********************************************************************/
/* AVL search tree for glyph code by glyph name */
static int comp_t1_glyphs(const void *pa, const void *pb, void *p)
{
return strcmp(*((const char * const *) pa), *((const char * const *) pb));
}
static struct avl_table *create_t1_glyph_tree(char **glyph_names)
{
int i;
void **aa;
static struct avl_table *gl_tree;
gl_tree = avl_create(comp_t1_glyphs, NULL, &avl_xallocator);
assert(gl_tree != NULL);
for (i = 0; i < 256; i++) {
if (glyph_names[i] != notdef &&
(char **) avl_find(gl_tree, &glyph_names[i]) == NULL) {
/* no strdup here, just point to the glyph_names array members */
aa = avl_probe(gl_tree, &glyph_names[i]);
assert(aa != NULL);
}
}
return gl_tree;
}
static void destroy_t1_glyph_tree(struct avl_table *gl_tree)
{
assert(gl_tree != NULL);
avl_destroy(gl_tree, NULL);
}
/**********************************************************************/
static void t1_subset_ascii_part(void)
{
int j, *p;
char *glyph, **gg, **glyph_names;
struct avl_table *gl_tree;
struct avl_traverser t;
void **aa;
assert(fd_cur != NULL);
assert(fd_cur->gl_tree != NULL);
t1_getline();
while (!t1_prefix("/Encoding")) {
t1_scan_param();
if (!(t1_prefix("/UniqueID")
&& !strncmp(t1_line_array + strlen(t1_line_array) -4, "def", 3)))
t1_putline();
t1_getline();
}
glyph_names = t1_builtin_enc();
fd_cur->builtin_glyph_names = glyph_names;
if (is_subsetted(fd_cur->fm)) {
assert(is_included(fd_cur->fm));
if (fd_cur->tx_tree != NULL) {
/* take over collected non-reencoded characters from TeX */
avl_t_init(&t, fd_cur->tx_tree);
for (p = (int *) avl_t_first(&t, fd_cur->tx_tree); p != NULL;
p = (int *) avl_t_next(&t)) {
if ((char *) avl_find(fd_cur->gl_tree, glyph_names[*p]) == NULL) {
glyph = xstrdup(glyph_names[*p]);
aa = avl_probe(fd_cur->gl_tree, glyph);
assert(aa != NULL);
}
}
}
make_subset_tag(fd_cur);
assert(t1_fontname_offset != 0);
strncpy(fb_array + t1_fontname_offset, fd_cur->subset_tag, 6);
}
/* now really all glyphs needed from this font are in the fd_cur->gl_tree */
if (t1_encoding == ENC_STANDARD)
t1_puts("/Encoding StandardEncoding def\n");
else {
t1_puts
("/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n");
gl_tree = create_t1_glyph_tree(glyph_names);
avl_t_init(&t, fd_cur->gl_tree);
j = 0;
for (glyph = (char *) avl_t_first(&t, fd_cur->gl_tree); glyph != NULL;
glyph = (char *) avl_t_next(&t)) {
if ((gg = (char **) avl_find(gl_tree, &glyph)) != NULL) {
t1_printf("dup %i /%s put\n", (int) (gg - glyph_names), *gg);
j++;
}
}
destroy_t1_glyph_tree(gl_tree);
if (j == 0)
/* We didn't mark anything for the Encoding array. */
/* We add "dup 0 /.notdef put" for compatibility */
/* with Acrobat 5.0. */
t1_puts("dup 0 /.notdef put\n");
t1_puts("readonly def\n");
}
do {
t1_getline();
t1_scan_param();
if (!t1_prefix("/UniqueID")) /* ignore UniqueID for subsetted fonts */
t1_putline();
} while (t1_in_eexec == 0);
}
static void cs_init(void)
{
cs_ptr = cs_tab = NULL;
cs_dict_start = cs_dict_end = NULL;
cs_count = cs_size = cs_size_pos = 0;
cs_token_pair = NULL;
subr_tab = NULL;
subr_array_start = subr_array_end = NULL;
subr_max = subr_size = subr_size_pos = 0;
}
static void init_cs_entry(cs_entry *cs)
{
cs->data = NULL;
cs->name = NULL;
cs->len = 0;
cs->cslen = 0;
cs->used = false;
cs->valid = false;
}
static void t1_read_subrs(void)
{
int i, s;
cs_entry *ptr;
t1_getline();
while (!(t1_charstrings() || t1_subrs())) {
t1_scan_param();
if (!t1_prefix("/UniqueID")) /* ignore UniqueID for subsetted fonts */
t1_putline();
t1_getline();
}
found:
t1_cs = true;
t1_scan = false;
if (!t1_subrs())
return;
subr_size_pos = strlen("/Subrs") + 1;
/* subr_size_pos points to the number indicating dict size after "/Subrs" */
subr_size = t1_scan_num(t1_line_array + subr_size_pos, 0);
if (subr_size == 0) {
while (!t1_charstrings())
t1_getline();
return;
}
subr_tab = xtalloc(subr_size, cs_entry);
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
init_cs_entry(ptr);
subr_array_start = xstrdup(t1_line_array);
t1_getline();
while (t1_cslen) {
store_subr();
t1_getline();
}
/* mark the first four entries without parsing */
for (i = 0; i < subr_size && i < 4; i++)
subr_tab[i].used = true;
/* the end of the Subrs array might have more than one line so we need to
concatnate them to subr_array_end. Unfortunately some fonts don't have
the Subrs array followed by the CharStrings dict immediately (synthetic
fonts). If we cannot find CharStrings in next POST_SUBRS_SCAN lines then
we will treat the font as synthetic and ignore everything until next
Subrs is found
*/
#define POST_SUBRS_SCAN 5
s = 0;
*t1_buf_array = 0;
for (i = 0; i < POST_SUBRS_SCAN; i++) {
if (t1_charstrings())
break;
s += t1_line_ptr - t1_line_array;
alloc_array(t1_buf, s, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
t1_getline();
}
subr_array_end = xstrdup(t1_buf_array);
if (i == POST_SUBRS_SCAN) { /* CharStrings not found;
suppose synthetic font */
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->valid)
xfree(ptr->data);
xfree(subr_tab);
xfree(subr_array_start);
xfree(subr_array_end);
cs_init();
t1_cs = false;
t1_synthetic = true;
while (!(t1_charstrings() || t1_subrs()))
t1_getline();
goto found;
}
}
#define t1_subr_flush() t1_flush_cs(true)
#define t1_cs_flush() t1_flush_cs(false)
static void t1_flush_cs(boolean is_subr)
{
char *p;
byte *r, *return_cs = NULL;
cs_entry *tab, *end_tab, *ptr;
char *start_line, *line_end;
int count, size_pos;
unsigned short cr, cs_len = 0; /* to avoid warning about uninitialized use of cs_len */
if (is_subr) {
start_line = subr_array_start;
line_end = subr_array_end;
size_pos = subr_size_pos;
tab = subr_tab;
count = subr_max + 1;
end_tab = subr_tab + count;
} else {
start_line = cs_dict_start;
line_end = cs_dict_end;
size_pos = cs_size_pos;
tab = cs_tab;
end_tab = cs_ptr;
count = cs_count;
}
t1_line_ptr = t1_line_array;
for (p = start_line; p - start_line < size_pos;)
*t1_line_ptr++ = *p++;
while (isdigit((unsigned char)*p))
p++;
sprintf(t1_line_ptr, "%u", count);
strcat(t1_line_ptr, p);
t1_line_ptr = eol(t1_line_array);
t1_putline();
/* create return_cs to replace unused subr's */
if (is_subr) {
cr = 4330;
cs_len = 0;
/* at this point we have t1_lenIV >= 0;
* a negative value would be caught in t1_scan_param() */
return_cs = xtalloc(t1_lenIV + 1, byte);
for (cs_len = 0, r = return_cs; cs_len < t1_lenIV; cs_len++, r++)
*r = cencrypt(0x00, &cr);
*r = cencrypt(CS_RETURN, &cr);
cs_len++;
}
for (ptr = tab; ptr < end_tab; ptr++) {
if (ptr->used) {
if (is_subr)
sprintf(t1_line_array, "dup %lu %u",
(unsigned long) (ptr - tab), ptr->cslen);
else
sprintf(t1_line_array, "/%s %u", ptr->name, ptr->cslen);
p = strend(t1_line_array);
memcpy(p, ptr->data, ptr->len);
t1_line_ptr = p + ptr->len;
t1_putline();
} else {
/* replace unsused subr's by return_cs */
if (is_subr) {
sprintf(t1_line_array, "dup %lu %u%s ",
(unsigned long) (ptr - tab), cs_len, cs_token_pair[0]);
p = strend(t1_line_array);
memcpy(p, return_cs, cs_len);
t1_line_ptr = p + cs_len;
t1_putline();
sprintf(t1_line_array, " %s", cs_token_pair[1]);
t1_line_ptr = eol(t1_line_array);
t1_putline();
}
}
xfree(ptr->data);
if (ptr->name != notdef)
xfree(ptr->name);
}
sprintf(t1_line_array, "%s", line_end);
t1_line_ptr = eol(t1_line_array);
t1_putline();
if (is_subr)
xfree(return_cs);
xfree(tab);
xfree(start_line);
xfree(line_end);
}
static void t1_mark_glyphs(void)
{
char *glyph;
struct avl_traverser t;
cs_entry *ptr;
if (t1_synthetic || fd_cur->all_glyphs) { /* mark everything */
if (cs_tab != NULL)
for (ptr = cs_tab; ptr < cs_ptr; ptr++)
if (ptr->valid)
ptr->used = true;
if (subr_tab != NULL) {
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->valid)
ptr->used = true;
subr_max = subr_size - 1;
}
return;
}
mark_cs(notdef);
avl_t_init(&t, fd_cur->gl_tree);
for (glyph = (char *) avl_t_first(&t, fd_cur->gl_tree); glyph != NULL;
glyph = (char *) avl_t_next(&t)) {
mark_cs(glyph);
}
if (subr_tab != NULL)
for (subr_max = -1, ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->used && ptr - subr_tab > subr_max)
subr_max = ptr - subr_tab;
}
static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/* if no number follows "/CharStrings", let's read the next line */
if (sscanf(p, "%i", &i) != 1) {
/* pdftex_warn("no number found after `%s', I assume it's on the next line",
charstringname); */
strcpy(t1_buf_array, t1_line_array);
/* t1_getline always appends EOL to t1_line_array; let's change it to
* space before appending the next line
*/
*(strend(t1_buf_array) - 1) = ' ';
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
static void t1_subset_charstrings(void)
{
cs_entry *ptr;
/* at this point t1_line_array contains "/CharStrings".
when we hit a case like this:
dup/CharStrings
229 dict dup begin
we read the next line and concatenate to t1_line_array before moving on
*/
t1_check_unusual_charstring();
cs_size_pos = strstr(t1_line_array, charstringname)
+ strlen(charstringname) - t1_line_array + 1;
/* cs_size_pos points to the number indicating
dict size after "/CharStrings" */
cs_size = t1_scan_num(t1_line_array + cs_size_pos, 0);
cs_ptr = cs_tab = xtalloc(cs_size, cs_entry);
for (ptr = cs_tab; ptr - cs_tab < cs_size; ptr++)
init_cs_entry(ptr);
cs_notdef = NULL;
cs_dict_start = xstrdup(t1_line_array);
t1_getline();
while (t1_cslen) {
store_cs();
t1_getline();
}
cs_dict_end = xstrdup(t1_line_array);
t1_mark_glyphs();
if (subr_tab != NULL) {
if (cs_token_pair == NULL)
pdftex_fail
("This Type 1 font uses mismatched subroutine begin/end token pairs.");
t1_subr_flush();
}
for (cs_count = 0, ptr = cs_tab; ptr < cs_ptr; ptr++)
if (ptr->used)
cs_count++;
t1_cs_flush();
}
static void t1_subset_end(void)
{
if (t1_synthetic) { /* copy to "dup /FontName get exch definefont pop" */
while (!strstr(t1_line_array, "definefont")) {
t1_getline();
t1_putline();
}
while (!t1_end_eexec())
t1_getline(); /* ignore the rest */
t1_putline(); /* write "mark currentfile closefile" */
} else
while (!t1_end_eexec()) { /* copy to "mark currentfile closefile" */
t1_getline();
t1_putline();
}
t1_stop_eexec();
if (fixedcontent) { /* copy 512 zeros (not needed for PDF) */
while (!t1_cleartomark()) {
t1_getline();
t1_putline();
}
if (!t1_synthetic) /* don't check "{restore}if" for synthetic fonts */
t1_check_end(); /* write "{restore}if" if found */
}
get_length3();
}
void writet1(fd_entry *fd)
{
fd_cur = fd; /* fd_cur is global inside writet1.c */
assert(fd_cur->fm != NULL);
assert(is_type1(fd->fm));
assert(is_included(fd->fm));
t1_save_offset = 0;
if (!is_subsetted(fd_cur->fm)) { /* include entire font */
if (!(fd->ff_found = t1_open_fontfile("<<")))
return;
t1_include();
t1_close_font_file(">>");
return;
}
/* partial downloading */
if (!(fd->ff_found = t1_open_fontfile("<")))
return;
t1_subset_ascii_part();
t1_start_eexec();
cc_init();
cs_init();
t1_read_subrs();
t1_subset_charstrings();
t1_subset_end();
t1_close_font_file(">");
}
void t1_free(void)
{
xfree(t1_line_array);
xfree(t1_buf_array);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_395_5 |
crossvul-cpp_data_good_5733_8 | /*
* Copyright (c) 2008 vmrsss
* Copyright (c) 2009 Stefano Sabatini
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* video padding filter
*/
#include "avfilter.h"
#include "formats.h"
#include "internal.h"
#include "video.h"
#include "libavutil/avstring.h"
#include "libavutil/common.h"
#include "libavutil/eval.h"
#include "libavutil/pixdesc.h"
#include "libavutil/colorspace.h"
#include "libavutil/avassert.h"
#include "libavutil/imgutils.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "drawutils.h"
static const char *const var_names[] = {
"in_w", "iw",
"in_h", "ih",
"out_w", "ow",
"out_h", "oh",
"x",
"y",
"a",
"sar",
"dar",
"hsub",
"vsub",
NULL
};
enum var_name {
VAR_IN_W, VAR_IW,
VAR_IN_H, VAR_IH,
VAR_OUT_W, VAR_OW,
VAR_OUT_H, VAR_OH,
VAR_X,
VAR_Y,
VAR_A,
VAR_SAR,
VAR_DAR,
VAR_HSUB,
VAR_VSUB,
VARS_NB
};
static int query_formats(AVFilterContext *ctx)
{
ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
return 0;
}
typedef struct {
const AVClass *class;
int w, h; ///< output dimensions, a value of 0 will result in the input size
int x, y; ///< offsets of the input area with respect to the padded area
int in_w, in_h; ///< width and height for the padded input video, which has to be aligned to the chroma values in order to avoid chroma issues
char *w_expr; ///< width expression string
char *h_expr; ///< height expression string
char *x_expr; ///< width expression string
char *y_expr; ///< height expression string
uint8_t rgba_color[4]; ///< color for the padding area
FFDrawContext draw;
FFDrawColor color;
} PadContext;
static int config_input(AVFilterLink *inlink)
{
AVFilterContext *ctx = inlink->dst;
PadContext *s = ctx->priv;
int ret;
double var_values[VARS_NB], res;
char *expr;
ff_draw_init(&s->draw, inlink->format, 0);
ff_draw_color(&s->draw, &s->color, s->rgba_color);
var_values[VAR_IN_W] = var_values[VAR_IW] = inlink->w;
var_values[VAR_IN_H] = var_values[VAR_IH] = inlink->h;
var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
var_values[VAR_A] = (double) inlink->w / inlink->h;
var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ?
(double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
var_values[VAR_DAR] = var_values[VAR_A] * var_values[VAR_SAR];
var_values[VAR_HSUB] = 1 << s->draw.hsub_max;
var_values[VAR_VSUB] = 1 << s->draw.vsub_max;
/* evaluate width and height */
av_expr_parse_and_eval(&res, (expr = s->w_expr),
var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx);
s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
goto eval_fail;
s->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
/* evaluate the width again, as it may depend on the evaluated output height */
if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
goto eval_fail;
s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
/* evaluate x and y */
av_expr_parse_and_eval(&res, (expr = s->x_expr),
var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx);
s->x = var_values[VAR_X] = res;
if ((ret = av_expr_parse_and_eval(&res, (expr = s->y_expr),
var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
goto eval_fail;
s->y = var_values[VAR_Y] = res;
/* evaluate x again, as it may depend on the evaluated y value */
if ((ret = av_expr_parse_and_eval(&res, (expr = s->x_expr),
var_names, var_values,
NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
goto eval_fail;
s->x = var_values[VAR_X] = res;
/* sanity check params */
if (s->w < 0 || s->h < 0 || s->x < 0 || s->y < 0) {
av_log(ctx, AV_LOG_ERROR, "Negative values are not acceptable.\n");
return AVERROR(EINVAL);
}
if (!s->w)
s->w = inlink->w;
if (!s->h)
s->h = inlink->h;
s->w = ff_draw_round_to_sub(&s->draw, 0, -1, s->w);
s->h = ff_draw_round_to_sub(&s->draw, 1, -1, s->h);
s->x = ff_draw_round_to_sub(&s->draw, 0, -1, s->x);
s->y = ff_draw_round_to_sub(&s->draw, 1, -1, s->y);
s->in_w = ff_draw_round_to_sub(&s->draw, 0, -1, inlink->w);
s->in_h = ff_draw_round_to_sub(&s->draw, 1, -1, inlink->h);
av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d x:%d y:%d color:0x%02X%02X%02X%02X\n",
inlink->w, inlink->h, s->w, s->h, s->x, s->y,
s->rgba_color[0], s->rgba_color[1], s->rgba_color[2], s->rgba_color[3]);
if (s->x < 0 || s->y < 0 ||
s->w <= 0 || s->h <= 0 ||
(unsigned)s->x + (unsigned)inlink->w > s->w ||
(unsigned)s->y + (unsigned)inlink->h > s->h) {
av_log(ctx, AV_LOG_ERROR,
"Input area %d:%d:%d:%d not within the padded area 0:0:%d:%d or zero-sized\n",
s->x, s->y, s->x + inlink->w, s->y + inlink->h, s->w, s->h);
return AVERROR(EINVAL);
}
return 0;
eval_fail:
av_log(NULL, AV_LOG_ERROR,
"Error when evaluating the expression '%s'\n", expr);
return ret;
}
static int config_output(AVFilterLink *outlink)
{
PadContext *s = outlink->src->priv;
outlink->w = s->w;
outlink->h = s->h;
return 0;
}
static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)
{
PadContext *s = inlink->dst->priv;
AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0],
w + (s->w - s->in_w),
h + (s->h - s->in_h));
int plane;
if (!frame)
return NULL;
frame->width = w;
frame->height = h;
for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {
int hsub = s->draw.hsub[plane];
int vsub = s->draw.vsub[plane];
frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] +
(s->y >> vsub) * frame->linesize[plane];
}
return frame;
}
/* check whether each plane in this buffer can be padded without copying */
static int buffer_needs_copy(PadContext *s, AVFrame *frame, AVBufferRef *buf)
{
int planes[4] = { -1, -1, -1, -1}, *p = planes;
int i, j;
/* get all planes in this buffer */
for (i = 0; i < FF_ARRAY_ELEMS(planes) && frame->data[i]; i++) {
if (av_frame_get_plane_buffer(frame, i) == buf)
*p++ = i;
}
/* for each plane in this buffer, check that it can be padded without
* going over buffer bounds or other planes */
for (i = 0; i < FF_ARRAY_ELEMS(planes) && planes[i] >= 0; i++) {
int hsub = s->draw.hsub[planes[i]];
int vsub = s->draw.vsub[planes[i]];
uint8_t *start = frame->data[planes[i]];
uint8_t *end = start + (frame->height >> vsub) *
frame->linesize[planes[i]];
/* amount of free space needed before the start and after the end
* of the plane */
ptrdiff_t req_start = (s->x >> hsub) * s->draw.pixelstep[planes[i]] +
(s->y >> vsub) * frame->linesize[planes[i]];
ptrdiff_t req_end = ((s->w - s->x - frame->width) >> hsub) *
s->draw.pixelstep[planes[i]] +
(s->y >> vsub) * frame->linesize[planes[i]];
if (frame->linesize[planes[i]] < (s->w >> hsub) * s->draw.pixelstep[planes[i]])
return 1;
if (start - buf->data < req_start ||
(buf->data + buf->size) - end < req_end)
return 1;
for (j = 0; j < FF_ARRAY_ELEMS(planes) && planes[j] >= 0; j++) {
int vsub1 = s->draw.vsub[planes[j]];
uint8_t *start1 = frame->data[planes[j]];
uint8_t *end1 = start1 + (frame->height >> vsub1) *
frame->linesize[planes[j]];
if (i == j)
continue;
if (FFSIGN(start - end1) != FFSIGN(start - end1 - req_start) ||
FFSIGN(end - start1) != FFSIGN(end - start1 + req_end))
return 1;
}
}
return 0;
}
static int frame_needs_copy(PadContext *s, AVFrame *frame)
{
int i;
if (!av_frame_is_writable(frame))
return 1;
for (i = 0; i < 4 && frame->buf[i]; i++)
if (buffer_needs_copy(s, frame, frame->buf[i]))
return 1;
return 0;
}
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
PadContext *s = inlink->dst->priv;
AVFrame *out;
int needs_copy = frame_needs_copy(s, in);
if (needs_copy) {
av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
out = ff_get_video_buffer(inlink->dst->outputs[0],
FFMAX(inlink->w, s->w),
FFMAX(inlink->h, s->h));
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
} else {
int i;
out = in;
for (i = 0; i < 4 && out->data[i] && out->linesize[i]; i++) {
int hsub = s->draw.hsub[i];
int vsub = s->draw.vsub[i];
out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] +
(s->y >> vsub) * out->linesize[i];
}
}
/* top bar */
if (s->y) {
ff_fill_rectangle(&s->draw, &s->color,
out->data, out->linesize,
0, 0, s->w, s->y);
}
/* bottom bar */
if (s->h > s->y + s->in_h) {
ff_fill_rectangle(&s->draw, &s->color,
out->data, out->linesize,
0, s->y + s->in_h, s->w, s->h - s->y - s->in_h);
}
/* left border */
ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
0, s->y, s->x, in->height);
if (needs_copy) {
ff_copy_rectangle2(&s->draw,
out->data, out->linesize, in->data, in->linesize,
s->x, s->y, 0, 0, in->width, in->height);
}
/* right border */
ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
s->x + s->in_w, s->y, s->w - s->x - s->in_w,
in->height);
out->width = s->w;
out->height = s->h;
if (in != out)
av_frame_free(&in);
return ff_filter_frame(inlink->dst->outputs[0], out);
}
#define OFFSET(x) offsetof(PadContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
static const AVOption pad_options[] = {
{ "width", "set the pad area width expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
{ "w", "set the pad area width expression", OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
{ "height", "set the pad area height expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
{ "h", "set the pad area height expression", OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
{ "x", "set the x offset expression for the input image position", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
{ "y", "set the y offset expression for the input image position", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
{ "color", "set the color of the padded area border", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str = "black"}, .flags = FLAGS },
{ NULL },
};
AVFILTER_DEFINE_CLASS(pad);
static const AVFilterPad avfilter_vf_pad_inputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.config_props = config_input,
.get_video_buffer = get_video_buffer,
.filter_frame = filter_frame,
},
{ NULL }
};
static const AVFilterPad avfilter_vf_pad_outputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.config_props = config_output,
},
{ NULL }
};
AVFilter avfilter_vf_pad = {
.name = "pad",
.description = NULL_IF_CONFIG_SMALL("Pad input image to width:height[:x:y[:color]] (default x and y: 0, default color: black)."),
.priv_size = sizeof(PadContext),
.priv_class = &pad_class,
.query_formats = query_formats,
.inputs = avfilter_vf_pad_inputs,
.outputs = avfilter_vf_pad_outputs,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5733_8 |
crossvul-cpp_data_good_4787_7 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC L IIIII PPPP BBBB OOO AAA RRRR DDDD %
% C L I P P B B O O A A R R D D %
% C L I PPP BBBB O O AAAAA RRRR D D %
% C L I P B B O O A A R R D D %
% CCCC LLLLL IIIII P BBBB OOO A A R R DDDD %
% %
% %
% Read/Write Windows Clipboard. %
% %
% Software Design %
% Leonard Rosenthol %
% May 2002 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
# if defined(__CYGWIN__)
# include <windows.h>
# else
/* All MinGW needs ... */
# include "magick/nt-base-private.h"
# include <wingdi.h>
# endif
#endif
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/nt-feature.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
static MagickBooleanType
WriteCLIPBOARDImage(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCLIPBOARDImage() reads an image from the system clipboard 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 ReadCLIPBOARDImage method is:
%
% Image *ReadCLIPBOARDImage(const ImageInfo *image_info,
% ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
{
HBITMAP
bitmapH;
HPALETTE
hPal;
OpenClipboard(NULL);
bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP);
hPal=(HPALETTE) GetClipboardData(CF_PALETTE);
CloseClipboard();
if (bitmapH == NULL)
ThrowReaderException(CoderError,"NoBitmapOnClipboard");
{
BITMAPINFO
DIBinfo;
BITMAP
bitmap;
HBITMAP
hBitmap,
hOldBitmap;
HDC
hDC,
hMemDC;
RGBQUAD
*pBits,
*ppBits;
/* create an offscreen DC for the source */
hMemDC=CreateCompatibleDC(NULL);
hOldBitmap=(HBITMAP) SelectObject(hMemDC,bitmapH);
GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap);
if ((image->columns == 0) || (image->rows == 0))
{
image->columns=bitmap.bmWidth;
image->rows=bitmap.bmHeight;
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Initialize the bitmap header info.
*/
(void) ResetMagickMemory(&DIBinfo,0,sizeof(BITMAPINFO));
DIBinfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
DIBinfo.bmiHeader.biWidth=(LONG) image->columns;
DIBinfo.bmiHeader.biHeight=(-1)*(LONG) image->rows;
DIBinfo.bmiHeader.biPlanes=1;
DIBinfo.bmiHeader.biBitCount=32;
DIBinfo.bmiHeader.biCompression=BI_RGB;
hDC=GetDC(NULL);
if (hDC == 0)
ThrowReaderException(CoderError,"UnableToCreateADC");
hBitmap=CreateDIBSection(hDC,&DIBinfo,DIB_RGB_COLORS,(void **) &ppBits,
NULL,0);
ReleaseDC(NULL,hDC);
if (hBitmap == 0)
ThrowReaderException(CoderError,"UnableToCreateBitmap");
/* create an offscreen DC */
hDC=CreateCompatibleDC(NULL);
if (hDC == 0)
{
DeleteObject(hBitmap);
ThrowReaderException(CoderError,"UnableToCreateADC");
}
hOldBitmap=(HBITMAP) SelectObject(hDC,hBitmap);
if (hOldBitmap == 0)
{
DeleteDC(hDC);
DeleteObject(hBitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
if (hPal != NULL)
{
/* Kenichi Masuko says this needed */
SelectPalette(hDC, hPal, FALSE);
RealizePalette(hDC);
}
/* bitblt from the memory to the DIB-based one */
BitBlt(hDC,0,0,(int) image->columns,(int) image->rows,hMemDC,0,0,SRCCOPY);
/* finally copy the pixels! */
pBits=ppBits;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(pBits->rgbRed));
SetPixelGreen(q,ScaleCharToQuantum(pBits->rgbGreen));
SetPixelBlue(q,ScaleCharToQuantum(pBits->rgbBlue));
SetPixelOpacity(q,OpaqueOpacity);
pBits++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteObject(hBitmap);
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif /* MAGICKCORE_WINGDI32_DELEGATE */
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCLIPBOARDImage() adds attributes for the clipboard "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 RegisterCLIPBOARDImage method is:
%
% size_t RegisterCLIPBOARDImage(void)
%
*/
ModuleExport size_t RegisterCLIPBOARDImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CLIPBOARD");
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadCLIPBOARDImage;
entry->encoder=(EncodeImageHandler *) WriteCLIPBOARDImage;
#endif
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("The system clipboard");
entry->module=ConstantString("CLIPBOARD");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCLIPBOARDImage() removes format registrations made by the
% RGB module from the list of supported formats.
%
% The format of the UnregisterCLIPBOARDImage method is:
%
% UnregisterCLIPBOARDImage(void)
%
*/
ModuleExport void UnregisterCLIPBOARDImage(void)
{
(void) UnregisterMagickInfo("CLIPBOARD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e C L I P B O A R D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteCLIPBOARDImage() writes an image to the system clipboard.
%
% The format of the WriteCLIPBOARDImage method is:
%
% MagickBooleanType WriteCLIPBOARDImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
static MagickBooleanType WriteCLIPBOARDImage(const ImageInfo *image_info,
Image *image)
{
/*
Allocate memory for pixels.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
{
HBITMAP
bitmapH;
OpenClipboard(NULL);
EmptyClipboard();
bitmapH=(HBITMAP) ImageToHBITMAP(image,&image->exception);
SetClipboardData(CF_BITMAP,bitmapH);
CloseClipboard();
}
return(MagickTrue);
}
#endif /* MAGICKCORE_WINGDI32_DELEGATE */
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_7 |
crossvul-cpp_data_good_3464_0 | /**
* ldm - Support for Windows Logical Disk Manager (Dynamic Disks)
*
* Copyright (C) 2001,2002 Richard Russon <ldm@flatcap.org>
* Copyright (c) 2001-2007 Anton Altaparmakov
* Copyright (C) 2001,2002 Jakob Kemi <jakob.kemi@telia.com>
*
* Documentation is available at http://www.linux-ntfs.org/doku.php?id=downloads
*
* 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 (in the main directory of the source in the file COPYING); if
* not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/stringify.h>
#include <linux/kernel.h>
#include "ldm.h"
#include "check.h"
#include "msdos.h"
/**
* ldm_debug/info/error/crit - Output an error message
* @f: A printf format string containing the message
* @...: Variables to substitute into @f
*
* ldm_debug() writes a DEBUG level message to the syslog but only if the
* driver was compiled with debug enabled. Otherwise, the call turns into a NOP.
*/
#ifndef CONFIG_LDM_DEBUG
#define ldm_debug(...) do {} while (0)
#else
#define ldm_debug(f, a...) _ldm_printk (KERN_DEBUG, __func__, f, ##a)
#endif
#define ldm_crit(f, a...) _ldm_printk (KERN_CRIT, __func__, f, ##a)
#define ldm_error(f, a...) _ldm_printk (KERN_ERR, __func__, f, ##a)
#define ldm_info(f, a...) _ldm_printk (KERN_INFO, __func__, f, ##a)
__attribute__ ((format (printf, 3, 4)))
static void _ldm_printk (const char *level, const char *function,
const char *fmt, ...)
{
static char buf[128];
va_list args;
va_start (args, fmt);
vsnprintf (buf, sizeof (buf), fmt, args);
va_end (args);
printk ("%s%s(): %s\n", level, function, buf);
}
/**
* ldm_parse_hexbyte - Convert a ASCII hex number to a byte
* @src: Pointer to at least 2 characters to convert.
*
* Convert a two character ASCII hex string to a number.
*
* Return: 0-255 Success, the byte was parsed correctly
* -1 Error, an invalid character was supplied
*/
static int ldm_parse_hexbyte (const u8 *src)
{
unsigned int x; /* For correct wrapping */
int h;
/* high part */
x = h = hex_to_bin(src[0]);
if (h < 0)
return -1;
/* low part */
h = hex_to_bin(src[1]);
if (h < 0)
return -1;
return (x << 4) + h;
}
/**
* ldm_parse_guid - Convert GUID from ASCII to binary
* @src: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
* @dest: Memory block to hold binary GUID (16 bytes)
*
* N.B. The GUID need not be NULL terminated.
*
* Return: 'true' @dest contains binary GUID
* 'false' @dest contents are undefined
*/
static bool ldm_parse_guid (const u8 *src, u8 *dest)
{
static const int size[] = { 4, 2, 2, 2, 6 };
int i, j, v;
if (src[8] != '-' || src[13] != '-' ||
src[18] != '-' || src[23] != '-')
return false;
for (j = 0; j < 5; j++, src++)
for (i = 0; i < size[j]; i++, src+=2, *dest++ = v)
if ((v = ldm_parse_hexbyte (src)) < 0)
return false;
return true;
}
/**
* ldm_parse_privhead - Read the LDM Database PRIVHEAD structure
* @data: Raw database PRIVHEAD structure loaded from the device
* @ph: In-memory privhead structure in which to return parsed information
*
* This parses the LDM database PRIVHEAD structure supplied in @data and
* sets up the in-memory privhead structure @ph with the obtained information.
*
* Return: 'true' @ph contains the PRIVHEAD data
* 'false' @ph contents are undefined
*/
static bool ldm_parse_privhead(const u8 *data, struct privhead *ph)
{
bool is_vista = false;
BUG_ON(!data || !ph);
if (MAGIC_PRIVHEAD != get_unaligned_be64(data)) {
ldm_error("Cannot find PRIVHEAD structure. LDM database is"
" corrupt. Aborting.");
return false;
}
ph->ver_major = get_unaligned_be16(data + 0x000C);
ph->ver_minor = get_unaligned_be16(data + 0x000E);
ph->logical_disk_start = get_unaligned_be64(data + 0x011B);
ph->logical_disk_size = get_unaligned_be64(data + 0x0123);
ph->config_start = get_unaligned_be64(data + 0x012B);
ph->config_size = get_unaligned_be64(data + 0x0133);
/* Version 2.11 is Win2k/XP and version 2.12 is Vista. */
if (ph->ver_major == 2 && ph->ver_minor == 12)
is_vista = true;
if (!is_vista && (ph->ver_major != 2 || ph->ver_minor != 11)) {
ldm_error("Expected PRIVHEAD version 2.11 or 2.12, got %d.%d."
" Aborting.", ph->ver_major, ph->ver_minor);
return false;
}
ldm_debug("PRIVHEAD version %d.%d (Windows %s).", ph->ver_major,
ph->ver_minor, is_vista ? "Vista" : "2000/XP");
if (ph->config_size != LDM_DB_SIZE) { /* 1 MiB in sectors. */
/* Warn the user and continue, carefully. */
ldm_info("Database is normally %u bytes, it claims to "
"be %llu bytes.", LDM_DB_SIZE,
(unsigned long long)ph->config_size);
}
if ((ph->logical_disk_size == 0) || (ph->logical_disk_start +
ph->logical_disk_size > ph->config_start)) {
ldm_error("PRIVHEAD disk size doesn't match real disk size");
return false;
}
if (!ldm_parse_guid(data + 0x0030, ph->disk_id)) {
ldm_error("PRIVHEAD contains an invalid GUID.");
return false;
}
ldm_debug("Parsed PRIVHEAD successfully.");
return true;
}
/**
* ldm_parse_tocblock - Read the LDM Database TOCBLOCK structure
* @data: Raw database TOCBLOCK structure loaded from the device
* @toc: In-memory toc structure in which to return parsed information
*
* This parses the LDM Database TOCBLOCK (table of contents) structure supplied
* in @data and sets up the in-memory tocblock structure @toc with the obtained
* information.
*
* N.B. The *_start and *_size values returned in @toc are not range-checked.
*
* Return: 'true' @toc contains the TOCBLOCK data
* 'false' @toc contents are undefined
*/
static bool ldm_parse_tocblock (const u8 *data, struct tocblock *toc)
{
BUG_ON (!data || !toc);
if (MAGIC_TOCBLOCK != get_unaligned_be64(data)) {
ldm_crit ("Cannot find TOCBLOCK, database may be corrupt.");
return false;
}
strncpy (toc->bitmap1_name, data + 0x24, sizeof (toc->bitmap1_name));
toc->bitmap1_name[sizeof (toc->bitmap1_name) - 1] = 0;
toc->bitmap1_start = get_unaligned_be64(data + 0x2E);
toc->bitmap1_size = get_unaligned_be64(data + 0x36);
if (strncmp (toc->bitmap1_name, TOC_BITMAP1,
sizeof (toc->bitmap1_name)) != 0) {
ldm_crit ("TOCBLOCK's first bitmap is '%s', should be '%s'.",
TOC_BITMAP1, toc->bitmap1_name);
return false;
}
strncpy (toc->bitmap2_name, data + 0x46, sizeof (toc->bitmap2_name));
toc->bitmap2_name[sizeof (toc->bitmap2_name) - 1] = 0;
toc->bitmap2_start = get_unaligned_be64(data + 0x50);
toc->bitmap2_size = get_unaligned_be64(data + 0x58);
if (strncmp (toc->bitmap2_name, TOC_BITMAP2,
sizeof (toc->bitmap2_name)) != 0) {
ldm_crit ("TOCBLOCK's second bitmap is '%s', should be '%s'.",
TOC_BITMAP2, toc->bitmap2_name);
return false;
}
ldm_debug ("Parsed TOCBLOCK successfully.");
return true;
}
/**
* ldm_parse_vmdb - Read the LDM Database VMDB structure
* @data: Raw database VMDB structure loaded from the device
* @vm: In-memory vmdb structure in which to return parsed information
*
* This parses the LDM Database VMDB structure supplied in @data and sets up
* the in-memory vmdb structure @vm with the obtained information.
*
* N.B. The *_start, *_size and *_seq values will be range-checked later.
*
* Return: 'true' @vm contains VMDB info
* 'false' @vm contents are undefined
*/
static bool ldm_parse_vmdb (const u8 *data, struct vmdb *vm)
{
BUG_ON (!data || !vm);
if (MAGIC_VMDB != get_unaligned_be32(data)) {
ldm_crit ("Cannot find the VMDB, database may be corrupt.");
return false;
}
vm->ver_major = get_unaligned_be16(data + 0x12);
vm->ver_minor = get_unaligned_be16(data + 0x14);
if ((vm->ver_major != 4) || (vm->ver_minor != 10)) {
ldm_error ("Expected VMDB version %d.%d, got %d.%d. "
"Aborting.", 4, 10, vm->ver_major, vm->ver_minor);
return false;
}
vm->vblk_size = get_unaligned_be32(data + 0x08);
if (vm->vblk_size == 0) {
ldm_error ("Illegal VBLK size");
return false;
}
vm->vblk_offset = get_unaligned_be32(data + 0x0C);
vm->last_vblk_seq = get_unaligned_be32(data + 0x04);
ldm_debug ("Parsed VMDB successfully.");
return true;
}
/**
* ldm_compare_privheads - Compare two privhead objects
* @ph1: First privhead
* @ph2: Second privhead
*
* This compares the two privhead structures @ph1 and @ph2.
*
* Return: 'true' Identical
* 'false' Different
*/
static bool ldm_compare_privheads (const struct privhead *ph1,
const struct privhead *ph2)
{
BUG_ON (!ph1 || !ph2);
return ((ph1->ver_major == ph2->ver_major) &&
(ph1->ver_minor == ph2->ver_minor) &&
(ph1->logical_disk_start == ph2->logical_disk_start) &&
(ph1->logical_disk_size == ph2->logical_disk_size) &&
(ph1->config_start == ph2->config_start) &&
(ph1->config_size == ph2->config_size) &&
!memcmp (ph1->disk_id, ph2->disk_id, GUID_SIZE));
}
/**
* ldm_compare_tocblocks - Compare two tocblock objects
* @toc1: First toc
* @toc2: Second toc
*
* This compares the two tocblock structures @toc1 and @toc2.
*
* Return: 'true' Identical
* 'false' Different
*/
static bool ldm_compare_tocblocks (const struct tocblock *toc1,
const struct tocblock *toc2)
{
BUG_ON (!toc1 || !toc2);
return ((toc1->bitmap1_start == toc2->bitmap1_start) &&
(toc1->bitmap1_size == toc2->bitmap1_size) &&
(toc1->bitmap2_start == toc2->bitmap2_start) &&
(toc1->bitmap2_size == toc2->bitmap2_size) &&
!strncmp (toc1->bitmap1_name, toc2->bitmap1_name,
sizeof (toc1->bitmap1_name)) &&
!strncmp (toc1->bitmap2_name, toc2->bitmap2_name,
sizeof (toc1->bitmap2_name)));
}
/**
* ldm_validate_privheads - Compare the primary privhead with its backups
* @state: Partition check state including device holding the LDM Database
* @ph1: Memory struct to fill with ph contents
*
* Read and compare all three privheads from disk.
*
* The privheads on disk show the size and location of the main disk area and
* the configuration area (the database). The values are range-checked against
* @hd, which contains the real size of the disk.
*
* Return: 'true' Success
* 'false' Error
*/
static bool ldm_validate_privheads(struct parsed_partitions *state,
struct privhead *ph1)
{
static const int off[3] = { OFF_PRIV1, OFF_PRIV2, OFF_PRIV3 };
struct privhead *ph[3] = { ph1 };
Sector sect;
u8 *data;
bool result = false;
long num_sects;
int i;
BUG_ON (!state || !ph1);
ph[1] = kmalloc (sizeof (*ph[1]), GFP_KERNEL);
ph[2] = kmalloc (sizeof (*ph[2]), GFP_KERNEL);
if (!ph[1] || !ph[2]) {
ldm_crit ("Out of memory.");
goto out;
}
/* off[1 & 2] are relative to ph[0]->config_start */
ph[0]->config_start = 0;
/* Read and parse privheads */
for (i = 0; i < 3; i++) {
data = read_part_sector(state, ph[0]->config_start + off[i],
§);
if (!data) {
ldm_crit ("Disk read failed.");
goto out;
}
result = ldm_parse_privhead (data, ph[i]);
put_dev_sector (sect);
if (!result) {
ldm_error ("Cannot find PRIVHEAD %d.", i+1); /* Log again */
if (i < 2)
goto out; /* Already logged */
else
break; /* FIXME ignore for now, 3rd PH can fail on odd-sized disks */
}
}
num_sects = state->bdev->bd_inode->i_size >> 9;
if ((ph[0]->config_start > num_sects) ||
((ph[0]->config_start + ph[0]->config_size) > num_sects)) {
ldm_crit ("Database extends beyond the end of the disk.");
goto out;
}
if ((ph[0]->logical_disk_start > ph[0]->config_start) ||
((ph[0]->logical_disk_start + ph[0]->logical_disk_size)
> ph[0]->config_start)) {
ldm_crit ("Disk and database overlap.");
goto out;
}
if (!ldm_compare_privheads (ph[0], ph[1])) {
ldm_crit ("Primary and backup PRIVHEADs don't match.");
goto out;
}
/* FIXME ignore this for now
if (!ldm_compare_privheads (ph[0], ph[2])) {
ldm_crit ("Primary and backup PRIVHEADs don't match.");
goto out;
}*/
ldm_debug ("Validated PRIVHEADs successfully.");
result = true;
out:
kfree (ph[1]);
kfree (ph[2]);
return result;
}
/**
* ldm_validate_tocblocks - Validate the table of contents and its backups
* @state: Partition check state including device holding the LDM Database
* @base: Offset, into @state->bdev, of the database
* @ldb: Cache of the database structures
*
* Find and compare the four tables of contents of the LDM Database stored on
* @state->bdev and return the parsed information into @toc1.
*
* The offsets and sizes of the configs are range-checked against a privhead.
*
* Return: 'true' @toc1 contains validated TOCBLOCK info
* 'false' @toc1 contents are undefined
*/
static bool ldm_validate_tocblocks(struct parsed_partitions *state,
unsigned long base, struct ldmdb *ldb)
{
static const int off[4] = { OFF_TOCB1, OFF_TOCB2, OFF_TOCB3, OFF_TOCB4};
struct tocblock *tb[4];
struct privhead *ph;
Sector sect;
u8 *data;
int i, nr_tbs;
bool result = false;
BUG_ON(!state || !ldb);
ph = &ldb->ph;
tb[0] = &ldb->toc;
tb[1] = kmalloc(sizeof(*tb[1]) * 3, GFP_KERNEL);
if (!tb[1]) {
ldm_crit("Out of memory.");
goto err;
}
tb[2] = (struct tocblock*)((u8*)tb[1] + sizeof(*tb[1]));
tb[3] = (struct tocblock*)((u8*)tb[2] + sizeof(*tb[2]));
/*
* Try to read and parse all four TOCBLOCKs.
*
* Windows Vista LDM v2.12 does not always have all four TOCBLOCKs so
* skip any that fail as long as we get at least one valid TOCBLOCK.
*/
for (nr_tbs = i = 0; i < 4; i++) {
data = read_part_sector(state, base + off[i], §);
if (!data) {
ldm_error("Disk read failed for TOCBLOCK %d.", i);
continue;
}
if (ldm_parse_tocblock(data, tb[nr_tbs]))
nr_tbs++;
put_dev_sector(sect);
}
if (!nr_tbs) {
ldm_crit("Failed to find a valid TOCBLOCK.");
goto err;
}
/* Range check the TOCBLOCK against a privhead. */
if (((tb[0]->bitmap1_start + tb[0]->bitmap1_size) > ph->config_size) ||
((tb[0]->bitmap2_start + tb[0]->bitmap2_size) >
ph->config_size)) {
ldm_crit("The bitmaps are out of range. Giving up.");
goto err;
}
/* Compare all loaded TOCBLOCKs. */
for (i = 1; i < nr_tbs; i++) {
if (!ldm_compare_tocblocks(tb[0], tb[i])) {
ldm_crit("TOCBLOCKs 0 and %d do not match.", i);
goto err;
}
}
ldm_debug("Validated %d TOCBLOCKs successfully.", nr_tbs);
result = true;
err:
kfree(tb[1]);
return result;
}
/**
* ldm_validate_vmdb - Read the VMDB and validate it
* @state: Partition check state including device holding the LDM Database
* @base: Offset, into @bdev, of the database
* @ldb: Cache of the database structures
*
* Find the vmdb of the LDM Database stored on @bdev and return the parsed
* information in @ldb.
*
* Return: 'true' @ldb contains validated VBDB info
* 'false' @ldb contents are undefined
*/
static bool ldm_validate_vmdb(struct parsed_partitions *state,
unsigned long base, struct ldmdb *ldb)
{
Sector sect;
u8 *data;
bool result = false;
struct vmdb *vm;
struct tocblock *toc;
BUG_ON (!state || !ldb);
vm = &ldb->vm;
toc = &ldb->toc;
data = read_part_sector(state, base + OFF_VMDB, §);
if (!data) {
ldm_crit ("Disk read failed.");
return false;
}
if (!ldm_parse_vmdb (data, vm))
goto out; /* Already logged */
/* Are there uncommitted transactions? */
if (get_unaligned_be16(data + 0x10) != 0x01) {
ldm_crit ("Database is not in a consistent state. Aborting.");
goto out;
}
if (vm->vblk_offset != 512)
ldm_info ("VBLKs start at offset 0x%04x.", vm->vblk_offset);
/*
* The last_vblkd_seq can be before the end of the vmdb, just make sure
* it is not out of bounds.
*/
if ((vm->vblk_size * vm->last_vblk_seq) > (toc->bitmap1_size << 9)) {
ldm_crit ("VMDB exceeds allowed size specified by TOCBLOCK. "
"Database is corrupt. Aborting.");
goto out;
}
result = true;
out:
put_dev_sector (sect);
return result;
}
/**
* ldm_validate_partition_table - Determine whether bdev might be a dynamic disk
* @state: Partition check state including device holding the LDM Database
*
* This function provides a weak test to decide whether the device is a dynamic
* disk or not. It looks for an MS-DOS-style partition table containing at
* least one partition of type 0x42 (formerly SFS, now used by Windows for
* dynamic disks).
*
* N.B. The only possible error can come from the read_part_sector and that is
* only likely to happen if the underlying device is strange. If that IS
* the case we should return zero to let someone else try.
*
* Return: 'true' @state->bdev is a dynamic disk
* 'false' @state->bdev is not a dynamic disk, or an error occurred
*/
static bool ldm_validate_partition_table(struct parsed_partitions *state)
{
Sector sect;
u8 *data;
struct partition *p;
int i;
bool result = false;
BUG_ON(!state);
data = read_part_sector(state, 0, §);
if (!data) {
ldm_crit ("Disk read failed.");
return false;
}
if (*(__le16*) (data + 0x01FE) != cpu_to_le16 (MSDOS_LABEL_MAGIC))
goto out;
p = (struct partition*)(data + 0x01BE);
for (i = 0; i < 4; i++, p++)
if (SYS_IND (p) == LDM_PARTITION) {
result = true;
break;
}
if (result)
ldm_debug ("Found W2K dynamic disk partition type.");
out:
put_dev_sector (sect);
return result;
}
/**
* ldm_get_disk_objid - Search a linked list of vblk's for a given Disk Id
* @ldb: Cache of the database structures
*
* The LDM Database contains a list of all partitions on all dynamic disks.
* The primary PRIVHEAD, at the beginning of the physical disk, tells us
* the GUID of this disk. This function searches for the GUID in a linked
* list of vblk's.
*
* Return: Pointer, A matching vblk was found
* NULL, No match, or an error
*/
static struct vblk * ldm_get_disk_objid (const struct ldmdb *ldb)
{
struct list_head *item;
BUG_ON (!ldb);
list_for_each (item, &ldb->v_disk) {
struct vblk *v = list_entry (item, struct vblk, list);
if (!memcmp (v->vblk.disk.disk_id, ldb->ph.disk_id, GUID_SIZE))
return v;
}
return NULL;
}
/**
* ldm_create_data_partitions - Create data partitions for this device
* @pp: List of the partitions parsed so far
* @ldb: Cache of the database structures
*
* The database contains ALL the partitions for ALL disk groups, so we need to
* filter out this specific disk. Using the disk's object id, we can find all
* the partitions in the database that belong to this disk.
*
* Add each partition in our database, to the parsed_partitions structure.
*
* N.B. This function creates the partitions in the order it finds partition
* objects in the linked list.
*
* Return: 'true' Partition created
* 'false' Error, probably a range checking problem
*/
static bool ldm_create_data_partitions (struct parsed_partitions *pp,
const struct ldmdb *ldb)
{
struct list_head *item;
struct vblk *vb;
struct vblk *disk;
struct vblk_part *part;
int part_num = 1;
BUG_ON (!pp || !ldb);
disk = ldm_get_disk_objid (ldb);
if (!disk) {
ldm_crit ("Can't find the ID of this disk in the database.");
return false;
}
strlcat(pp->pp_buf, " [LDM]", PAGE_SIZE);
/* Create the data partitions */
list_for_each (item, &ldb->v_part) {
vb = list_entry (item, struct vblk, list);
part = &vb->vblk.part;
if (part->disk_id != disk->obj_id)
continue;
put_partition (pp, part_num, ldb->ph.logical_disk_start +
part->start, part->size);
part_num++;
}
strlcat(pp->pp_buf, "\n", PAGE_SIZE);
return true;
}
/**
* ldm_relative - Calculate the next relative offset
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @base: Size of the previous fixed width fields
* @offset: Cumulative size of the previous variable-width fields
*
* Because many of the VBLK fields are variable-width, it's necessary
* to calculate each offset based on the previous one and the length
* of the field it pointed to.
*
* Return: -1 Error, the calculated offset exceeded the size of the buffer
* n OK, a range-checked offset into buffer
*/
static int ldm_relative(const u8 *buffer, int buflen, int base, int offset)
{
base += offset;
if (!buffer || offset < 0 || base > buflen) {
if (!buffer)
ldm_error("!buffer");
if (offset < 0)
ldm_error("offset (%d) < 0", offset);
if (base > buflen)
ldm_error("base (%d) > buflen (%d)", base, buflen);
return -1;
}
if (base + buffer[base] >= buflen) {
ldm_error("base (%d) + buffer[base] (%d) >= buflen (%d)", base,
buffer[base], buflen);
return -1;
}
return buffer[base] + offset + 1;
}
/**
* ldm_get_vnum - Convert a variable-width, big endian number, into cpu order
* @block: Pointer to the variable-width number to convert
*
* Large numbers in the LDM Database are often stored in a packed format. Each
* number is prefixed by a one byte width marker. All numbers in the database
* are stored in big-endian byte order. This function reads one of these
* numbers and returns the result
*
* N.B. This function DOES NOT perform any range checking, though the most
* it will read is eight bytes.
*
* Return: n A number
* 0 Zero, or an error occurred
*/
static u64 ldm_get_vnum (const u8 *block)
{
u64 tmp = 0;
u8 length;
BUG_ON (!block);
length = *block++;
if (length && length <= 8)
while (length--)
tmp = (tmp << 8) | *block++;
else
ldm_error ("Illegal length %d.", length);
return tmp;
}
/**
* ldm_get_vstr - Read a length-prefixed string into a buffer
* @block: Pointer to the length marker
* @buffer: Location to copy string to
* @buflen: Size of the output buffer
*
* Many of the strings in the LDM Database are not NULL terminated. Instead
* they are prefixed by a one byte length marker. This function copies one of
* these strings into a buffer.
*
* N.B. This function DOES NOT perform any range checking on the input.
* If the buffer is too small, the output will be truncated.
*
* Return: 0, Error and @buffer contents are undefined
* n, String length in characters (excluding NULL)
* buflen-1, String was truncated.
*/
static int ldm_get_vstr (const u8 *block, u8 *buffer, int buflen)
{
int length;
BUG_ON (!block || !buffer);
length = block[0];
if (length >= buflen) {
ldm_error ("Truncating string %d -> %d.", length, buflen);
length = buflen - 1;
}
memcpy (buffer, block + 1, length);
buffer[length] = 0;
return length;
}
/**
* ldm_parse_cmp3 - Read a raw VBLK Component object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Component object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Component VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_cmp3 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_vstate, r_child, r_parent, r_stripe, r_cols, len;
struct vblk_comp *comp;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
r_vstate = ldm_relative (buffer, buflen, 0x18, r_name);
r_child = ldm_relative (buffer, buflen, 0x1D, r_vstate);
r_parent = ldm_relative (buffer, buflen, 0x2D, r_child);
if (buffer[0x12] & VBLK_FLAG_COMP_STRIPE) {
r_stripe = ldm_relative (buffer, buflen, 0x2E, r_parent);
r_cols = ldm_relative (buffer, buflen, 0x2E, r_stripe);
len = r_cols;
} else {
r_stripe = 0;
r_cols = 0;
len = r_parent;
}
if (len < 0)
return false;
len += VBLK_SIZE_CMP3;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
comp = &vb->vblk.comp;
ldm_get_vstr (buffer + 0x18 + r_name, comp->state,
sizeof (comp->state));
comp->type = buffer[0x18 + r_vstate];
comp->children = ldm_get_vnum (buffer + 0x1D + r_vstate);
comp->parent_id = ldm_get_vnum (buffer + 0x2D + r_child);
comp->chunksize = r_stripe ? ldm_get_vnum (buffer+r_parent+0x2E) : 0;
return true;
}
/**
* ldm_parse_dgr3 - Read a raw VBLK Disk Group object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk Group object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Disk Group VBLK
* 'false' @vb contents are not defined
*/
static int ldm_parse_dgr3 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_diskid, r_id1, r_id2, len;
struct vblk_dgrp *dgrp;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
r_diskid = ldm_relative (buffer, buflen, 0x18, r_name);
if (buffer[0x12] & VBLK_FLAG_DGR3_IDS) {
r_id1 = ldm_relative (buffer, buflen, 0x24, r_diskid);
r_id2 = ldm_relative (buffer, buflen, 0x24, r_id1);
len = r_id2;
} else {
r_id1 = 0;
r_id2 = 0;
len = r_diskid;
}
if (len < 0)
return false;
len += VBLK_SIZE_DGR3;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
dgrp = &vb->vblk.dgrp;
ldm_get_vstr (buffer + 0x18 + r_name, dgrp->disk_id,
sizeof (dgrp->disk_id));
return true;
}
/**
* ldm_parse_dgr4 - Read a raw VBLK Disk Group object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk Group object (version 4) into a vblk structure.
*
* Return: 'true' @vb contains a Disk Group VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_dgr4 (const u8 *buffer, int buflen, struct vblk *vb)
{
char buf[64];
int r_objid, r_name, r_id1, r_id2, len;
struct vblk_dgrp *dgrp;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
if (buffer[0x12] & VBLK_FLAG_DGR4_IDS) {
r_id1 = ldm_relative (buffer, buflen, 0x44, r_name);
r_id2 = ldm_relative (buffer, buflen, 0x44, r_id1);
len = r_id2;
} else {
r_id1 = 0;
r_id2 = 0;
len = r_name;
}
if (len < 0)
return false;
len += VBLK_SIZE_DGR4;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
dgrp = &vb->vblk.dgrp;
ldm_get_vstr (buffer + 0x18 + r_objid, buf, sizeof (buf));
return true;
}
/**
* ldm_parse_dsk3 - Read a raw VBLK Disk object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Disk VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_dsk3 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_diskid, r_altname, len;
struct vblk_disk *disk;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
r_diskid = ldm_relative (buffer, buflen, 0x18, r_name);
r_altname = ldm_relative (buffer, buflen, 0x18, r_diskid);
len = r_altname;
if (len < 0)
return false;
len += VBLK_SIZE_DSK3;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
disk = &vb->vblk.disk;
ldm_get_vstr (buffer + 0x18 + r_diskid, disk->alt_name,
sizeof (disk->alt_name));
if (!ldm_parse_guid (buffer + 0x19 + r_name, disk->disk_id))
return false;
return true;
}
/**
* ldm_parse_dsk4 - Read a raw VBLK Disk object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Disk object (version 4) into a vblk structure.
*
* Return: 'true' @vb contains a Disk VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_dsk4 (const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, len;
struct vblk_disk *disk;
BUG_ON (!buffer || !vb);
r_objid = ldm_relative (buffer, buflen, 0x18, 0);
r_name = ldm_relative (buffer, buflen, 0x18, r_objid);
len = r_name;
if (len < 0)
return false;
len += VBLK_SIZE_DSK4;
if (len != get_unaligned_be32(buffer + 0x14))
return false;
disk = &vb->vblk.disk;
memcpy (disk->disk_id, buffer + 0x18 + r_name, GUID_SIZE);
return true;
}
/**
* ldm_parse_prt3 - Read a raw VBLK Partition object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Partition object (version 3) into a vblk structure.
*
* Return: 'true' @vb contains a Partition VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_prt3(const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_size, r_parent, r_diskid, r_index, len;
struct vblk_part *part;
BUG_ON(!buffer || !vb);
r_objid = ldm_relative(buffer, buflen, 0x18, 0);
if (r_objid < 0) {
ldm_error("r_objid %d < 0", r_objid);
return false;
}
r_name = ldm_relative(buffer, buflen, 0x18, r_objid);
if (r_name < 0) {
ldm_error("r_name %d < 0", r_name);
return false;
}
r_size = ldm_relative(buffer, buflen, 0x34, r_name);
if (r_size < 0) {
ldm_error("r_size %d < 0", r_size);
return false;
}
r_parent = ldm_relative(buffer, buflen, 0x34, r_size);
if (r_parent < 0) {
ldm_error("r_parent %d < 0", r_parent);
return false;
}
r_diskid = ldm_relative(buffer, buflen, 0x34, r_parent);
if (r_diskid < 0) {
ldm_error("r_diskid %d < 0", r_diskid);
return false;
}
if (buffer[0x12] & VBLK_FLAG_PART_INDEX) {
r_index = ldm_relative(buffer, buflen, 0x34, r_diskid);
if (r_index < 0) {
ldm_error("r_index %d < 0", r_index);
return false;
}
len = r_index;
} else {
r_index = 0;
len = r_diskid;
}
if (len < 0) {
ldm_error("len %d < 0", len);
return false;
}
len += VBLK_SIZE_PRT3;
if (len > get_unaligned_be32(buffer + 0x14)) {
ldm_error("len %d > BE32(buffer + 0x14) %d", len,
get_unaligned_be32(buffer + 0x14));
return false;
}
part = &vb->vblk.part;
part->start = get_unaligned_be64(buffer + 0x24 + r_name);
part->volume_offset = get_unaligned_be64(buffer + 0x2C + r_name);
part->size = ldm_get_vnum(buffer + 0x34 + r_name);
part->parent_id = ldm_get_vnum(buffer + 0x34 + r_size);
part->disk_id = ldm_get_vnum(buffer + 0x34 + r_parent);
if (vb->flags & VBLK_FLAG_PART_INDEX)
part->partnum = buffer[0x35 + r_diskid];
else
part->partnum = 0;
return true;
}
/**
* ldm_parse_vol5 - Read a raw VBLK Volume object into a vblk structure
* @buffer: Block of data being worked on
* @buflen: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK Volume object (version 5) into a vblk structure.
*
* Return: 'true' @vb contains a Volume VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_vol5(const u8 *buffer, int buflen, struct vblk *vb)
{
int r_objid, r_name, r_vtype, r_disable_drive_letter, r_child, r_size;
int r_id1, r_id2, r_size2, r_drive, len;
struct vblk_volu *volu;
BUG_ON(!buffer || !vb);
r_objid = ldm_relative(buffer, buflen, 0x18, 0);
if (r_objid < 0) {
ldm_error("r_objid %d < 0", r_objid);
return false;
}
r_name = ldm_relative(buffer, buflen, 0x18, r_objid);
if (r_name < 0) {
ldm_error("r_name %d < 0", r_name);
return false;
}
r_vtype = ldm_relative(buffer, buflen, 0x18, r_name);
if (r_vtype < 0) {
ldm_error("r_vtype %d < 0", r_vtype);
return false;
}
r_disable_drive_letter = ldm_relative(buffer, buflen, 0x18, r_vtype);
if (r_disable_drive_letter < 0) {
ldm_error("r_disable_drive_letter %d < 0",
r_disable_drive_letter);
return false;
}
r_child = ldm_relative(buffer, buflen, 0x2D, r_disable_drive_letter);
if (r_child < 0) {
ldm_error("r_child %d < 0", r_child);
return false;
}
r_size = ldm_relative(buffer, buflen, 0x3D, r_child);
if (r_size < 0) {
ldm_error("r_size %d < 0", r_size);
return false;
}
if (buffer[0x12] & VBLK_FLAG_VOLU_ID1) {
r_id1 = ldm_relative(buffer, buflen, 0x52, r_size);
if (r_id1 < 0) {
ldm_error("r_id1 %d < 0", r_id1);
return false;
}
} else
r_id1 = r_size;
if (buffer[0x12] & VBLK_FLAG_VOLU_ID2) {
r_id2 = ldm_relative(buffer, buflen, 0x52, r_id1);
if (r_id2 < 0) {
ldm_error("r_id2 %d < 0", r_id2);
return false;
}
} else
r_id2 = r_id1;
if (buffer[0x12] & VBLK_FLAG_VOLU_SIZE) {
r_size2 = ldm_relative(buffer, buflen, 0x52, r_id2);
if (r_size2 < 0) {
ldm_error("r_size2 %d < 0", r_size2);
return false;
}
} else
r_size2 = r_id2;
if (buffer[0x12] & VBLK_FLAG_VOLU_DRIVE) {
r_drive = ldm_relative(buffer, buflen, 0x52, r_size2);
if (r_drive < 0) {
ldm_error("r_drive %d < 0", r_drive);
return false;
}
} else
r_drive = r_size2;
len = r_drive;
if (len < 0) {
ldm_error("len %d < 0", len);
return false;
}
len += VBLK_SIZE_VOL5;
if (len > get_unaligned_be32(buffer + 0x14)) {
ldm_error("len %d > BE32(buffer + 0x14) %d", len,
get_unaligned_be32(buffer + 0x14));
return false;
}
volu = &vb->vblk.volu;
ldm_get_vstr(buffer + 0x18 + r_name, volu->volume_type,
sizeof(volu->volume_type));
memcpy(volu->volume_state, buffer + 0x18 + r_disable_drive_letter,
sizeof(volu->volume_state));
volu->size = ldm_get_vnum(buffer + 0x3D + r_child);
volu->partition_type = buffer[0x41 + r_size];
memcpy(volu->guid, buffer + 0x42 + r_size, sizeof(volu->guid));
if (buffer[0x12] & VBLK_FLAG_VOLU_DRIVE) {
ldm_get_vstr(buffer + 0x52 + r_size, volu->drive_hint,
sizeof(volu->drive_hint));
}
return true;
}
/**
* ldm_parse_vblk - Read a raw VBLK object into a vblk structure
* @buf: Block of data being worked on
* @len: Size of the block of data
* @vb: In-memory vblk in which to return information
*
* Read a raw VBLK object into a vblk structure. This function just reads the
* information common to all VBLK types, then delegates the rest of the work to
* helper functions: ldm_parse_*.
*
* Return: 'true' @vb contains a VBLK
* 'false' @vb contents are not defined
*/
static bool ldm_parse_vblk (const u8 *buf, int len, struct vblk *vb)
{
bool result = false;
int r_objid;
BUG_ON (!buf || !vb);
r_objid = ldm_relative (buf, len, 0x18, 0);
if (r_objid < 0) {
ldm_error ("VBLK header is corrupt.");
return false;
}
vb->flags = buf[0x12];
vb->type = buf[0x13];
vb->obj_id = ldm_get_vnum (buf + 0x18);
ldm_get_vstr (buf+0x18+r_objid, vb->name, sizeof (vb->name));
switch (vb->type) {
case VBLK_CMP3: result = ldm_parse_cmp3 (buf, len, vb); break;
case VBLK_DSK3: result = ldm_parse_dsk3 (buf, len, vb); break;
case VBLK_DSK4: result = ldm_parse_dsk4 (buf, len, vb); break;
case VBLK_DGR3: result = ldm_parse_dgr3 (buf, len, vb); break;
case VBLK_DGR4: result = ldm_parse_dgr4 (buf, len, vb); break;
case VBLK_PRT3: result = ldm_parse_prt3 (buf, len, vb); break;
case VBLK_VOL5: result = ldm_parse_vol5 (buf, len, vb); break;
}
if (result)
ldm_debug ("Parsed VBLK 0x%llx (type: 0x%02x) ok.",
(unsigned long long) vb->obj_id, vb->type);
else
ldm_error ("Failed to parse VBLK 0x%llx (type: 0x%02x).",
(unsigned long long) vb->obj_id, vb->type);
return result;
}
/**
* ldm_ldmdb_add - Adds a raw VBLK entry to the ldmdb database
* @data: Raw VBLK to add to the database
* @len: Size of the raw VBLK
* @ldb: Cache of the database structures
*
* The VBLKs are sorted into categories. Partitions are also sorted by offset.
*
* N.B. This function does not check the validity of the VBLKs.
*
* Return: 'true' The VBLK was added
* 'false' An error occurred
*/
static bool ldm_ldmdb_add (u8 *data, int len, struct ldmdb *ldb)
{
struct vblk *vb;
struct list_head *item;
BUG_ON (!data || !ldb);
vb = kmalloc (sizeof (*vb), GFP_KERNEL);
if (!vb) {
ldm_crit ("Out of memory.");
return false;
}
if (!ldm_parse_vblk (data, len, vb)) {
kfree(vb);
return false; /* Already logged */
}
/* Put vblk into the correct list. */
switch (vb->type) {
case VBLK_DGR3:
case VBLK_DGR4:
list_add (&vb->list, &ldb->v_dgrp);
break;
case VBLK_DSK3:
case VBLK_DSK4:
list_add (&vb->list, &ldb->v_disk);
break;
case VBLK_VOL5:
list_add (&vb->list, &ldb->v_volu);
break;
case VBLK_CMP3:
list_add (&vb->list, &ldb->v_comp);
break;
case VBLK_PRT3:
/* Sort by the partition's start sector. */
list_for_each (item, &ldb->v_part) {
struct vblk *v = list_entry (item, struct vblk, list);
if ((v->vblk.part.disk_id == vb->vblk.part.disk_id) &&
(v->vblk.part.start > vb->vblk.part.start)) {
list_add_tail (&vb->list, &v->list);
return true;
}
}
list_add_tail (&vb->list, &ldb->v_part);
break;
}
return true;
}
/**
* ldm_frag_add - Add a VBLK fragment to a list
* @data: Raw fragment to be added to the list
* @size: Size of the raw fragment
* @frags: Linked list of VBLK fragments
*
* Fragmented VBLKs may not be consecutive in the database, so they are placed
* in a list so they can be pieced together later.
*
* Return: 'true' Success, the VBLK was added to the list
* 'false' Error, a problem occurred
*/
static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags)
{
struct frag *f;
struct list_head *item;
int rec, num, group;
BUG_ON (!data || !frags);
if (size < 2 * VBLK_SIZE_HEAD) {
ldm_error("Value of size is to small.");
return false;
}
group = get_unaligned_be32(data + 0x08);
rec = get_unaligned_be16(data + 0x0C);
num = get_unaligned_be16(data + 0x0E);
if ((num < 1) || (num > 4)) {
ldm_error ("A VBLK claims to have %d parts.", num);
return false;
}
if (rec >= num) {
ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num);
return false;
}
list_for_each (item, frags) {
f = list_entry (item, struct frag, list);
if (f->group == group)
goto found;
}
f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL);
if (!f) {
ldm_crit ("Out of memory.");
return false;
}
f->group = group;
f->num = num;
f->rec = rec;
f->map = 0xFF << num;
list_add_tail (&f->list, frags);
found:
if (rec >= f->num) {
ldm_error("REC value (%d) exceeds NUM value (%d)", rec, f->num);
return false;
}
if (f->map & (1 << rec)) {
ldm_error ("Duplicate VBLK, part %d.", rec);
f->map &= 0x7F; /* Mark the group as broken */
return false;
}
f->map |= (1 << rec);
data += VBLK_SIZE_HEAD;
size -= VBLK_SIZE_HEAD;
memcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size);
return true;
}
/**
* ldm_frag_free - Free a linked list of VBLK fragments
* @list: Linked list of fragments
*
* Free a linked list of VBLK fragments
*
* Return: none
*/
static void ldm_frag_free (struct list_head *list)
{
struct list_head *item, *tmp;
BUG_ON (!list);
list_for_each_safe (item, tmp, list)
kfree (list_entry (item, struct frag, list));
}
/**
* ldm_frag_commit - Validate fragmented VBLKs and add them to the database
* @frags: Linked list of VBLK fragments
* @ldb: Cache of the database structures
*
* Now that all the fragmented VBLKs have been collected, they must be added to
* the database for later use.
*
* Return: 'true' All the fragments we added successfully
* 'false' One or more of the fragments we invalid
*/
static bool ldm_frag_commit (struct list_head *frags, struct ldmdb *ldb)
{
struct frag *f;
struct list_head *item;
BUG_ON (!frags || !ldb);
list_for_each (item, frags) {
f = list_entry (item, struct frag, list);
if (f->map != 0xFF) {
ldm_error ("VBLK group %d is incomplete (0x%02x).",
f->group, f->map);
return false;
}
if (!ldm_ldmdb_add (f->data, f->num*ldb->vm.vblk_size, ldb))
return false; /* Already logged */
}
return true;
}
/**
* ldm_get_vblks - Read the on-disk database of VBLKs into memory
* @state: Partition check state including device holding the LDM Database
* @base: Offset, into @state->bdev, of the database
* @ldb: Cache of the database structures
*
* To use the information from the VBLKs, they need to be read from the disk,
* unpacked and validated. We cache them in @ldb according to their type.
*
* Return: 'true' All the VBLKs were read successfully
* 'false' An error occurred
*/
static bool ldm_get_vblks(struct parsed_partitions *state, unsigned long base,
struct ldmdb *ldb)
{
int size, perbuf, skip, finish, s, v, recs;
u8 *data = NULL;
Sector sect;
bool result = false;
LIST_HEAD (frags);
BUG_ON(!state || !ldb);
size = ldb->vm.vblk_size;
perbuf = 512 / size;
skip = ldb->vm.vblk_offset >> 9; /* Bytes to sectors */
finish = (size * ldb->vm.last_vblk_seq) >> 9;
for (s = skip; s < finish; s++) { /* For each sector */
data = read_part_sector(state, base + OFF_VMDB + s, §);
if (!data) {
ldm_crit ("Disk read failed.");
goto out;
}
for (v = 0; v < perbuf; v++, data+=size) { /* For each vblk */
if (MAGIC_VBLK != get_unaligned_be32(data)) {
ldm_error ("Expected to find a VBLK.");
goto out;
}
recs = get_unaligned_be16(data + 0x0E); /* Number of records */
if (recs == 1) {
if (!ldm_ldmdb_add (data, size, ldb))
goto out; /* Already logged */
} else if (recs > 1) {
if (!ldm_frag_add (data, size, &frags))
goto out; /* Already logged */
}
/* else Record is not in use, ignore it. */
}
put_dev_sector (sect);
data = NULL;
}
result = ldm_frag_commit (&frags, ldb); /* Failures, already logged */
out:
if (data)
put_dev_sector (sect);
ldm_frag_free (&frags);
return result;
}
/**
* ldm_free_vblks - Free a linked list of vblk's
* @lh: Head of a linked list of struct vblk
*
* Free a list of vblk's and free the memory used to maintain the list.
*
* Return: none
*/
static void ldm_free_vblks (struct list_head *lh)
{
struct list_head *item, *tmp;
BUG_ON (!lh);
list_for_each_safe (item, tmp, lh)
kfree (list_entry (item, struct vblk, list));
}
/**
* ldm_partition - Find out whether a device is a dynamic disk and handle it
* @state: Partition check state including device holding the LDM Database
*
* This determines whether the device @bdev is a dynamic disk and if so creates
* the partitions necessary in the gendisk structure pointed to by @hd.
*
* We create a dummy device 1, which contains the LDM database, and then create
* each partition described by the LDM database in sequence as devices 2+. For
* example, if the device is hda, we would have: hda1: LDM database, hda2, hda3,
* and so on: the actual data containing partitions.
*
* Return: 1 Success, @state->bdev is a dynamic disk and we handled it
* 0 Success, @state->bdev is not a dynamic disk
* -1 An error occurred before enough information had been read
* Or @state->bdev is a dynamic disk, but it may be corrupted
*/
int ldm_partition(struct parsed_partitions *state)
{
struct ldmdb *ldb;
unsigned long base;
int result = -1;
BUG_ON(!state);
/* Look for signs of a Dynamic Disk */
if (!ldm_validate_partition_table(state))
return 0;
ldb = kmalloc (sizeof (*ldb), GFP_KERNEL);
if (!ldb) {
ldm_crit ("Out of memory.");
goto out;
}
/* Parse and check privheads. */
if (!ldm_validate_privheads(state, &ldb->ph))
goto out; /* Already logged */
/* All further references are relative to base (database start). */
base = ldb->ph.config_start;
/* Parse and check tocs and vmdb. */
if (!ldm_validate_tocblocks(state, base, ldb) ||
!ldm_validate_vmdb(state, base, ldb))
goto out; /* Already logged */
/* Initialize vblk lists in ldmdb struct */
INIT_LIST_HEAD (&ldb->v_dgrp);
INIT_LIST_HEAD (&ldb->v_disk);
INIT_LIST_HEAD (&ldb->v_volu);
INIT_LIST_HEAD (&ldb->v_comp);
INIT_LIST_HEAD (&ldb->v_part);
if (!ldm_get_vblks(state, base, ldb)) {
ldm_crit ("Failed to read the VBLKs from the database.");
goto cleanup;
}
/* Finally, create the data partition devices. */
if (ldm_create_data_partitions(state, ldb)) {
ldm_debug ("Parsed LDM database successfully.");
result = 1;
}
/* else Already logged */
cleanup:
ldm_free_vblks (&ldb->v_dgrp);
ldm_free_vblks (&ldb->v_disk);
ldm_free_vblks (&ldb->v_volu);
ldm_free_vblks (&ldb->v_comp);
ldm_free_vblks (&ldb->v_part);
out:
kfree (ldb);
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3464_0 |
crossvul-cpp_data_good_341_9 | /*
* Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com>
*
* This file is part of OpenSC.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "egk-tool-cmdline.h"
#include "libopensc/log.h"
#include "libopensc/opensc.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#ifdef ENABLE_ZLIB
#include <zlib.h>
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
z_stream stream;
memset(&stream, 0, sizeof stream);
stream.total_in = compressed_len;
stream.avail_in = compressed_len;
stream.total_out = *uncompressed_len;
stream.avail_out = *uncompressed_len;
stream.next_in = (Bytef *) compressed;
stream.next_out = (Bytef *) uncompressed;
/* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */
if (Z_OK == inflateInit2(&stream, (15 + 32))
&& Z_STREAM_END == inflate(&stream, Z_FINISH)) {
*uncompressed_len = stream.total_out;
} else {
return SC_ERROR_INVALID_DATA;
}
inflateEnd(&stream);
return SC_SUCCESS;
}
#else
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif
#define PRINT(c) (isprint(c) ? c : '?')
void dump_binary(void *buf, size_t buf_len)
{
#ifdef _WIN32
_setmode(fileno(stdout), _O_BINARY);
#endif
fwrite(buf, 1, buf_len, stdout);
#ifdef _WIN32
_setmode(fileno(stdout), _O_TEXT);
#endif
}
const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02};
static int initialize(int reader_id, int verbose,
sc_context_t **ctx, sc_reader_t **reader)
{
unsigned int i, reader_count;
int r;
if (!ctx || !reader)
return SC_ERROR_INVALID_ARGUMENTS;
r = sc_establish_context(ctx, "");
if (r < 0 || !*ctx) {
fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r));
return r;
}
(*ctx)->debug = verbose;
(*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
reader_count = sc_ctx_get_reader_count(*ctx);
if (reader_count == 0) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n");
return SC_ERROR_NO_READERS_FOUND;
}
if (reader_id < 0) {
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < reader_count; i++) {
*reader = sc_ctx_get_reader(*ctx, i);
if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) {
reader_id = i;
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader"
" with a card: %s", (*reader)->name);
break;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader.");
reader_id = 0;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number "
"(%d), only %d available.\n", reader_id, reader_count);
return SC_ERROR_NO_READERS_FOUND;
}
*reader = sc_ctx_get_reader(*ctx, reader_id);
return SC_SUCCESS;
}
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file && file->size > 0 ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix)
{
*major = 0;
*minor = 0;
*fix = 0;
/* decode BCD to decimal */
if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) {
*major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4);
}
if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) {
*minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF);
}
if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10)
&& (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) {
*fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100
+ (bcd[4]>>4)*10 + (bcd[4]&0xF);
}
}
int
main (int argc, char **argv)
{
struct gengetopt_args_info cmdline;
struct sc_path path;
struct sc_context *ctx;
struct sc_reader *reader = NULL;
struct sc_card *card;
unsigned char *data = NULL;
size_t data_len = 0;
int r;
if (cmdline_parser(argc, argv, &cmdline) != 0)
exit(1);
r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader);
if (r < 0) {
fprintf(stderr, "Can't initialize reader\n");
exit(1);
}
if (sc_connect_card(reader, &card) < 0) {
fprintf(stderr, "Could not connect to card\n");
sc_release_context(ctx);
exit(1);
}
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0);
if (SC_SUCCESS != sc_select_file(card, &path, NULL))
goto err;
if (cmdline.pd_flag
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 2) {
size_t len_pd = (data[0] << 8) | data[1];
if (len_pd + 2 <= data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + 2, len_pd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + 2, len_pd);
}
}
}
if ((cmdline.vd_flag || cmdline.gvd_flag)
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 8) {
size_t off_vd = (data[0] << 8) | data[1];
size_t end_vd = (data[2] << 8) | data[3];
size_t off_gvd = (data[4] << 8) | data[5];
size_t end_gvd = (data[6] << 8) | data[7];
size_t len_vd = end_vd - off_vd + 1;
size_t len_gvd = end_gvd - off_gvd + 1;
if (off_vd <= end_vd && end_vd < data_len
&& off_gvd <= end_gvd && end_gvd < data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (cmdline.vd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_vd, len_vd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_vd, len_vd);
}
}
if (cmdline.gvd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_gvd, len_gvd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_gvd, len_gvd);
}
}
}
}
if (cmdline.vsd_status_flag
&& read_file(card, "D00C", &data, &data_len)
&& data_len >= 25) {
char *status;
unsigned int major, minor, fix;
switch (data[0]) {
case '0':
status = "Transactions pending";
break;
case '1':
status = "No transactions pending";
break;
default:
status = "Unknown";
break;
}
decode_version(data+15, &major, &minor, &fix);
printf(
"Status %s\n"
"Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n"
"Version %u.%u.%u\n",
status,
PRINT(data[7]), PRINT(data[8]),
PRINT(data[5]), PRINT(data[6]),
PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]),
PRINT(data[9]), PRINT(data[10]),
PRINT(data[11]), PRINT(data[12]),
PRINT(data[13]), PRINT(data[14]),
major, minor, fix);
}
err:
sc_disconnect_card(card);
sc_release_context(ctx);
cmdline_parser_free (&cmdline);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_341_9 |
crossvul-cpp_data_bad_3277_0 | /*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* Toplevel file. Relies on dhd_linux.c to send commands to the dongle. */
#include <linux/kernel.h>
#include <linux/etherdevice.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <net/cfg80211.h>
#include <net/netlink.h>
#include <brcmu_utils.h>
#include <defs.h>
#include <brcmu_wifi.h>
#include "core.h"
#include "debug.h"
#include "tracepoint.h"
#include "fwil_types.h"
#include "p2p.h"
#include "btcoex.h"
#include "pno.h"
#include "cfg80211.h"
#include "feature.h"
#include "fwil.h"
#include "proto.h"
#include "vendor.h"
#include "bus.h"
#include "common.h"
#define BRCMF_SCAN_IE_LEN_MAX 2048
#define WPA_OUI "\x00\x50\xF2" /* WPA OUI */
#define WPA_OUI_TYPE 1
#define RSN_OUI "\x00\x0F\xAC" /* RSN OUI */
#define WME_OUI_TYPE 2
#define WPS_OUI_TYPE 4
#define VS_IE_FIXED_HDR_LEN 6
#define WPA_IE_VERSION_LEN 2
#define WPA_IE_MIN_OUI_LEN 4
#define WPA_IE_SUITE_COUNT_LEN 2
#define WPA_CIPHER_NONE 0 /* None */
#define WPA_CIPHER_WEP_40 1 /* WEP (40-bit) */
#define WPA_CIPHER_TKIP 2 /* TKIP: default for WPA */
#define WPA_CIPHER_AES_CCM 4 /* AES (CCM) */
#define WPA_CIPHER_WEP_104 5 /* WEP (104-bit) */
#define RSN_AKM_NONE 0 /* None (IBSS) */
#define RSN_AKM_UNSPECIFIED 1 /* Over 802.1x */
#define RSN_AKM_PSK 2 /* Pre-shared Key */
#define RSN_AKM_SHA256_1X 5 /* SHA256, 802.1X */
#define RSN_AKM_SHA256_PSK 6 /* SHA256, Pre-shared Key */
#define RSN_CAP_LEN 2 /* Length of RSN capabilities */
#define RSN_CAP_PTK_REPLAY_CNTR_MASK (BIT(2) | BIT(3))
#define RSN_CAP_MFPR_MASK BIT(6)
#define RSN_CAP_MFPC_MASK BIT(7)
#define RSN_PMKID_COUNT_LEN 2
#define VNDR_IE_CMD_LEN 4 /* length of the set command
* string :"add", "del" (+ NUL)
*/
#define VNDR_IE_COUNT_OFFSET 4
#define VNDR_IE_PKTFLAG_OFFSET 8
#define VNDR_IE_VSIE_OFFSET 12
#define VNDR_IE_HDR_SIZE 12
#define VNDR_IE_PARSE_LIMIT 5
#define DOT11_MGMT_HDR_LEN 24 /* d11 management header len */
#define DOT11_BCN_PRB_FIXED_LEN 12 /* beacon/probe fixed length */
#define BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS 320
#define BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS 400
#define BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS 20
#define BRCMF_SCAN_CHANNEL_TIME 40
#define BRCMF_SCAN_UNASSOC_TIME 40
#define BRCMF_SCAN_PASSIVE_TIME 120
#define BRCMF_ND_INFO_TIMEOUT msecs_to_jiffies(2000)
#define BRCMF_ASSOC_PARAMS_FIXED_SIZE \
(sizeof(struct brcmf_assoc_params_le) - sizeof(u16))
static bool check_vif_up(struct brcmf_cfg80211_vif *vif)
{
if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state)) {
brcmf_dbg(INFO, "device is not ready : status (%lu)\n",
vif->sme_state);
return false;
}
return true;
}
#define RATE_TO_BASE100KBPS(rate) (((rate) * 10) / 2)
#define RATETAB_ENT(_rateid, _flags) \
{ \
.bitrate = RATE_TO_BASE100KBPS(_rateid), \
.hw_value = (_rateid), \
.flags = (_flags), \
}
static struct ieee80211_rate __wl_rates[] = {
RATETAB_ENT(BRCM_RATE_1M, 0),
RATETAB_ENT(BRCM_RATE_2M, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_5M5, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_11M, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_6M, 0),
RATETAB_ENT(BRCM_RATE_9M, 0),
RATETAB_ENT(BRCM_RATE_12M, 0),
RATETAB_ENT(BRCM_RATE_18M, 0),
RATETAB_ENT(BRCM_RATE_24M, 0),
RATETAB_ENT(BRCM_RATE_36M, 0),
RATETAB_ENT(BRCM_RATE_48M, 0),
RATETAB_ENT(BRCM_RATE_54M, 0),
};
#define wl_g_rates (__wl_rates + 0)
#define wl_g_rates_size ARRAY_SIZE(__wl_rates)
#define wl_a_rates (__wl_rates + 4)
#define wl_a_rates_size (wl_g_rates_size - 4)
#define CHAN2G(_channel, _freq) { \
.band = NL80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_channel), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
#define CHAN5G(_channel) { \
.band = NL80211_BAND_5GHZ, \
.center_freq = 5000 + (5 * (_channel)), \
.hw_value = (_channel), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel __wl_2ghz_channels[] = {
CHAN2G(1, 2412), CHAN2G(2, 2417), CHAN2G(3, 2422), CHAN2G(4, 2427),
CHAN2G(5, 2432), CHAN2G(6, 2437), CHAN2G(7, 2442), CHAN2G(8, 2447),
CHAN2G(9, 2452), CHAN2G(10, 2457), CHAN2G(11, 2462), CHAN2G(12, 2467),
CHAN2G(13, 2472), CHAN2G(14, 2484)
};
static struct ieee80211_channel __wl_5ghz_channels[] = {
CHAN5G(34), CHAN5G(36), CHAN5G(38), CHAN5G(40), CHAN5G(42),
CHAN5G(44), CHAN5G(46), CHAN5G(48), CHAN5G(52), CHAN5G(56),
CHAN5G(60), CHAN5G(64), CHAN5G(100), CHAN5G(104), CHAN5G(108),
CHAN5G(112), CHAN5G(116), CHAN5G(120), CHAN5G(124), CHAN5G(128),
CHAN5G(132), CHAN5G(136), CHAN5G(140), CHAN5G(144), CHAN5G(149),
CHAN5G(153), CHAN5G(157), CHAN5G(161), CHAN5G(165)
};
/* Band templates duplicated per wiphy. The channel info
* above is added to the band during setup.
*/
static const struct ieee80211_supported_band __wl_band_2ghz = {
.band = NL80211_BAND_2GHZ,
.bitrates = wl_g_rates,
.n_bitrates = wl_g_rates_size,
};
static const struct ieee80211_supported_band __wl_band_5ghz = {
.band = NL80211_BAND_5GHZ,
.bitrates = wl_a_rates,
.n_bitrates = wl_a_rates_size,
};
/* This is to override regulatory domains defined in cfg80211 module (reg.c)
* By default world regulatory domain defined in reg.c puts the flags
* NL80211_RRF_NO_IR for 5GHz channels (for * 36..48 and 149..165).
* With respect to these flags, wpa_supplicant doesn't * start p2p
* operations on 5GHz channels. All the changes in world regulatory
* domain are to be done here.
*/
static const struct ieee80211_regdomain brcmf_regdom = {
.n_reg_rules = 4,
.alpha2 = "99",
.reg_rules = {
/* IEEE 802.11b/g, channels 1..11 */
REG_RULE(2412-10, 2472+10, 40, 6, 20, 0),
/* If any */
/* IEEE 802.11 channel 14 - Only JP enables
* this and for 802.11b only
*/
REG_RULE(2484-10, 2484+10, 20, 6, 20, 0),
/* IEEE 802.11a, channel 36..64 */
REG_RULE(5150-10, 5350+10, 80, 6, 20, 0),
/* IEEE 802.11a, channel 100..165 */
REG_RULE(5470-10, 5850+10, 80, 6, 20, 0), }
};
/* Note: brcmf_cipher_suites is an array of int defining which cipher suites
* are supported. A pointer to this array and the number of entries is passed
* on to upper layers. AES_CMAC defines whether or not the driver supports MFP.
* So the cipher suite AES_CMAC has to be the last one in the array, and when
* device does not support MFP then the number of suites will be decreased by 1
*/
static const u32 brcmf_cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
/* Keep as last entry: */
WLAN_CIPHER_SUITE_AES_CMAC
};
/* Vendor specific ie. id = 221, oui and type defines exact ie */
struct brcmf_vs_tlv {
u8 id;
u8 len;
u8 oui[3];
u8 oui_type;
};
struct parsed_vndr_ie_info {
u8 *ie_ptr;
u32 ie_len; /* total length including id & length field */
struct brcmf_vs_tlv vndrie;
};
struct parsed_vndr_ies {
u32 count;
struct parsed_vndr_ie_info ie_info[VNDR_IE_PARSE_LIMIT];
};
static u8 nl80211_band_to_fwil(enum nl80211_band band)
{
switch (band) {
case NL80211_BAND_2GHZ:
return WLC_BAND_2G;
case NL80211_BAND_5GHZ:
return WLC_BAND_5G;
default:
WARN_ON(1);
break;
}
return 0;
}
static u16 chandef_to_chanspec(struct brcmu_d11inf *d11inf,
struct cfg80211_chan_def *ch)
{
struct brcmu_chan ch_inf;
s32 primary_offset;
brcmf_dbg(TRACE, "chandef: control %d center %d width %d\n",
ch->chan->center_freq, ch->center_freq1, ch->width);
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq1);
primary_offset = ch->chan->center_freq - ch->center_freq1;
switch (ch->width) {
case NL80211_CHAN_WIDTH_20:
case NL80211_CHAN_WIDTH_20_NOHT:
ch_inf.bw = BRCMU_CHAN_BW_20;
WARN_ON(primary_offset != 0);
break;
case NL80211_CHAN_WIDTH_40:
ch_inf.bw = BRCMU_CHAN_BW_40;
if (primary_offset > 0)
ch_inf.sb = BRCMU_CHAN_SB_U;
else
ch_inf.sb = BRCMU_CHAN_SB_L;
break;
case NL80211_CHAN_WIDTH_80:
ch_inf.bw = BRCMU_CHAN_BW_80;
if (primary_offset == -30)
ch_inf.sb = BRCMU_CHAN_SB_LL;
else if (primary_offset == -10)
ch_inf.sb = BRCMU_CHAN_SB_LU;
else if (primary_offset == 10)
ch_inf.sb = BRCMU_CHAN_SB_UL;
else
ch_inf.sb = BRCMU_CHAN_SB_UU;
break;
case NL80211_CHAN_WIDTH_80P80:
case NL80211_CHAN_WIDTH_160:
case NL80211_CHAN_WIDTH_5:
case NL80211_CHAN_WIDTH_10:
default:
WARN_ON_ONCE(1);
}
switch (ch->chan->band) {
case NL80211_BAND_2GHZ:
ch_inf.band = BRCMU_CHAN_BAND_2G;
break;
case NL80211_BAND_5GHZ:
ch_inf.band = BRCMU_CHAN_BAND_5G;
break;
case NL80211_BAND_60GHZ:
default:
WARN_ON_ONCE(1);
}
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
u16 channel_to_chanspec(struct brcmu_d11inf *d11inf,
struct ieee80211_channel *ch)
{
struct brcmu_chan ch_inf;
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq);
ch_inf.bw = BRCMU_CHAN_BW_20;
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
/* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
*/
static const struct brcmf_tlv *
brcmf_parse_tlvs(const void *buf, int buflen, uint key)
{
const struct brcmf_tlv *elt = buf;
int totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
int len = elt->len;
/* validate remaining totlen */
if ((elt->id == key) && (totlen >= (len + TLV_HDR_LEN)))
return elt;
elt = (struct brcmf_tlv *)((u8 *)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
/* Is any of the tlvs the expected entry? If
* not update the tlvs buffer pointer/length.
*/
static bool
brcmf_tlv_has_ie(const u8 *ie, const u8 **tlvs, u32 *tlvs_len,
const u8 *oui, u32 oui_len, u8 type)
{
/* If the contents match the OUI and the type */
if (ie[TLV_LEN_OFF] >= oui_len + 1 &&
!memcmp(&ie[TLV_BODY_OFF], oui, oui_len) &&
type == ie[TLV_BODY_OFF + oui_len]) {
return true;
}
if (tlvs == NULL)
return false;
/* point to the next ie */
ie += ie[TLV_LEN_OFF] + TLV_HDR_LEN;
/* calculate the length of the rest of the buffer */
*tlvs_len -= (int)(ie - *tlvs);
/* update the pointer to the start of the buffer */
*tlvs = ie;
return false;
}
static struct brcmf_vs_tlv *
brcmf_find_wpaie(const u8 *parse, u32 len)
{
const struct brcmf_tlv *ie;
while ((ie = brcmf_parse_tlvs(parse, len, WLAN_EID_VENDOR_SPECIFIC))) {
if (brcmf_tlv_has_ie((const u8 *)ie, &parse, &len,
WPA_OUI, TLV_OUI_LEN, WPA_OUI_TYPE))
return (struct brcmf_vs_tlv *)ie;
}
return NULL;
}
static struct brcmf_vs_tlv *
brcmf_find_wpsie(const u8 *parse, u32 len)
{
const struct brcmf_tlv *ie;
while ((ie = brcmf_parse_tlvs(parse, len, WLAN_EID_VENDOR_SPECIFIC))) {
if (brcmf_tlv_has_ie((u8 *)ie, &parse, &len,
WPA_OUI, TLV_OUI_LEN, WPS_OUI_TYPE))
return (struct brcmf_vs_tlv *)ie;
}
return NULL;
}
static int brcmf_vif_change_validate(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif,
enum nl80211_iftype new_type)
{
struct brcmf_cfg80211_vif *pos;
bool check_combos = false;
int ret = 0;
struct iface_combination_params params = {
.num_different_channels = 1,
};
list_for_each_entry(pos, &cfg->vif_list, list)
if (pos == vif) {
params.iftype_num[new_type]++;
} else {
/* concurrent interfaces so need check combinations */
check_combos = true;
params.iftype_num[pos->wdev.iftype]++;
}
if (check_combos)
ret = cfg80211_check_combinations(cfg->wiphy, ¶ms);
return ret;
}
static int brcmf_vif_add_validate(struct brcmf_cfg80211_info *cfg,
enum nl80211_iftype new_type)
{
struct brcmf_cfg80211_vif *pos;
struct iface_combination_params params = {
.num_different_channels = 1,
};
list_for_each_entry(pos, &cfg->vif_list, list)
params.iftype_num[pos->wdev.iftype]++;
params.iftype_num[new_type]++;
return cfg80211_check_combinations(cfg->wiphy, ¶ms);
}
static void convert_key_from_CPU(struct brcmf_wsec_key *key,
struct brcmf_wsec_key_le *key_le)
{
key_le->index = cpu_to_le32(key->index);
key_le->len = cpu_to_le32(key->len);
key_le->algo = cpu_to_le32(key->algo);
key_le->flags = cpu_to_le32(key->flags);
key_le->rxiv.hi = cpu_to_le32(key->rxiv.hi);
key_le->rxiv.lo = cpu_to_le16(key->rxiv.lo);
key_le->iv_initialized = cpu_to_le32(key->iv_initialized);
memcpy(key_le->data, key->data, sizeof(key->data));
memcpy(key_le->ea, key->ea, sizeof(key->ea));
}
static int
send_key_to_dongle(struct brcmf_if *ifp, struct brcmf_wsec_key *key)
{
int err;
struct brcmf_wsec_key_le key_le;
convert_key_from_CPU(key, &key_le);
brcmf_netdev_wait_pend8021x(ifp);
err = brcmf_fil_bsscfg_data_set(ifp, "wsec_key", &key_le,
sizeof(key_le));
if (err)
brcmf_err("wsec_key error (%d)\n", err);
return err;
}
static s32
brcmf_configure_arp_nd_offload(struct brcmf_if *ifp, bool enable)
{
s32 err;
u32 mode;
if (enable)
mode = BRCMF_ARP_OL_AGENT | BRCMF_ARP_OL_PEER_AUTO_REPLY;
else
mode = 0;
/* Try to set and enable ARP offload feature, this may fail, then it */
/* is simply not supported and err 0 will be returned */
err = brcmf_fil_iovar_int_set(ifp, "arp_ol", mode);
if (err) {
brcmf_dbg(TRACE, "failed to set ARP offload mode to 0x%x, err = %d\n",
mode, err);
err = 0;
} else {
err = brcmf_fil_iovar_int_set(ifp, "arpoe", enable);
if (err) {
brcmf_dbg(TRACE, "failed to configure (%d) ARP offload err = %d\n",
enable, err);
err = 0;
} else
brcmf_dbg(TRACE, "successfully configured (%d) ARP offload to 0x%x\n",
enable, mode);
}
err = brcmf_fil_iovar_int_set(ifp, "ndoe", enable);
if (err) {
brcmf_dbg(TRACE, "failed to configure (%d) ND offload err = %d\n",
enable, err);
err = 0;
} else
brcmf_dbg(TRACE, "successfully configured (%d) ND offload to 0x%x\n",
enable, mode);
return err;
}
static void
brcmf_cfg80211_update_proto_addr_mode(struct wireless_dev *wdev)
{
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
ifp = vif->ifp;
if ((wdev->iftype == NL80211_IFTYPE_ADHOC) ||
(wdev->iftype == NL80211_IFTYPE_AP) ||
(wdev->iftype == NL80211_IFTYPE_P2P_GO))
brcmf_proto_configure_addr_mode(ifp->drvr, ifp->ifidx,
ADDR_DIRECT);
else
brcmf_proto_configure_addr_mode(ifp->drvr, ifp->ifidx,
ADDR_INDIRECT);
}
static int brcmf_get_first_free_bsscfgidx(struct brcmf_pub *drvr)
{
int bsscfgidx;
for (bsscfgidx = 0; bsscfgidx < BRCMF_MAX_IFS; bsscfgidx++) {
/* bsscfgidx 1 is reserved for legacy P2P */
if (bsscfgidx == 1)
continue;
if (!drvr->iflist[bsscfgidx])
return bsscfgidx;
}
return -ENOMEM;
}
static int brcmf_cfg80211_request_ap_if(struct brcmf_if *ifp)
{
struct brcmf_mbss_ssid_le mbss_ssid_le;
int bsscfgidx;
int err;
memset(&mbss_ssid_le, 0, sizeof(mbss_ssid_le));
bsscfgidx = brcmf_get_first_free_bsscfgidx(ifp->drvr);
if (bsscfgidx < 0)
return bsscfgidx;
mbss_ssid_le.bsscfgidx = cpu_to_le32(bsscfgidx);
mbss_ssid_le.SSID_len = cpu_to_le32(5);
sprintf(mbss_ssid_le.SSID, "ssid%d" , bsscfgidx);
err = brcmf_fil_bsscfg_data_set(ifp, "bsscfg:ssid", &mbss_ssid_le,
sizeof(mbss_ssid_le));
if (err < 0)
brcmf_err("setting ssid failed %d\n", err);
return err;
}
/**
* brcmf_ap_add_vif() - create a new AP virtual interface for multiple BSS
*
* @wiphy: wiphy device of new interface.
* @name: name of the new interface.
* @params: contains mac address for AP device.
*/
static
struct wireless_dev *brcmf_ap_add_vif(struct wiphy *wiphy, const char *name,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_cfg80211_vif *vif;
int err;
if (brcmf_cfg80211_vif_event_armed(cfg))
return ERR_PTR(-EBUSY);
brcmf_dbg(INFO, "Adding vif \"%s\"\n", name);
vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_AP);
if (IS_ERR(vif))
return (struct wireless_dev *)vif;
brcmf_cfg80211_arm_vif_event(cfg, vif);
err = brcmf_cfg80211_request_ap_if(ifp);
if (err) {
brcmf_cfg80211_arm_vif_event(cfg, NULL);
goto fail;
}
/* wait for firmware event */
err = brcmf_cfg80211_wait_vif_event(cfg, BRCMF_E_IF_ADD,
BRCMF_VIF_EVENT_TIMEOUT);
brcmf_cfg80211_arm_vif_event(cfg, NULL);
if (!err) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto fail;
}
/* interface created in firmware */
ifp = vif->ifp;
if (!ifp) {
brcmf_err("no if pointer provided\n");
err = -ENOENT;
goto fail;
}
strncpy(ifp->ndev->name, name, sizeof(ifp->ndev->name) - 1);
err = brcmf_net_attach(ifp, true);
if (err) {
brcmf_err("Registering netdevice failed\n");
free_netdev(ifp->ndev);
goto fail;
}
return &ifp->vif->wdev;
fail:
brcmf_free_vif(vif);
return ERR_PTR(err);
}
static bool brcmf_is_apmode(struct brcmf_cfg80211_vif *vif)
{
enum nl80211_iftype iftype;
iftype = vif->wdev.iftype;
return iftype == NL80211_IFTYPE_AP || iftype == NL80211_IFTYPE_P2P_GO;
}
static bool brcmf_is_ibssmode(struct brcmf_cfg80211_vif *vif)
{
return vif->wdev.iftype == NL80211_IFTYPE_ADHOC;
}
static struct wireless_dev *brcmf_cfg80211_add_iface(struct wiphy *wiphy,
const char *name,
unsigned char name_assign_type,
enum nl80211_iftype type,
struct vif_params *params)
{
struct wireless_dev *wdev;
int err;
brcmf_dbg(TRACE, "enter: %s type %d\n", name, type);
err = brcmf_vif_add_validate(wiphy_to_cfg(wiphy), type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return ERR_PTR(err);
}
switch (type) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
return ERR_PTR(-EOPNOTSUPP);
case NL80211_IFTYPE_AP:
wdev = brcmf_ap_add_vif(wiphy, name, params);
break;
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
wdev = brcmf_p2p_add_vif(wiphy, name, name_assign_type, type, params);
break;
case NL80211_IFTYPE_UNSPECIFIED:
default:
return ERR_PTR(-EINVAL);
}
if (IS_ERR(wdev))
brcmf_err("add iface %s type %d failed: err=%d\n",
name, type, (int)PTR_ERR(wdev));
else
brcmf_cfg80211_update_proto_addr_mode(wdev);
return wdev;
}
static void brcmf_scan_config_mpc(struct brcmf_if *ifp, int mpc)
{
if (brcmf_feat_is_quirk_enabled(ifp, BRCMF_FEAT_QUIRK_NEED_MPC))
brcmf_set_mpc(ifp, mpc);
}
void brcmf_set_mpc(struct brcmf_if *ifp, int mpc)
{
s32 err = 0;
if (check_vif_up(ifp->vif)) {
err = brcmf_fil_iovar_int_set(ifp, "mpc", mpc);
if (err) {
brcmf_err("fail to set mpc\n");
return;
}
brcmf_dbg(INFO, "MPC : %d\n", mpc);
}
}
s32 brcmf_notify_escan_complete(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp, bool aborted,
bool fw_abort)
{
struct brcmf_scan_params_le params_le;
struct cfg80211_scan_request *scan_request;
u64 reqid;
u32 bucket;
s32 err = 0;
brcmf_dbg(SCAN, "Enter\n");
/* clear scan request, because the FW abort can cause a second call */
/* to this functon and might cause a double cfg80211_scan_done */
scan_request = cfg->scan_request;
cfg->scan_request = NULL;
if (timer_pending(&cfg->escan_timeout))
del_timer_sync(&cfg->escan_timeout);
if (fw_abort) {
/* Do a scan abort to stop the driver's scan engine */
brcmf_dbg(SCAN, "ABORT scan in firmware\n");
memset(¶ms_le, 0, sizeof(params_le));
eth_broadcast_addr(params_le.bssid);
params_le.bss_type = DOT11_BSSTYPE_ANY;
params_le.scan_type = 0;
params_le.channel_num = cpu_to_le32(1);
params_le.nprobes = cpu_to_le32(1);
params_le.active_time = cpu_to_le32(-1);
params_le.passive_time = cpu_to_le32(-1);
params_le.home_time = cpu_to_le32(-1);
/* Scan is aborted by setting channel_list[0] to -1 */
params_le.channel_list[0] = cpu_to_le16(-1);
/* E-Scan (or anyother type) can be aborted by SCAN */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN,
¶ms_le, sizeof(params_le));
if (err)
brcmf_err("Scan abort failed\n");
}
brcmf_scan_config_mpc(ifp, 1);
/*
* e-scan can be initiated internally
* which takes precedence.
*/
if (cfg->int_escan_map) {
brcmf_dbg(SCAN, "scheduled scan completed (%x)\n",
cfg->int_escan_map);
while (cfg->int_escan_map) {
bucket = __ffs(cfg->int_escan_map);
cfg->int_escan_map &= ~BIT(bucket);
reqid = brcmf_pno_find_reqid_by_bucket(cfg->pno,
bucket);
if (!aborted) {
brcmf_dbg(SCAN, "report results: reqid=%llu\n",
reqid);
cfg80211_sched_scan_results(cfg_to_wiphy(cfg),
reqid);
}
}
} else if (scan_request) {
struct cfg80211_scan_info info = {
.aborted = aborted,
};
brcmf_dbg(SCAN, "ESCAN Completed scan: %s\n",
aborted ? "Aborted" : "Done");
cfg80211_scan_done(scan_request, &info);
}
if (!test_and_clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_dbg(SCAN, "Scan complete, probably P2P scan\n");
return err;
}
static int brcmf_cfg80211_del_ap_iface(struct wiphy *wiphy,
struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct net_device *ndev = wdev->netdev;
struct brcmf_if *ifp = netdev_priv(ndev);
int ret;
int err;
brcmf_cfg80211_arm_vif_event(cfg, ifp->vif);
err = brcmf_fil_bsscfg_data_set(ifp, "interface_remove", NULL, 0);
if (err) {
brcmf_err("interface_remove failed %d\n", err);
goto err_unarm;
}
/* wait for firmware event */
ret = brcmf_cfg80211_wait_vif_event(cfg, BRCMF_E_IF_DEL,
BRCMF_VIF_EVENT_TIMEOUT);
if (!ret) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto err_unarm;
}
brcmf_remove_interface(ifp, true);
err_unarm:
brcmf_cfg80211_arm_vif_event(cfg, NULL);
return err;
}
static
int brcmf_cfg80211_del_iface(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct net_device *ndev = wdev->netdev;
if (ndev && ndev == cfg_to_ndev(cfg))
return -ENOTSUPP;
/* vif event pending in firmware */
if (brcmf_cfg80211_vif_event_armed(cfg))
return -EBUSY;
if (ndev) {
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status) &&
cfg->escan_info.ifp == netdev_priv(ndev))
brcmf_notify_escan_complete(cfg, netdev_priv(ndev),
true, true);
brcmf_fil_iovar_int_set(netdev_priv(ndev), "mpc", 1);
}
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
return -EOPNOTSUPP;
case NL80211_IFTYPE_AP:
return brcmf_cfg80211_del_ap_iface(wiphy, wdev);
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
return brcmf_p2p_del_vif(wiphy, wdev);
case NL80211_IFTYPE_UNSPECIFIED:
default:
return -EINVAL;
}
return -EOPNOTSUPP;
}
static s32
brcmf_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
enum nl80211_iftype type,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif = ifp->vif;
s32 infra = 0;
s32 ap = 0;
s32 err = 0;
brcmf_dbg(TRACE, "Enter, bsscfgidx=%d, type=%d\n", ifp->bsscfgidx,
type);
/* WAR: There are a number of p2p interface related problems which
* need to be handled initially (before doing the validate).
* wpa_supplicant tends to do iface changes on p2p device/client/go
* which are not always possible/allowed. However we need to return
* OK otherwise the wpa_supplicant wont start. The situation differs
* on configuration and setup (p2pon=1 module param). The first check
* is to see if the request is a change to station for p2p iface.
*/
if ((type == NL80211_IFTYPE_STATION) &&
((vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_GO) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_DEVICE))) {
brcmf_dbg(TRACE, "Ignoring cmd for p2p if\n");
/* Now depending on whether module param p2pon=1 was used the
* response needs to be either 0 or EOPNOTSUPP. The reason is
* that if p2pon=1 is used, but a newer supplicant is used then
* we should return an error, as this combination wont work.
* In other situations 0 is returned and supplicant will start
* normally. It will give a trace in cfg80211, but it is the
* only way to get it working. Unfortunately this will result
* in situation where we wont support new supplicant in
* combination with module param p2pon=1, but that is the way
* it is. If the user tries this then unloading of driver might
* fail/lock.
*/
if (cfg->p2p.p2pdev_dynamically)
return -EOPNOTSUPP;
else
return 0;
}
err = brcmf_vif_change_validate(wiphy_to_cfg(wiphy), vif, type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return err;
}
switch (type) {
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_WDS:
brcmf_err("type (%d) : currently we do not support this type\n",
type);
return -EOPNOTSUPP;
case NL80211_IFTYPE_ADHOC:
infra = 0;
break;
case NL80211_IFTYPE_STATION:
infra = 1;
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
ap = 1;
break;
default:
err = -EINVAL;
goto done;
}
if (ap) {
if (type == NL80211_IFTYPE_P2P_GO) {
brcmf_dbg(INFO, "IF Type = P2P GO\n");
err = brcmf_p2p_ifchange(cfg, BRCMF_FIL_P2P_IF_GO);
}
if (!err) {
brcmf_dbg(INFO, "IF Type = AP\n");
}
} else {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, infra);
if (err) {
brcmf_err("WLC_SET_INFRA error (%d)\n", err);
err = -EAGAIN;
goto done;
}
brcmf_dbg(INFO, "IF Type = %s\n", brcmf_is_ibssmode(vif) ?
"Adhoc" : "Infra");
}
ndev->ieee80211_ptr->iftype = type;
brcmf_cfg80211_update_proto_addr_mode(&vif->wdev);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static void brcmf_escan_prep(struct brcmf_cfg80211_info *cfg,
struct brcmf_scan_params_le *params_le,
struct cfg80211_scan_request *request)
{
u32 n_ssids;
u32 n_channels;
s32 i;
s32 offset;
u16 chanspec;
char *ptr;
struct brcmf_ssid_le ssid_le;
eth_broadcast_addr(params_le->bssid);
params_le->bss_type = DOT11_BSSTYPE_ANY;
params_le->scan_type = 0;
params_le->channel_num = 0;
params_le->nprobes = cpu_to_le32(-1);
params_le->active_time = cpu_to_le32(-1);
params_le->passive_time = cpu_to_le32(-1);
params_le->home_time = cpu_to_le32(-1);
memset(¶ms_le->ssid_le, 0, sizeof(params_le->ssid_le));
/* if request is null exit so it will be all channel broadcast scan */
if (!request)
return;
n_ssids = request->n_ssids;
n_channels = request->n_channels;
/* Copy channel array if applicable */
brcmf_dbg(SCAN, "### List of channelspecs to scan ### %d\n",
n_channels);
if (n_channels > 0) {
for (i = 0; i < n_channels; i++) {
chanspec = channel_to_chanspec(&cfg->d11inf,
request->channels[i]);
brcmf_dbg(SCAN, "Chan : %d, Channel spec: %x\n",
request->channels[i]->hw_value, chanspec);
params_le->channel_list[i] = cpu_to_le16(chanspec);
}
} else {
brcmf_dbg(SCAN, "Scanning all channels\n");
}
/* Copy ssid array if applicable */
brcmf_dbg(SCAN, "### List of SSIDs to scan ### %d\n", n_ssids);
if (n_ssids > 0) {
offset = offsetof(struct brcmf_scan_params_le, channel_list) +
n_channels * sizeof(u16);
offset = roundup(offset, sizeof(u32));
ptr = (char *)params_le + offset;
for (i = 0; i < n_ssids; i++) {
memset(&ssid_le, 0, sizeof(ssid_le));
ssid_le.SSID_len =
cpu_to_le32(request->ssids[i].ssid_len);
memcpy(ssid_le.SSID, request->ssids[i].ssid,
request->ssids[i].ssid_len);
if (!ssid_le.SSID_len)
brcmf_dbg(SCAN, "%d: Broadcast scan\n", i);
else
brcmf_dbg(SCAN, "%d: scan for %.32s size=%d\n",
i, ssid_le.SSID, ssid_le.SSID_len);
memcpy(ptr, &ssid_le, sizeof(ssid_le));
ptr += sizeof(ssid_le);
}
} else {
brcmf_dbg(SCAN, "Broadcast scan %p\n", request->ssids);
if ((request->ssids) && request->ssids->ssid_len) {
brcmf_dbg(SCAN, "SSID %s len=%d\n",
params_le->ssid_le.SSID,
request->ssids->ssid_len);
params_le->ssid_le.SSID_len =
cpu_to_le32(request->ssids->ssid_len);
memcpy(¶ms_le->ssid_le.SSID, request->ssids->ssid,
request->ssids->ssid_len);
}
}
/* Adding mask to channel numbers */
params_le->channel_num =
cpu_to_le32((n_ssids << BRCMF_SCAN_PARAMS_NSSID_SHIFT) |
(n_channels & BRCMF_SCAN_PARAMS_COUNT_MASK));
}
static s32
brcmf_run_escan(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp,
struct cfg80211_scan_request *request)
{
s32 params_size = BRCMF_SCAN_PARAMS_FIXED_SIZE +
offsetof(struct brcmf_escan_params_le, params_le);
struct brcmf_escan_params_le *params;
s32 err = 0;
brcmf_dbg(SCAN, "E-SCAN START\n");
if (request != NULL) {
/* Allocate space for populating ssids in struct */
params_size += sizeof(u32) * ((request->n_channels + 1) / 2);
/* Allocate space for populating ssids in struct */
params_size += sizeof(struct brcmf_ssid_le) * request->n_ssids;
}
params = kzalloc(params_size, GFP_KERNEL);
if (!params) {
err = -ENOMEM;
goto exit;
}
BUG_ON(params_size + sizeof("escan") >= BRCMF_DCMD_MEDLEN);
brcmf_escan_prep(cfg, ¶ms->params_le, request);
params->version = cpu_to_le32(BRCMF_ESCAN_REQ_VERSION);
params->action = cpu_to_le16(WL_ESCAN_ACTION_START);
params->sync_id = cpu_to_le16(0x1234);
err = brcmf_fil_iovar_data_set(ifp, "escan", params, params_size);
if (err) {
if (err == -EBUSY)
brcmf_dbg(INFO, "system busy : escan canceled\n");
else
brcmf_err("error (%d)\n", err);
}
kfree(params);
exit:
return err;
}
static s32
brcmf_do_escan(struct brcmf_if *ifp, struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err;
u32 passive_scan;
struct brcmf_scan_results *results;
struct escan_info *escan = &cfg->escan_info;
brcmf_dbg(SCAN, "Enter\n");
escan->ifp = ifp;
escan->wiphy = cfg->wiphy;
escan->escan_state = WL_ESCAN_STATE_SCANNING;
passive_scan = cfg->active_scan ? 0 : 1;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN,
passive_scan);
if (err) {
brcmf_err("error (%d)\n", err);
return err;
}
brcmf_scan_config_mpc(ifp, 0);
results = (struct brcmf_scan_results *)cfg->escan_info.escan_buf;
results->version = 0;
results->count = 0;
results->buflen = WL_ESCAN_RESULTS_FIXED_SIZE;
err = escan->run(cfg, ifp, request);
if (err)
brcmf_scan_config_mpc(ifp, 1);
return err;
}
static s32
brcmf_cfg80211_escan(struct wiphy *wiphy, struct brcmf_cfg80211_vif *vif,
struct cfg80211_scan_request *request,
struct cfg80211_ssid *this_ssid)
{
struct brcmf_if *ifp = vif->ifp;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct cfg80211_ssid *ssids;
u32 passive_scan;
bool escan_req;
bool spec_scan;
s32 err;
struct brcmf_ssid_le ssid_le;
u32 SSID_len;
brcmf_dbg(SCAN, "START ESCAN\n");
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("Scanning already: status (%lu)\n", cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status)) {
brcmf_err("Scanning being aborted: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) {
brcmf_err("Scanning suppressed: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state)) {
brcmf_err("Connecting: status (%lu)\n", ifp->vif->sme_state);
return -EAGAIN;
}
/* If scan req comes for p2p0, send it over primary I/F */
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
escan_req = false;
if (request) {
/* scan bss */
ssids = request->ssids;
escan_req = true;
} else {
/* scan in ibss */
/* we don't do escan in ibss */
ssids = this_ssid;
}
cfg->scan_request = request;
set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
if (escan_req) {
cfg->escan_info.run = brcmf_run_escan;
err = brcmf_p2p_scan_prep(wiphy, request, vif);
if (err)
goto scan_out;
err = brcmf_do_escan(vif->ifp, request);
if (err)
goto scan_out;
} else {
brcmf_dbg(SCAN, "ssid \"%s\", ssid_len (%d)\n",
ssids->ssid, ssids->ssid_len);
memset(&ssid_le, 0, sizeof(ssid_le));
SSID_len = min_t(u8, sizeof(ssid_le.SSID), ssids->ssid_len);
ssid_le.SSID_len = cpu_to_le32(0);
spec_scan = false;
if (SSID_len) {
memcpy(ssid_le.SSID, ssids->ssid, SSID_len);
ssid_le.SSID_len = cpu_to_le32(SSID_len);
spec_scan = true;
} else
brcmf_dbg(SCAN, "Broadcast scan\n");
passive_scan = cfg->active_scan ? 0 : 1;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN,
passive_scan);
if (err) {
brcmf_err("WLC_SET_PASSIVE_SCAN error (%d)\n", err);
goto scan_out;
}
brcmf_scan_config_mpc(ifp, 0);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN, &ssid_le,
sizeof(ssid_le));
if (err) {
if (err == -EBUSY)
brcmf_dbg(INFO, "BUSY: scan for \"%s\" canceled\n",
ssid_le.SSID);
else
brcmf_err("WLC_SCAN error (%d)\n", err);
brcmf_scan_config_mpc(ifp, 1);
goto scan_out;
}
}
/* Arm scan timeout timer */
mod_timer(&cfg->escan_timeout, jiffies +
BRCMF_ESCAN_TIMER_INTERVAL_MS * HZ / 1000);
return 0;
scan_out:
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
cfg->scan_request = NULL;
return err;
}
static s32
brcmf_cfg80211_scan(struct wiphy *wiphy, struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
vif = container_of(request->wdev, struct brcmf_cfg80211_vif, wdev);
if (!check_vif_up(vif))
return -EIO;
err = brcmf_cfg80211_escan(wiphy, vif, request, NULL);
if (err)
brcmf_err("scan error (%d)\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_set_rts(struct net_device *ndev, u32 rts_threshold)
{
s32 err = 0;
err = brcmf_fil_iovar_int_set(netdev_priv(ndev), "rtsthresh",
rts_threshold);
if (err)
brcmf_err("Error (%d)\n", err);
return err;
}
static s32 brcmf_set_frag(struct net_device *ndev, u32 frag_threshold)
{
s32 err = 0;
err = brcmf_fil_iovar_int_set(netdev_priv(ndev), "fragthresh",
frag_threshold);
if (err)
brcmf_err("Error (%d)\n", err);
return err;
}
static s32 brcmf_set_retry(struct net_device *ndev, u32 retry, bool l)
{
s32 err = 0;
u32 cmd = (l ? BRCMF_C_SET_LRL : BRCMF_C_SET_SRL);
err = brcmf_fil_cmd_int_set(netdev_priv(ndev), cmd, retry);
if (err) {
brcmf_err("cmd (%d) , error (%d)\n", cmd, err);
return err;
}
return err;
}
static s32 brcmf_cfg80211_set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (changed & WIPHY_PARAM_RTS_THRESHOLD &&
(cfg->conf->rts_threshold != wiphy->rts_threshold)) {
cfg->conf->rts_threshold = wiphy->rts_threshold;
err = brcmf_set_rts(ndev, cfg->conf->rts_threshold);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD &&
(cfg->conf->frag_threshold != wiphy->frag_threshold)) {
cfg->conf->frag_threshold = wiphy->frag_threshold;
err = brcmf_set_frag(ndev, cfg->conf->frag_threshold);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_RETRY_LONG
&& (cfg->conf->retry_long != wiphy->retry_long)) {
cfg->conf->retry_long = wiphy->retry_long;
err = brcmf_set_retry(ndev, cfg->conf->retry_long, true);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_RETRY_SHORT
&& (cfg->conf->retry_short != wiphy->retry_short)) {
cfg->conf->retry_short = wiphy->retry_short;
err = brcmf_set_retry(ndev, cfg->conf->retry_short, false);
if (!err)
goto done;
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static void brcmf_init_prof(struct brcmf_cfg80211_profile *prof)
{
memset(prof, 0, sizeof(*prof));
}
static u16 brcmf_map_fw_linkdown_reason(const struct brcmf_event_msg *e)
{
u16 reason;
switch (e->event_code) {
case BRCMF_E_DEAUTH:
case BRCMF_E_DEAUTH_IND:
case BRCMF_E_DISASSOC_IND:
reason = e->reason;
break;
case BRCMF_E_LINK:
default:
reason = 0;
break;
}
return reason;
}
static int brcmf_set_pmk(struct brcmf_if *ifp, const u8 *pmk_data, u16 pmk_len)
{
struct brcmf_wsec_pmk_le pmk;
int i, err;
/* convert to firmware key format */
pmk.key_len = cpu_to_le16(pmk_len << 1);
pmk.flags = cpu_to_le16(BRCMF_WSEC_PASSPHRASE);
for (i = 0; i < pmk_len; i++)
snprintf(&pmk.key[2 * i], 3, "%02x", pmk_data[i]);
/* store psk in firmware */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_WSEC_PMK,
&pmk, sizeof(pmk));
if (err < 0)
brcmf_err("failed to change PSK in firmware (len=%u)\n",
pmk_len);
return err;
}
static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(vif->wdev.wiphy);
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_VIF_STATUS_CONNECTED, &vif->sme_state)) {
brcmf_dbg(INFO, "Call WLC_DISASSOC to stop excess roaming\n ");
err = brcmf_fil_cmd_data_set(vif->ifp,
BRCMF_C_DISASSOC, NULL, 0);
if (err) {
brcmf_err("WLC_DISASSOC failed (%d)\n", err);
}
if ((vif->wdev.iftype == NL80211_IFTYPE_STATION) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT))
cfg80211_disconnected(vif->wdev.netdev, reason, NULL, 0,
true, GFP_KERNEL);
}
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &vif->sme_state);
clear_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_ENABLED, 0);
if (vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_NONE) {
brcmf_set_pmk(vif->ifp, NULL, 0);
vif->profile.use_fwsup = BRCMF_PROFILE_FWSUP_NONE;
}
brcmf_dbg(TRACE, "Exit\n");
}
static s32
brcmf_cfg80211_join_ibss(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ibss_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_join_params join_params;
size_t join_params_size = 0;
s32 err = 0;
s32 wsec = 0;
s32 bcnprd;
u16 chanspec;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (params->ssid)
brcmf_dbg(CONN, "SSID: %s\n", params->ssid);
else {
brcmf_dbg(CONN, "SSID: NULL, Not supported\n");
return -EOPNOTSUPP;
}
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (params->bssid)
brcmf_dbg(CONN, "BSSID: %pM\n", params->bssid);
else
brcmf_dbg(CONN, "No BSSID specified\n");
if (params->chandef.chan)
brcmf_dbg(CONN, "channel: %d\n",
params->chandef.chan->center_freq);
else
brcmf_dbg(CONN, "no channel specified\n");
if (params->channel_fixed)
brcmf_dbg(CONN, "fixed channel required\n");
else
brcmf_dbg(CONN, "no fixed channel required\n");
if (params->ie && params->ie_len)
brcmf_dbg(CONN, "ie len: %d\n", params->ie_len);
else
brcmf_dbg(CONN, "no ie specified\n");
if (params->beacon_interval)
brcmf_dbg(CONN, "beacon interval: %d\n",
params->beacon_interval);
else
brcmf_dbg(CONN, "no beacon interval specified\n");
if (params->basic_rates)
brcmf_dbg(CONN, "basic rates: %08X\n", params->basic_rates);
else
brcmf_dbg(CONN, "no basic rates specified\n");
if (params->privacy)
brcmf_dbg(CONN, "privacy required\n");
else
brcmf_dbg(CONN, "no privacy required\n");
/* Configure Privacy for starter */
if (params->privacy)
wsec |= WEP_ENABLED;
err = brcmf_fil_iovar_int_set(ifp, "wsec", wsec);
if (err) {
brcmf_err("wsec failed (%d)\n", err);
goto done;
}
/* Configure Beacon Interval for starter */
if (params->beacon_interval)
bcnprd = params->beacon_interval;
else
bcnprd = 100;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD, bcnprd);
if (err) {
brcmf_err("WLC_SET_BCNPRD failed (%d)\n", err);
goto done;
}
/* Configure required join parameter */
memset(&join_params, 0, sizeof(struct brcmf_join_params));
/* SSID */
ssid_len = min_t(u32, params->ssid_len, IEEE80211_MAX_SSID_LEN);
memcpy(join_params.ssid_le.SSID, params->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
join_params_size = sizeof(join_params.ssid_le);
/* BSSID */
if (params->bssid) {
memcpy(join_params.params_le.bssid, params->bssid, ETH_ALEN);
join_params_size += BRCMF_ASSOC_PARAMS_FIXED_SIZE;
memcpy(profile->bssid, params->bssid, ETH_ALEN);
} else {
eth_broadcast_addr(join_params.params_le.bssid);
eth_zero_addr(profile->bssid);
}
/* Channel */
if (params->chandef.chan) {
u32 target_channel;
cfg->channel =
ieee80211_frequency_to_channel(
params->chandef.chan->center_freq);
if (params->channel_fixed) {
/* adding chanspec */
chanspec = chandef_to_chanspec(&cfg->d11inf,
¶ms->chandef);
join_params.params_le.chanspec_list[0] =
cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
/* set channel for starter */
target_channel = cfg->channel;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_CHANNEL,
target_channel);
if (err) {
brcmf_err("WLC_SET_CHANNEL failed (%d)\n", err);
goto done;
}
} else
cfg->channel = 0;
cfg->ibss_starter = false;
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err) {
brcmf_err("WLC_SET_SSID failed (%d)\n", err);
goto done;
}
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_leave_ibss(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif)) {
/* When driver is being unloaded, it can end up here. If an
* error is returned then later on a debug trace in the wireless
* core module will be printed. To avoid this 0 is returned.
*/
return 0;
}
brcmf_link_down(ifp->vif, WLAN_REASON_DEAUTH_LEAVING);
brcmf_net_setcarrier(ifp, false);
brcmf_dbg(TRACE, "Exit\n");
return 0;
}
static s32 brcmf_set_wpa_version(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 val = 0;
s32 err = 0;
if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_1)
val = WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED;
else if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_2)
val = WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED;
else
val = WPA_AUTH_DISABLED;
brcmf_dbg(CONN, "setting wpa_auth to 0x%0x\n", val);
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wpa_auth", val);
if (err) {
brcmf_err("set wpa_auth failed (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->wpa_versions = sme->crypto.wpa_versions;
return err;
}
static s32 brcmf_set_auth_type(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 val = 0;
s32 err = 0;
switch (sme->auth_type) {
case NL80211_AUTHTYPE_OPEN_SYSTEM:
val = 0;
brcmf_dbg(CONN, "open system\n");
break;
case NL80211_AUTHTYPE_SHARED_KEY:
val = 1;
brcmf_dbg(CONN, "shared key\n");
break;
default:
val = 2;
brcmf_dbg(CONN, "automatic, auth type (%d)\n", sme->auth_type);
break;
}
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "auth", val);
if (err) {
brcmf_err("set auth failed (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->auth_type = sme->auth_type;
return err;
}
static s32
brcmf_set_wsec_mode(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 pval = 0;
s32 gval = 0;
s32 wsec;
s32 err = 0;
if (sme->crypto.n_ciphers_pairwise) {
switch (sme->crypto.ciphers_pairwise[0]) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
pval = WEP_ENABLED;
break;
case WLAN_CIPHER_SUITE_TKIP:
pval = TKIP_ENABLED;
break;
case WLAN_CIPHER_SUITE_CCMP:
pval = AES_ENABLED;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
pval = AES_ENABLED;
break;
default:
brcmf_err("invalid cipher pairwise (%d)\n",
sme->crypto.ciphers_pairwise[0]);
return -EINVAL;
}
}
if (sme->crypto.cipher_group) {
switch (sme->crypto.cipher_group) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
gval = WEP_ENABLED;
break;
case WLAN_CIPHER_SUITE_TKIP:
gval = TKIP_ENABLED;
break;
case WLAN_CIPHER_SUITE_CCMP:
gval = AES_ENABLED;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
gval = AES_ENABLED;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
}
brcmf_dbg(CONN, "pval (%d) gval (%d)\n", pval, gval);
/* In case of privacy, but no security and WPS then simulate */
/* setting AES. WPS-2.0 allows no security */
if (brcmf_find_wpsie(sme->ie, sme->ie_len) && !pval && !gval &&
sme->privacy)
pval = AES_ENABLED;
wsec = pval | gval;
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wsec", wsec);
if (err) {
brcmf_err("error (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->cipher_pairwise = sme->crypto.ciphers_pairwise[0];
sec->cipher_group = sme->crypto.cipher_group;
return err;
}
static s32
brcmf_set_key_mgmt(struct net_device *ndev, struct cfg80211_connect_params *sme)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
s32 val;
s32 err;
const struct brcmf_tlv *rsn_ie;
const u8 *ie;
u32 ie_len;
u32 offset;
u16 rsn_cap;
u32 mfp;
u16 count;
profile->use_fwsup = BRCMF_PROFILE_FWSUP_NONE;
if (!sme->crypto.n_akm_suites)
return 0;
err = brcmf_fil_bsscfg_int_get(netdev_priv(ndev), "wpa_auth", &val);
if (err) {
brcmf_err("could not get wpa_auth (%d)\n", err);
return err;
}
if (val & (WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED)) {
switch (sme->crypto.akm_suites[0]) {
case WLAN_AKM_SUITE_8021X:
val = WPA_AUTH_UNSPECIFIED;
if (sme->want_1x)
profile->use_fwsup = BRCMF_PROFILE_FWSUP_1X;
break;
case WLAN_AKM_SUITE_PSK:
val = WPA_AUTH_PSK;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
} else if (val & (WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED)) {
switch (sme->crypto.akm_suites[0]) {
case WLAN_AKM_SUITE_8021X:
val = WPA2_AUTH_UNSPECIFIED;
if (sme->want_1x)
profile->use_fwsup = BRCMF_PROFILE_FWSUP_1X;
break;
case WLAN_AKM_SUITE_8021X_SHA256:
val = WPA2_AUTH_1X_SHA256;
if (sme->want_1x)
profile->use_fwsup = BRCMF_PROFILE_FWSUP_1X;
break;
case WLAN_AKM_SUITE_PSK_SHA256:
val = WPA2_AUTH_PSK_SHA256;
break;
case WLAN_AKM_SUITE_PSK:
val = WPA2_AUTH_PSK;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
}
if (profile->use_fwsup == BRCMF_PROFILE_FWSUP_1X)
brcmf_dbg(INFO, "using 1X offload\n");
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
goto skip_mfp_config;
/* The MFP mode (1 or 2) needs to be determined, parse IEs. The
* IE will not be verified, just a quick search for MFP config
*/
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie, sme->ie_len,
WLAN_EID_RSN);
if (!rsn_ie)
goto skip_mfp_config;
ie = (const u8 *)rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
/* Skip unicast suite */
offset = TLV_HDR_LEN + WPA_IE_VERSION_LEN + WPA_IE_MIN_OUI_LEN;
if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len)
goto skip_mfp_config;
/* Skip multicast suite */
count = ie[offset] + (ie[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN);
if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len)
goto skip_mfp_config;
/* Skip auth key management suite(s) */
count = ie[offset] + (ie[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN);
if (offset + WPA_IE_SUITE_COUNT_LEN > ie_len)
goto skip_mfp_config;
/* Ready to read capabilities */
mfp = BRCMF_MFP_NONE;
rsn_cap = ie[offset] + (ie[offset + 1] << 8);
if (rsn_cap & RSN_CAP_MFPR_MASK)
mfp = BRCMF_MFP_REQUIRED;
else if (rsn_cap & RSN_CAP_MFPC_MASK)
mfp = BRCMF_MFP_CAPABLE;
brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "mfp", mfp);
skip_mfp_config:
brcmf_dbg(CONN, "setting wpa_auth to %d\n", val);
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wpa_auth", val);
if (err) {
brcmf_err("could not set wpa_auth (%d)\n", err);
return err;
}
return err;
}
static s32
brcmf_set_sharedkey(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
struct brcmf_wsec_key key;
s32 val;
s32 err = 0;
brcmf_dbg(CONN, "key len (%d)\n", sme->key_len);
if (sme->key_len == 0)
return 0;
sec = &profile->sec;
brcmf_dbg(CONN, "wpa_versions 0x%x cipher_pairwise 0x%x\n",
sec->wpa_versions, sec->cipher_pairwise);
if (sec->wpa_versions & (NL80211_WPA_VERSION_1 | NL80211_WPA_VERSION_2))
return 0;
if (!(sec->cipher_pairwise &
(WLAN_CIPHER_SUITE_WEP40 | WLAN_CIPHER_SUITE_WEP104)))
return 0;
memset(&key, 0, sizeof(key));
key.len = (u32) sme->key_len;
key.index = (u32) sme->key_idx;
if (key.len > sizeof(key.data)) {
brcmf_err("Too long key length (%u)\n", key.len);
return -EINVAL;
}
memcpy(key.data, sme->key, key.len);
key.flags = BRCMF_PRIMARY_KEY;
switch (sec->cipher_pairwise) {
case WLAN_CIPHER_SUITE_WEP40:
key.algo = CRYPTO_ALGO_WEP1;
break;
case WLAN_CIPHER_SUITE_WEP104:
key.algo = CRYPTO_ALGO_WEP128;
break;
default:
brcmf_err("Invalid algorithm (%d)\n",
sme->crypto.ciphers_pairwise[0]);
return -EINVAL;
}
/* Set the new key/index */
brcmf_dbg(CONN, "key length (%d) key index (%d) algo (%d)\n",
key.len, key.index, key.algo);
brcmf_dbg(CONN, "key \"%s\"\n", key.data);
err = send_key_to_dongle(netdev_priv(ndev), &key);
if (err)
return err;
if (sec->auth_type == NL80211_AUTHTYPE_SHARED_KEY) {
brcmf_dbg(CONN, "set auth_type to shared key\n");
val = WL_AUTH_SHARED_KEY; /* shared key */
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "auth", val);
if (err)
brcmf_err("set auth failed (%d)\n", err);
}
return err;
}
static
enum nl80211_auth_type brcmf_war_auth_type(struct brcmf_if *ifp,
enum nl80211_auth_type type)
{
if (type == NL80211_AUTHTYPE_AUTOMATIC &&
brcmf_feat_is_quirk_enabled(ifp, BRCMF_FEAT_QUIRK_AUTO_AUTH)) {
brcmf_dbg(CONN, "WAR: use OPEN instead of AUTO\n");
type = NL80211_AUTHTYPE_OPEN_SYSTEM;
}
return type;
}
static void brcmf_set_join_pref(struct brcmf_if *ifp,
struct cfg80211_bss_selection *bss_select)
{
struct brcmf_join_pref_params join_pref_params[2];
enum nl80211_band band;
int err, i = 0;
join_pref_params[i].len = 2;
join_pref_params[i].rssi_gain = 0;
if (bss_select->behaviour != NL80211_BSS_SELECT_ATTR_BAND_PREF)
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_ASSOC_PREFER, WLC_BAND_AUTO);
switch (bss_select->behaviour) {
case __NL80211_BSS_SELECT_ATTR_INVALID:
brcmf_c_set_joinpref_default(ifp);
return;
case NL80211_BSS_SELECT_ATTR_BAND_PREF:
join_pref_params[i].type = BRCMF_JOIN_PREF_BAND;
band = bss_select->param.band_pref;
join_pref_params[i].band = nl80211_band_to_fwil(band);
i++;
break;
case NL80211_BSS_SELECT_ATTR_RSSI_ADJUST:
join_pref_params[i].type = BRCMF_JOIN_PREF_RSSI_DELTA;
band = bss_select->param.adjust.band;
join_pref_params[i].band = nl80211_band_to_fwil(band);
join_pref_params[i].rssi_gain = bss_select->param.adjust.delta;
i++;
break;
case NL80211_BSS_SELECT_ATTR_RSSI:
default:
break;
}
join_pref_params[i].type = BRCMF_JOIN_PREF_RSSI;
join_pref_params[i].len = 2;
join_pref_params[i].rssi_gain = 0;
join_pref_params[i].band = 0;
err = brcmf_fil_iovar_data_set(ifp, "join_pref", join_pref_params,
sizeof(join_pref_params));
if (err)
brcmf_err("Set join_pref error (%d)\n", err);
}
static s32
brcmf_cfg80211_connect(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct ieee80211_channel *chan = sme->channel;
struct brcmf_join_params join_params;
size_t join_params_size;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
const void *ie;
u32 ie_len;
struct brcmf_ext_join_params_le *ext_join_params;
u16 chanspec;
s32 err = 0;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (!sme->ssid) {
brcmf_err("Invalid ssid\n");
return -EOPNOTSUPP;
}
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif) {
/* A normal (non P2P) connection request setup. */
ie = NULL;
ie_len = 0;
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)sme->ie, sme->ie_len);
if (wpa_ie) {
ie = wpa_ie;
ie_len = wpa_ie->len + TLV_HDR_LEN;
} else {
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie,
sme->ie_len,
WLAN_EID_RSN);
if (rsn_ie) {
ie = rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
}
}
brcmf_fil_iovar_data_set(ifp, "wpaie", ie, ie_len);
}
err = brcmf_vif_set_mgmt_ie(ifp->vif, BRCMF_VNDR_IE_ASSOCREQ_FLAG,
sme->ie, sme->ie_len);
if (err)
brcmf_err("Set Assoc REQ IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Assoc request\n");
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (chan) {
cfg->channel =
ieee80211_frequency_to_channel(chan->center_freq);
chanspec = channel_to_chanspec(&cfg->d11inf, chan);
brcmf_dbg(CONN, "channel=%d, center_req=%d, chanspec=0x%04x\n",
cfg->channel, chan->center_freq, chanspec);
} else {
cfg->channel = 0;
chanspec = 0;
}
brcmf_dbg(INFO, "ie (%p), ie_len (%zd)\n", sme->ie, sme->ie_len);
err = brcmf_set_wpa_version(ndev, sme);
if (err) {
brcmf_err("wl_set_wpa_version failed (%d)\n", err);
goto done;
}
sme->auth_type = brcmf_war_auth_type(ifp, sme->auth_type);
err = brcmf_set_auth_type(ndev, sme);
if (err) {
brcmf_err("wl_set_auth_type failed (%d)\n", err);
goto done;
}
err = brcmf_set_wsec_mode(ndev, sme);
if (err) {
brcmf_err("wl_set_set_cipher failed (%d)\n", err);
goto done;
}
err = brcmf_set_key_mgmt(ndev, sme);
if (err) {
brcmf_err("wl_set_key_mgmt failed (%d)\n", err);
goto done;
}
err = brcmf_set_sharedkey(ndev, sme);
if (err) {
brcmf_err("brcmf_set_sharedkey failed (%d)\n", err);
goto done;
}
if (sme->crypto.psk) {
if (WARN_ON(profile->use_fwsup != BRCMF_PROFILE_FWSUP_NONE)) {
err = -EINVAL;
goto done;
}
brcmf_dbg(INFO, "using PSK offload\n");
profile->use_fwsup = BRCMF_PROFILE_FWSUP_PSK;
}
if (profile->use_fwsup != BRCMF_PROFILE_FWSUP_NONE) {
/* enable firmware supplicant for this interface */
err = brcmf_fil_iovar_int_set(ifp, "sup_wpa", 1);
if (err < 0) {
brcmf_err("failed to enable fw supplicant\n");
goto done;
}
}
if (profile->use_fwsup == BRCMF_PROFILE_FWSUP_PSK) {
err = brcmf_set_pmk(ifp, sme->crypto.psk,
BRCMF_WSEC_MAX_PSK_LEN);
if (err)
goto done;
}
/* Join with specific BSSID and cached SSID
* If SSID is zero join based on BSSID only
*/
join_params_size = offsetof(struct brcmf_ext_join_params_le, assoc_le) +
offsetof(struct brcmf_assoc_params_le, chanspec_list);
if (cfg->channel)
join_params_size += sizeof(u16);
ext_join_params = kzalloc(join_params_size, GFP_KERNEL);
if (ext_join_params == NULL) {
err = -ENOMEM;
goto done;
}
ssid_len = min_t(u32, sme->ssid_len, IEEE80211_MAX_SSID_LEN);
ext_join_params->ssid_le.SSID_len = cpu_to_le32(ssid_len);
memcpy(&ext_join_params->ssid_le.SSID, sme->ssid, ssid_len);
if (ssid_len < IEEE80211_MAX_SSID_LEN)
brcmf_dbg(CONN, "SSID \"%s\", len (%d)\n",
ext_join_params->ssid_le.SSID, ssid_len);
/* Set up join scan parameters */
ext_join_params->scan_le.scan_type = -1;
ext_join_params->scan_le.home_time = cpu_to_le32(-1);
if (sme->bssid)
memcpy(&ext_join_params->assoc_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(ext_join_params->assoc_le.bssid);
if (cfg->channel) {
ext_join_params->assoc_le.chanspec_num = cpu_to_le32(1);
ext_join_params->assoc_le.chanspec_list[0] =
cpu_to_le16(chanspec);
/* Increase dwell time to receive probe response or detect
* beacon from target AP at a noisy air only during connect
* command.
*/
ext_join_params->scan_le.active_time =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS);
ext_join_params->scan_le.passive_time =
cpu_to_le32(BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS);
/* To sync with presence period of VSDB GO send probe request
* more frequently. Probe request will be stopped when it gets
* probe response from target AP/GO.
*/
ext_join_params->scan_le.nprobes =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS /
BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS);
} else {
ext_join_params->scan_le.active_time = cpu_to_le32(-1);
ext_join_params->scan_le.passive_time = cpu_to_le32(-1);
ext_join_params->scan_le.nprobes = cpu_to_le32(-1);
}
brcmf_set_join_pref(ifp, &sme->bss_select);
err = brcmf_fil_bsscfg_data_set(ifp, "join", ext_join_params,
join_params_size);
kfree(ext_join_params);
if (!err)
/* This is it. join command worked, we are done */
goto done;
/* join command failed, fallback to set ssid */
memset(&join_params, 0, sizeof(join_params));
join_params_size = sizeof(join_params.ssid_le);
memcpy(&join_params.ssid_le.SSID, sme->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
if (sme->bssid)
memcpy(join_params.params_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(join_params.params_le.bssid);
if (cfg->channel) {
join_params.params_le.chanspec_list[0] = cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err)
brcmf_err("BRCMF_C_SET_SSID failed (%d)\n", err);
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_disconnect(struct wiphy *wiphy, struct net_device *ndev,
u16 reason_code)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_scb_val_le scbval;
s32 err = 0;
brcmf_dbg(TRACE, "Enter. Reason code = %d\n", reason_code);
if (!check_vif_up(ifp->vif))
return -EIO;
clear_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state);
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
cfg80211_disconnected(ndev, reason_code, NULL, 0, true, GFP_KERNEL);
memcpy(&scbval.ea, &profile->bssid, ETH_ALEN);
scbval.val = cpu_to_le32(reason_code);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_DISASSOC,
&scbval, sizeof(scbval));
if (err)
brcmf_err("error (%d)\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_set_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
enum nl80211_tx_power_setting type, s32 mbm)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
s32 disable;
u32 qdbm = 127;
brcmf_dbg(TRACE, "Enter %d %d\n", type, mbm);
if (!check_vif_up(ifp->vif))
return -EIO;
switch (type) {
case NL80211_TX_POWER_AUTOMATIC:
break;
case NL80211_TX_POWER_LIMITED:
case NL80211_TX_POWER_FIXED:
if (mbm < 0) {
brcmf_err("TX_POWER_FIXED - dbm is negative\n");
err = -EINVAL;
goto done;
}
qdbm = MBM_TO_DBM(4 * mbm);
if (qdbm > 127)
qdbm = 127;
qdbm |= WL_TXPWR_OVERRIDE;
break;
default:
brcmf_err("Unsupported type %d\n", type);
err = -EINVAL;
goto done;
}
/* Make sure radio is off or on as far as software is concerned */
disable = WL_RADIO_SW_DISABLE << 16;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_RADIO, disable);
if (err)
brcmf_err("WLC_SET_RADIO error (%d)\n", err);
err = brcmf_fil_iovar_int_set(ifp, "qtxpower", qdbm);
if (err)
brcmf_err("qtxpower error (%d)\n", err);
done:
brcmf_dbg(TRACE, "Exit %d (qdbm)\n", qdbm & ~WL_TXPWR_OVERRIDE);
return err;
}
static s32
brcmf_cfg80211_get_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
s32 *dbm)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 qdbm = 0;
s32 err;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
err = brcmf_fil_iovar_int_get(ifp, "qtxpower", &qdbm);
if (err) {
brcmf_err("error (%d)\n", err);
goto done;
}
*dbm = (qdbm & ~WL_TXPWR_OVERRIDE) / 4;
done:
brcmf_dbg(TRACE, "Exit (0x%x %d)\n", qdbm, *dbm);
return err;
}
static s32
brcmf_cfg80211_config_default_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool unicast, bool multicast)
{
struct brcmf_if *ifp = netdev_priv(ndev);
u32 index;
u32 wsec;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("WLC_GET_WSEC error (%d)\n", err);
goto done;
}
if (wsec & WEP_ENABLED) {
/* Just select a new current key */
index = key_idx;
err = brcmf_fil_cmd_int_set(ifp,
BRCMF_C_SET_KEY_PRIMARY, index);
if (err)
brcmf_err("error (%d)\n", err);
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool pairwise, const u8 *mac_addr)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_wsec_key *key;
s32 err;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
if (key_idx >= BRCMF_MAX_DEFAULT_KEYS) {
/* we ignore this key index in this case */
return -EINVAL;
}
key = &ifp->vif->profile.key[key_idx];
if (key->algo == CRYPTO_ALGO_OFF) {
brcmf_dbg(CONN, "Ignore clearing of (never configured) key\n");
return -EINVAL;
}
memset(key, 0, sizeof(*key));
key->index = (u32)key_idx;
key->flags = BRCMF_PRIMARY_KEY;
/* Clear the key/index */
err = send_key_to_dongle(ifp, key);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_add_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_wsec_key *key;
s32 val;
s32 wsec;
s32 err;
u8 keybuf[8];
bool ext_key;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
if (key_idx >= BRCMF_MAX_DEFAULT_KEYS) {
/* we ignore this key index in this case */
brcmf_err("invalid key index (%d)\n", key_idx);
return -EINVAL;
}
if (params->key_len == 0)
return brcmf_cfg80211_del_key(wiphy, ndev, key_idx, pairwise,
mac_addr);
if (params->key_len > sizeof(key->data)) {
brcmf_err("Too long key length (%u)\n", params->key_len);
return -EINVAL;
}
ext_key = false;
if (mac_addr && (params->cipher != WLAN_CIPHER_SUITE_WEP40) &&
(params->cipher != WLAN_CIPHER_SUITE_WEP104)) {
brcmf_dbg(TRACE, "Ext key, mac %pM", mac_addr);
ext_key = true;
}
key = &ifp->vif->profile.key[key_idx];
memset(key, 0, sizeof(*key));
if ((ext_key) && (!is_multicast_ether_addr(mac_addr)))
memcpy((char *)&key->ea, (void *)mac_addr, ETH_ALEN);
key->len = params->key_len;
key->index = key_idx;
memcpy(key->data, params->key, key->len);
if (!ext_key)
key->flags = BRCMF_PRIMARY_KEY;
switch (params->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
key->algo = CRYPTO_ALGO_WEP1;
val = WEP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP40\n");
break;
case WLAN_CIPHER_SUITE_WEP104:
key->algo = CRYPTO_ALGO_WEP128;
val = WEP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP104\n");
break;
case WLAN_CIPHER_SUITE_TKIP:
if (!brcmf_is_apmode(ifp->vif)) {
brcmf_dbg(CONN, "Swapping RX/TX MIC key\n");
memcpy(keybuf, &key->data[24], sizeof(keybuf));
memcpy(&key->data[24], &key->data[16], sizeof(keybuf));
memcpy(&key->data[16], keybuf, sizeof(keybuf));
}
key->algo = CRYPTO_ALGO_TKIP;
val = TKIP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_TKIP\n");
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
key->algo = CRYPTO_ALGO_AES_CCM;
val = AES_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_AES_CMAC\n");
break;
case WLAN_CIPHER_SUITE_CCMP:
key->algo = CRYPTO_ALGO_AES_CCM;
val = AES_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_CCMP\n");
break;
default:
brcmf_err("Invalid cipher (0x%x)\n", params->cipher);
err = -EINVAL;
goto done;
}
err = send_key_to_dongle(ifp, key);
if (ext_key || err)
goto done;
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
goto done;
}
wsec |= val;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err) {
brcmf_err("set wsec error (%d)\n", err);
goto done;
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_get_key(struct wiphy *wiphy, struct net_device *ndev, u8 key_idx,
bool pairwise, const u8 *mac_addr, void *cookie,
void (*callback)(void *cookie,
struct key_params *params))
{
struct key_params params;
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_security *sec;
s32 wsec;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
memset(¶ms, 0, sizeof(params));
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("WLC_GET_WSEC error (%d)\n", err);
/* Ignore this error, may happen during DISASSOC */
err = -EAGAIN;
goto done;
}
if (wsec & WEP_ENABLED) {
sec = &profile->sec;
if (sec->cipher_pairwise & WLAN_CIPHER_SUITE_WEP40) {
params.cipher = WLAN_CIPHER_SUITE_WEP40;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP40\n");
} else if (sec->cipher_pairwise & WLAN_CIPHER_SUITE_WEP104) {
params.cipher = WLAN_CIPHER_SUITE_WEP104;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP104\n");
}
} else if (wsec & TKIP_ENABLED) {
params.cipher = WLAN_CIPHER_SUITE_TKIP;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_TKIP\n");
} else if (wsec & AES_ENABLED) {
params.cipher = WLAN_CIPHER_SUITE_AES_CMAC;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_AES_CMAC\n");
} else {
brcmf_err("Invalid algo (0x%x)\n", wsec);
err = -EINVAL;
goto done;
}
callback(cookie, ¶ms);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_config_default_mgmt_key(struct wiphy *wiphy,
struct net_device *ndev, u8 key_idx)
{
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter key_idx %d\n", key_idx);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
return 0;
brcmf_dbg(INFO, "Not supported\n");
return -EOPNOTSUPP;
}
static void
brcmf_cfg80211_reconfigure_wep(struct brcmf_if *ifp)
{
s32 err;
u8 key_idx;
struct brcmf_wsec_key *key;
s32 wsec;
for (key_idx = 0; key_idx < BRCMF_MAX_DEFAULT_KEYS; key_idx++) {
key = &ifp->vif->profile.key[key_idx];
if ((key->algo == CRYPTO_ALGO_WEP1) ||
(key->algo == CRYPTO_ALGO_WEP128))
break;
}
if (key_idx == BRCMF_MAX_DEFAULT_KEYS)
return;
err = send_key_to_dongle(ifp, key);
if (err) {
brcmf_err("Setting WEP key failed (%d)\n", err);
return;
}
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
return;
}
wsec |= WEP_ENABLED;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err)
brcmf_err("set wsec error (%d)\n", err);
}
static void brcmf_convert_sta_flags(u32 fw_sta_flags, struct station_info *si)
{
struct nl80211_sta_flag_update *sfu;
brcmf_dbg(TRACE, "flags %08x\n", fw_sta_flags);
si->filled |= BIT(NL80211_STA_INFO_STA_FLAGS);
sfu = &si->sta_flags;
sfu->mask = BIT(NL80211_STA_FLAG_WME) |
BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_ASSOCIATED) |
BIT(NL80211_STA_FLAG_AUTHORIZED);
if (fw_sta_flags & BRCMF_STA_WME)
sfu->set |= BIT(NL80211_STA_FLAG_WME);
if (fw_sta_flags & BRCMF_STA_AUTHE)
sfu->set |= BIT(NL80211_STA_FLAG_AUTHENTICATED);
if (fw_sta_flags & BRCMF_STA_ASSOC)
sfu->set |= BIT(NL80211_STA_FLAG_ASSOCIATED);
if (fw_sta_flags & BRCMF_STA_AUTHO)
sfu->set |= BIT(NL80211_STA_FLAG_AUTHORIZED);
}
static void brcmf_fill_bss_param(struct brcmf_if *ifp, struct station_info *si)
{
struct {
__le32 len;
struct brcmf_bss_info_le bss_le;
} *buf;
u16 capability;
int err;
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (!buf)
return;
buf->len = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO, buf,
WL_BSS_INFO_MAX);
if (err) {
brcmf_err("Failed to get bss info (%d)\n", err);
goto out_kfree;
}
si->filled |= BIT(NL80211_STA_INFO_BSS_PARAM);
si->bss_param.beacon_interval = le16_to_cpu(buf->bss_le.beacon_period);
si->bss_param.dtim_period = buf->bss_le.dtim_period;
capability = le16_to_cpu(buf->bss_le.capability);
if (capability & IEEE80211_HT_STBC_PARAM_DUAL_CTS_PROT)
si->bss_param.flags |= BSS_PARAM_FLAGS_CTS_PROT;
if (capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
si->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_PREAMBLE;
if (capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
si->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_SLOT_TIME;
out_kfree:
kfree(buf);
}
static s32
brcmf_cfg80211_get_station_ibss(struct brcmf_if *ifp,
struct station_info *sinfo)
{
struct brcmf_scb_val_le scbval;
struct brcmf_pktcnt_le pktcnt;
s32 err;
u32 rate;
u32 rssi;
/* Get the current tx rate */
err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_RATE, &rate);
if (err < 0) {
brcmf_err("BRCMF_C_GET_RATE error (%d)\n", err);
return err;
}
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE);
sinfo->txrate.legacy = rate * 5;
memset(&scbval, 0, sizeof(scbval));
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI, &scbval,
sizeof(scbval));
if (err) {
brcmf_err("BRCMF_C_GET_RSSI error (%d)\n", err);
return err;
}
rssi = le32_to_cpu(scbval.val);
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
sinfo->signal = rssi;
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_GET_PKTCNTS, &pktcnt,
sizeof(pktcnt));
if (err) {
brcmf_err("BRCMF_C_GET_GET_PKTCNTS error (%d)\n", err);
return err;
}
sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS) |
BIT(NL80211_STA_INFO_RX_DROP_MISC) |
BIT(NL80211_STA_INFO_TX_PACKETS) |
BIT(NL80211_STA_INFO_TX_FAILED);
sinfo->rx_packets = le32_to_cpu(pktcnt.rx_good_pkt);
sinfo->rx_dropped_misc = le32_to_cpu(pktcnt.rx_bad_pkt);
sinfo->tx_packets = le32_to_cpu(pktcnt.tx_good_pkt);
sinfo->tx_failed = le32_to_cpu(pktcnt.tx_bad_pkt);
return 0;
}
static s32
brcmf_cfg80211_get_station(struct wiphy *wiphy, struct net_device *ndev,
const u8 *mac, struct station_info *sinfo)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_scb_val_le scb_val;
s32 err = 0;
struct brcmf_sta_info_le sta_info_le;
u32 sta_flags;
u32 is_tdls_peer;
s32 total_rssi;
s32 count_rssi;
int rssi;
u32 i;
brcmf_dbg(TRACE, "Enter, MAC %pM\n", mac);
if (!check_vif_up(ifp->vif))
return -EIO;
if (brcmf_is_ibssmode(ifp->vif))
return brcmf_cfg80211_get_station_ibss(ifp, sinfo);
memset(&sta_info_le, 0, sizeof(sta_info_le));
memcpy(&sta_info_le, mac, ETH_ALEN);
err = brcmf_fil_iovar_data_get(ifp, "tdls_sta_info",
&sta_info_le,
sizeof(sta_info_le));
is_tdls_peer = !err;
if (err) {
err = brcmf_fil_iovar_data_get(ifp, "sta_info",
&sta_info_le,
sizeof(sta_info_le));
if (err < 0) {
brcmf_err("GET STA INFO failed, %d\n", err);
goto done;
}
}
brcmf_dbg(TRACE, "version %d\n", le16_to_cpu(sta_info_le.ver));
sinfo->filled = BIT(NL80211_STA_INFO_INACTIVE_TIME);
sinfo->inactive_time = le32_to_cpu(sta_info_le.idle) * 1000;
sta_flags = le32_to_cpu(sta_info_le.flags);
brcmf_convert_sta_flags(sta_flags, sinfo);
sinfo->sta_flags.mask |= BIT(NL80211_STA_FLAG_TDLS_PEER);
if (is_tdls_peer)
sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_TDLS_PEER);
else
sinfo->sta_flags.set &= ~BIT(NL80211_STA_FLAG_TDLS_PEER);
if (sta_flags & BRCMF_STA_ASSOC) {
sinfo->filled |= BIT(NL80211_STA_INFO_CONNECTED_TIME);
sinfo->connected_time = le32_to_cpu(sta_info_le.in);
brcmf_fill_bss_param(ifp, sinfo);
}
if (sta_flags & BRCMF_STA_SCBSTATS) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_FAILED);
sinfo->tx_failed = le32_to_cpu(sta_info_le.tx_failures);
sinfo->filled |= BIT(NL80211_STA_INFO_TX_PACKETS);
sinfo->tx_packets = le32_to_cpu(sta_info_le.tx_pkts);
sinfo->tx_packets += le32_to_cpu(sta_info_le.tx_mcast_pkts);
sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS);
sinfo->rx_packets = le32_to_cpu(sta_info_le.rx_ucast_pkts);
sinfo->rx_packets += le32_to_cpu(sta_info_le.rx_mcast_pkts);
if (sinfo->tx_packets) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE);
sinfo->txrate.legacy =
le32_to_cpu(sta_info_le.tx_rate) / 100;
}
if (sinfo->rx_packets) {
sinfo->filled |= BIT(NL80211_STA_INFO_RX_BITRATE);
sinfo->rxrate.legacy =
le32_to_cpu(sta_info_le.rx_rate) / 100;
}
if (le16_to_cpu(sta_info_le.ver) >= 4) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BYTES);
sinfo->tx_bytes = le64_to_cpu(sta_info_le.tx_tot_bytes);
sinfo->filled |= BIT(NL80211_STA_INFO_RX_BYTES);
sinfo->rx_bytes = le64_to_cpu(sta_info_le.rx_tot_bytes);
}
total_rssi = 0;
count_rssi = 0;
for (i = 0; i < BRCMF_ANT_MAX; i++) {
if (sta_info_le.rssi[i]) {
sinfo->chain_signal_avg[count_rssi] =
sta_info_le.rssi[i];
sinfo->chain_signal[count_rssi] =
sta_info_le.rssi[i];
total_rssi += sta_info_le.rssi[i];
count_rssi++;
}
}
if (count_rssi) {
sinfo->filled |= BIT(NL80211_STA_INFO_CHAIN_SIGNAL);
sinfo->chains = count_rssi;
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
total_rssi /= count_rssi;
sinfo->signal = total_rssi;
} else if (test_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state)) {
memset(&scb_val, 0, sizeof(scb_val));
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI,
&scb_val, sizeof(scb_val));
if (err) {
brcmf_err("Could not get rssi (%d)\n", err);
goto done;
} else {
rssi = le32_to_cpu(scb_val.val);
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
sinfo->signal = rssi;
brcmf_dbg(CONN, "RSSI %d dBm\n", rssi);
}
}
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static int
brcmf_cfg80211_dump_station(struct wiphy *wiphy, struct net_device *ndev,
int idx, u8 *mac, struct station_info *sinfo)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter, idx %d\n", idx);
if (idx == 0) {
cfg->assoclist.count = cpu_to_le32(BRCMF_MAX_ASSOCLIST);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_ASSOCLIST,
&cfg->assoclist,
sizeof(cfg->assoclist));
if (err) {
brcmf_err("BRCMF_C_GET_ASSOCLIST unsupported, err=%d\n",
err);
cfg->assoclist.count = 0;
return -EOPNOTSUPP;
}
}
if (idx < le32_to_cpu(cfg->assoclist.count)) {
memcpy(mac, cfg->assoclist.mac[idx], ETH_ALEN);
return brcmf_cfg80211_get_station(wiphy, ndev, mac, sinfo);
}
return -ENOENT;
}
static s32
brcmf_cfg80211_set_power_mgmt(struct wiphy *wiphy, struct net_device *ndev,
bool enabled, s32 timeout)
{
s32 pm;
s32 err = 0;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
/*
* Powersave enable/disable request is coming from the
* cfg80211 even before the interface is up. In that
* scenario, driver will be storing the power save
* preference in cfg struct to apply this to
* FW later while initializing the dongle
*/
cfg->pwr_save = enabled;
if (!check_vif_up(ifp->vif)) {
brcmf_dbg(INFO, "Device is not ready, storing the value in cfg_info struct\n");
goto done;
}
pm = enabled ? PM_FAST : PM_OFF;
/* Do not enable the power save after assoc if it is a p2p interface */
if (ifp->vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) {
brcmf_dbg(INFO, "Do not enable power save for P2P clients\n");
pm = PM_OFF;
}
brcmf_dbg(INFO, "power save %s\n", (pm ? "enabled" : "disabled"));
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, pm);
if (err) {
if (err == -ENODEV)
brcmf_err("net_device is not ready yet\n");
else
brcmf_err("error (%d)\n", err);
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_inform_single_bss(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bi)
{
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel;
struct cfg80211_bss *bss;
struct ieee80211_supported_band *band;
struct brcmu_chan ch;
u16 channel;
u32 freq;
u16 notify_capability;
u16 notify_interval;
u8 *notify_ie;
size_t notify_ielen;
s32 notify_signal;
if (le32_to_cpu(bi->length) > WL_BSS_INFO_MAX) {
brcmf_err("Bss info is larger than buffer. Discarding\n");
return 0;
}
if (!bi->ctl_ch) {
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
bi->ctl_ch = ch.control_ch_num;
}
channel = bi->ctl_ch;
if (channel <= CH_MAX_2G_CHANNEL)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(channel, band->band);
notify_channel = ieee80211_get_channel(wiphy, freq);
notify_capability = le16_to_cpu(bi->capability);
notify_interval = le16_to_cpu(bi->beacon_period);
notify_ie = (u8 *)bi + le16_to_cpu(bi->ie_offset);
notify_ielen = le32_to_cpu(bi->ie_length);
notify_signal = (s16)le16_to_cpu(bi->RSSI) * 100;
brcmf_dbg(CONN, "bssid: %pM\n", bi->BSSID);
brcmf_dbg(CONN, "Channel: %d(%d)\n", channel, freq);
brcmf_dbg(CONN, "Capability: %X\n", notify_capability);
brcmf_dbg(CONN, "Beacon interval: %d\n", notify_interval);
brcmf_dbg(CONN, "Signal: %d\n", notify_signal);
bss = cfg80211_inform_bss(wiphy, notify_channel,
CFG80211_BSS_FTYPE_UNKNOWN,
(const u8 *)bi->BSSID,
0, notify_capability,
notify_interval, notify_ie,
notify_ielen, notify_signal,
GFP_KERNEL);
if (!bss)
return -ENOMEM;
cfg80211_put_bss(wiphy, bss);
return 0;
}
static struct brcmf_bss_info_le *
next_bss_le(struct brcmf_scan_results *list, struct brcmf_bss_info_le *bss)
{
if (bss == NULL)
return list->bss_info_le;
return (struct brcmf_bss_info_le *)((unsigned long)bss +
le32_to_cpu(bss->length));
}
static s32 brcmf_inform_bss(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_scan_results *bss_list;
struct brcmf_bss_info_le *bi = NULL; /* must be initialized */
s32 err = 0;
int i;
bss_list = (struct brcmf_scan_results *)cfg->escan_info.escan_buf;
if (bss_list->count != 0 &&
bss_list->version != BRCMF_BSS_INFO_VERSION) {
brcmf_err("Version %d != WL_BSS_INFO_VERSION\n",
bss_list->version);
return -EOPNOTSUPP;
}
brcmf_dbg(SCAN, "scanned AP count (%d)\n", bss_list->count);
for (i = 0; i < bss_list->count; i++) {
bi = next_bss_le(bss_list, bi);
err = brcmf_inform_single_bss(cfg, bi);
if (err)
break;
}
return err;
}
static s32 brcmf_inform_ibss(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev, const u8 *bssid)
{
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel;
struct brcmf_bss_info_le *bi = NULL;
struct ieee80211_supported_band *band;
struct cfg80211_bss *bss;
struct brcmu_chan ch;
u8 *buf = NULL;
s32 err = 0;
u32 freq;
u16 notify_capability;
u16 notify_interval;
u8 *notify_ie;
size_t notify_ielen;
s32 notify_signal;
brcmf_dbg(TRACE, "Enter\n");
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
goto CleanUp;
}
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(netdev_priv(ndev), BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX);
if (err) {
brcmf_err("WLC_GET_BSS_INFO failed: %d\n", err);
goto CleanUp;
}
bi = (struct brcmf_bss_info_le *)(buf + 4);
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band->band);
cfg->channel = freq;
notify_channel = ieee80211_get_channel(wiphy, freq);
notify_capability = le16_to_cpu(bi->capability);
notify_interval = le16_to_cpu(bi->beacon_period);
notify_ie = (u8 *)bi + le16_to_cpu(bi->ie_offset);
notify_ielen = le32_to_cpu(bi->ie_length);
notify_signal = (s16)le16_to_cpu(bi->RSSI) * 100;
brcmf_dbg(CONN, "channel: %d(%d)\n", ch.control_ch_num, freq);
brcmf_dbg(CONN, "capability: %X\n", notify_capability);
brcmf_dbg(CONN, "beacon interval: %d\n", notify_interval);
brcmf_dbg(CONN, "signal: %d\n", notify_signal);
bss = cfg80211_inform_bss(wiphy, notify_channel,
CFG80211_BSS_FTYPE_UNKNOWN, bssid, 0,
notify_capability, notify_interval,
notify_ie, notify_ielen, notify_signal,
GFP_KERNEL);
if (!bss) {
err = -ENOMEM;
goto CleanUp;
}
cfg80211_put_bss(wiphy, bss);
CleanUp:
kfree(buf);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_update_bss_info(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp)
{
struct brcmf_bss_info_le *bi;
const struct brcmf_tlv *tim;
u16 beacon_interval;
u8 dtim_period;
size_t ie_len;
u8 *ie;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (brcmf_is_ibssmode(ifp->vif))
return err;
*(__le32 *)cfg->extra_buf = cpu_to_le32(WL_EXTRA_BUF_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
cfg->extra_buf, WL_EXTRA_BUF_MAX);
if (err) {
brcmf_err("Could not get bss info %d\n", err);
goto update_bss_info_out;
}
bi = (struct brcmf_bss_info_le *)(cfg->extra_buf + 4);
err = brcmf_inform_single_bss(cfg, bi);
if (err)
goto update_bss_info_out;
ie = ((u8 *)bi) + le16_to_cpu(bi->ie_offset);
ie_len = le32_to_cpu(bi->ie_length);
beacon_interval = le16_to_cpu(bi->beacon_period);
tim = brcmf_parse_tlvs(ie, ie_len, WLAN_EID_TIM);
if (tim)
dtim_period = tim->data[1];
else {
/*
* active scan was done so we could not get dtim
* information out of probe response.
* so we speficially query dtim information to dongle.
*/
u32 var;
err = brcmf_fil_iovar_int_get(ifp, "dtim_assoc", &var);
if (err) {
brcmf_err("wl dtim_assoc failed (%d)\n", err);
goto update_bss_info_out;
}
dtim_period = (u8)var;
}
update_bss_info_out:
brcmf_dbg(TRACE, "Exit");
return err;
}
void brcmf_abort_scanning(struct brcmf_cfg80211_info *cfg)
{
struct escan_info *escan = &cfg->escan_info;
set_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status);
if (cfg->int_escan_map || cfg->scan_request) {
escan->escan_state = WL_ESCAN_STATE_IDLE;
brcmf_notify_escan_complete(cfg, escan->ifp, true, true);
}
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
clear_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status);
}
static void brcmf_cfg80211_escan_timeout_worker(struct work_struct *work)
{
struct brcmf_cfg80211_info *cfg =
container_of(work, struct brcmf_cfg80211_info,
escan_timeout_work);
brcmf_inform_bss(cfg);
brcmf_notify_escan_complete(cfg, cfg->escan_info.ifp, true, true);
}
static void brcmf_escan_timeout(unsigned long data)
{
struct brcmf_cfg80211_info *cfg =
(struct brcmf_cfg80211_info *)data;
if (cfg->int_escan_map || cfg->scan_request) {
brcmf_err("timer expired\n");
schedule_work(&cfg->escan_timeout_work);
}
}
static s32
brcmf_compare_update_same_bss(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bss,
struct brcmf_bss_info_le *bss_info_le)
{
struct brcmu_chan ch_bss, ch_bss_info_le;
ch_bss.chspec = le16_to_cpu(bss->chanspec);
cfg->d11inf.decchspec(&ch_bss);
ch_bss_info_le.chspec = le16_to_cpu(bss_info_le->chanspec);
cfg->d11inf.decchspec(&ch_bss_info_le);
if (!memcmp(&bss_info_le->BSSID, &bss->BSSID, ETH_ALEN) &&
ch_bss.band == ch_bss_info_le.band &&
bss_info_le->SSID_len == bss->SSID_len &&
!memcmp(bss_info_le->SSID, bss->SSID, bss_info_le->SSID_len)) {
if ((bss->flags & BRCMF_BSS_RSSI_ON_CHANNEL) ==
(bss_info_le->flags & BRCMF_BSS_RSSI_ON_CHANNEL)) {
s16 bss_rssi = le16_to_cpu(bss->RSSI);
s16 bss_info_rssi = le16_to_cpu(bss_info_le->RSSI);
/* preserve max RSSI if the measurements are
* both on-channel or both off-channel
*/
if (bss_info_rssi > bss_rssi)
bss->RSSI = bss_info_le->RSSI;
} else if ((bss->flags & BRCMF_BSS_RSSI_ON_CHANNEL) &&
(bss_info_le->flags & BRCMF_BSS_RSSI_ON_CHANNEL) == 0) {
/* preserve the on-channel rssi measurement
* if the new measurement is off channel
*/
bss->RSSI = bss_info_le->RSSI;
bss->flags |= BRCMF_BSS_RSSI_ON_CHANNEL;
}
return 1;
}
return 0;
}
static s32
brcmf_cfg80211_escan_handler(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 status;
struct brcmf_escan_result_le *escan_result_le;
struct brcmf_bss_info_le *bss_info_le;
struct brcmf_bss_info_le *bss = NULL;
u32 bi_length;
struct brcmf_scan_results *list;
u32 i;
bool aborted;
status = e->status;
if (status == BRCMF_E_STATUS_ABORT)
goto exit;
if (!test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("scan not ready, bsscfgidx=%d\n", ifp->bsscfgidx);
return -EPERM;
}
if (status == BRCMF_E_STATUS_PARTIAL) {
brcmf_dbg(SCAN, "ESCAN Partial result\n");
escan_result_le = (struct brcmf_escan_result_le *) data;
if (!escan_result_le) {
brcmf_err("Invalid escan result (NULL pointer)\n");
goto exit;
}
if (le16_to_cpu(escan_result_le->bss_count) != 1) {
brcmf_err("Invalid bss_count %d: ignoring\n",
escan_result_le->bss_count);
goto exit;
}
bss_info_le = &escan_result_le->bss_info_le;
if (brcmf_p2p_scan_finding_common_channel(cfg, bss_info_le))
goto exit;
if (!cfg->int_escan_map && !cfg->scan_request) {
brcmf_dbg(SCAN, "result without cfg80211 request\n");
goto exit;
}
bi_length = le32_to_cpu(bss_info_le->length);
if (bi_length != (le32_to_cpu(escan_result_le->buflen) -
WL_ESCAN_RESULTS_FIXED_SIZE)) {
brcmf_err("Invalid bss_info length %d: ignoring\n",
bi_length);
goto exit;
}
if (!(cfg_to_wiphy(cfg)->interface_modes &
BIT(NL80211_IFTYPE_ADHOC))) {
if (le16_to_cpu(bss_info_le->capability) &
WLAN_CAPABILITY_IBSS) {
brcmf_err("Ignoring IBSS result\n");
goto exit;
}
}
list = (struct brcmf_scan_results *)
cfg->escan_info.escan_buf;
if (bi_length > BRCMF_ESCAN_BUF_SIZE - list->buflen) {
brcmf_err("Buffer is too small: ignoring\n");
goto exit;
}
for (i = 0; i < list->count; i++) {
bss = bss ? (struct brcmf_bss_info_le *)
((unsigned char *)bss +
le32_to_cpu(bss->length)) : list->bss_info_le;
if (brcmf_compare_update_same_bss(cfg, bss,
bss_info_le))
goto exit;
}
memcpy(&cfg->escan_info.escan_buf[list->buflen], bss_info_le,
bi_length);
list->version = le32_to_cpu(bss_info_le->version);
list->buflen += bi_length;
list->count++;
} else {
cfg->escan_info.escan_state = WL_ESCAN_STATE_IDLE;
if (brcmf_p2p_scan_finding_common_channel(cfg, NULL))
goto exit;
if (cfg->int_escan_map || cfg->scan_request) {
brcmf_inform_bss(cfg);
aborted = status != BRCMF_E_STATUS_SUCCESS;
brcmf_notify_escan_complete(cfg, ifp, aborted, false);
} else
brcmf_dbg(SCAN, "Ignored scan complete result 0x%x\n",
status);
}
exit:
return 0;
}
static void brcmf_init_escan(struct brcmf_cfg80211_info *cfg)
{
brcmf_fweh_register(cfg->pub, BRCMF_E_ESCAN_RESULT,
brcmf_cfg80211_escan_handler);
cfg->escan_info.escan_state = WL_ESCAN_STATE_IDLE;
/* Init scan_timeout timer */
init_timer(&cfg->escan_timeout);
cfg->escan_timeout.data = (unsigned long) cfg;
cfg->escan_timeout.function = brcmf_escan_timeout;
INIT_WORK(&cfg->escan_timeout_work,
brcmf_cfg80211_escan_timeout_worker);
}
static struct cfg80211_scan_request *
brcmf_alloc_internal_escan_request(struct wiphy *wiphy, u32 n_netinfo) {
struct cfg80211_scan_request *req;
size_t req_size;
req_size = sizeof(*req) +
n_netinfo * sizeof(req->channels[0]) +
n_netinfo * sizeof(*req->ssids);
req = kzalloc(req_size, GFP_KERNEL);
if (req) {
req->wiphy = wiphy;
req->ssids = (void *)(&req->channels[0]) +
n_netinfo * sizeof(req->channels[0]);
}
return req;
}
static int brcmf_internal_escan_add_info(struct cfg80211_scan_request *req,
u8 *ssid, u8 ssid_len, u8 channel)
{
struct ieee80211_channel *chan;
enum nl80211_band band;
int freq, i;
if (channel <= CH_MAX_2G_CHANNEL)
band = NL80211_BAND_2GHZ;
else
band = NL80211_BAND_5GHZ;
freq = ieee80211_channel_to_frequency(channel, band);
if (!freq)
return -EINVAL;
chan = ieee80211_get_channel(req->wiphy, freq);
if (!chan)
return -EINVAL;
for (i = 0; i < req->n_channels; i++) {
if (req->channels[i] == chan)
break;
}
if (i == req->n_channels)
req->channels[req->n_channels++] = chan;
for (i = 0; i < req->n_ssids; i++) {
if (req->ssids[i].ssid_len == ssid_len &&
!memcmp(req->ssids[i].ssid, ssid, ssid_len))
break;
}
if (i == req->n_ssids) {
memcpy(req->ssids[req->n_ssids].ssid, ssid, ssid_len);
req->ssids[req->n_ssids++].ssid_len = ssid_len;
}
return 0;
}
static int brcmf_start_internal_escan(struct brcmf_if *ifp, u32 fwmap,
struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
int err;
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
if (cfg->int_escan_map)
brcmf_dbg(SCAN, "aborting internal scan: map=%u\n",
cfg->int_escan_map);
/* Abort any on-going scan */
brcmf_abort_scanning(cfg);
}
brcmf_dbg(SCAN, "start internal scan: map=%u\n", fwmap);
set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
cfg->escan_info.run = brcmf_run_escan;
err = brcmf_do_escan(ifp, request);
if (err) {
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
return err;
}
cfg->int_escan_map = fwmap;
return 0;
}
static struct brcmf_pno_net_info_le *
brcmf_get_netinfo_array(struct brcmf_pno_scanresults_le *pfn_v1)
{
struct brcmf_pno_scanresults_v2_le *pfn_v2;
struct brcmf_pno_net_info_le *netinfo;
switch (pfn_v1->version) {
default:
WARN_ON(1);
/* fall-thru */
case cpu_to_le32(1):
netinfo = (struct brcmf_pno_net_info_le *)(pfn_v1 + 1);
break;
case cpu_to_le32(2):
pfn_v2 = (struct brcmf_pno_scanresults_v2_le *)pfn_v1;
netinfo = (struct brcmf_pno_net_info_le *)(pfn_v2 + 1);
break;
}
return netinfo;
}
/* PFN result doesn't have all the info which are required by the supplicant
* (For e.g IEs) Do a target Escan so that sched scan results are reported
* via wl_inform_single_bss in the required format. Escan does require the
* scan request in the form of cfg80211_scan_request. For timebeing, create
* cfg80211_scan_request one out of the received PNO event.
*/
static s32
brcmf_notify_sched_scan_results(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_pno_net_info_le *netinfo, *netinfo_start;
struct cfg80211_scan_request *request = NULL;
struct wiphy *wiphy = cfg_to_wiphy(cfg);
int i, err = 0;
struct brcmf_pno_scanresults_le *pfn_result;
u32 bucket_map;
u32 result_count;
u32 status;
u32 datalen;
brcmf_dbg(SCAN, "Enter\n");
if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {
brcmf_dbg(SCAN, "Event data to small. Ignore\n");
return 0;
}
if (e->event_code == BRCMF_E_PFN_NET_LOST) {
brcmf_dbg(SCAN, "PFN NET LOST event. Do Nothing\n");
return 0;
}
pfn_result = (struct brcmf_pno_scanresults_le *)data;
result_count = le32_to_cpu(pfn_result->count);
status = le32_to_cpu(pfn_result->status);
/* PFN event is limited to fit 512 bytes so we may get
* multiple NET_FOUND events. For now place a warning here.
*/
WARN_ON(status != BRCMF_PNO_SCAN_COMPLETE);
brcmf_dbg(SCAN, "PFN NET FOUND event. count: %d\n", result_count);
if (!result_count) {
brcmf_err("FALSE PNO Event. (pfn_count == 0)\n");
goto out_err;
}
netinfo_start = brcmf_get_netinfo_array(pfn_result);
datalen = e->datalen - ((void *)netinfo_start - (void *)pfn_result);
if (datalen < result_count * sizeof(*netinfo)) {
brcmf_err("insufficient event data\n");
goto out_err;
}
request = brcmf_alloc_internal_escan_request(wiphy,
result_count);
if (!request) {
err = -ENOMEM;
goto out_err;
}
bucket_map = 0;
for (i = 0; i < result_count; i++) {
netinfo = &netinfo_start[i];
if (netinfo->SSID_len > IEEE80211_MAX_SSID_LEN)
netinfo->SSID_len = IEEE80211_MAX_SSID_LEN;
brcmf_dbg(SCAN, "SSID:%.32s Channel:%d\n",
netinfo->SSID, netinfo->channel);
bucket_map |= brcmf_pno_get_bucket_map(cfg->pno, netinfo);
err = brcmf_internal_escan_add_info(request,
netinfo->SSID,
netinfo->SSID_len,
netinfo->channel);
if (err)
goto out_err;
}
if (!bucket_map)
goto free_req;
err = brcmf_start_internal_escan(ifp, bucket_map, request);
if (!err)
goto free_req;
out_err:
cfg80211_sched_scan_stopped(wiphy, 0);
free_req:
kfree(request);
return err;
}
static int
brcmf_cfg80211_sched_scan_start(struct wiphy *wiphy,
struct net_device *ndev,
struct cfg80211_sched_scan_request *req)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
brcmf_dbg(SCAN, "Enter: n_match_sets=%d n_ssids=%d\n",
req->n_match_sets, req->n_ssids);
if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) {
brcmf_err("Scanning suppressed: status=%lu\n",
cfg->scan_status);
return -EAGAIN;
}
if (req->n_match_sets <= 0) {
brcmf_dbg(SCAN, "invalid number of matchsets specified: %d\n",
req->n_match_sets);
return -EINVAL;
}
return brcmf_pno_start_sched_scan(ifp, req);
}
static int brcmf_cfg80211_sched_scan_stop(struct wiphy *wiphy,
struct net_device *ndev, u64 reqid)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(SCAN, "enter\n");
brcmf_pno_stop_sched_scan(ifp, reqid);
if (cfg->int_escan_map)
brcmf_notify_escan_complete(cfg, ifp, true, true);
return 0;
}
static __always_inline void brcmf_delay(u32 ms)
{
if (ms < 1000 / HZ) {
cond_resched();
mdelay(ms);
} else {
msleep(ms);
}
}
static s32 brcmf_config_wowl_pattern(struct brcmf_if *ifp, u8 cmd[4],
u8 *pattern, u32 patternsize, u8 *mask,
u32 packet_offset)
{
struct brcmf_fil_wowl_pattern_le *filter;
u32 masksize;
u32 patternoffset;
u8 *buf;
u32 bufsize;
s32 ret;
masksize = (patternsize + 7) / 8;
patternoffset = sizeof(*filter) - sizeof(filter->cmd) + masksize;
bufsize = sizeof(*filter) + patternsize + masksize;
buf = kzalloc(bufsize, GFP_KERNEL);
if (!buf)
return -ENOMEM;
filter = (struct brcmf_fil_wowl_pattern_le *)buf;
memcpy(filter->cmd, cmd, 4);
filter->masksize = cpu_to_le32(masksize);
filter->offset = cpu_to_le32(packet_offset);
filter->patternoffset = cpu_to_le32(patternoffset);
filter->patternsize = cpu_to_le32(patternsize);
filter->type = cpu_to_le32(BRCMF_WOWL_PATTERN_TYPE_BITMAP);
if ((mask) && (masksize))
memcpy(buf + sizeof(*filter), mask, masksize);
if ((pattern) && (patternsize))
memcpy(buf + sizeof(*filter) + masksize, pattern, patternsize);
ret = brcmf_fil_iovar_data_set(ifp, "wowl_pattern", buf, bufsize);
kfree(buf);
return ret;
}
static s32
brcmf_wowl_nd_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_pno_scanresults_le *pfn_result;
struct brcmf_pno_net_info_le *netinfo;
brcmf_dbg(SCAN, "Enter\n");
if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {
brcmf_dbg(SCAN, "Event data to small. Ignore\n");
return 0;
}
pfn_result = (struct brcmf_pno_scanresults_le *)data;
if (e->event_code == BRCMF_E_PFN_NET_LOST) {
brcmf_dbg(SCAN, "PFN NET LOST event. Ignore\n");
return 0;
}
if (le32_to_cpu(pfn_result->count) < 1) {
brcmf_err("Invalid result count, expected 1 (%d)\n",
le32_to_cpu(pfn_result->count));
return -EINVAL;
}
netinfo = brcmf_get_netinfo_array(pfn_result);
memcpy(cfg->wowl.nd->ssid.ssid, netinfo->SSID, netinfo->SSID_len);
cfg->wowl.nd->ssid.ssid_len = netinfo->SSID_len;
cfg->wowl.nd->n_channels = 1;
cfg->wowl.nd->channels[0] =
ieee80211_channel_to_frequency(netinfo->channel,
netinfo->channel <= CH_MAX_2G_CHANNEL ?
NL80211_BAND_2GHZ : NL80211_BAND_5GHZ);
cfg->wowl.nd_info->n_matches = 1;
cfg->wowl.nd_info->matches[0] = cfg->wowl.nd;
/* Inform (the resume task) that the net detect information was recvd */
cfg->wowl.nd_data_completed = true;
wake_up(&cfg->wowl.nd_data_wait);
return 0;
}
#ifdef CONFIG_PM
static void brcmf_report_wowl_wakeind(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_wowl_wakeind_le wake_ind_le;
struct cfg80211_wowlan_wakeup wakeup_data;
struct cfg80211_wowlan_wakeup *wakeup;
u32 wakeind;
s32 err;
int timeout;
err = brcmf_fil_iovar_data_get(ifp, "wowl_wakeind", &wake_ind_le,
sizeof(wake_ind_le));
if (err) {
brcmf_err("Get wowl_wakeind failed, err = %d\n", err);
return;
}
wakeind = le32_to_cpu(wake_ind_le.ucode_wakeind);
if (wakeind & (BRCMF_WOWL_MAGIC | BRCMF_WOWL_DIS | BRCMF_WOWL_BCN |
BRCMF_WOWL_RETR | BRCMF_WOWL_NET |
BRCMF_WOWL_PFN_FOUND)) {
wakeup = &wakeup_data;
memset(&wakeup_data, 0, sizeof(wakeup_data));
wakeup_data.pattern_idx = -1;
if (wakeind & BRCMF_WOWL_MAGIC) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_MAGIC\n");
wakeup_data.magic_pkt = true;
}
if (wakeind & BRCMF_WOWL_DIS) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_DIS\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_BCN) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_BCN\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_RETR) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_RETR\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_NET) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_NET\n");
/* For now always map to pattern 0, no API to get
* correct information available at the moment.
*/
wakeup_data.pattern_idx = 0;
}
if (wakeind & BRCMF_WOWL_PFN_FOUND) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_PFN_FOUND\n");
timeout = wait_event_timeout(cfg->wowl.nd_data_wait,
cfg->wowl.nd_data_completed,
BRCMF_ND_INFO_TIMEOUT);
if (!timeout)
brcmf_err("No result for wowl net detect\n");
else
wakeup_data.net_detect = cfg->wowl.nd_info;
}
if (wakeind & BRCMF_WOWL_GTK_FAILURE) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_GTK_FAILURE\n");
wakeup_data.gtk_rekey_failure = true;
}
} else {
wakeup = NULL;
}
cfg80211_report_wowlan_wakeup(&ifp->vif->wdev, wakeup, GFP_KERNEL);
}
#else
static void brcmf_report_wowl_wakeind(struct wiphy *wiphy, struct brcmf_if *ifp)
{
}
#endif /* CONFIG_PM */
static s32 brcmf_cfg80211_resume(struct wiphy *wiphy)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
if (cfg->wowl.active) {
brcmf_report_wowl_wakeind(wiphy, ifp);
brcmf_fil_iovar_int_set(ifp, "wowl_clear", 0);
brcmf_config_wowl_pattern(ifp, "clr", NULL, 0, NULL, 0);
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, true);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM,
cfg->wowl.pre_pmmode);
cfg->wowl.active = false;
if (cfg->wowl.nd_enabled) {
brcmf_cfg80211_sched_scan_stop(cfg->wiphy, ifp->ndev, 0);
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_notify_sched_scan_results);
cfg->wowl.nd_enabled = false;
}
}
return 0;
}
static void brcmf_configure_wowl(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp,
struct cfg80211_wowlan *wowl)
{
u32 wowl_config;
struct brcmf_wowl_wakeind_le wowl_wakeind;
u32 i;
brcmf_dbg(TRACE, "Suspend, wowl config.\n");
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, false);
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_PM, &cfg->wowl.pre_pmmode);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, PM_MAX);
wowl_config = 0;
if (wowl->disconnect)
wowl_config = BRCMF_WOWL_DIS | BRCMF_WOWL_BCN | BRCMF_WOWL_RETR;
if (wowl->magic_pkt)
wowl_config |= BRCMF_WOWL_MAGIC;
if ((wowl->patterns) && (wowl->n_patterns)) {
wowl_config |= BRCMF_WOWL_NET;
for (i = 0; i < wowl->n_patterns; i++) {
brcmf_config_wowl_pattern(ifp, "add",
(u8 *)wowl->patterns[i].pattern,
wowl->patterns[i].pattern_len,
(u8 *)wowl->patterns[i].mask,
wowl->patterns[i].pkt_offset);
}
}
if (wowl->nd_config) {
brcmf_cfg80211_sched_scan_start(cfg->wiphy, ifp->ndev,
wowl->nd_config);
wowl_config |= BRCMF_WOWL_PFN_FOUND;
cfg->wowl.nd_data_completed = false;
cfg->wowl.nd_enabled = true;
/* Now reroute the event for PFN to the wowl function. */
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_wowl_nd_results);
}
if (wowl->gtk_rekey_failure)
wowl_config |= BRCMF_WOWL_GTK_FAILURE;
if (!test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
wowl_config |= BRCMF_WOWL_UNASSOC;
memcpy(&wowl_wakeind, "clear", 6);
brcmf_fil_iovar_data_set(ifp, "wowl_wakeind", &wowl_wakeind,
sizeof(wowl_wakeind));
brcmf_fil_iovar_int_set(ifp, "wowl", wowl_config);
brcmf_fil_iovar_int_set(ifp, "wowl_activate", 1);
brcmf_bus_wowl_config(cfg->pub->bus_if, true);
cfg->wowl.active = true;
}
static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy,
struct cfg80211_wowlan *wowl)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "Enter\n");
/* if the primary net_device is not READY there is nothing
* we can do but pray resume goes smoothly.
*/
if (!check_vif_up(ifp->vif))
goto exit;
/* Stop scheduled scan */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO))
brcmf_cfg80211_sched_scan_stop(wiphy, ndev, 0);
/* end any scanning */
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_abort_scanning(cfg);
if (wowl == NULL) {
brcmf_bus_wowl_config(cfg->pub->bus_if, false);
list_for_each_entry(vif, &cfg->vif_list, list) {
if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state))
continue;
/* While going to suspend if associated with AP
* disassociate from AP to save power while system is
* in suspended state
*/
brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED);
/* Make sure WPA_Supplicant receives all the event
* generated due to DISASSOC call to the fw to keep
* the state fw and WPA_Supplicant state consistent
*/
brcmf_delay(500);
}
/* Configure MPC */
brcmf_set_mpc(ifp, 1);
} else {
/* Configure WOWL paramaters */
brcmf_configure_wowl(cfg, ifp, wowl);
}
exit:
brcmf_dbg(TRACE, "Exit\n");
/* clear any scanning activity */
cfg->scan_status = 0;
return 0;
}
static __used s32
brcmf_update_pmklist(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp)
{
struct brcmf_pmk_list_le *pmk_list;
int i;
u32 npmk;
s32 err;
pmk_list = &cfg->pmk_list;
npmk = le32_to_cpu(pmk_list->npmk);
brcmf_dbg(CONN, "No of elements %d\n", npmk);
for (i = 0; i < npmk; i++)
brcmf_dbg(CONN, "PMK[%d]: %pM\n", i, &pmk_list->pmk[i].bssid);
err = brcmf_fil_iovar_data_set(ifp, "pmkid_info", pmk_list,
sizeof(*pmk_list));
return err;
}
static s32
brcmf_cfg80211_set_pmksa(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_pmksa *pmksa)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_pmksa *pmk = &cfg->pmk_list.pmk[0];
s32 err;
u32 npmk, i;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
npmk = le32_to_cpu(cfg->pmk_list.npmk);
for (i = 0; i < npmk; i++)
if (!memcmp(pmksa->bssid, pmk[i].bssid, ETH_ALEN))
break;
if (i < BRCMF_MAXPMKID) {
memcpy(pmk[i].bssid, pmksa->bssid, ETH_ALEN);
memcpy(pmk[i].pmkid, pmksa->pmkid, WLAN_PMKID_LEN);
if (i == npmk) {
npmk++;
cfg->pmk_list.npmk = cpu_to_le32(npmk);
}
} else {
brcmf_err("Too many PMKSA entries cached %d\n", npmk);
return -EINVAL;
}
brcmf_dbg(CONN, "set_pmksa - PMK bssid: %pM =\n", pmk[npmk].bssid);
for (i = 0; i < WLAN_PMKID_LEN; i += 4)
brcmf_dbg(CONN, "%02x %02x %02x %02x\n", pmk[npmk].pmkid[i],
pmk[npmk].pmkid[i + 1], pmk[npmk].pmkid[i + 2],
pmk[npmk].pmkid[i + 3]);
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_del_pmksa(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_pmksa *pmksa)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_pmksa *pmk = &cfg->pmk_list.pmk[0];
s32 err;
u32 npmk, i;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
brcmf_dbg(CONN, "del_pmksa - PMK bssid = %pM\n", pmksa->bssid);
npmk = le32_to_cpu(cfg->pmk_list.npmk);
for (i = 0; i < npmk; i++)
if (!memcmp(pmksa->bssid, pmk[i].bssid, ETH_ALEN))
break;
if ((npmk > 0) && (i < npmk)) {
for (; i < (npmk - 1); i++) {
memcpy(&pmk[i].bssid, &pmk[i + 1].bssid, ETH_ALEN);
memcpy(&pmk[i].pmkid, &pmk[i + 1].pmkid,
WLAN_PMKID_LEN);
}
memset(&pmk[i], 0, sizeof(*pmk));
cfg->pmk_list.npmk = cpu_to_le32(npmk - 1);
} else {
brcmf_err("Cache entry not found\n");
return -EINVAL;
}
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_flush_pmksa(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
memset(&cfg->pmk_list, 0, sizeof(cfg->pmk_list));
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_configure_opensecurity(struct brcmf_if *ifp)
{
s32 err;
/* set auth */
err = brcmf_fil_bsscfg_int_set(ifp, "auth", 0);
if (err < 0) {
brcmf_err("auth error %d\n", err);
return err;
}
/* set wsec */
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", 0);
if (err < 0) {
brcmf_err("wsec error %d\n", err);
return err;
}
/* set upper-layer auth */
err = brcmf_fil_bsscfg_int_set(ifp, "wpa_auth", WPA_AUTH_NONE);
if (err < 0) {
brcmf_err("wpa_auth error %d\n", err);
return err;
}
return 0;
}
static bool brcmf_valid_wpa_oui(u8 *oui, bool is_rsn_ie)
{
if (is_rsn_ie)
return (memcmp(oui, RSN_OUI, TLV_OUI_LEN) == 0);
return (memcmp(oui, WPA_OUI, TLV_OUI_LEN) == 0);
}
static s32
brcmf_configure_wpaie(struct brcmf_if *ifp,
const struct brcmf_vs_tlv *wpa_ie,
bool is_rsn_ie)
{
u32 auth = 0; /* d11 open authentication */
u16 count;
s32 err = 0;
s32 len;
u32 i;
u32 wsec;
u32 pval = 0;
u32 gval = 0;
u32 wpa_auth = 0;
u32 offset;
u8 *data;
u16 rsn_cap;
u32 wme_bss_disable;
u32 mfp;
brcmf_dbg(TRACE, "Enter\n");
if (wpa_ie == NULL)
goto exit;
len = wpa_ie->len + TLV_HDR_LEN;
data = (u8 *)wpa_ie;
offset = TLV_HDR_LEN;
if (!is_rsn_ie)
offset += VS_IE_FIXED_HDR_LEN;
else
offset += WPA_IE_VERSION_LEN;
/* check for multicast cipher suite */
if (offset + WPA_IE_MIN_OUI_LEN > len) {
err = -EINVAL;
brcmf_err("no multicast cipher suite\n");
goto exit;
}
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
/* pick up multicast cipher */
switch (data[offset]) {
case WPA_CIPHER_NONE:
gval = 0;
break;
case WPA_CIPHER_WEP_40:
case WPA_CIPHER_WEP_104:
gval = WEP_ENABLED;
break;
case WPA_CIPHER_TKIP:
gval = TKIP_ENABLED;
break;
case WPA_CIPHER_AES_CCM:
gval = AES_ENABLED;
break;
default:
err = -EINVAL;
brcmf_err("Invalid multi cast cipher info\n");
goto exit;
}
offset++;
/* walk thru unicast cipher list and pick up what we recognize */
count = data[offset] + (data[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN;
/* Check for unicast suite(s) */
if (offset + (WPA_IE_MIN_OUI_LEN * count) > len) {
err = -EINVAL;
brcmf_err("no unicast cipher suite\n");
goto exit;
}
for (i = 0; i < count; i++) {
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
switch (data[offset]) {
case WPA_CIPHER_NONE:
break;
case WPA_CIPHER_WEP_40:
case WPA_CIPHER_WEP_104:
pval |= WEP_ENABLED;
break;
case WPA_CIPHER_TKIP:
pval |= TKIP_ENABLED;
break;
case WPA_CIPHER_AES_CCM:
pval |= AES_ENABLED;
break;
default:
brcmf_err("Invalid unicast security info\n");
}
offset++;
}
/* walk thru auth management suite list and pick up what we recognize */
count = data[offset] + (data[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN;
/* Check for auth key management suite(s) */
if (offset + (WPA_IE_MIN_OUI_LEN * count) > len) {
err = -EINVAL;
brcmf_err("no auth key mgmt suite\n");
goto exit;
}
for (i = 0; i < count; i++) {
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
switch (data[offset]) {
case RSN_AKM_NONE:
brcmf_dbg(TRACE, "RSN_AKM_NONE\n");
wpa_auth |= WPA_AUTH_NONE;
break;
case RSN_AKM_UNSPECIFIED:
brcmf_dbg(TRACE, "RSN_AKM_UNSPECIFIED\n");
is_rsn_ie ? (wpa_auth |= WPA2_AUTH_UNSPECIFIED) :
(wpa_auth |= WPA_AUTH_UNSPECIFIED);
break;
case RSN_AKM_PSK:
brcmf_dbg(TRACE, "RSN_AKM_PSK\n");
is_rsn_ie ? (wpa_auth |= WPA2_AUTH_PSK) :
(wpa_auth |= WPA_AUTH_PSK);
break;
case RSN_AKM_SHA256_PSK:
brcmf_dbg(TRACE, "RSN_AKM_MFP_PSK\n");
wpa_auth |= WPA2_AUTH_PSK_SHA256;
break;
case RSN_AKM_SHA256_1X:
brcmf_dbg(TRACE, "RSN_AKM_MFP_1X\n");
wpa_auth |= WPA2_AUTH_1X_SHA256;
break;
default:
brcmf_err("Invalid key mgmt info\n");
}
offset++;
}
mfp = BRCMF_MFP_NONE;
if (is_rsn_ie) {
wme_bss_disable = 1;
if ((offset + RSN_CAP_LEN) <= len) {
rsn_cap = data[offset] + (data[offset + 1] << 8);
if (rsn_cap & RSN_CAP_PTK_REPLAY_CNTR_MASK)
wme_bss_disable = 0;
if (rsn_cap & RSN_CAP_MFPR_MASK) {
brcmf_dbg(TRACE, "MFP Required\n");
mfp = BRCMF_MFP_REQUIRED;
/* Firmware only supports mfp required in
* combination with WPA2_AUTH_PSK_SHA256 or
* WPA2_AUTH_1X_SHA256.
*/
if (!(wpa_auth & (WPA2_AUTH_PSK_SHA256 |
WPA2_AUTH_1X_SHA256))) {
err = -EINVAL;
goto exit;
}
/* Firmware has requirement that WPA2_AUTH_PSK/
* WPA2_AUTH_UNSPECIFIED be set, if SHA256 OUI
* is to be included in the rsn ie.
*/
if (wpa_auth & WPA2_AUTH_PSK_SHA256)
wpa_auth |= WPA2_AUTH_PSK;
else if (wpa_auth & WPA2_AUTH_1X_SHA256)
wpa_auth |= WPA2_AUTH_UNSPECIFIED;
} else if (rsn_cap & RSN_CAP_MFPC_MASK) {
brcmf_dbg(TRACE, "MFP Capable\n");
mfp = BRCMF_MFP_CAPABLE;
}
}
offset += RSN_CAP_LEN;
/* set wme_bss_disable to sync RSN Capabilities */
err = brcmf_fil_bsscfg_int_set(ifp, "wme_bss_disable",
wme_bss_disable);
if (err < 0) {
brcmf_err("wme_bss_disable error %d\n", err);
goto exit;
}
/* Skip PMKID cnt as it is know to be 0 for AP. */
offset += RSN_PMKID_COUNT_LEN;
/* See if there is BIP wpa suite left for MFP */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP) &&
((offset + WPA_IE_MIN_OUI_LEN) <= len)) {
err = brcmf_fil_bsscfg_data_set(ifp, "bip",
&data[offset],
WPA_IE_MIN_OUI_LEN);
if (err < 0) {
brcmf_err("bip error %d\n", err);
goto exit;
}
}
}
/* FOR WPS , set SES_OW_ENABLED */
wsec = (pval | gval | SES_OW_ENABLED);
/* set auth */
err = brcmf_fil_bsscfg_int_set(ifp, "auth", auth);
if (err < 0) {
brcmf_err("auth error %d\n", err);
goto exit;
}
/* set wsec */
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err < 0) {
brcmf_err("wsec error %d\n", err);
goto exit;
}
/* Configure MFP, this needs to go after wsec otherwise the wsec command
* will overwrite the values set by MFP
*/
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP)) {
err = brcmf_fil_bsscfg_int_set(ifp, "mfp", mfp);
if (err < 0) {
brcmf_err("mfp error %d\n", err);
goto exit;
}
}
/* set upper-layer auth */
err = brcmf_fil_bsscfg_int_set(ifp, "wpa_auth", wpa_auth);
if (err < 0) {
brcmf_err("wpa_auth error %d\n", err);
goto exit;
}
exit:
return err;
}
static s32
brcmf_parse_vndr_ies(const u8 *vndr_ie_buf, u32 vndr_ie_len,
struct parsed_vndr_ies *vndr_ies)
{
struct brcmf_vs_tlv *vndrie;
struct brcmf_tlv *ie;
struct parsed_vndr_ie_info *parsed_info;
s32 remaining_len;
remaining_len = (s32)vndr_ie_len;
memset(vndr_ies, 0, sizeof(*vndr_ies));
ie = (struct brcmf_tlv *)vndr_ie_buf;
while (ie) {
if (ie->id != WLAN_EID_VENDOR_SPECIFIC)
goto next;
vndrie = (struct brcmf_vs_tlv *)ie;
/* len should be bigger than OUI length + one */
if (vndrie->len < (VS_IE_FIXED_HDR_LEN - TLV_HDR_LEN + 1)) {
brcmf_err("invalid vndr ie. length is too small %d\n",
vndrie->len);
goto next;
}
/* if wpa or wme ie, do not add ie */
if (!memcmp(vndrie->oui, (u8 *)WPA_OUI, TLV_OUI_LEN) &&
((vndrie->oui_type == WPA_OUI_TYPE) ||
(vndrie->oui_type == WME_OUI_TYPE))) {
brcmf_dbg(TRACE, "Found WPA/WME oui. Do not add it\n");
goto next;
}
parsed_info = &vndr_ies->ie_info[vndr_ies->count];
/* save vndr ie information */
parsed_info->ie_ptr = (char *)vndrie;
parsed_info->ie_len = vndrie->len + TLV_HDR_LEN;
memcpy(&parsed_info->vndrie, vndrie, sizeof(*vndrie));
vndr_ies->count++;
brcmf_dbg(TRACE, "** OUI %02x %02x %02x, type 0x%02x\n",
parsed_info->vndrie.oui[0],
parsed_info->vndrie.oui[1],
parsed_info->vndrie.oui[2],
parsed_info->vndrie.oui_type);
if (vndr_ies->count >= VNDR_IE_PARSE_LIMIT)
break;
next:
remaining_len -= (ie->len + TLV_HDR_LEN);
if (remaining_len <= TLV_HDR_LEN)
ie = NULL;
else
ie = (struct brcmf_tlv *)(((u8 *)ie) + ie->len +
TLV_HDR_LEN);
}
return 0;
}
static u32
brcmf_vndr_ie(u8 *iebuf, s32 pktflag, u8 *ie_ptr, u32 ie_len, s8 *add_del_cmd)
{
strncpy(iebuf, add_del_cmd, VNDR_IE_CMD_LEN - 1);
iebuf[VNDR_IE_CMD_LEN - 1] = '\0';
put_unaligned_le32(1, &iebuf[VNDR_IE_COUNT_OFFSET]);
put_unaligned_le32(pktflag, &iebuf[VNDR_IE_PKTFLAG_OFFSET]);
memcpy(&iebuf[VNDR_IE_VSIE_OFFSET], ie_ptr, ie_len);
return ie_len + VNDR_IE_HDR_SIZE;
}
s32 brcmf_vif_set_mgmt_ie(struct brcmf_cfg80211_vif *vif, s32 pktflag,
const u8 *vndr_ie_buf, u32 vndr_ie_len)
{
struct brcmf_if *ifp;
struct vif_saved_ie *saved_ie;
s32 err = 0;
u8 *iovar_ie_buf;
u8 *curr_ie_buf;
u8 *mgmt_ie_buf = NULL;
int mgmt_ie_buf_len;
u32 *mgmt_ie_len;
u32 del_add_ie_buf_len = 0;
u32 total_ie_buf_len = 0;
u32 parsed_ie_buf_len = 0;
struct parsed_vndr_ies old_vndr_ies;
struct parsed_vndr_ies new_vndr_ies;
struct parsed_vndr_ie_info *vndrie_info;
s32 i;
u8 *ptr;
int remained_buf_len;
if (!vif)
return -ENODEV;
ifp = vif->ifp;
saved_ie = &vif->saved_ie;
brcmf_dbg(TRACE, "bsscfgidx %d, pktflag : 0x%02X\n", ifp->bsscfgidx,
pktflag);
iovar_ie_buf = kzalloc(WL_EXTRA_BUF_MAX, GFP_KERNEL);
if (!iovar_ie_buf)
return -ENOMEM;
curr_ie_buf = iovar_ie_buf;
switch (pktflag) {
case BRCMF_VNDR_IE_PRBREQ_FLAG:
mgmt_ie_buf = saved_ie->probe_req_ie;
mgmt_ie_len = &saved_ie->probe_req_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->probe_req_ie);
break;
case BRCMF_VNDR_IE_PRBRSP_FLAG:
mgmt_ie_buf = saved_ie->probe_res_ie;
mgmt_ie_len = &saved_ie->probe_res_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->probe_res_ie);
break;
case BRCMF_VNDR_IE_BEACON_FLAG:
mgmt_ie_buf = saved_ie->beacon_ie;
mgmt_ie_len = &saved_ie->beacon_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->beacon_ie);
break;
case BRCMF_VNDR_IE_ASSOCREQ_FLAG:
mgmt_ie_buf = saved_ie->assoc_req_ie;
mgmt_ie_len = &saved_ie->assoc_req_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->assoc_req_ie);
break;
default:
err = -EPERM;
brcmf_err("not suitable type\n");
goto exit;
}
if (vndr_ie_len > mgmt_ie_buf_len) {
err = -ENOMEM;
brcmf_err("extra IE size too big\n");
goto exit;
}
/* parse and save new vndr_ie in curr_ie_buff before comparing it */
if (vndr_ie_buf && vndr_ie_len && curr_ie_buf) {
ptr = curr_ie_buf;
brcmf_parse_vndr_ies(vndr_ie_buf, vndr_ie_len, &new_vndr_ies);
for (i = 0; i < new_vndr_ies.count; i++) {
vndrie_info = &new_vndr_ies.ie_info[i];
memcpy(ptr + parsed_ie_buf_len, vndrie_info->ie_ptr,
vndrie_info->ie_len);
parsed_ie_buf_len += vndrie_info->ie_len;
}
}
if (mgmt_ie_buf && *mgmt_ie_len) {
if (parsed_ie_buf_len && (parsed_ie_buf_len == *mgmt_ie_len) &&
(memcmp(mgmt_ie_buf, curr_ie_buf,
parsed_ie_buf_len) == 0)) {
brcmf_dbg(TRACE, "Previous mgmt IE equals to current IE\n");
goto exit;
}
/* parse old vndr_ie */
brcmf_parse_vndr_ies(mgmt_ie_buf, *mgmt_ie_len, &old_vndr_ies);
/* make a command to delete old ie */
for (i = 0; i < old_vndr_ies.count; i++) {
vndrie_info = &old_vndr_ies.ie_info[i];
brcmf_dbg(TRACE, "DEL ID : %d, Len: %d , OUI:%02x:%02x:%02x\n",
vndrie_info->vndrie.id,
vndrie_info->vndrie.len,
vndrie_info->vndrie.oui[0],
vndrie_info->vndrie.oui[1],
vndrie_info->vndrie.oui[2]);
del_add_ie_buf_len = brcmf_vndr_ie(curr_ie_buf, pktflag,
vndrie_info->ie_ptr,
vndrie_info->ie_len,
"del");
curr_ie_buf += del_add_ie_buf_len;
total_ie_buf_len += del_add_ie_buf_len;
}
}
*mgmt_ie_len = 0;
/* Add if there is any extra IE */
if (mgmt_ie_buf && parsed_ie_buf_len) {
ptr = mgmt_ie_buf;
remained_buf_len = mgmt_ie_buf_len;
/* make a command to add new ie */
for (i = 0; i < new_vndr_ies.count; i++) {
vndrie_info = &new_vndr_ies.ie_info[i];
/* verify remained buf size before copy data */
if (remained_buf_len < (vndrie_info->vndrie.len +
VNDR_IE_VSIE_OFFSET)) {
brcmf_err("no space in mgmt_ie_buf: len left %d",
remained_buf_len);
break;
}
remained_buf_len -= (vndrie_info->ie_len +
VNDR_IE_VSIE_OFFSET);
brcmf_dbg(TRACE, "ADDED ID : %d, Len: %d, OUI:%02x:%02x:%02x\n",
vndrie_info->vndrie.id,
vndrie_info->vndrie.len,
vndrie_info->vndrie.oui[0],
vndrie_info->vndrie.oui[1],
vndrie_info->vndrie.oui[2]);
del_add_ie_buf_len = brcmf_vndr_ie(curr_ie_buf, pktflag,
vndrie_info->ie_ptr,
vndrie_info->ie_len,
"add");
/* save the parsed IE in wl struct */
memcpy(ptr + (*mgmt_ie_len), vndrie_info->ie_ptr,
vndrie_info->ie_len);
*mgmt_ie_len += vndrie_info->ie_len;
curr_ie_buf += del_add_ie_buf_len;
total_ie_buf_len += del_add_ie_buf_len;
}
}
if (total_ie_buf_len) {
err = brcmf_fil_bsscfg_data_set(ifp, "vndr_ie", iovar_ie_buf,
total_ie_buf_len);
if (err)
brcmf_err("vndr ie set error : %d\n", err);
}
exit:
kfree(iovar_ie_buf);
return err;
}
s32 brcmf_vif_clear_mgmt_ies(struct brcmf_cfg80211_vif *vif)
{
s32 pktflags[] = {
BRCMF_VNDR_IE_PRBREQ_FLAG,
BRCMF_VNDR_IE_PRBRSP_FLAG,
BRCMF_VNDR_IE_BEACON_FLAG
};
int i;
for (i = 0; i < ARRAY_SIZE(pktflags); i++)
brcmf_vif_set_mgmt_ie(vif, pktflags[i], NULL, 0);
memset(&vif->saved_ie, 0, sizeof(vif->saved_ie));
return 0;
}
static s32
brcmf_config_ap_mgmt_ie(struct brcmf_cfg80211_vif *vif,
struct cfg80211_beacon_data *beacon)
{
s32 err;
/* Set Beacon IEs to FW */
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_BEACON_FLAG,
beacon->tail, beacon->tail_len);
if (err) {
brcmf_err("Set Beacon IE Failed\n");
return err;
}
brcmf_dbg(TRACE, "Applied Vndr IEs for Beacon\n");
/* Set Probe Response IEs to FW */
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_PRBRSP_FLAG,
beacon->proberesp_ies,
beacon->proberesp_ies_len);
if (err)
brcmf_err("Set Probe Resp IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Probe Resp\n");
return err;
}
static s32
brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ap_settings *settings)
{
s32 ie_offset;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
const struct brcmf_tlv *ssid_ie;
const struct brcmf_tlv *country_ie;
struct brcmf_ssid_le ssid_le;
s32 err = -EPERM;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
struct brcmf_join_params join_params;
enum nl80211_iftype dev_role;
struct brcmf_fil_bss_enable_le bss_enable;
u16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef);
bool mbss;
int is_11d;
bool supports_11d;
brcmf_dbg(TRACE, "ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\n",
settings->chandef.chan->hw_value,
settings->chandef.center_freq1, settings->chandef.width,
settings->beacon_interval, settings->dtim_period);
brcmf_dbg(TRACE, "ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\n",
settings->ssid, settings->ssid_len, settings->auth_type,
settings->inactivity_timeout);
dev_role = ifp->vif->wdev.iftype;
mbss = ifp->vif->mbss;
/* store current 11d setting */
if (brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY,
&ifp->vif->is_11d)) {
is_11d = supports_11d = false;
} else {
country_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len,
WLAN_EID_COUNTRY);
is_11d = country_ie ? 1 : 0;
supports_11d = true;
}
memset(&ssid_le, 0, sizeof(ssid_le));
if (settings->ssid == NULL || settings->ssid_len == 0) {
ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN;
ssid_ie = brcmf_parse_tlvs(
(u8 *)&settings->beacon.head[ie_offset],
settings->beacon.head_len - ie_offset,
WLAN_EID_SSID);
if (!ssid_ie || ssid_ie->len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);
ssid_le.SSID_len = cpu_to_le32(ssid_ie->len);
brcmf_dbg(TRACE, "SSID is (%s) in Head\n", ssid_le.SSID);
} else {
memcpy(ssid_le.SSID, settings->ssid, settings->ssid_len);
ssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len);
}
if (!mbss) {
brcmf_set_mpc(ifp, 0);
brcmf_configure_arp_nd_offload(ifp, false);
}
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len, WLAN_EID_RSN);
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail,
settings->beacon.tail_len);
if ((wpa_ie != NULL || rsn_ie != NULL)) {
brcmf_dbg(TRACE, "WPA(2) IE is found\n");
if (wpa_ie != NULL) {
/* WPA IE */
err = brcmf_configure_wpaie(ifp, wpa_ie, false);
if (err < 0)
goto exit;
} else {
struct brcmf_vs_tlv *tmp_ie;
tmp_ie = (struct brcmf_vs_tlv *)rsn_ie;
/* RSN IE */
err = brcmf_configure_wpaie(ifp, tmp_ie, true);
if (err < 0)
goto exit;
}
} else {
brcmf_dbg(TRACE, "No WPA(2) IEs found\n");
brcmf_configure_opensecurity(ifp);
}
/* Parameters shared by all radio interfaces */
if (!mbss) {
if ((supports_11d) && (is_11d != ifp->vif->is_11d)) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
is_11d);
if (err < 0) {
brcmf_err("Regulatory Set Error, %d\n", err);
goto exit;
}
}
if (settings->beacon_interval) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD,
settings->beacon_interval);
if (err < 0) {
brcmf_err("Beacon Interval Set Error, %d\n",
err);
goto exit;
}
}
if (settings->dtim_period) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD,
settings->dtim_period);
if (err < 0) {
brcmf_err("DTIM Interval Set Error, %d\n", err);
goto exit;
}
}
if ((dev_role == NL80211_IFTYPE_AP) &&
((ifp->ifidx == 0) ||
!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0) {
brcmf_err("BRCMF_C_DOWN error %d\n", err);
goto exit;
}
brcmf_fil_iovar_int_set(ifp, "apsta", 0);
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1);
if (err < 0) {
brcmf_err("SET INFRA error %d\n", err);
goto exit;
}
} else if (WARN_ON(supports_11d && (is_11d != ifp->vif->is_11d))) {
/* Multiple-BSS should use same 11d configuration */
err = -EINVAL;
goto exit;
}
/* Interface specific setup */
if (dev_role == NL80211_IFTYPE_AP) {
if ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss))
brcmf_fil_iovar_int_set(ifp, "mbss", 1);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1);
if (err < 0) {
brcmf_err("setting AP mode failed %d\n", err);
goto exit;
}
if (!mbss) {
/* Firmware 10.x requires setting channel after enabling
* AP and before bringing interface up.
*/
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0) {
brcmf_err("BRCMF_C_UP error (%d)\n", err);
goto exit;
}
/* On DOWN the firmware removes the WEP keys, reconfigure
* them if they were set.
*/
brcmf_cfg80211_reconfigure_wep(ifp);
memset(&join_params, 0, sizeof(join_params));
/* join parameters starts with ssid */
memcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le));
/* create softap */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0) {
brcmf_err("SET SSID error (%d)\n", err);
goto exit;
}
if (settings->hidden_ssid) {
err = brcmf_fil_iovar_int_set(ifp, "closednet", 1);
if (err) {
brcmf_err("closednet error (%d)\n", err);
goto exit;
}
}
brcmf_dbg(TRACE, "AP mode configuration complete\n");
} else if (dev_role == NL80211_IFTYPE_P2P_GO) {
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
err = brcmf_fil_bsscfg_data_set(ifp, "ssid", &ssid_le,
sizeof(ssid_le));
if (err < 0) {
brcmf_err("setting ssid failed %d\n", err);
goto exit;
}
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(1);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0) {
brcmf_err("bss_enable config failed %d\n", err);
goto exit;
}
brcmf_dbg(TRACE, "GO mode configuration complete\n");
} else {
WARN_ON(1);
}
brcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon);
set_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, true);
exit:
if ((err) && (!mbss)) {
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
}
return err;
}
static int brcmf_cfg80211_stop_ap(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
struct brcmf_fil_bss_enable_le bss_enable;
struct brcmf_join_params join_params;
brcmf_dbg(TRACE, "Enter\n");
if (ifp->vif->wdev.iftype == NL80211_IFTYPE_AP) {
/* Due to most likely deauths outstanding we sleep */
/* first to make sure they get processed by fw. */
msleep(400);
if (ifp->vif->mbss) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
return err;
}
/* First BSS doesn't get a full reset */
if (ifp->bsscfgidx == 0)
brcmf_fil_iovar_int_set(ifp, "closednet", 0);
memset(&join_params, 0, sizeof(join_params));
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0)
brcmf_err("SET SSID error (%d)\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0)
brcmf_err("BRCMF_C_DOWN error %d\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 0);
if (err < 0)
brcmf_err("setting AP mode failed %d\n", err);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS))
brcmf_fil_iovar_int_set(ifp, "mbss", 0);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
ifp->vif->is_11d);
/* Bring device back up so it can be used again */
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0)
brcmf_err("BRCMF_C_UP error %d\n", err);
brcmf_vif_clear_mgmt_ies(ifp->vif);
} else {
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(0);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0)
brcmf_err("bss_enable config failed %d\n", err);
}
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
clear_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, false);
return err;
}
static s32
brcmf_cfg80211_change_beacon(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_beacon_data *info)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter\n");
err = brcmf_config_ap_mgmt_ie(ifp->vif, info);
return err;
}
static int
brcmf_cfg80211_del_station(struct wiphy *wiphy, struct net_device *ndev,
struct station_del_parameters *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_scb_val_le scbval;
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
if (!params->mac)
return -EFAULT;
brcmf_dbg(TRACE, "Enter %pM\n", params->mac);
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
ifp = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->ifp;
if (!check_vif_up(ifp->vif))
return -EIO;
memcpy(&scbval.ea, params->mac, ETH_ALEN);
scbval.val = cpu_to_le32(params->reason_code);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCB_DEAUTHENTICATE_FOR_REASON,
&scbval, sizeof(scbval));
if (err)
brcmf_err("SCB_DEAUTHENTICATE_FOR_REASON failed %d\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static int
brcmf_cfg80211_change_station(struct wiphy *wiphy, struct net_device *ndev,
const u8 *mac, struct station_parameters *params)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter, MAC %pM, mask 0x%04x set 0x%04x\n", mac,
params->sta_flags_mask, params->sta_flags_set);
/* Ignore all 00 MAC */
if (is_zero_ether_addr(mac))
return 0;
if (!(params->sta_flags_mask & BIT(NL80211_STA_FLAG_AUTHORIZED)))
return 0;
if (params->sta_flags_set & BIT(NL80211_STA_FLAG_AUTHORIZED))
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SCB_AUTHORIZE,
(void *)mac, ETH_ALEN);
else
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SCB_DEAUTHORIZE,
(void *)mac, ETH_ALEN);
if (err < 0)
brcmf_err("Setting SCB (de-)authorize failed, %d\n", err);
return err;
}
static void
brcmf_cfg80211_mgmt_frame_register(struct wiphy *wiphy,
struct wireless_dev *wdev,
u16 frame_type, bool reg)
{
struct brcmf_cfg80211_vif *vif;
u16 mgmt_type;
brcmf_dbg(TRACE, "Enter, frame_type %04x, reg=%d\n", frame_type, reg);
mgmt_type = (frame_type & IEEE80211_FCTL_STYPE) >> 4;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (reg)
vif->mgmt_rx_reg |= BIT(mgmt_type);
else
vif->mgmt_rx_reg &= ~BIT(mgmt_type);
}
static int
brcmf_cfg80211_mgmt_tx(struct wiphy *wiphy, struct wireless_dev *wdev,
struct cfg80211_mgmt_tx_params *params, u64 *cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct ieee80211_channel *chan = params->chan;
const u8 *buf = params->buf;
size_t len = params->len;
const struct ieee80211_mgmt *mgmt;
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
s32 ie_offset;
s32 ie_len;
struct brcmf_fil_action_frame_le *action_frame;
struct brcmf_fil_af_params_le *af_params;
bool ack;
s32 chan_nr;
u32 freq;
brcmf_dbg(TRACE, "Enter\n");
*cookie = 0;
mgmt = (const struct ieee80211_mgmt *)buf;
if (!ieee80211_is_mgmt(mgmt->frame_control)) {
brcmf_err("Driver only allows MGMT packet type\n");
return -EPERM;
}
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
/* Right now the only reason to get a probe response */
/* is for p2p listen response or for p2p GO from */
/* wpa_supplicant. Unfortunately the probe is send */
/* on primary ndev, while dongle wants it on the p2p */
/* vif. Since this is only reason for a probe */
/* response to be sent, the vif is taken from cfg. */
/* If ever desired to send proberesp for non p2p */
/* response then data should be checked for */
/* "DIRECT-". Note in future supplicant will take */
/* dedicated p2p wdev to do this and then this 'hack'*/
/* is not needed anymore. */
ie_offset = DOT11_MGMT_HDR_LEN +
DOT11_BCN_PRB_FIXED_LEN;
ie_len = len - ie_offset;
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
err = brcmf_vif_set_mgmt_ie(vif,
BRCMF_VNDR_IE_PRBRSP_FLAG,
&buf[ie_offset],
ie_len);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, true,
GFP_KERNEL);
} else if (ieee80211_is_action(mgmt->frame_control)) {
af_params = kzalloc(sizeof(*af_params), GFP_KERNEL);
if (af_params == NULL) {
brcmf_err("unable to allocate frame\n");
err = -ENOMEM;
goto exit;
}
action_frame = &af_params->action_frame;
/* Add the packet Id */
action_frame->packet_id = cpu_to_le32(*cookie);
/* Add BSSID */
memcpy(&action_frame->da[0], &mgmt->da[0], ETH_ALEN);
memcpy(&af_params->bssid[0], &mgmt->bssid[0], ETH_ALEN);
/* Add the length exepted for 802.11 header */
action_frame->len = cpu_to_le16(len - DOT11_MGMT_HDR_LEN);
/* Add the channel. Use the one specified as parameter if any or
* the current one (got from the firmware) otherwise
*/
if (chan)
freq = chan->center_freq;
else
brcmf_fil_cmd_int_get(vif->ifp, BRCMF_C_GET_CHANNEL,
&freq);
chan_nr = ieee80211_frequency_to_channel(freq);
af_params->channel = cpu_to_le32(chan_nr);
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
brcmf_dbg(TRACE, "Action frame, cookie=%lld, len=%d, freq=%d\n",
*cookie, le16_to_cpu(action_frame->len), freq);
ack = brcmf_p2p_send_action_frame(cfg, cfg_to_ndev(cfg),
af_params);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, ack,
GFP_KERNEL);
kfree(af_params);
} else {
brcmf_dbg(TRACE, "Unhandled, fc=%04x!!\n", mgmt->frame_control);
brcmf_dbg_hex_dump(true, buf, len, "payload, len=%zu\n", len);
}
exit:
return err;
}
static int
brcmf_cfg80211_cancel_remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
int err = 0;
brcmf_dbg(TRACE, "Enter p2p listen cancel\n");
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
if (vif == NULL) {
brcmf_err("No p2p device available for probe response\n");
err = -ENODEV;
goto exit;
}
brcmf_p2p_cancel_remain_on_channel(vif->ifp);
exit:
return err;
}
static int brcmf_cfg80211_get_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct cfg80211_chan_def *chandef)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = wdev->netdev;
struct brcmf_if *ifp;
struct brcmu_chan ch;
enum nl80211_band band = 0;
enum nl80211_chan_width width = 0;
u32 chanspec;
int freq, err;
if (!ndev)
return -ENODEV;
ifp = netdev_priv(ndev);
err = brcmf_fil_iovar_int_get(ifp, "chanspec", &chanspec);
if (err) {
brcmf_err("chanspec failed (%d)\n", err);
return err;
}
ch.chspec = chanspec;
cfg->d11inf.decchspec(&ch);
switch (ch.band) {
case BRCMU_CHAN_BAND_2G:
band = NL80211_BAND_2GHZ;
break;
case BRCMU_CHAN_BAND_5G:
band = NL80211_BAND_5GHZ;
break;
}
switch (ch.bw) {
case BRCMU_CHAN_BW_80:
width = NL80211_CHAN_WIDTH_80;
break;
case BRCMU_CHAN_BW_40:
width = NL80211_CHAN_WIDTH_40;
break;
case BRCMU_CHAN_BW_20:
width = NL80211_CHAN_WIDTH_20;
break;
case BRCMU_CHAN_BW_80P80:
width = NL80211_CHAN_WIDTH_80P80;
break;
case BRCMU_CHAN_BW_160:
width = NL80211_CHAN_WIDTH_160;
break;
}
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band);
chandef->chan = ieee80211_get_channel(wiphy, freq);
chandef->width = width;
chandef->center_freq1 = ieee80211_channel_to_frequency(ch.chnum, band);
chandef->center_freq2 = 0;
return 0;
}
static int brcmf_cfg80211_crit_proto_start(struct wiphy *wiphy,
struct wireless_dev *wdev,
enum nl80211_crit_proto_id proto,
u16 duration)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
/* only DHCP support for now */
if (proto != NL80211_CRIT_PROTO_DHCP)
return -EINVAL;
/* suppress and abort scanning */
set_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
brcmf_abort_scanning(cfg);
return brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_DISABLED, duration);
}
static void brcmf_cfg80211_crit_proto_stop(struct wiphy *wiphy,
struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_ENABLED, 0);
clear_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
}
static s32
brcmf_notify_tdls_peer_event(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
switch (e->reason) {
case BRCMF_E_REASON_TDLS_PEER_DISCOVERED:
brcmf_dbg(TRACE, "TDLS Peer Discovered\n");
break;
case BRCMF_E_REASON_TDLS_PEER_CONNECTED:
brcmf_dbg(TRACE, "TDLS Peer Connected\n");
brcmf_proto_add_tdls_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
break;
case BRCMF_E_REASON_TDLS_PEER_DISCONNECTED:
brcmf_dbg(TRACE, "TDLS Peer Disconnected\n");
brcmf_proto_delete_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
break;
}
return 0;
}
static int brcmf_convert_nl80211_tdls_oper(enum nl80211_tdls_operation oper)
{
int ret;
switch (oper) {
case NL80211_TDLS_DISCOVERY_REQ:
ret = BRCMF_TDLS_MANUAL_EP_DISCOVERY;
break;
case NL80211_TDLS_SETUP:
ret = BRCMF_TDLS_MANUAL_EP_CREATE;
break;
case NL80211_TDLS_TEARDOWN:
ret = BRCMF_TDLS_MANUAL_EP_DELETE;
break;
default:
brcmf_err("unsupported operation: %d\n", oper);
ret = -EOPNOTSUPP;
}
return ret;
}
static int brcmf_cfg80211_tdls_oper(struct wiphy *wiphy,
struct net_device *ndev, const u8 *peer,
enum nl80211_tdls_operation oper)
{
struct brcmf_if *ifp;
struct brcmf_tdls_iovar_le info;
int ret = 0;
ret = brcmf_convert_nl80211_tdls_oper(oper);
if (ret < 0)
return ret;
ifp = netdev_priv(ndev);
memset(&info, 0, sizeof(info));
info.mode = (u8)ret;
if (peer)
memcpy(info.ea, peer, ETH_ALEN);
ret = brcmf_fil_iovar_data_set(ifp, "tdls_endpoint",
&info, sizeof(info));
if (ret < 0)
brcmf_err("tdls_endpoint iovar failed: ret=%d\n", ret);
return ret;
}
static int
brcmf_cfg80211_update_conn_params(struct wiphy *wiphy,
struct net_device *ndev,
struct cfg80211_connect_params *sme,
u32 changed)
{
struct brcmf_if *ifp;
int err;
if (!(changed & UPDATE_ASSOC_IES))
return 0;
ifp = netdev_priv(ndev);
err = brcmf_vif_set_mgmt_ie(ifp->vif, BRCMF_VNDR_IE_ASSOCREQ_FLAG,
sme->ie, sme->ie_len);
if (err)
brcmf_err("Set Assoc REQ IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Assoc request\n");
return err;
}
#ifdef CONFIG_PM
static int
brcmf_cfg80211_set_rekey_data(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_gtk_rekey_data *gtk)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_gtk_keyinfo_le gtk_le;
int ret;
brcmf_dbg(TRACE, "Enter, bssidx=%d\n", ifp->bsscfgidx);
memcpy(gtk_le.kck, gtk->kck, sizeof(gtk_le.kck));
memcpy(gtk_le.kek, gtk->kek, sizeof(gtk_le.kek));
memcpy(gtk_le.replay_counter, gtk->replay_ctr,
sizeof(gtk_le.replay_counter));
ret = brcmf_fil_iovar_data_set(ifp, "gtk_key_info", >k_le,
sizeof(gtk_le));
if (ret < 0)
brcmf_err("gtk_key_info iovar failed: ret=%d\n", ret);
return ret;
}
#endif
static int brcmf_cfg80211_set_pmk(struct wiphy *wiphy, struct net_device *dev,
const struct cfg80211_pmk_conf *conf)
{
struct brcmf_if *ifp;
brcmf_dbg(TRACE, "enter\n");
/* expect using firmware supplicant for 1X */
ifp = netdev_priv(dev);
if (WARN_ON(ifp->vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_1X))
return -EINVAL;
return brcmf_set_pmk(ifp, conf->pmk, conf->pmk_len);
}
static int brcmf_cfg80211_del_pmk(struct wiphy *wiphy, struct net_device *dev,
const u8 *aa)
{
struct brcmf_if *ifp;
brcmf_dbg(TRACE, "enter\n");
ifp = netdev_priv(dev);
if (WARN_ON(ifp->vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_1X))
return -EINVAL;
return brcmf_set_pmk(ifp, NULL, 0);
}
static struct cfg80211_ops brcmf_cfg80211_ops = {
.add_virtual_intf = brcmf_cfg80211_add_iface,
.del_virtual_intf = brcmf_cfg80211_del_iface,
.change_virtual_intf = brcmf_cfg80211_change_iface,
.scan = brcmf_cfg80211_scan,
.set_wiphy_params = brcmf_cfg80211_set_wiphy_params,
.join_ibss = brcmf_cfg80211_join_ibss,
.leave_ibss = brcmf_cfg80211_leave_ibss,
.get_station = brcmf_cfg80211_get_station,
.dump_station = brcmf_cfg80211_dump_station,
.set_tx_power = brcmf_cfg80211_set_tx_power,
.get_tx_power = brcmf_cfg80211_get_tx_power,
.add_key = brcmf_cfg80211_add_key,
.del_key = brcmf_cfg80211_del_key,
.get_key = brcmf_cfg80211_get_key,
.set_default_key = brcmf_cfg80211_config_default_key,
.set_default_mgmt_key = brcmf_cfg80211_config_default_mgmt_key,
.set_power_mgmt = brcmf_cfg80211_set_power_mgmt,
.connect = brcmf_cfg80211_connect,
.disconnect = brcmf_cfg80211_disconnect,
.suspend = brcmf_cfg80211_suspend,
.resume = brcmf_cfg80211_resume,
.set_pmksa = brcmf_cfg80211_set_pmksa,
.del_pmksa = brcmf_cfg80211_del_pmksa,
.flush_pmksa = brcmf_cfg80211_flush_pmksa,
.start_ap = brcmf_cfg80211_start_ap,
.stop_ap = brcmf_cfg80211_stop_ap,
.change_beacon = brcmf_cfg80211_change_beacon,
.del_station = brcmf_cfg80211_del_station,
.change_station = brcmf_cfg80211_change_station,
.sched_scan_start = brcmf_cfg80211_sched_scan_start,
.sched_scan_stop = brcmf_cfg80211_sched_scan_stop,
.mgmt_frame_register = brcmf_cfg80211_mgmt_frame_register,
.mgmt_tx = brcmf_cfg80211_mgmt_tx,
.remain_on_channel = brcmf_p2p_remain_on_channel,
.cancel_remain_on_channel = brcmf_cfg80211_cancel_remain_on_channel,
.get_channel = brcmf_cfg80211_get_channel,
.start_p2p_device = brcmf_p2p_start_device,
.stop_p2p_device = brcmf_p2p_stop_device,
.crit_proto_start = brcmf_cfg80211_crit_proto_start,
.crit_proto_stop = brcmf_cfg80211_crit_proto_stop,
.tdls_oper = brcmf_cfg80211_tdls_oper,
.update_connect_params = brcmf_cfg80211_update_conn_params,
.set_pmk = brcmf_cfg80211_set_pmk,
.del_pmk = brcmf_cfg80211_del_pmk,
};
struct brcmf_cfg80211_vif *brcmf_alloc_vif(struct brcmf_cfg80211_info *cfg,
enum nl80211_iftype type)
{
struct brcmf_cfg80211_vif *vif_walk;
struct brcmf_cfg80211_vif *vif;
bool mbss;
brcmf_dbg(TRACE, "allocating virtual interface (size=%zu)\n",
sizeof(*vif));
vif = kzalloc(sizeof(*vif), GFP_KERNEL);
if (!vif)
return ERR_PTR(-ENOMEM);
vif->wdev.wiphy = cfg->wiphy;
vif->wdev.iftype = type;
brcmf_init_prof(&vif->profile);
if (type == NL80211_IFTYPE_AP) {
mbss = false;
list_for_each_entry(vif_walk, &cfg->vif_list, list) {
if (vif_walk->wdev.iftype == NL80211_IFTYPE_AP) {
mbss = true;
break;
}
}
vif->mbss = mbss;
}
list_add_tail(&vif->list, &cfg->vif_list);
return vif;
}
void brcmf_free_vif(struct brcmf_cfg80211_vif *vif)
{
list_del(&vif->list);
kfree(vif);
}
void brcmf_cfg80211_free_netdev(struct net_device *ndev)
{
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
ifp = netdev_priv(ndev);
vif = ifp->vif;
if (vif)
brcmf_free_vif(vif);
}
static bool brcmf_is_linkup(struct brcmf_cfg80211_vif *vif,
const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u32 status = e->status;
if (vif->profile.use_fwsup == BRCMF_PROFILE_FWSUP_PSK &&
event == BRCMF_E_PSK_SUP &&
status == BRCMF_E_STATUS_FWSUP_COMPLETED)
set_bit(BRCMF_VIF_STATUS_EAP_SUCCESS, &vif->sme_state);
if (event == BRCMF_E_SET_SSID && status == BRCMF_E_STATUS_SUCCESS) {
brcmf_dbg(CONN, "Processing set ssid\n");
memcpy(vif->profile.bssid, e->addr, ETH_ALEN);
if (vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_PSK)
return true;
set_bit(BRCMF_VIF_STATUS_ASSOC_SUCCESS, &vif->sme_state);
}
if (test_bit(BRCMF_VIF_STATUS_EAP_SUCCESS, &vif->sme_state) &&
test_bit(BRCMF_VIF_STATUS_ASSOC_SUCCESS, &vif->sme_state)) {
clear_bit(BRCMF_VIF_STATUS_EAP_SUCCESS, &vif->sme_state);
clear_bit(BRCMF_VIF_STATUS_ASSOC_SUCCESS, &vif->sme_state);
return true;
}
return false;
}
static bool brcmf_is_linkdown(const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u16 flags = e->flags;
if ((event == BRCMF_E_DEAUTH) || (event == BRCMF_E_DEAUTH_IND) ||
(event == BRCMF_E_DISASSOC_IND) ||
((event == BRCMF_E_LINK) && (!(flags & BRCMF_EVENT_MSG_LINK)))) {
brcmf_dbg(CONN, "Processing link down\n");
return true;
}
return false;
}
static bool brcmf_is_nonetwork(struct brcmf_cfg80211_info *cfg,
const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_LINK && status == BRCMF_E_STATUS_NO_NETWORKS) {
brcmf_dbg(CONN, "Processing Link %s & no network found\n",
e->flags & BRCMF_EVENT_MSG_LINK ? "up" : "down");
return true;
}
if (event == BRCMF_E_SET_SSID && status != BRCMF_E_STATUS_SUCCESS) {
brcmf_dbg(CONN, "Processing connecting & no network found\n");
return true;
}
if (event == BRCMF_E_PSK_SUP &&
status != BRCMF_E_STATUS_FWSUP_COMPLETED) {
brcmf_dbg(CONN, "Processing failed supplicant state: %u\n",
status);
return true;
}
return false;
}
static void brcmf_clear_assoc_ies(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
kfree(conn_info->req_ie);
conn_info->req_ie = NULL;
conn_info->req_ie_len = 0;
kfree(conn_info->resp_ie);
conn_info->resp_ie = NULL;
conn_info->resp_ie_len = 0;
}
static s32 brcmf_get_assoc_ies(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp)
{
struct brcmf_cfg80211_assoc_ielen_le *assoc_info;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
u32 req_len;
u32 resp_len;
s32 err = 0;
brcmf_clear_assoc_ies(cfg);
err = brcmf_fil_iovar_data_get(ifp, "assoc_info",
cfg->extra_buf, WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc info (%d)\n", err);
return err;
}
assoc_info =
(struct brcmf_cfg80211_assoc_ielen_le *)cfg->extra_buf;
req_len = le32_to_cpu(assoc_info->req_len);
resp_len = le32_to_cpu(assoc_info->resp_len);
if (req_len) {
err = brcmf_fil_iovar_data_get(ifp, "assoc_req_ies",
cfg->extra_buf,
WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc req (%d)\n", err);
return err;
}
conn_info->req_ie_len = req_len;
conn_info->req_ie =
kmemdup(cfg->extra_buf, conn_info->req_ie_len,
GFP_KERNEL);
} else {
conn_info->req_ie_len = 0;
conn_info->req_ie = NULL;
}
if (resp_len) {
err = brcmf_fil_iovar_data_get(ifp, "assoc_resp_ies",
cfg->extra_buf,
WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc resp (%d)\n", err);
return err;
}
conn_info->resp_ie_len = resp_len;
conn_info->resp_ie =
kmemdup(cfg->extra_buf, conn_info->resp_ie_len,
GFP_KERNEL);
} else {
conn_info->resp_ie_len = 0;
conn_info->resp_ie = NULL;
}
brcmf_dbg(CONN, "req len (%d) resp len (%d)\n",
conn_info->req_ie_len, conn_info->resp_ie_len);
return err;
}
static s32
brcmf_bss_roaming_done(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
const struct brcmf_event_msg *e)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel = NULL;
struct ieee80211_supported_band *band;
struct brcmf_bss_info_le *bi;
struct brcmu_chan ch;
struct cfg80211_roam_info roam_info = {};
u32 freq;
s32 err = 0;
u8 *buf;
brcmf_dbg(TRACE, "Enter\n");
brcmf_get_assoc_ies(cfg, ifp);
memcpy(profile->bssid, e->addr, ETH_ALEN);
brcmf_update_bss_info(cfg, ifp);
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
goto done;
}
/* data sent to dongle has to be little endian */
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX);
if (err)
goto done;
bi = (struct brcmf_bss_info_le *)(buf + 4);
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band->band);
notify_channel = ieee80211_get_channel(wiphy, freq);
done:
kfree(buf);
roam_info.channel = notify_channel;
roam_info.bssid = profile->bssid;
roam_info.req_ie = conn_info->req_ie;
roam_info.req_ie_len = conn_info->req_ie_len;
roam_info.resp_ie = conn_info->resp_ie;
roam_info.resp_ie_len = conn_info->resp_ie_len;
cfg80211_roamed(ndev, &roam_info, GFP_KERNEL);
brcmf_dbg(CONN, "Report roaming result\n");
set_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_bss_connect_done(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev, const struct brcmf_event_msg *e,
bool completed)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
struct cfg80211_connect_resp_params conn_params;
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state)) {
memset(&conn_params, 0, sizeof(conn_params));
if (completed) {
brcmf_get_assoc_ies(cfg, ifp);
brcmf_update_bss_info(cfg, ifp);
set_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state);
conn_params.status = WLAN_STATUS_SUCCESS;
} else {
conn_params.status = WLAN_STATUS_AUTH_TIMEOUT;
}
conn_params.bssid = profile->bssid;
conn_params.req_ie = conn_info->req_ie;
conn_params.req_ie_len = conn_info->req_ie_len;
conn_params.resp_ie = conn_info->resp_ie;
conn_params.resp_ie_len = conn_info->resp_ie_len;
cfg80211_connect_done(ndev, &conn_params, GFP_KERNEL);
brcmf_dbg(CONN, "Report connect result - connection %s\n",
completed ? "succeeded" : "failed");
}
brcmf_dbg(TRACE, "Exit\n");
return 0;
}
static s32
brcmf_notify_connect_status_ap(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
const struct brcmf_event_msg *e, void *data)
{
static int generation;
u32 event = e->event_code;
u32 reason = e->reason;
struct station_info sinfo;
brcmf_dbg(CONN, "event %s (%u), reason %d\n",
brcmf_fweh_event_name(event), event, reason);
if (event == BRCMF_E_LINK && reason == BRCMF_E_REASON_LINK_BSSCFG_DIS &&
ndev != cfg_to_ndev(cfg)) {
brcmf_dbg(CONN, "AP mode link down\n");
complete(&cfg->vif_disabled);
return 0;
}
if (((event == BRCMF_E_ASSOC_IND) || (event == BRCMF_E_REASSOC_IND)) &&
(reason == BRCMF_E_STATUS_SUCCESS)) {
memset(&sinfo, 0, sizeof(sinfo));
if (!data) {
brcmf_err("No IEs present in ASSOC/REASSOC_IND");
return -EINVAL;
}
sinfo.assoc_req_ies = data;
sinfo.assoc_req_ies_len = e->datalen;
generation++;
sinfo.generation = generation;
cfg80211_new_sta(ndev, e->addr, &sinfo, GFP_KERNEL);
} else if ((event == BRCMF_E_DISASSOC_IND) ||
(event == BRCMF_E_DEAUTH_IND) ||
(event == BRCMF_E_DEAUTH)) {
cfg80211_del_sta(ndev, e->addr, GFP_KERNEL);
}
return 0;
}
static s32
brcmf_notify_connect_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct net_device *ndev = ifp->ndev;
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct ieee80211_channel *chan;
s32 err = 0;
if ((e->event_code == BRCMF_E_DEAUTH) ||
(e->event_code == BRCMF_E_DEAUTH_IND) ||
(e->event_code == BRCMF_E_DISASSOC_IND) ||
((e->event_code == BRCMF_E_LINK) && (!e->flags))) {
brcmf_proto_delete_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
}
if (brcmf_is_apmode(ifp->vif)) {
err = brcmf_notify_connect_status_ap(cfg, ndev, e, data);
} else if (brcmf_is_linkup(ifp->vif, e)) {
brcmf_dbg(CONN, "Linkup\n");
if (brcmf_is_ibssmode(ifp->vif)) {
brcmf_inform_ibss(cfg, ndev, e->addr);
chan = ieee80211_get_channel(cfg->wiphy, cfg->channel);
memcpy(profile->bssid, e->addr, ETH_ALEN);
cfg80211_ibss_joined(ndev, e->addr, chan, GFP_KERNEL);
clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state);
set_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state);
} else
brcmf_bss_connect_done(cfg, ndev, e, true);
brcmf_net_setcarrier(ifp, true);
} else if (brcmf_is_linkdown(e)) {
brcmf_dbg(CONN, "Linkdown\n");
if (!brcmf_is_ibssmode(ifp->vif)) {
brcmf_bss_connect_done(cfg, ndev, e, false);
brcmf_link_down(ifp->vif,
brcmf_map_fw_linkdown_reason(e));
brcmf_init_prof(ndev_to_prof(ndev));
if (ndev != cfg_to_ndev(cfg))
complete(&cfg->vif_disabled);
brcmf_net_setcarrier(ifp, false);
}
} else if (brcmf_is_nonetwork(cfg, e)) {
if (brcmf_is_ibssmode(ifp->vif))
clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state);
else
brcmf_bss_connect_done(cfg, ndev, e, false);
}
return err;
}
static s32
brcmf_notify_roaming_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_ROAM && status == BRCMF_E_STATUS_SUCCESS) {
if (test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
brcmf_bss_roaming_done(cfg, ifp->ndev, e);
else
brcmf_bss_connect_done(cfg, ifp->ndev, e, true);
}
return 0;
}
static s32
brcmf_notify_mic_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
u16 flags = e->flags;
enum nl80211_key_type key_type;
if (flags & BRCMF_EVENT_MSG_GROUP)
key_type = NL80211_KEYTYPE_GROUP;
else
key_type = NL80211_KEYTYPE_PAIRWISE;
cfg80211_michael_mic_failure(ifp->ndev, (u8 *)&e->addr, key_type, -1,
NULL, GFP_KERNEL);
return 0;
}
static s32 brcmf_notify_vif_event(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_if_event *ifevent = (struct brcmf_if_event *)data;
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "Enter: action %u flags %u ifidx %u bsscfgidx %u\n",
ifevent->action, ifevent->flags, ifevent->ifidx,
ifevent->bsscfgidx);
spin_lock(&event->vif_event_lock);
event->action = ifevent->action;
vif = event->vif;
switch (ifevent->action) {
case BRCMF_E_IF_ADD:
/* waiting process may have timed out */
if (!cfg->vif_event.vif) {
spin_unlock(&event->vif_event_lock);
return -EBADF;
}
ifp->vif = vif;
vif->ifp = ifp;
if (ifp->ndev) {
vif->wdev.netdev = ifp->ndev;
ifp->ndev->ieee80211_ptr = &vif->wdev;
SET_NETDEV_DEV(ifp->ndev, wiphy_dev(cfg->wiphy));
}
spin_unlock(&event->vif_event_lock);
wake_up(&event->vif_wq);
return 0;
case BRCMF_E_IF_DEL:
spin_unlock(&event->vif_event_lock);
/* event may not be upon user request */
if (brcmf_cfg80211_vif_event_armed(cfg))
wake_up(&event->vif_wq);
return 0;
case BRCMF_E_IF_CHANGE:
spin_unlock(&event->vif_event_lock);
wake_up(&event->vif_wq);
return 0;
default:
spin_unlock(&event->vif_event_lock);
break;
}
return -EINVAL;
}
static void brcmf_init_conf(struct brcmf_cfg80211_conf *conf)
{
conf->frag_threshold = (u32)-1;
conf->rts_threshold = (u32)-1;
conf->retry_short = (u32)-1;
conf->retry_long = (u32)-1;
}
static void brcmf_register_event_handlers(struct brcmf_cfg80211_info *cfg)
{
brcmf_fweh_register(cfg->pub, BRCMF_E_LINK,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DEAUTH_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DEAUTH,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DISASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_ASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_REASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_ROAM,
brcmf_notify_roaming_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_MIC_ERROR,
brcmf_notify_mic_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_SET_SSID,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_notify_sched_scan_results);
brcmf_fweh_register(cfg->pub, BRCMF_E_IF,
brcmf_notify_vif_event);
brcmf_fweh_register(cfg->pub, BRCMF_E_P2P_PROBEREQ_MSG,
brcmf_p2p_notify_rx_mgmt_p2p_probereq);
brcmf_fweh_register(cfg->pub, BRCMF_E_P2P_DISC_LISTEN_COMPLETE,
brcmf_p2p_notify_listen_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_RX,
brcmf_p2p_notify_action_frame_rx);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_COMPLETE,
brcmf_p2p_notify_action_tx_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_OFF_CHAN_COMPLETE,
brcmf_p2p_notify_action_tx_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_PSK_SUP,
brcmf_notify_connect_status);
}
static void brcmf_deinit_priv_mem(struct brcmf_cfg80211_info *cfg)
{
kfree(cfg->conf);
cfg->conf = NULL;
kfree(cfg->extra_buf);
cfg->extra_buf = NULL;
kfree(cfg->wowl.nd);
cfg->wowl.nd = NULL;
kfree(cfg->wowl.nd_info);
cfg->wowl.nd_info = NULL;
kfree(cfg->escan_info.escan_buf);
cfg->escan_info.escan_buf = NULL;
}
static s32 brcmf_init_priv_mem(struct brcmf_cfg80211_info *cfg)
{
cfg->conf = kzalloc(sizeof(*cfg->conf), GFP_KERNEL);
if (!cfg->conf)
goto init_priv_mem_out;
cfg->extra_buf = kzalloc(WL_EXTRA_BUF_MAX, GFP_KERNEL);
if (!cfg->extra_buf)
goto init_priv_mem_out;
cfg->wowl.nd = kzalloc(sizeof(*cfg->wowl.nd) + sizeof(u32), GFP_KERNEL);
if (!cfg->wowl.nd)
goto init_priv_mem_out;
cfg->wowl.nd_info = kzalloc(sizeof(*cfg->wowl.nd_info) +
sizeof(struct cfg80211_wowlan_nd_match *),
GFP_KERNEL);
if (!cfg->wowl.nd_info)
goto init_priv_mem_out;
cfg->escan_info.escan_buf = kzalloc(BRCMF_ESCAN_BUF_SIZE, GFP_KERNEL);
if (!cfg->escan_info.escan_buf)
goto init_priv_mem_out;
return 0;
init_priv_mem_out:
brcmf_deinit_priv_mem(cfg);
return -ENOMEM;
}
static s32 wl_init_priv(struct brcmf_cfg80211_info *cfg)
{
s32 err = 0;
cfg->scan_request = NULL;
cfg->pwr_save = true;
cfg->active_scan = true; /* we do active scan per default */
cfg->dongle_up = false; /* dongle is not up yet */
err = brcmf_init_priv_mem(cfg);
if (err)
return err;
brcmf_register_event_handlers(cfg);
mutex_init(&cfg->usr_sync);
brcmf_init_escan(cfg);
brcmf_init_conf(cfg->conf);
init_completion(&cfg->vif_disabled);
return err;
}
static void wl_deinit_priv(struct brcmf_cfg80211_info *cfg)
{
cfg->dongle_up = false; /* dongle down */
brcmf_abort_scanning(cfg);
brcmf_deinit_priv_mem(cfg);
}
static void init_vif_event(struct brcmf_cfg80211_vif_event *event)
{
init_waitqueue_head(&event->vif_wq);
spin_lock_init(&event->vif_event_lock);
}
static s32 brcmf_dongle_roam(struct brcmf_if *ifp)
{
s32 err;
u32 bcn_timeout;
__le32 roamtrigger[2];
__le32 roam_delta[2];
/* Configure beacon timeout value based upon roaming setting */
if (ifp->drvr->settings->roamoff)
bcn_timeout = BRCMF_DEFAULT_BCN_TIMEOUT_ROAM_OFF;
else
bcn_timeout = BRCMF_DEFAULT_BCN_TIMEOUT_ROAM_ON;
err = brcmf_fil_iovar_int_set(ifp, "bcn_timeout", bcn_timeout);
if (err) {
brcmf_err("bcn_timeout error (%d)\n", err);
goto roam_setup_done;
}
/* Enable/Disable built-in roaming to allow supplicant to take care of
* roaming.
*/
brcmf_dbg(INFO, "Internal Roaming = %s\n",
ifp->drvr->settings->roamoff ? "Off" : "On");
err = brcmf_fil_iovar_int_set(ifp, "roam_off",
ifp->drvr->settings->roamoff);
if (err) {
brcmf_err("roam_off error (%d)\n", err);
goto roam_setup_done;
}
roamtrigger[0] = cpu_to_le32(WL_ROAM_TRIGGER_LEVEL);
roamtrigger[1] = cpu_to_le32(BRCM_BAND_ALL);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_ROAM_TRIGGER,
(void *)roamtrigger, sizeof(roamtrigger));
if (err) {
brcmf_err("WLC_SET_ROAM_TRIGGER error (%d)\n", err);
goto roam_setup_done;
}
roam_delta[0] = cpu_to_le32(WL_ROAM_DELTA);
roam_delta[1] = cpu_to_le32(BRCM_BAND_ALL);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_ROAM_DELTA,
(void *)roam_delta, sizeof(roam_delta));
if (err) {
brcmf_err("WLC_SET_ROAM_DELTA error (%d)\n", err);
goto roam_setup_done;
}
roam_setup_done:
return err;
}
static s32
brcmf_dongle_scantime(struct brcmf_if *ifp)
{
s32 err = 0;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_CHANNEL_TIME,
BRCMF_SCAN_CHANNEL_TIME);
if (err) {
brcmf_err("Scan assoc time error (%d)\n", err);
goto dongle_scantime_out;
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_UNASSOC_TIME,
BRCMF_SCAN_UNASSOC_TIME);
if (err) {
brcmf_err("Scan unassoc time error (%d)\n", err);
goto dongle_scantime_out;
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_PASSIVE_TIME,
BRCMF_SCAN_PASSIVE_TIME);
if (err) {
brcmf_err("Scan passive time error (%d)\n", err);
goto dongle_scantime_out;
}
dongle_scantime_out:
return err;
}
static void brcmf_update_bw40_channel_flag(struct ieee80211_channel *channel,
struct brcmu_chan *ch)
{
u32 ht40_flag;
ht40_flag = channel->flags & IEEE80211_CHAN_NO_HT40;
if (ch->sb == BRCMU_CHAN_SB_U) {
if (ht40_flag == IEEE80211_CHAN_NO_HT40)
channel->flags &= ~IEEE80211_CHAN_NO_HT40;
channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
} else {
/* It should be one of
* IEEE80211_CHAN_NO_HT40 or
* IEEE80211_CHAN_NO_HT40PLUS
*/
channel->flags &= ~IEEE80211_CHAN_NO_HT40;
if (ht40_flag == IEEE80211_CHAN_NO_HT40)
channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
}
}
static int brcmf_construct_chaninfo(struct brcmf_cfg80211_info *cfg,
u32 bw_cap[])
{
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct ieee80211_supported_band *band;
struct ieee80211_channel *channel;
struct wiphy *wiphy;
struct brcmf_chanspec_list *list;
struct brcmu_chan ch;
int err;
u8 *pbuf;
u32 i, j;
u32 total;
u32 chaninfo;
pbuf = kzalloc(BRCMF_DCMD_MEDLEN, GFP_KERNEL);
if (pbuf == NULL)
return -ENOMEM;
list = (struct brcmf_chanspec_list *)pbuf;
err = brcmf_fil_iovar_data_get(ifp, "chanspecs", pbuf,
BRCMF_DCMD_MEDLEN);
if (err) {
brcmf_err("get chanspecs error (%d)\n", err);
goto fail_pbuf;
}
wiphy = cfg_to_wiphy(cfg);
band = wiphy->bands[NL80211_BAND_2GHZ];
if (band)
for (i = 0; i < band->n_channels; i++)
band->channels[i].flags = IEEE80211_CHAN_DISABLED;
band = wiphy->bands[NL80211_BAND_5GHZ];
if (band)
for (i = 0; i < band->n_channels; i++)
band->channels[i].flags = IEEE80211_CHAN_DISABLED;
total = le32_to_cpu(list->count);
for (i = 0; i < total; i++) {
ch.chspec = (u16)le32_to_cpu(list->element[i]);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G) {
band = wiphy->bands[NL80211_BAND_2GHZ];
} else if (ch.band == BRCMU_CHAN_BAND_5G) {
band = wiphy->bands[NL80211_BAND_5GHZ];
} else {
brcmf_err("Invalid channel Spec. 0x%x.\n", ch.chspec);
continue;
}
if (!band)
continue;
if (!(bw_cap[band->band] & WLC_BW_40MHZ_BIT) &&
ch.bw == BRCMU_CHAN_BW_40)
continue;
if (!(bw_cap[band->band] & WLC_BW_80MHZ_BIT) &&
ch.bw == BRCMU_CHAN_BW_80)
continue;
channel = NULL;
for (j = 0; j < band->n_channels; j++) {
if (band->channels[j].hw_value == ch.control_ch_num) {
channel = &band->channels[j];
break;
}
}
if (!channel) {
/* It seems firmware supports some channel we never
* considered. Something new in IEEE standard?
*/
brcmf_err("Ignoring unexpected firmware channel %d\n",
ch.control_ch_num);
continue;
}
if (channel->orig_flags & IEEE80211_CHAN_DISABLED)
continue;
/* assuming the chanspecs order is HT20,
* HT40 upper, HT40 lower, and VHT80.
*/
if (ch.bw == BRCMU_CHAN_BW_80) {
channel->flags &= ~IEEE80211_CHAN_NO_80MHZ;
} else if (ch.bw == BRCMU_CHAN_BW_40) {
brcmf_update_bw40_channel_flag(channel, &ch);
} else {
/* enable the channel and disable other bandwidths
* for now as mentioned order assure they are enabled
* for subsequent chanspecs.
*/
channel->flags = IEEE80211_CHAN_NO_HT40 |
IEEE80211_CHAN_NO_80MHZ;
ch.bw = BRCMU_CHAN_BW_20;
cfg->d11inf.encchspec(&ch);
chaninfo = ch.chspec;
err = brcmf_fil_bsscfg_int_get(ifp, "per_chan_info",
&chaninfo);
if (!err) {
if (chaninfo & WL_CHAN_RADAR)
channel->flags |=
(IEEE80211_CHAN_RADAR |
IEEE80211_CHAN_NO_IR);
if (chaninfo & WL_CHAN_PASSIVE)
channel->flags |=
IEEE80211_CHAN_NO_IR;
}
}
}
fail_pbuf:
kfree(pbuf);
return err;
}
static int brcmf_enable_bw40_2g(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct ieee80211_supported_band *band;
struct brcmf_fil_bwcap_le band_bwcap;
struct brcmf_chanspec_list *list;
u8 *pbuf;
u32 val;
int err;
struct brcmu_chan ch;
u32 num_chan;
int i, j;
/* verify support for bw_cap command */
val = WLC_BAND_5G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &val);
if (!err) {
/* only set 2G bandwidth using bw_cap command */
band_bwcap.band = cpu_to_le32(WLC_BAND_2G);
band_bwcap.bw_cap = cpu_to_le32(WLC_BW_CAP_40MHZ);
err = brcmf_fil_iovar_data_set(ifp, "bw_cap", &band_bwcap,
sizeof(band_bwcap));
} else {
brcmf_dbg(INFO, "fallback to mimo_bw_cap\n");
val = WLC_N_BW_40ALL;
err = brcmf_fil_iovar_int_set(ifp, "mimo_bw_cap", val);
}
if (!err) {
/* update channel info in 2G band */
pbuf = kzalloc(BRCMF_DCMD_MEDLEN, GFP_KERNEL);
if (pbuf == NULL)
return -ENOMEM;
ch.band = BRCMU_CHAN_BAND_2G;
ch.bw = BRCMU_CHAN_BW_40;
ch.sb = BRCMU_CHAN_SB_NONE;
ch.chnum = 0;
cfg->d11inf.encchspec(&ch);
/* pass encoded chanspec in query */
*(__le16 *)pbuf = cpu_to_le16(ch.chspec);
err = brcmf_fil_iovar_data_get(ifp, "chanspecs", pbuf,
BRCMF_DCMD_MEDLEN);
if (err) {
brcmf_err("get chanspecs error (%d)\n", err);
kfree(pbuf);
return err;
}
band = cfg_to_wiphy(cfg)->bands[NL80211_BAND_2GHZ];
list = (struct brcmf_chanspec_list *)pbuf;
num_chan = le32_to_cpu(list->count);
for (i = 0; i < num_chan; i++) {
ch.chspec = (u16)le32_to_cpu(list->element[i]);
cfg->d11inf.decchspec(&ch);
if (WARN_ON(ch.band != BRCMU_CHAN_BAND_2G))
continue;
if (WARN_ON(ch.bw != BRCMU_CHAN_BW_40))
continue;
for (j = 0; j < band->n_channels; j++) {
if (band->channels[j].hw_value == ch.control_ch_num)
break;
}
if (WARN_ON(j == band->n_channels))
continue;
brcmf_update_bw40_channel_flag(&band->channels[j], &ch);
}
kfree(pbuf);
}
return err;
}
static void brcmf_get_bwcap(struct brcmf_if *ifp, u32 bw_cap[])
{
u32 band, mimo_bwcap;
int err;
band = WLC_BAND_2G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &band);
if (!err) {
bw_cap[NL80211_BAND_2GHZ] = band;
band = WLC_BAND_5G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &band);
if (!err) {
bw_cap[NL80211_BAND_5GHZ] = band;
return;
}
WARN_ON(1);
return;
}
brcmf_dbg(INFO, "fallback to mimo_bw_cap info\n");
mimo_bwcap = 0;
err = brcmf_fil_iovar_int_get(ifp, "mimo_bw_cap", &mimo_bwcap);
if (err)
/* assume 20MHz if firmware does not give a clue */
mimo_bwcap = WLC_N_BW_20ALL;
switch (mimo_bwcap) {
case WLC_N_BW_40ALL:
bw_cap[NL80211_BAND_2GHZ] |= WLC_BW_40MHZ_BIT;
/* fall-thru */
case WLC_N_BW_20IN2G_40IN5G:
bw_cap[NL80211_BAND_5GHZ] |= WLC_BW_40MHZ_BIT;
/* fall-thru */
case WLC_N_BW_20ALL:
bw_cap[NL80211_BAND_2GHZ] |= WLC_BW_20MHZ_BIT;
bw_cap[NL80211_BAND_5GHZ] |= WLC_BW_20MHZ_BIT;
break;
default:
brcmf_err("invalid mimo_bw_cap value\n");
}
}
static void brcmf_update_ht_cap(struct ieee80211_supported_band *band,
u32 bw_cap[2], u32 nchain)
{
band->ht_cap.ht_supported = true;
if (bw_cap[band->band] & WLC_BW_40MHZ_BIT) {
band->ht_cap.cap |= IEEE80211_HT_CAP_SGI_40;
band->ht_cap.cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
band->ht_cap.cap |= IEEE80211_HT_CAP_SGI_20;
band->ht_cap.cap |= IEEE80211_HT_CAP_DSSSCCK40;
band->ht_cap.ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K;
band->ht_cap.ampdu_density = IEEE80211_HT_MPDU_DENSITY_16;
memset(band->ht_cap.mcs.rx_mask, 0xff, nchain);
band->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
}
static __le16 brcmf_get_mcs_map(u32 nchain, enum ieee80211_vht_mcs_support supp)
{
u16 mcs_map;
int i;
for (i = 0, mcs_map = 0xFFFF; i < nchain; i++)
mcs_map = (mcs_map << 2) | supp;
return cpu_to_le16(mcs_map);
}
static void brcmf_update_vht_cap(struct ieee80211_supported_band *band,
u32 bw_cap[2], u32 nchain, u32 txstreams,
u32 txbf_bfe_cap, u32 txbf_bfr_cap)
{
__le16 mcs_map;
/* not allowed in 2.4G band */
if (band->band == NL80211_BAND_2GHZ)
return;
band->vht_cap.vht_supported = true;
/* 80MHz is mandatory */
band->vht_cap.cap |= IEEE80211_VHT_CAP_SHORT_GI_80;
if (bw_cap[band->band] & WLC_BW_160MHZ_BIT) {
band->vht_cap.cap |= IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ;
band->vht_cap.cap |= IEEE80211_VHT_CAP_SHORT_GI_160;
}
/* all support 256-QAM */
mcs_map = brcmf_get_mcs_map(nchain, IEEE80211_VHT_MCS_SUPPORT_0_9);
band->vht_cap.vht_mcs.rx_mcs_map = mcs_map;
band->vht_cap.vht_mcs.tx_mcs_map = mcs_map;
/* Beamforming support information */
if (txbf_bfe_cap & BRCMF_TXBF_SU_BFE_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE;
if (txbf_bfe_cap & BRCMF_TXBF_MU_BFE_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE;
if (txbf_bfr_cap & BRCMF_TXBF_SU_BFR_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE;
if (txbf_bfr_cap & BRCMF_TXBF_MU_BFR_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE;
if ((txbf_bfe_cap || txbf_bfr_cap) && (txstreams > 1)) {
band->vht_cap.cap |=
(2 << IEEE80211_VHT_CAP_BEAMFORMEE_STS_SHIFT);
band->vht_cap.cap |= ((txstreams - 1) <<
IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_SHIFT);
band->vht_cap.cap |=
IEEE80211_VHT_CAP_VHT_LINK_ADAPTATION_VHT_MRQ_MFB;
}
}
static int brcmf_setup_wiphybands(struct wiphy *wiphy)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
u32 nmode = 0;
u32 vhtmode = 0;
u32 bw_cap[2] = { WLC_BW_20MHZ_BIT, WLC_BW_20MHZ_BIT };
u32 rxchain;
u32 nchain;
int err;
s32 i;
struct ieee80211_supported_band *band;
u32 txstreams = 0;
u32 txbf_bfe_cap = 0;
u32 txbf_bfr_cap = 0;
(void)brcmf_fil_iovar_int_get(ifp, "vhtmode", &vhtmode);
err = brcmf_fil_iovar_int_get(ifp, "nmode", &nmode);
if (err) {
brcmf_err("nmode error (%d)\n", err);
} else {
brcmf_get_bwcap(ifp, bw_cap);
}
brcmf_dbg(INFO, "nmode=%d, vhtmode=%d, bw_cap=(%d, %d)\n",
nmode, vhtmode, bw_cap[NL80211_BAND_2GHZ],
bw_cap[NL80211_BAND_5GHZ]);
err = brcmf_fil_iovar_int_get(ifp, "rxchain", &rxchain);
if (err) {
brcmf_err("rxchain error (%d)\n", err);
nchain = 1;
} else {
for (nchain = 0; rxchain; nchain++)
rxchain = rxchain & (rxchain - 1);
}
brcmf_dbg(INFO, "nchain=%d\n", nchain);
err = brcmf_construct_chaninfo(cfg, bw_cap);
if (err) {
brcmf_err("brcmf_construct_chaninfo failed (%d)\n", err);
return err;
}
if (vhtmode) {
(void)brcmf_fil_iovar_int_get(ifp, "txstreams", &txstreams);
(void)brcmf_fil_iovar_int_get(ifp, "txbf_bfe_cap",
&txbf_bfe_cap);
(void)brcmf_fil_iovar_int_get(ifp, "txbf_bfr_cap",
&txbf_bfr_cap);
}
wiphy = cfg_to_wiphy(cfg);
for (i = 0; i < ARRAY_SIZE(wiphy->bands); i++) {
band = wiphy->bands[i];
if (band == NULL)
continue;
if (nmode)
brcmf_update_ht_cap(band, bw_cap, nchain);
if (vhtmode)
brcmf_update_vht_cap(band, bw_cap, nchain, txstreams,
txbf_bfe_cap, txbf_bfr_cap);
}
return 0;
}
static const struct ieee80211_txrx_stypes
brcmf_txrx_stypes[NUM_NL80211_IFTYPES] = {
[NL80211_IFTYPE_STATION] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_CLIENT] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_GO] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4) |
BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_P2P_DEVICE] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
}
};
/**
* brcmf_setup_ifmodes() - determine interface modes and combinations.
*
* @wiphy: wiphy object.
* @ifp: interface object needed for feat module api.
*
* The interface modes and combinations are determined dynamically here
* based on firmware functionality.
*
* no p2p and no mbss:
*
* #STA <= 1, #AP <= 1, channels = 1, 2 total
*
* no p2p and mbss:
*
* #STA <= 1, #AP <= 1, channels = 1, 2 total
* #AP <= 4, matching BI, channels = 1, 4 total
*
* p2p, no mchan, and mbss:
*
* #STA <= 1, #P2P-DEV <= 1, #{P2P-CL, P2P-GO} <= 1, channels = 1, 3 total
* #STA <= 1, #P2P-DEV <= 1, #AP <= 1, #P2P-CL <= 1, channels = 1, 4 total
* #AP <= 4, matching BI, channels = 1, 4 total
*
* p2p, mchan, and mbss:
*
* #STA <= 1, #P2P-DEV <= 1, #{P2P-CL, P2P-GO} <= 1, channels = 2, 3 total
* #STA <= 1, #P2P-DEV <= 1, #AP <= 1, #P2P-CL <= 1, channels = 1, 4 total
* #AP <= 4, matching BI, channels = 1, 4 total
*/
static int brcmf_setup_ifmodes(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct ieee80211_iface_combination *combo = NULL;
struct ieee80211_iface_limit *c0_limits = NULL;
struct ieee80211_iface_limit *p2p_limits = NULL;
struct ieee80211_iface_limit *mbss_limits = NULL;
bool mbss, p2p;
int i, c, n_combos;
mbss = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS);
p2p = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_P2P);
n_combos = 1 + !!p2p + !!mbss;
combo = kcalloc(n_combos, sizeof(*combo), GFP_KERNEL);
if (!combo)
goto err;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP);
c = 0;
i = 0;
c0_limits = kcalloc(p2p ? 3 : 2, sizeof(*c0_limits), GFP_KERNEL);
if (!c0_limits)
goto err;
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_STATION);
if (p2p) {
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MCHAN))
combo[c].num_different_channels = 2;
wiphy->interface_modes |= BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_DEVICE);
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_P2P_DEVICE);
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO);
} else {
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_AP);
}
combo[c].num_different_channels = 1;
combo[c].max_interfaces = i;
combo[c].n_limits = i;
combo[c].limits = c0_limits;
if (p2p) {
c++;
i = 0;
p2p_limits = kcalloc(4, sizeof(*p2p_limits), GFP_KERNEL);
if (!p2p_limits)
goto err;
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_STATION);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_AP);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_P2P_CLIENT);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_P2P_DEVICE);
combo[c].num_different_channels = 1;
combo[c].max_interfaces = i;
combo[c].n_limits = i;
combo[c].limits = p2p_limits;
}
if (mbss) {
c++;
i = 0;
mbss_limits = kcalloc(1, sizeof(*mbss_limits), GFP_KERNEL);
if (!mbss_limits)
goto err;
mbss_limits[i].max = 4;
mbss_limits[i++].types = BIT(NL80211_IFTYPE_AP);
combo[c].beacon_int_infra_match = true;
combo[c].num_different_channels = 1;
combo[c].max_interfaces = 4;
combo[c].n_limits = i;
combo[c].limits = mbss_limits;
}
wiphy->n_iface_combinations = n_combos;
wiphy->iface_combinations = combo;
return 0;
err:
kfree(c0_limits);
kfree(p2p_limits);
kfree(mbss_limits);
kfree(combo);
return -ENOMEM;
}
#ifdef CONFIG_PM
static const struct wiphy_wowlan_support brcmf_wowlan_support = {
.flags = WIPHY_WOWLAN_MAGIC_PKT | WIPHY_WOWLAN_DISCONNECT,
.n_patterns = BRCMF_WOWL_MAXPATTERNS,
.pattern_max_len = BRCMF_WOWL_MAXPATTERNSIZE,
.pattern_min_len = 1,
.max_pkt_offset = 1500,
};
#endif
static void brcmf_wiphy_wowl_params(struct wiphy *wiphy, struct brcmf_if *ifp)
{
#ifdef CONFIG_PM
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct wiphy_wowlan_support *wowl;
wowl = kmemdup(&brcmf_wowlan_support, sizeof(brcmf_wowlan_support),
GFP_KERNEL);
if (!wowl) {
brcmf_err("only support basic wowlan features\n");
wiphy->wowlan = &brcmf_wowlan_support;
return;
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO)) {
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ND)) {
wowl->flags |= WIPHY_WOWLAN_NET_DETECT;
wowl->max_nd_match_sets = BRCMF_PNO_MAX_PFN_COUNT;
init_waitqueue_head(&cfg->wowl.nd_data_wait);
}
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK)) {
wowl->flags |= WIPHY_WOWLAN_SUPPORTS_GTK_REKEY;
wowl->flags |= WIPHY_WOWLAN_GTK_REKEY_FAILURE;
}
wiphy->wowlan = wowl;
#endif
}
static int brcmf_setup_wiphy(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct brcmf_pub *drvr = ifp->drvr;
const struct ieee80211_iface_combination *combo;
struct ieee80211_supported_band *band;
u16 max_interfaces = 0;
bool gscan;
__le32 bandlist[3];
u32 n_bands;
int err, i;
wiphy->max_scan_ssids = WL_NUM_SCAN_MAX;
wiphy->max_scan_ie_len = BRCMF_SCAN_IE_LEN_MAX;
wiphy->max_num_pmkids = BRCMF_MAXPMKID;
err = brcmf_setup_ifmodes(wiphy, ifp);
if (err)
return err;
for (i = 0, combo = wiphy->iface_combinations;
i < wiphy->n_iface_combinations; i++, combo++) {
max_interfaces = max(max_interfaces, combo->max_interfaces);
}
for (i = 0; i < max_interfaces && i < ARRAY_SIZE(drvr->addresses);
i++) {
u8 *addr = drvr->addresses[i].addr;
memcpy(addr, drvr->mac, ETH_ALEN);
if (i) {
addr[0] |= BIT(1);
addr[ETH_ALEN - 1] ^= i;
}
}
wiphy->addresses = drvr->addresses;
wiphy->n_addresses = i;
wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
wiphy->cipher_suites = brcmf_cipher_suites;
wiphy->n_cipher_suites = ARRAY_SIZE(brcmf_cipher_suites);
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
wiphy->n_cipher_suites--;
wiphy->bss_select_support = BIT(NL80211_BSS_SELECT_ATTR_RSSI) |
BIT(NL80211_BSS_SELECT_ATTR_BAND_PREF) |
BIT(NL80211_BSS_SELECT_ATTR_RSSI_ADJUST);
wiphy->flags |= WIPHY_FLAG_NETNS_OK |
WIPHY_FLAG_PS_ON_BY_DEFAULT |
WIPHY_FLAG_OFFCHAN_TX |
WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS))
wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
if (!ifp->drvr->settings->roamoff)
wiphy->flags |= WIPHY_FLAG_SUPPORTS_FW_ROAM;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_FWSUP)) {
wiphy_ext_feature_set(wiphy,
NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_PSK);
wiphy_ext_feature_set(wiphy,
NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_1X);
}
wiphy->mgmt_stypes = brcmf_txrx_stypes;
wiphy->max_remain_on_channel_duration = 5000;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO)) {
gscan = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_GSCAN);
brcmf_pno_wiphy_params(wiphy, gscan);
}
/* vendor commands/events support */
wiphy->vendor_commands = brcmf_vendor_cmds;
wiphy->n_vendor_commands = BRCMF_VNDR_CMDS_LAST - 1;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL))
brcmf_wiphy_wowl_params(wiphy, ifp);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BANDLIST, &bandlist,
sizeof(bandlist));
if (err) {
brcmf_err("could not obtain band info: err=%d\n", err);
return err;
}
/* first entry in bandlist is number of bands */
n_bands = le32_to_cpu(bandlist[0]);
for (i = 1; i <= n_bands && i < ARRAY_SIZE(bandlist); i++) {
if (bandlist[i] == cpu_to_le32(WLC_BAND_2G)) {
band = kmemdup(&__wl_band_2ghz, sizeof(__wl_band_2ghz),
GFP_KERNEL);
if (!band)
return -ENOMEM;
band->channels = kmemdup(&__wl_2ghz_channels,
sizeof(__wl_2ghz_channels),
GFP_KERNEL);
if (!band->channels) {
kfree(band);
return -ENOMEM;
}
band->n_channels = ARRAY_SIZE(__wl_2ghz_channels);
wiphy->bands[NL80211_BAND_2GHZ] = band;
}
if (bandlist[i] == cpu_to_le32(WLC_BAND_5G)) {
band = kmemdup(&__wl_band_5ghz, sizeof(__wl_band_5ghz),
GFP_KERNEL);
if (!band)
return -ENOMEM;
band->channels = kmemdup(&__wl_5ghz_channels,
sizeof(__wl_5ghz_channels),
GFP_KERNEL);
if (!band->channels) {
kfree(band);
return -ENOMEM;
}
band->n_channels = ARRAY_SIZE(__wl_5ghz_channels);
wiphy->bands[NL80211_BAND_5GHZ] = band;
}
}
wiphy_read_of_freq_limits(wiphy);
return 0;
}
static s32 brcmf_config_dongle(struct brcmf_cfg80211_info *cfg)
{
struct net_device *ndev;
struct wireless_dev *wdev;
struct brcmf_if *ifp;
s32 power_mode;
s32 err = 0;
if (cfg->dongle_up)
return err;
ndev = cfg_to_ndev(cfg);
wdev = ndev->ieee80211_ptr;
ifp = netdev_priv(ndev);
/* make sure RF is ready for work */
brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 0);
brcmf_dongle_scantime(ifp);
power_mode = cfg->pwr_save ? PM_FAST : PM_OFF;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, power_mode);
if (err)
goto default_conf_out;
brcmf_dbg(INFO, "power save set to %s\n",
(power_mode ? "enabled" : "disabled"));
err = brcmf_dongle_roam(ifp);
if (err)
goto default_conf_out;
err = brcmf_cfg80211_change_iface(wdev->wiphy, ndev, wdev->iftype,
NULL);
if (err)
goto default_conf_out;
brcmf_configure_arp_nd_offload(ifp, true);
cfg->dongle_up = true;
default_conf_out:
return err;
}
static s32 __brcmf_cfg80211_up(struct brcmf_if *ifp)
{
set_bit(BRCMF_VIF_STATUS_READY, &ifp->vif->sme_state);
return brcmf_config_dongle(ifp->drvr->config);
}
static s32 __brcmf_cfg80211_down(struct brcmf_if *ifp)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
/*
* While going down, if associated with AP disassociate
* from AP to save power
*/
if (check_vif_up(ifp->vif)) {
brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED);
/* Make sure WPA_Supplicant receives all the event
generated due to DISASSOC call to the fw to keep
the state fw and WPA_Supplicant state consistent
*/
brcmf_delay(500);
}
brcmf_abort_scanning(cfg);
clear_bit(BRCMF_VIF_STATUS_READY, &ifp->vif->sme_state);
return 0;
}
s32 brcmf_cfg80211_up(struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err = 0;
mutex_lock(&cfg->usr_sync);
err = __brcmf_cfg80211_up(ifp);
mutex_unlock(&cfg->usr_sync);
return err;
}
s32 brcmf_cfg80211_down(struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err = 0;
mutex_lock(&cfg->usr_sync);
err = __brcmf_cfg80211_down(ifp);
mutex_unlock(&cfg->usr_sync);
return err;
}
enum nl80211_iftype brcmf_cfg80211_get_iftype(struct brcmf_if *ifp)
{
struct wireless_dev *wdev = &ifp->vif->wdev;
return wdev->iftype;
}
bool brcmf_get_vif_state_any(struct brcmf_cfg80211_info *cfg,
unsigned long state)
{
struct brcmf_cfg80211_vif *vif;
list_for_each_entry(vif, &cfg->vif_list, list) {
if (test_bit(state, &vif->sme_state))
return true;
}
return false;
}
static inline bool vif_event_equals(struct brcmf_cfg80211_vif_event *event,
u8 action)
{
u8 evt_action;
spin_lock(&event->vif_event_lock);
evt_action = event->action;
spin_unlock(&event->vif_event_lock);
return evt_action == action;
}
void brcmf_cfg80211_arm_vif_event(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
spin_lock(&event->vif_event_lock);
event->vif = vif;
event->action = 0;
spin_unlock(&event->vif_event_lock);
}
bool brcmf_cfg80211_vif_event_armed(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
bool armed;
spin_lock(&event->vif_event_lock);
armed = event->vif != NULL;
spin_unlock(&event->vif_event_lock);
return armed;
}
int brcmf_cfg80211_wait_vif_event(struct brcmf_cfg80211_info *cfg,
u8 action, ulong timeout)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
return wait_event_timeout(event->vif_wq,
vif_event_equals(event, action), timeout);
}
static s32 brcmf_translate_country_code(struct brcmf_pub *drvr, char alpha2[2],
struct brcmf_fil_country_le *ccreq)
{
struct brcmfmac_pd_cc *country_codes;
struct brcmfmac_pd_cc_entry *cc;
s32 found_index;
int i;
country_codes = drvr->settings->country_codes;
if (!country_codes) {
brcmf_dbg(TRACE, "No country codes configured for device\n");
return -EINVAL;
}
if ((alpha2[0] == ccreq->country_abbrev[0]) &&
(alpha2[1] == ccreq->country_abbrev[1])) {
brcmf_dbg(TRACE, "Country code already set\n");
return -EAGAIN;
}
found_index = -1;
for (i = 0; i < country_codes->table_size; i++) {
cc = &country_codes->table[i];
if ((cc->iso3166[0] == '\0') && (found_index == -1))
found_index = i;
if ((cc->iso3166[0] == alpha2[0]) &&
(cc->iso3166[1] == alpha2[1])) {
found_index = i;
break;
}
}
if (found_index == -1) {
brcmf_dbg(TRACE, "No country code match found\n");
return -EINVAL;
}
memset(ccreq, 0, sizeof(*ccreq));
ccreq->rev = cpu_to_le32(country_codes->table[found_index].rev);
memcpy(ccreq->ccode, country_codes->table[found_index].cc,
BRCMF_COUNTRY_BUF_SZ);
ccreq->country_abbrev[0] = alpha2[0];
ccreq->country_abbrev[1] = alpha2[1];
ccreq->country_abbrev[2] = 0;
return 0;
}
static void brcmf_cfg80211_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *req)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_fil_country_le ccreq;
s32 err;
int i;
/* The country code gets set to "00" by default at boot, ignore */
if (req->alpha2[0] == '0' && req->alpha2[1] == '0')
return;
/* ignore non-ISO3166 country codes */
for (i = 0; i < sizeof(req->alpha2); i++)
if (req->alpha2[i] < 'A' || req->alpha2[i] > 'Z') {
brcmf_err("not an ISO3166 code (0x%02x 0x%02x)\n",
req->alpha2[0], req->alpha2[1]);
return;
}
brcmf_dbg(TRACE, "Enter: initiator=%d, alpha=%c%c\n", req->initiator,
req->alpha2[0], req->alpha2[1]);
err = brcmf_fil_iovar_data_get(ifp, "country", &ccreq, sizeof(ccreq));
if (err) {
brcmf_err("Country code iovar returned err = %d\n", err);
return;
}
err = brcmf_translate_country_code(ifp->drvr, req->alpha2, &ccreq);
if (err)
return;
err = brcmf_fil_iovar_data_set(ifp, "country", &ccreq, sizeof(ccreq));
if (err) {
brcmf_err("Firmware rejected country setting\n");
return;
}
brcmf_setup_wiphybands(wiphy);
}
static void brcmf_free_wiphy(struct wiphy *wiphy)
{
int i;
if (!wiphy)
return;
if (wiphy->iface_combinations) {
for (i = 0; i < wiphy->n_iface_combinations; i++)
kfree(wiphy->iface_combinations[i].limits);
}
kfree(wiphy->iface_combinations);
if (wiphy->bands[NL80211_BAND_2GHZ]) {
kfree(wiphy->bands[NL80211_BAND_2GHZ]->channels);
kfree(wiphy->bands[NL80211_BAND_2GHZ]);
}
if (wiphy->bands[NL80211_BAND_5GHZ]) {
kfree(wiphy->bands[NL80211_BAND_5GHZ]->channels);
kfree(wiphy->bands[NL80211_BAND_5GHZ]);
}
#if IS_ENABLED(CONFIG_PM)
if (wiphy->wowlan != &brcmf_wowlan_support)
kfree(wiphy->wowlan);
#endif
wiphy_free(wiphy);
}
struct brcmf_cfg80211_info *brcmf_cfg80211_attach(struct brcmf_pub *drvr,
struct device *busdev,
bool p2pdev_forced)
{
struct net_device *ndev = brcmf_get_ifp(drvr, 0)->ndev;
struct brcmf_cfg80211_info *cfg;
struct wiphy *wiphy;
struct cfg80211_ops *ops;
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
s32 err = 0;
s32 io_type;
u16 *cap = NULL;
if (!ndev) {
brcmf_err("ndev is invalid\n");
return NULL;
}
ops = kmemdup(&brcmf_cfg80211_ops, sizeof(*ops), GFP_KERNEL);
if (!ops)
return NULL;
ifp = netdev_priv(ndev);
#ifdef CONFIG_PM
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK))
ops->set_rekey_data = brcmf_cfg80211_set_rekey_data;
#endif
wiphy = wiphy_new(ops, sizeof(struct brcmf_cfg80211_info));
if (!wiphy) {
brcmf_err("Could not allocate wiphy device\n");
goto ops_out;
}
memcpy(wiphy->perm_addr, drvr->mac, ETH_ALEN);
set_wiphy_dev(wiphy, busdev);
cfg = wiphy_priv(wiphy);
cfg->wiphy = wiphy;
cfg->ops = ops;
cfg->pub = drvr;
init_vif_event(&cfg->vif_event);
INIT_LIST_HEAD(&cfg->vif_list);
vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_STATION);
if (IS_ERR(vif))
goto wiphy_out;
vif->ifp = ifp;
vif->wdev.netdev = ndev;
ndev->ieee80211_ptr = &vif->wdev;
SET_NETDEV_DEV(ndev, wiphy_dev(cfg->wiphy));
err = wl_init_priv(cfg);
if (err) {
brcmf_err("Failed to init iwm_priv (%d)\n", err);
brcmf_free_vif(vif);
goto wiphy_out;
}
ifp->vif = vif;
/* determine d11 io type before wiphy setup */
err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_VERSION, &io_type);
if (err) {
brcmf_err("Failed to get D11 version (%d)\n", err);
goto priv_out;
}
cfg->d11inf.io_type = (u8)io_type;
brcmu_d11_attach(&cfg->d11inf);
err = brcmf_setup_wiphy(wiphy, ifp);
if (err < 0)
goto priv_out;
brcmf_dbg(INFO, "Registering custom regulatory\n");
wiphy->reg_notifier = brcmf_cfg80211_reg_notifier;
wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
wiphy_apply_custom_regulatory(wiphy, &brcmf_regdom);
/* firmware defaults to 40MHz disabled in 2G band. We signal
* cfg80211 here that we do and have it decide we can enable
* it. But first check if device does support 2G operation.
*/
if (wiphy->bands[NL80211_BAND_2GHZ]) {
cap = &wiphy->bands[NL80211_BAND_2GHZ]->ht_cap.cap;
*cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
err = wiphy_register(wiphy);
if (err < 0) {
brcmf_err("Could not register wiphy device (%d)\n", err);
goto priv_out;
}
err = brcmf_setup_wiphybands(wiphy);
if (err) {
brcmf_err("Setting wiphy bands failed (%d)\n", err);
goto wiphy_unreg_out;
}
/* If cfg80211 didn't disable 40MHz HT CAP in wiphy_register(),
* setup 40MHz in 2GHz band and enable OBSS scanning.
*/
if (cap && (*cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40)) {
err = brcmf_enable_bw40_2g(cfg);
if (!err)
err = brcmf_fil_iovar_int_set(ifp, "obss_coex",
BRCMF_OBSS_COEX_AUTO);
else
*cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
/* p2p might require that "if-events" get processed by fweh. So
* activate the already registered event handlers now and activate
* the rest when initialization has completed. drvr->config needs to
* be assigned before activating events.
*/
drvr->config = cfg;
err = brcmf_fweh_activate_events(ifp);
if (err) {
brcmf_err("FWEH activation failed (%d)\n", err);
goto wiphy_unreg_out;
}
err = brcmf_p2p_attach(cfg, p2pdev_forced);
if (err) {
brcmf_err("P2P initialisation failed (%d)\n", err);
goto wiphy_unreg_out;
}
err = brcmf_btcoex_attach(cfg);
if (err) {
brcmf_err("BT-coex initialisation failed (%d)\n", err);
brcmf_p2p_detach(&cfg->p2p);
goto wiphy_unreg_out;
}
err = brcmf_pno_attach(cfg);
if (err) {
brcmf_err("PNO initialisation failed (%d)\n", err);
brcmf_btcoex_detach(cfg);
brcmf_p2p_detach(&cfg->p2p);
goto wiphy_unreg_out;
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS)) {
err = brcmf_fil_iovar_int_set(ifp, "tdls_enable", 1);
if (err) {
brcmf_dbg(INFO, "TDLS not enabled (%d)\n", err);
wiphy->flags &= ~WIPHY_FLAG_SUPPORTS_TDLS;
} else {
brcmf_fweh_register(cfg->pub, BRCMF_E_TDLS_PEER_EVENT,
brcmf_notify_tdls_peer_event);
}
}
/* (re-) activate FWEH event handling */
err = brcmf_fweh_activate_events(ifp);
if (err) {
brcmf_err("FWEH activation failed (%d)\n", err);
goto detach;
}
/* Fill in some of the advertised nl80211 supported features */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_SCAN_RANDOM_MAC)) {
wiphy->features |= NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR;
#ifdef CONFIG_PM
if (wiphy->wowlan &&
wiphy->wowlan->flags & WIPHY_WOWLAN_NET_DETECT)
wiphy->features |= NL80211_FEATURE_ND_RANDOM_MAC_ADDR;
#endif
}
return cfg;
detach:
brcmf_pno_detach(cfg);
brcmf_btcoex_detach(cfg);
brcmf_p2p_detach(&cfg->p2p);
wiphy_unreg_out:
wiphy_unregister(cfg->wiphy);
priv_out:
wl_deinit_priv(cfg);
brcmf_free_vif(vif);
ifp->vif = NULL;
wiphy_out:
brcmf_free_wiphy(wiphy);
ops_out:
kfree(ops);
return NULL;
}
void brcmf_cfg80211_detach(struct brcmf_cfg80211_info *cfg)
{
if (!cfg)
return;
brcmf_pno_detach(cfg);
brcmf_btcoex_detach(cfg);
wiphy_unregister(cfg->wiphy);
kfree(cfg->ops);
wl_deinit_priv(cfg);
brcmf_free_wiphy(cfg->wiphy);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3277_0 |
crossvul-cpp_data_bad_1826_0 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "jv.h"
#include "jv_dtoa.h"
#include "jv_unicode.h"
#include "jv_alloc.h"
#include "jv_dtoa.h"
typedef const char* presult;
#define TRY(x) do {presult msg__ = (x); if (msg__) return msg__; } while(0)
#ifdef __GNUC__
#define pfunc __attribute__((warn_unused_result)) presult
#else
#define pfunc presult
#endif
enum last_seen {
JV_LAST_NONE = 0,
JV_LAST_OPEN_ARRAY = '[',
JV_LAST_OPEN_OBJECT = '{',
JV_LAST_COLON = ':',
JV_LAST_COMMA = ',',
JV_LAST_VALUE = 'V',
};
struct jv_parser {
const char* curr_buf;
int curr_buf_length;
int curr_buf_pos;
int curr_buf_is_partial;
int eof;
unsigned bom_strip_position;
int flags;
jv* stack; // parser
int stackpos; // parser
int stacklen; // both (optimization; it's really pathlen for streaming)
jv path; // streamer
enum last_seen last_seen; // streamer
jv output; // streamer
jv next; // both
char* tokenbuf;
int tokenpos;
int tokenlen;
int line, column;
struct dtoa_context dtoa;
enum {
JV_PARSER_NORMAL,
JV_PARSER_STRING,
JV_PARSER_STRING_ESCAPE,
JV_PARSER_WAITING_FOR_RS // parse error, waiting for RS
} st;
unsigned int last_ch_was_ws:1;
};
static void parser_init(struct jv_parser* p, int flags) {
p->flags = flags;
if ((p->flags & JV_PARSE_STREAMING)) {
p->path = jv_array();
} else {
p->path = jv_invalid();
p->flags &= ~(JV_PARSE_STREAM_ERRORS);
}
p->stack = 0;
p->stacklen = p->stackpos = 0;
p->last_seen = JV_LAST_NONE;
p->output = jv_invalid();
p->next = jv_invalid();
p->tokenbuf = 0;
p->tokenlen = p->tokenpos = 0;
if ((p->flags & JV_PARSE_SEQ))
p->st = JV_PARSER_WAITING_FOR_RS;
else
p->st = JV_PARSER_NORMAL;
p->eof = 0;
p->curr_buf = 0;
p->curr_buf_length = p->curr_buf_pos = p->curr_buf_is_partial = 0;
p->bom_strip_position = 0;
p->last_ch_was_ws = 0;
p->line = 1;
p->column = 0;
jvp_dtoa_context_init(&p->dtoa);
}
static void parser_reset(struct jv_parser* p) {
if ((p->flags & JV_PARSE_STREAMING)) {
jv_free(p->path);
p->path = jv_array();
p->stacklen = 0;
}
p->last_seen = JV_LAST_NONE;
jv_free(p->output);
p->output = jv_invalid();
jv_free(p->next);
p->next = jv_invalid();
for (int i=0; i<p->stackpos; i++)
jv_free(p->stack[i]);
p->stackpos = 0;
p->tokenpos = 0;
p->st = JV_PARSER_NORMAL;
}
static void parser_free(struct jv_parser* p) {
parser_reset(p);
jv_free(p->path);
jv_free(p->output);
jv_mem_free(p->stack);
jv_mem_free(p->tokenbuf);
jvp_dtoa_context_free(&p->dtoa);
}
static pfunc value(struct jv_parser* p, jv val) {
if ((p->flags & JV_PARSE_STREAMING)) {
if (jv_is_valid(p->next) || p->last_seen == JV_LAST_VALUE)
return "Expected separator between values";
if (p->stacklen > 0)
p->last_seen = JV_LAST_VALUE;
else
p->last_seen = JV_LAST_NONE;
} else {
if (jv_is_valid(p->next)) return "Expected separator between values";
}
jv_free(p->next);
p->next = val;
return 0;
}
static void push(struct jv_parser* p, jv v) {
assert(p->stackpos <= p->stacklen);
if (p->stackpos == p->stacklen) {
p->stacklen = p->stacklen * 2 + 10;
p->stack = jv_mem_realloc(p->stack, p->stacklen * sizeof(jv));
}
assert(p->stackpos < p->stacklen);
p->stack[p->stackpos++] = v;
}
static pfunc parse_token(struct jv_parser* p, char ch) {
switch (ch) {
case '[':
if (jv_is_valid(p->next)) return "Expected separator between values";
push(p, jv_array());
break;
case '{':
if (jv_is_valid(p->next)) return "Expected separator between values";
push(p, jv_object());
break;
case ':':
if (!jv_is_valid(p->next))
return "Expected string key before ':'";
if (p->stackpos == 0 || jv_get_kind(p->stack[p->stackpos-1]) != JV_KIND_OBJECT)
return "':' not as part of an object";
if (jv_get_kind(p->next) != JV_KIND_STRING)
return "Object keys must be strings";
push(p, p->next);
p->next = jv_invalid();
break;
case ',':
if (!jv_is_valid(p->next))
return "Expected value before ','";
if (p->stackpos == 0)
return "',' not as part of an object or array";
if (jv_get_kind(p->stack[p->stackpos-1]) == JV_KIND_ARRAY) {
p->stack[p->stackpos-1] = jv_array_append(p->stack[p->stackpos-1], p->next);
p->next = jv_invalid();
} else if (jv_get_kind(p->stack[p->stackpos-1]) == JV_KIND_STRING) {
assert(p->stackpos > 1 && jv_get_kind(p->stack[p->stackpos-2]) == JV_KIND_OBJECT);
p->stack[p->stackpos-2] = jv_object_set(p->stack[p->stackpos-2],
p->stack[p->stackpos-1], p->next);
p->stackpos--;
p->next = jv_invalid();
} else {
// this case hits on input like {"a", "b"}
return "Objects must consist of key:value pairs";
}
break;
case ']':
if (p->stackpos == 0 || jv_get_kind(p->stack[p->stackpos-1]) != JV_KIND_ARRAY)
return "Unmatched ']'";
if (jv_is_valid(p->next)) {
p->stack[p->stackpos-1] = jv_array_append(p->stack[p->stackpos-1], p->next);
p->next = jv_invalid();
} else {
if (jv_array_length(jv_copy(p->stack[p->stackpos-1])) != 0) {
// this case hits on input like [1,2,3,]
return "Expected another array element";
}
}
jv_free(p->next);
p->next = p->stack[--p->stackpos];
break;
case '}':
if (p->stackpos == 0)
return "Unmatched '}'";
if (jv_is_valid(p->next)) {
if (jv_get_kind(p->stack[p->stackpos-1]) != JV_KIND_STRING)
return "Objects must consist of key:value pairs";
assert(p->stackpos > 1 && jv_get_kind(p->stack[p->stackpos-2]) == JV_KIND_OBJECT);
p->stack[p->stackpos-2] = jv_object_set(p->stack[p->stackpos-2],
p->stack[p->stackpos-1], p->next);
p->stackpos--;
p->next = jv_invalid();
} else {
if (jv_get_kind(p->stack[p->stackpos-1]) != JV_KIND_OBJECT)
return "Unmatched '}'";
if (jv_object_length(jv_copy(p->stack[p->stackpos-1])) != 0)
return "Expected another key-value pair";
}
jv_free(p->next);
p->next = p->stack[--p->stackpos];
break;
}
return 0;
}
static pfunc stream_token(struct jv_parser* p, char ch) {
jv_kind k;
jv last;
switch (ch) {
case '[':
if (jv_is_valid(p->next))
return "Expected a separator between values";
p->path = jv_array_append(p->path, jv_number(0)); // push
p->last_seen = JV_LAST_OPEN_ARRAY;
p->stacklen++;
break;
case '{':
if (p->last_seen == JV_LAST_VALUE)
return "Expected a separator between values";
// Push object key: null, since we don't know it yet
p->path = jv_array_append(p->path, jv_null()); // push
p->last_seen = JV_LAST_OPEN_OBJECT;
p->stacklen++;
break;
case ':':
if (p->stacklen == 0 || jv_get_kind(jv_array_get(jv_copy(p->path), p->stacklen - 1)) == JV_KIND_NUMBER)
return "':' not as part of an object";
if (!jv_is_valid(p->next) || p->last_seen == JV_LAST_NONE)
return "Expected string key before ':'";
if (jv_get_kind(p->next) != JV_KIND_STRING)
return "Object keys must be strings";
if (p->last_seen != JV_LAST_VALUE)
return "':' should follow a key";
p->last_seen = JV_LAST_COLON;
p->path = jv_array_set(p->path, p->stacklen - 1, p->next);
p->next = jv_invalid();
break;
case ',':
if (p->last_seen != JV_LAST_VALUE)
return "Expected value before ','";
if (p->stacklen == 0)
return "',' not as part of an object or array";
last = jv_array_get(jv_copy(p->path), p->stacklen - 1);
k = jv_get_kind(last);
if (k == JV_KIND_NUMBER) {
int idx = jv_number_value(last);
if (jv_is_valid(p->next)) {
p->output = JV_ARRAY(jv_copy(p->path), p->next);
p->next = jv_invalid();
}
p->path = jv_array_set(p->path, p->stacklen - 1, jv_number(idx + 1));
p->last_seen = JV_LAST_COMMA;
} else if (k == JV_KIND_STRING) {
if (jv_is_valid(p->next)) {
p->output = JV_ARRAY(jv_copy(p->path), p->next);
p->next = jv_invalid();
}
p->path = jv_array_set(p->path, p->stacklen - 1, jv_true()); // ready for another name:value pair
p->last_seen = JV_LAST_COMMA;
} else {
assert(k == JV_KIND_NULL);
// this case hits on input like {,}
// make sure to handle input like {"a", "b"} and {"a":, ...}
jv_free(last);
return "Objects must consist of key:value pairs";
}
jv_free(last);
break;
case ']':
if (p->stacklen == 0)
return "Unmatched ']' at the top-level";
if (p->last_seen == JV_LAST_COMMA)
return "Expected another array element";
if (p->last_seen == JV_LAST_OPEN_ARRAY)
assert(!jv_is_valid(p->next));
last = jv_array_get(jv_copy(p->path), p->stacklen - 1);
k = jv_get_kind(last);
jv_free(last);
if (k != JV_KIND_NUMBER)
return "Unmatched ']' in the middle of an object";
if (jv_is_valid(p->next)) {
p->output = JV_ARRAY(jv_copy(p->path), p->next, jv_true());
p->next = jv_invalid();
} else if (p->last_seen != JV_LAST_OPEN_ARRAY) {
p->output = JV_ARRAY(jv_copy(p->path));
}
p->path = jv_array_slice(p->path, 0, --(p->stacklen)); // pop
//assert(!jv_is_valid(p->next));
jv_free(p->next);
p->next = jv_invalid();
if (p->last_seen == JV_LAST_OPEN_ARRAY)
p->output = JV_ARRAY(jv_copy(p->path), jv_array()); // Empty arrays are leaves
if (p->stacklen == 0)
p->last_seen = JV_LAST_NONE;
else
p->last_seen = JV_LAST_VALUE;
break;
case '}':
if (p->stacklen == 0)
return "Unmatched '}' at the top-level";
if (p->last_seen == JV_LAST_COMMA)
return "Expected another key:value pair";
if (p->last_seen == JV_LAST_OPEN_OBJECT)
assert(!jv_is_valid(p->next));
last = jv_array_get(jv_copy(p->path), p->stacklen - 1);
k = jv_get_kind(last);
jv_free(last);
if (k == JV_KIND_NUMBER)
return "Unmatched '}' in the middle of an array";
if (jv_is_valid(p->next)) {
if (k != JV_KIND_STRING)
return "Objects must consist of key:value pairs";
p->output = JV_ARRAY(jv_copy(p->path), p->next, jv_true());
p->next = jv_invalid();
} else {
// Perhaps {"a":[]}
if (p->last_seen == JV_LAST_COLON)
// Looks like {"a":}
return "Missing value in key:value pair";
if (p->last_seen == JV_LAST_COMMA)
// Looks like {"a":0,}
return "Expected another key-value pair";
if (p->last_seen == JV_LAST_OPEN_ARRAY)
return "Unmatched '}' in the middle of an array";
if (p->last_seen != JV_LAST_VALUE && p->last_seen != JV_LAST_OPEN_OBJECT)
return "Unmatched '}'";
if (p->last_seen != JV_LAST_OPEN_OBJECT)
p->output = JV_ARRAY(jv_copy(p->path));
}
p->path = jv_array_slice(p->path, 0, --(p->stacklen)); // pop
jv_free(p->next);
p->next = jv_invalid();
if (p->last_seen == JV_LAST_OPEN_OBJECT)
p->output = JV_ARRAY(jv_copy(p->path), jv_object()); // Empty arrays are leaves
if (p->stacklen == 0)
p->last_seen = JV_LAST_NONE;
else
p->last_seen = JV_LAST_VALUE;
break;
}
return 0;
}
static void tokenadd(struct jv_parser* p, char c) {
assert(p->tokenpos <= p->tokenlen);
if (p->tokenpos == p->tokenlen) {
p->tokenlen = p->tokenlen*2 + 256;
p->tokenbuf = jv_mem_realloc(p->tokenbuf, p->tokenlen);
}
assert(p->tokenpos < p->tokenlen);
p->tokenbuf[p->tokenpos++] = c;
}
static int unhex4(char* hex) {
int r = 0;
for (int i=0; i<4; i++) {
char c = *hex++;
int n;
if ('0' <= c && c <= '9') n = c - '0';
else if ('a' <= c && c <= 'f') n = c - 'a' + 10;
else if ('A' <= c && c <= 'F') n = c - 'A' + 10;
else return -1;
r <<= 4;
r |= n;
}
return r;
}
static pfunc found_string(struct jv_parser* p) {
char* in = p->tokenbuf;
char* out = p->tokenbuf;
char* end = p->tokenbuf + p->tokenpos;
while (in < end) {
char c = *in++;
if (c == '\\') {
if (in >= end)
return "Expected escape character at end of string";
c = *in++;
switch (c) {
case '\\':
case '"':
case '/': *out++ = c; break;
case 'b': *out++ = '\b'; break;
case 'f': *out++ = '\f'; break;
case 't': *out++ = '\t'; break;
case 'n': *out++ = '\n'; break;
case 'r': *out++ = '\r'; break;
case 'u':
/* ahh, the complicated case */
if (in + 4 > end)
return "Invalid \\uXXXX escape";
int hexvalue = unhex4(in);
if (hexvalue < 0)
return "Invalid characters in \\uXXXX escape";
unsigned long codepoint = (unsigned long)hexvalue;
in += 4;
if (0xD800 <= codepoint && codepoint <= 0xDBFF) {
/* who thought UTF-16 surrogate pairs were a good idea? */
if (in + 6 > end || in[0] != '\\' || in[1] != 'u')
return "Invalid \\uXXXX\\uXXXX surrogate pair escape";
unsigned long surrogate = unhex4(in+2);
if (!(0xDC00 <= surrogate && surrogate <= 0xDFFF))
return "Invalid \\uXXXX\\uXXXX surrogate pair escape";
in += 6;
codepoint = 0x10000 + (((codepoint - 0xD800) << 10)
|(surrogate - 0xDC00));
}
if (codepoint > 0x10FFFF)
codepoint = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER
out += jvp_utf8_encode(codepoint, out);
break;
default:
return "Invalid escape";
}
} else {
if (c > 0 && c < 0x001f)
return "Invalid string: control characters from U+0000 through U+001F must be escaped";
*out++ = c;
}
}
TRY(value(p, jv_string_sized(p->tokenbuf, out - p->tokenbuf)));
p->tokenpos = 0;
return 0;
}
static pfunc check_literal(struct jv_parser* p) {
if (p->tokenpos == 0) return 0;
const char* pattern = 0;
int plen;
jv v;
switch (p->tokenbuf[0]) {
case 't': pattern = "true"; plen = 4; v = jv_true(); break;
case 'f': pattern = "false"; plen = 5; v = jv_false(); break;
case 'n': pattern = "null"; plen = 4; v = jv_null(); break;
}
if (pattern) {
if (p->tokenpos != plen) return "Invalid literal";
for (int i=0; i<plen; i++)
if (p->tokenbuf[i] != pattern[i])
return "Invalid literal";
TRY(value(p, v));
} else {
// FIXME: better parser
p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid
char* end = 0;
double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end);
if (end == 0 || *end != 0)
return "Invalid numeric literal";
TRY(value(p, jv_number(d)));
}
p->tokenpos = 0;
return 0;
}
typedef enum {
LITERAL,
WHITESPACE,
STRUCTURE,
QUOTE,
INVALID
} chclass;
static chclass classify(char c) {
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
return WHITESPACE;
case '"':
return QUOTE;
case '[':
case ',':
case ']':
case '{':
case ':':
case '}':
return STRUCTURE;
default:
return LITERAL;
}
}
static const presult OK = "output produced";
static int parse_check_done(struct jv_parser* p, jv* out) {
if (p->stackpos == 0 && jv_is_valid(p->next)) {
*out = p->next;
p->next = jv_invalid();
return 1;
} else {
return 0;
}
}
static int stream_check_done(struct jv_parser* p, jv* out) {
if (p->stacklen == 0 && jv_is_valid(p->next)) {
*out = JV_ARRAY(jv_copy(p->path),p->next);
p->next = jv_invalid();
return 1;
} else if (jv_is_valid(p->output)) {
if (jv_array_length(jv_copy(p->output)) > 2) {
// At end of an array or object, necessitating one more output by
// which to indicate this
*out = jv_array_slice(jv_copy(p->output), 0, 2);
p->output = jv_array_slice(p->output, 0, 1); // arrange one more output
} else {
// No further processing needed
*out = p->output;
p->output = jv_invalid();
}
return 1;
} else {
return 0;
}
}
static int parse_check_truncation(struct jv_parser* p) {
return ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && (p->stackpos > 0 || p->tokenpos > 0 || jv_get_kind(p->next) == JV_KIND_NUMBER));
}
static int stream_check_truncation(struct jv_parser* p) {
jv_kind k = jv_get_kind(p->next);
return (p->stacklen > 0 || k == JV_KIND_NUMBER || k == JV_KIND_TRUE || k == JV_KIND_FALSE || k == JV_KIND_NULL);
}
static int parse_is_top_num(struct jv_parser* p) {
return (p->stackpos == 0 && jv_get_kind(p->next) == JV_KIND_NUMBER);
}
static int stream_is_top_num(struct jv_parser* p) {
return (p->stacklen == 0 && jv_get_kind(p->next) == JV_KIND_NUMBER);
}
#define check_done(p, o) \
(((p)->flags & JV_PARSE_STREAMING) ? stream_check_done((p), (o)) : parse_check_done((p), (o)))
#define token(p, ch) \
(((p)->flags & JV_PARSE_STREAMING) ? stream_token((p), (ch)) : parse_token((p), (ch)))
#define check_truncation(p) \
(((p)->flags & JV_PARSE_STREAMING) ? stream_check_truncation((p)) : parse_check_truncation((p)))
#define is_top_num(p) \
(((p)->flags & JV_PARSE_STREAMING) ? stream_is_top_num((p)) : parse_is_top_num((p)))
static pfunc scan(struct jv_parser* p, char ch, jv* out) {
p->column++;
if (ch == '\n') {
p->line++;
p->column = 0;
}
if (ch == '\036' /* ASCII RS; see draft-ietf-json-sequence-07 */) {
if (check_truncation(p)) {
if (check_literal(p) == 0 && is_top_num(p))
return "Potentially truncated top-level numeric value";
return "Truncated value";
}
TRY(check_literal(p));
if (p->st == JV_PARSER_NORMAL && check_done(p, out))
return OK;
// shouldn't happen?
assert(!jv_is_valid(*out));
parser_reset(p);
jv_free(*out);
*out = jv_invalid();
return OK;
}
presult answer = 0;
p->last_ch_was_ws = 0;
if (p->st == JV_PARSER_NORMAL) {
chclass cls = classify(ch);
if (cls == WHITESPACE)
p->last_ch_was_ws = 1;
if (cls != LITERAL) {
TRY(check_literal(p));
if (check_done(p, out)) answer = OK;
}
switch (cls) {
case LITERAL:
tokenadd(p, ch);
break;
case WHITESPACE:
break;
case QUOTE:
p->st = JV_PARSER_STRING;
break;
case STRUCTURE:
TRY(token(p, ch));
break;
case INVALID:
return "Invalid character";
}
if (check_done(p, out)) answer = OK;
} else {
if (ch == '"' && p->st == JV_PARSER_STRING) {
TRY(found_string(p));
p->st = JV_PARSER_NORMAL;
if (check_done(p, out)) answer = OK;
} else {
tokenadd(p, ch);
if (ch == '\\' && p->st == JV_PARSER_STRING) {
p->st = JV_PARSER_STRING_ESCAPE;
} else {
p->st = JV_PARSER_STRING;
}
}
}
return answer;
}
struct jv_parser* jv_parser_new(int flags) {
struct jv_parser* p = jv_mem_alloc(sizeof(struct jv_parser));
parser_init(p, flags);
p->flags = flags;
return p;
}
void jv_parser_free(struct jv_parser* p) {
parser_free(p);
jv_mem_free(p);
}
static const unsigned char UTF8_BOM[] = {0xEF,0xBB,0xBF};
int jv_parser_remaining(struct jv_parser* p) {
if (p->curr_buf == 0)
return 0;
return (p->curr_buf_length - p->curr_buf_pos);
}
void jv_parser_set_buf(struct jv_parser* p, const char* buf, int length, int is_partial) {
assert((p->curr_buf == 0 || p->curr_buf_pos == p->curr_buf_length)
&& "previous buffer not exhausted");
while (length > 0 && p->bom_strip_position < sizeof(UTF8_BOM)) {
if ((unsigned char)*buf == UTF8_BOM[p->bom_strip_position]) {
// matched a BOM character
buf++;
length--;
p->bom_strip_position++;
} else {
if (p->bom_strip_position == 0) {
// no BOM in this document
p->bom_strip_position = sizeof(UTF8_BOM);
} else {
// malformed BOM (prefix present, rest missing)
p->bom_strip_position = 0xff;
}
}
}
p->curr_buf = buf;
p->curr_buf_length = length;
p->curr_buf_pos = 0;
p->curr_buf_is_partial = is_partial;
}
static jv make_error(struct jv_parser*, const char *, ...) JV_PRINTF_LIKE(2, 3);
static jv make_error(struct jv_parser* p, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
jv e = jv_string_vfmt(fmt, ap);
va_end(ap);
if ((p->flags & JV_PARSE_STREAM_ERRORS))
return JV_ARRAY(e, jv_copy(p->path));
return jv_invalid_with_msg(e);
}
jv jv_parser_next(struct jv_parser* p) {
if (p->eof)
return jv_invalid();
if (!p->curr_buf)
return jv_invalid(); // Need a buffer
if (p->bom_strip_position == 0xff) {
if (!(p->flags & JV_PARSE_SEQ))
return jv_invalid_with_msg(jv_string("Malformed BOM"));
p->st =JV_PARSER_WAITING_FOR_RS;
parser_reset(p);
}
jv value = jv_invalid();
if ((p->flags & JV_PARSE_STREAMING) && stream_check_done(p, &value))
return value;
char ch;
presult msg = 0;
while (!msg && p->curr_buf_pos < p->curr_buf_length) {
ch = p->curr_buf[p->curr_buf_pos++];
if (p->st == JV_PARSER_WAITING_FOR_RS) {
if (ch == '\n') {
p->line++;
p->column = 0;
} else {
p->column++;
}
if (ch == '\036')
p->st = JV_PARSER_NORMAL;
continue; // need to resync, wait for RS
}
msg = scan(p, ch, &value);
}
if (msg == OK) {
return value;
} else if (msg) {
jv_free(value);
if (ch != '\036' && (p->flags & JV_PARSE_SEQ)) {
// Skip to the next RS
p->st = JV_PARSER_WAITING_FOR_RS;
value = make_error(p, "%s at line %d, column %d (need RS to resync)", msg, p->line, p->column);
parser_reset(p);
return value;
}
value = make_error(p, "%s at line %d, column %d", msg, p->line, p->column);
parser_reset(p);
if (!(p->flags & JV_PARSE_SEQ)) {
// We're not parsing a JSON text sequence; throw this buffer away.
// XXX We should fail permanently here.
p->curr_buf = 0;
p->curr_buf_pos = 0;
} // Else ch must be RS; don't clear buf so we can start parsing again after this ch
return value;
} else if (p->curr_buf_is_partial) {
assert(p->curr_buf_pos == p->curr_buf_length);
// need another buffer
return jv_invalid();
} else {
// at EOF
p->eof = 1;
assert(p->curr_buf_pos == p->curr_buf_length);
jv_free(value);
if (p->st == JV_PARSER_WAITING_FOR_RS)
return make_error(p, "Unfinished abandoned text at EOF at line %d, column %d", p->line, p->column);
if (p->st != JV_PARSER_NORMAL) {
value = make_error(p, "Unfinished string at EOF at line %d, column %d", p->line, p->column);
parser_reset(p);
p->st = JV_PARSER_WAITING_FOR_RS;
return value;
}
if ((msg = check_literal(p))) {
value = make_error(p, "%s at EOF at line %d, column %d", msg, p->line, p->column);
parser_reset(p);
p->st = JV_PARSER_WAITING_FOR_RS;
return value;
}
if (((p->flags & JV_PARSE_STREAMING) && p->stacklen != 0) ||
(!(p->flags & JV_PARSE_STREAMING) && p->stackpos != 0)) {
value = make_error(p, "Unfinished JSON term at EOF at line %d, column %d", p->line, p->column);
parser_reset(p);
p->st = JV_PARSER_WAITING_FOR_RS;
return value;
}
// p->next is either invalid (nothing here, but no syntax error)
// or valid (this is the value). either way it's the thing to return
if ((p->flags & JV_PARSE_STREAMING) && jv_is_valid(p->next)) {
value = JV_ARRAY(jv_copy(p->path), p->next); // except in streaming mode we've got to make it [path,value]
} else {
value = p->next;
}
p->next = jv_invalid();
if ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && jv_get_kind(value) == JV_KIND_NUMBER) {
jv_free(value);
return make_error(p, "Potentially truncated top-level numeric value at EOF at line %d, column %d", p->line, p->column);
}
return value;
}
}
jv jv_parse_sized(const char* string, int length) {
struct jv_parser parser;
parser_init(&parser, 0);
jv_parser_set_buf(&parser, string, length, 0);
jv value = jv_parser_next(&parser);
if (jv_is_valid(value)) {
jv next = jv_parser_next(&parser);
if (jv_is_valid(next)) {
// multiple JSON values, we only wanted one
jv_free(value);
jv_free(next);
value = jv_invalid_with_msg(jv_string("Unexpected extra JSON values"));
} else if (jv_invalid_has_msg(jv_copy(next))) {
// parser error after the first JSON value
jv_free(value);
value = next;
} else {
// a single valid JSON value
jv_free(next);
}
} else if (jv_invalid_has_msg(jv_copy(value))) {
// parse error, we'll return it
} else {
// no value at all
jv_free(value);
value = jv_invalid_with_msg(jv_string("Expected JSON value"));
}
parser_free(&parser);
if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {
jv msg = jv_invalid_get_msg(value);
value = jv_invalid_with_msg(jv_string_fmt("%s (while parsing '%s')",
jv_string_value(msg),
string));
jv_free(msg);
}
return value;
}
jv jv_parse(const char* string) {
return jv_parse_sized(string, strlen(string));
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1826_0 |
crossvul-cpp_data_bad_2483_3 | /*
* Architecture-specific setup.
*
* Copyright (C) 1998-2001, 2003-2004 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
* Stephane Eranian <eranian@hpl.hp.com>
* Copyright (C) 2000, 2004 Intel Corp
* Rohit Seth <rohit.seth@intel.com>
* Suresh Siddha <suresh.b.siddha@intel.com>
* Gordon Jin <gordon.jin@intel.com>
* Copyright (C) 1999 VA Linux Systems
* Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
*
* 12/26/04 S.Siddha, G.Jin, R.Seth
* Add multi-threading and multi-core detection
* 11/12/01 D.Mosberger Convert get_cpuinfo() to seq_file based show_cpuinfo().
* 04/04/00 D.Mosberger renamed cpu_initialized to cpu_online_map
* 03/31/00 R.Seth cpu_initialized and current->processor fixes
* 02/04/00 D.Mosberger some more get_cpuinfo fixes...
* 02/01/00 R.Seth fixed get_cpuinfo for SMP
* 01/07/99 S.Eranian added the support for command line argument
* 06/24/99 W.Drummond added boot_cpu_data.
* 05/28/05 Z. Menyhart Dynamic stride size for "flush_icache_range()"
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/bootmem.h>
#include <linux/console.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/string.h>
#include <linux/threads.h>
#include <linux/screen_info.h>
#include <linux/dmi.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/efi.h>
#include <linux/initrd.h>
#include <linux/pm.h>
#include <linux/cpufreq.h>
#include <linux/kexec.h>
#include <linux/crash_dump.h>
#include <asm/ia32.h>
#include <asm/machvec.h>
#include <asm/mca.h>
#include <asm/meminit.h>
#include <asm/page.h>
#include <asm/patch.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/sal.h>
#include <asm/sections.h>
#include <asm/setup.h>
#include <asm/smp.h>
#include <asm/system.h>
#include <asm/tlbflush.h>
#include <asm/unistd.h>
#include <asm/hpsim.h>
#if defined(CONFIG_SMP) && (IA64_CPU_SIZE > PAGE_SIZE)
# error "struct cpuinfo_ia64 too big!"
#endif
#ifdef CONFIG_SMP
unsigned long __per_cpu_offset[NR_CPUS];
EXPORT_SYMBOL(__per_cpu_offset);
#endif
DEFINE_PER_CPU(struct cpuinfo_ia64, cpu_info);
DEFINE_PER_CPU(unsigned long, local_per_cpu_offset);
unsigned long ia64_cycles_per_usec;
struct ia64_boot_param *ia64_boot_param;
struct screen_info screen_info;
unsigned long vga_console_iobase;
unsigned long vga_console_membase;
static struct resource data_resource = {
.name = "Kernel data",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource code_resource = {
.name = "Kernel code",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource bss_resource = {
.name = "Kernel bss",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
unsigned long ia64_max_cacheline_size;
int dma_get_cache_alignment(void)
{
return ia64_max_cacheline_size;
}
EXPORT_SYMBOL(dma_get_cache_alignment);
unsigned long ia64_iobase; /* virtual address for I/O accesses */
EXPORT_SYMBOL(ia64_iobase);
struct io_space io_space[MAX_IO_SPACES];
EXPORT_SYMBOL(io_space);
unsigned int num_io_spaces;
/*
* "flush_icache_range()" needs to know what processor dependent stride size to use
* when it makes i-cache(s) coherent with d-caches.
*/
#define I_CACHE_STRIDE_SHIFT 5 /* Safest way to go: 32 bytes by 32 bytes */
unsigned long ia64_i_cache_stride_shift = ~0;
/*
* The merge_mask variable needs to be set to (max(iommu_page_size(iommu)) - 1). This
* mask specifies a mask of address bits that must be 0 in order for two buffers to be
* mergeable by the I/O MMU (i.e., the end address of the first buffer and the start
* address of the second buffer must be aligned to (merge_mask+1) in order to be
* mergeable). By default, we assume there is no I/O MMU which can merge physically
* discontiguous buffers, so we set the merge_mask to ~0UL, which corresponds to a iommu
* page-size of 2^64.
*/
unsigned long ia64_max_iommu_merge_mask = ~0UL;
EXPORT_SYMBOL(ia64_max_iommu_merge_mask);
/*
* We use a special marker for the end of memory and it uses the extra (+1) slot
*/
struct rsvd_region rsvd_region[IA64_MAX_RSVD_REGIONS + 1] __initdata;
int num_rsvd_regions __initdata;
/*
* Filter incoming memory segments based on the primitive map created from the boot
* parameters. Segments contained in the map are removed from the memory ranges. A
* caller-specified function is called with the memory ranges that remain after filtering.
* This routine does not assume the incoming segments are sorted.
*/
int __init
filter_rsvd_memory (unsigned long start, unsigned long end, void *arg)
{
unsigned long range_start, range_end, prev_start;
void (*func)(unsigned long, unsigned long, int);
int i;
#if IGNORE_PFN0
if (start == PAGE_OFFSET) {
printk(KERN_WARNING "warning: skipping physical page 0\n");
start += PAGE_SIZE;
if (start >= end) return 0;
}
#endif
/*
* lowest possible address(walker uses virtual)
*/
prev_start = PAGE_OFFSET;
func = arg;
for (i = 0; i < num_rsvd_regions; ++i) {
range_start = max(start, prev_start);
range_end = min(end, rsvd_region[i].start);
if (range_start < range_end)
call_pernode_memory(__pa(range_start), range_end - range_start, func);
/* nothing more available in this segment */
if (range_end == end) return 0;
prev_start = rsvd_region[i].end;
}
/* end of memory marker allows full processing inside loop body */
return 0;
}
/*
* Similar to "filter_rsvd_memory()", but the reserved memory ranges
* are not filtered out.
*/
int __init
filter_memory(unsigned long start, unsigned long end, void *arg)
{
void (*func)(unsigned long, unsigned long, int);
#if IGNORE_PFN0
if (start == PAGE_OFFSET) {
printk(KERN_WARNING "warning: skipping physical page 0\n");
start += PAGE_SIZE;
if (start >= end)
return 0;
}
#endif
func = arg;
if (start < end)
call_pernode_memory(__pa(start), end - start, func);
return 0;
}
static void __init
sort_regions (struct rsvd_region *rsvd_region, int max)
{
int j;
/* simple bubble sorting */
while (max--) {
for (j = 0; j < max; ++j) {
if (rsvd_region[j].start > rsvd_region[j+1].start) {
struct rsvd_region tmp;
tmp = rsvd_region[j];
rsvd_region[j] = rsvd_region[j + 1];
rsvd_region[j + 1] = tmp;
}
}
}
}
/*
* Request address space for all standard resources
*/
static int __init register_memory(void)
{
code_resource.start = ia64_tpa(_text);
code_resource.end = ia64_tpa(_etext) - 1;
data_resource.start = ia64_tpa(_etext);
data_resource.end = ia64_tpa(_edata) - 1;
bss_resource.start = ia64_tpa(__bss_start);
bss_resource.end = ia64_tpa(_end) - 1;
efi_initialize_iomem_resources(&code_resource, &data_resource,
&bss_resource);
return 0;
}
__initcall(register_memory);
#ifdef CONFIG_KEXEC
/*
* This function checks if the reserved crashkernel is allowed on the specific
* IA64 machine flavour. Machines without an IO TLB use swiotlb and require
* some memory below 4 GB (i.e. in 32 bit area), see the implementation of
* lib/swiotlb.c. The hpzx1 architecture has an IO TLB but cannot use that
* in kdump case. See the comment in sba_init() in sba_iommu.c.
*
* So, the only machvec that really supports loading the kdump kernel
* over 4 GB is "sn2".
*/
static int __init check_crashkernel_memory(unsigned long pbase, size_t size)
{
if (ia64_platform_is("sn2") || ia64_platform_is("uv"))
return 1;
else
return pbase < (1UL << 32);
}
static void __init setup_crashkernel(unsigned long total, int *n)
{
unsigned long long base = 0, size = 0;
int ret;
ret = parse_crashkernel(boot_command_line, total,
&size, &base);
if (ret == 0 && size > 0) {
if (!base) {
sort_regions(rsvd_region, *n);
base = kdump_find_rsvd_region(size,
rsvd_region, *n);
}
if (!check_crashkernel_memory(base, size)) {
pr_warning("crashkernel: There would be kdump memory "
"at %ld GB but this is unusable because it "
"must\nbe below 4 GB. Change the memory "
"configuration of the machine.\n",
(unsigned long)(base >> 30));
return;
}
if (base != ~0UL) {
printk(KERN_INFO "Reserving %ldMB of memory at %ldMB "
"for crashkernel (System RAM: %ldMB)\n",
(unsigned long)(size >> 20),
(unsigned long)(base >> 20),
(unsigned long)(total >> 20));
rsvd_region[*n].start =
(unsigned long)__va(base);
rsvd_region[*n].end =
(unsigned long)__va(base + size);
(*n)++;
crashk_res.start = base;
crashk_res.end = base + size - 1;
}
}
efi_memmap_res.start = ia64_boot_param->efi_memmap;
efi_memmap_res.end = efi_memmap_res.start +
ia64_boot_param->efi_memmap_size;
boot_param_res.start = __pa(ia64_boot_param);
boot_param_res.end = boot_param_res.start +
sizeof(*ia64_boot_param);
}
#else
static inline void __init setup_crashkernel(unsigned long total, int *n)
{}
#endif
/**
* reserve_memory - setup reserved memory areas
*
* Setup the reserved memory areas set aside for the boot parameters,
* initrd, etc. There are currently %IA64_MAX_RSVD_REGIONS defined,
* see include/asm-ia64/meminit.h if you need to define more.
*/
void __init
reserve_memory (void)
{
int n = 0;
unsigned long total_memory;
/*
* none of the entries in this table overlap
*/
rsvd_region[n].start = (unsigned long) ia64_boot_param;
rsvd_region[n].end = rsvd_region[n].start + sizeof(*ia64_boot_param);
n++;
rsvd_region[n].start = (unsigned long) __va(ia64_boot_param->efi_memmap);
rsvd_region[n].end = rsvd_region[n].start + ia64_boot_param->efi_memmap_size;
n++;
rsvd_region[n].start = (unsigned long) __va(ia64_boot_param->command_line);
rsvd_region[n].end = (rsvd_region[n].start
+ strlen(__va(ia64_boot_param->command_line)) + 1);
n++;
rsvd_region[n].start = (unsigned long) ia64_imva((void *)KERNEL_START);
rsvd_region[n].end = (unsigned long) ia64_imva(_end);
n++;
#ifdef CONFIG_BLK_DEV_INITRD
if (ia64_boot_param->initrd_start) {
rsvd_region[n].start = (unsigned long)__va(ia64_boot_param->initrd_start);
rsvd_region[n].end = rsvd_region[n].start + ia64_boot_param->initrd_size;
n++;
}
#endif
#ifdef CONFIG_PROC_VMCORE
if (reserve_elfcorehdr(&rsvd_region[n].start,
&rsvd_region[n].end) == 0)
n++;
#endif
total_memory = efi_memmap_init(&rsvd_region[n].start, &rsvd_region[n].end);
n++;
setup_crashkernel(total_memory, &n);
/* end of memory marker */
rsvd_region[n].start = ~0UL;
rsvd_region[n].end = ~0UL;
n++;
num_rsvd_regions = n;
BUG_ON(IA64_MAX_RSVD_REGIONS + 1 < n);
sort_regions(rsvd_region, num_rsvd_regions);
}
/**
* find_initrd - get initrd parameters from the boot parameter structure
*
* Grab the initrd start and end from the boot parameter struct given us by
* the boot loader.
*/
void __init
find_initrd (void)
{
#ifdef CONFIG_BLK_DEV_INITRD
if (ia64_boot_param->initrd_start) {
initrd_start = (unsigned long)__va(ia64_boot_param->initrd_start);
initrd_end = initrd_start+ia64_boot_param->initrd_size;
printk(KERN_INFO "Initial ramdisk at: 0x%lx (%lu bytes)\n",
initrd_start, ia64_boot_param->initrd_size);
}
#endif
}
static void __init
io_port_init (void)
{
unsigned long phys_iobase;
/*
* Set `iobase' based on the EFI memory map or, failing that, the
* value firmware left in ar.k0.
*
* Note that in ia32 mode, IN/OUT instructions use ar.k0 to compute
* the port's virtual address, so ia32_load_state() loads it with a
* user virtual address. But in ia64 mode, glibc uses the
* *physical* address in ar.k0 to mmap the appropriate area from
* /dev/mem, and the inX()/outX() interfaces use MMIO. In both
* cases, user-mode can only use the legacy 0-64K I/O port space.
*
* ar.k0 is not involved in kernel I/O port accesses, which can use
* any of the I/O port spaces and are done via MMIO using the
* virtual mmio_base from the appropriate io_space[].
*/
phys_iobase = efi_get_iobase();
if (!phys_iobase) {
phys_iobase = ia64_get_kr(IA64_KR_IO_BASE);
printk(KERN_INFO "No I/O port range found in EFI memory map, "
"falling back to AR.KR0 (0x%lx)\n", phys_iobase);
}
ia64_iobase = (unsigned long) ioremap(phys_iobase, 0);
ia64_set_kr(IA64_KR_IO_BASE, __pa(ia64_iobase));
/* setup legacy IO port space */
io_space[0].mmio_base = ia64_iobase;
io_space[0].sparse = 1;
num_io_spaces = 1;
}
/**
* early_console_setup - setup debugging console
*
* Consoles started here require little enough setup that we can start using
* them very early in the boot process, either right after the machine
* vector initialization, or even before if the drivers can detect their hw.
*
* Returns non-zero if a console couldn't be setup.
*/
static inline int __init
early_console_setup (char *cmdline)
{
int earlycons = 0;
#ifdef CONFIG_SERIAL_SGI_L1_CONSOLE
{
extern int sn_serial_console_early_setup(void);
if (!sn_serial_console_early_setup())
earlycons++;
}
#endif
#ifdef CONFIG_EFI_PCDP
if (!efi_setup_pcdp_console(cmdline))
earlycons++;
#endif
if (!simcons_register())
earlycons++;
return (earlycons) ? 0 : -1;
}
static inline void
mark_bsp_online (void)
{
#ifdef CONFIG_SMP
/* If we register an early console, allow CPU 0 to printk */
cpu_set(smp_processor_id(), cpu_online_map);
#endif
}
static __initdata int nomca;
static __init int setup_nomca(char *s)
{
nomca = 1;
return 0;
}
early_param("nomca", setup_nomca);
#ifdef CONFIG_PROC_VMCORE
/* elfcorehdr= specifies the location of elf core header
* stored by the crashed kernel.
*/
static int __init parse_elfcorehdr(char *arg)
{
if (!arg)
return -EINVAL;
elfcorehdr_addr = memparse(arg, &arg);
return 0;
}
early_param("elfcorehdr", parse_elfcorehdr);
int __init reserve_elfcorehdr(unsigned long *start, unsigned long *end)
{
unsigned long length;
/* We get the address using the kernel command line,
* but the size is extracted from the EFI tables.
* Both address and size are required for reservation
* to work properly.
*/
if (elfcorehdr_addr >= ELFCORE_ADDR_MAX)
return -EINVAL;
if ((length = vmcore_find_descriptor_size(elfcorehdr_addr)) == 0) {
elfcorehdr_addr = ELFCORE_ADDR_MAX;
return -EINVAL;
}
*start = (unsigned long)__va(elfcorehdr_addr);
*end = *start + length;
return 0;
}
#endif /* CONFIG_PROC_VMCORE */
void __init
setup_arch (char **cmdline_p)
{
unw_init();
ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);
*cmdline_p = __va(ia64_boot_param->command_line);
strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);
efi_init();
io_port_init();
#ifdef CONFIG_IA64_GENERIC
/* machvec needs to be parsed from the command line
* before parse_early_param() is called to ensure
* that ia64_mv is initialised before any command line
* settings may cause console setup to occur
*/
machvec_init_from_cmdline(*cmdline_p);
#endif
parse_early_param();
if (early_console_setup(*cmdline_p) == 0)
mark_bsp_online();
#ifdef CONFIG_ACPI
/* Initialize the ACPI boot-time table parser */
acpi_table_init();
# ifdef CONFIG_ACPI_NUMA
acpi_numa_init();
per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ?
32 : cpus_weight(early_cpu_possible_map)), additional_cpus);
# endif
#else
# ifdef CONFIG_SMP
smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */
# endif
#endif /* CONFIG_APCI_BOOT */
find_memory();
/* process SAL system table: */
ia64_sal_init(__va(efi.sal_systab));
#ifdef CONFIG_SMP
cpu_physical_id(0) = hard_smp_processor_id();
#endif
cpu_init(); /* initialize the bootstrap CPU */
mmu_context_init(); /* initialize context_id bitmap */
check_sal_cache_flush();
#ifdef CONFIG_ACPI
acpi_boot_init();
#endif
#ifdef CONFIG_VT
if (!conswitchp) {
# if defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
# endif
# if defined(CONFIG_VGA_CONSOLE)
/*
* Non-legacy systems may route legacy VGA MMIO range to system
* memory. vga_con probes the MMIO hole, so memory looks like
* a VGA device to it. The EFI memory map can tell us if it's
* memory so we can avoid this problem.
*/
if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)
conswitchp = &vga_con;
# endif
}
#endif
/* enable IA-64 Machine Check Abort Handling unless disabled */
if (!nomca)
ia64_mca_init();
platform_setup(cmdline_p);
paging_init();
}
/*
* Display cpu info for all CPUs.
*/
static int
show_cpuinfo (struct seq_file *m, void *v)
{
#ifdef CONFIG_SMP
# define lpj c->loops_per_jiffy
# define cpunum c->cpu
#else
# define lpj loops_per_jiffy
# define cpunum 0
#endif
static struct {
unsigned long mask;
const char *feature_name;
} feature_bits[] = {
{ 1UL << 0, "branchlong" },
{ 1UL << 1, "spontaneous deferral"},
{ 1UL << 2, "16-byte atomic ops" }
};
char features[128], *cp, *sep;
struct cpuinfo_ia64 *c = v;
unsigned long mask;
unsigned long proc_freq;
int i, size;
mask = c->features;
/* build the feature string: */
memcpy(features, "standard", 9);
cp = features;
size = sizeof(features);
sep = "";
for (i = 0; i < ARRAY_SIZE(feature_bits) && size > 1; ++i) {
if (mask & feature_bits[i].mask) {
cp += snprintf(cp, size, "%s%s", sep,
feature_bits[i].feature_name),
sep = ", ";
mask &= ~feature_bits[i].mask;
size = sizeof(features) - (cp - features);
}
}
if (mask && size > 1) {
/* print unknown features as a hex value */
snprintf(cp, size, "%s0x%lx", sep, mask);
}
proc_freq = cpufreq_quick_get(cpunum);
if (!proc_freq)
proc_freq = c->proc_freq / 1000;
seq_printf(m,
"processor : %d\n"
"vendor : %s\n"
"arch : IA-64\n"
"family : %u\n"
"model : %u\n"
"model name : %s\n"
"revision : %u\n"
"archrev : %u\n"
"features : %s\n"
"cpu number : %lu\n"
"cpu regs : %u\n"
"cpu MHz : %lu.%03lu\n"
"itc MHz : %lu.%06lu\n"
"BogoMIPS : %lu.%02lu\n",
cpunum, c->vendor, c->family, c->model,
c->model_name, c->revision, c->archrev,
features, c->ppn, c->number,
proc_freq / 1000, proc_freq % 1000,
c->itc_freq / 1000000, c->itc_freq % 1000000,
lpj*HZ/500000, (lpj*HZ/5000) % 100);
#ifdef CONFIG_SMP
seq_printf(m, "siblings : %u\n", cpus_weight(cpu_core_map[cpunum]));
if (c->socket_id != -1)
seq_printf(m, "physical id: %u\n", c->socket_id);
if (c->threads_per_core > 1 || c->cores_per_socket > 1)
seq_printf(m,
"core id : %u\n"
"thread id : %u\n",
c->core_id, c->thread_id);
#endif
seq_printf(m,"\n");
return 0;
}
static void *
c_start (struct seq_file *m, loff_t *pos)
{
#ifdef CONFIG_SMP
while (*pos < NR_CPUS && !cpu_isset(*pos, cpu_online_map))
++*pos;
#endif
return *pos < NR_CPUS ? cpu_data(*pos) : NULL;
}
static void *
c_next (struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void
c_stop (struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo
};
#define MAX_BRANDS 8
static char brandname[MAX_BRANDS][128];
static char * __cpuinit
get_model_name(__u8 family, __u8 model)
{
static int overflow;
char brand[128];
int i;
memcpy(brand, "Unknown", 8);
if (ia64_pal_get_brand_info(brand)) {
if (family == 0x7)
memcpy(brand, "Merced", 7);
else if (family == 0x1f) switch (model) {
case 0: memcpy(brand, "McKinley", 9); break;
case 1: memcpy(brand, "Madison", 8); break;
case 2: memcpy(brand, "Madison up to 9M cache", 23); break;
}
}
for (i = 0; i < MAX_BRANDS; i++)
if (strcmp(brandname[i], brand) == 0)
return brandname[i];
for (i = 0; i < MAX_BRANDS; i++)
if (brandname[i][0] == '\0')
return strcpy(brandname[i], brand);
if (overflow++ == 0)
printk(KERN_ERR
"%s: Table overflow. Some processor model information will be missing\n",
__func__);
return "Unknown";
}
static void __cpuinit
identify_cpu (struct cpuinfo_ia64 *c)
{
union {
unsigned long bits[5];
struct {
/* id 0 & 1: */
char vendor[16];
/* id 2 */
u64 ppn; /* processor serial number */
/* id 3: */
unsigned number : 8;
unsigned revision : 8;
unsigned model : 8;
unsigned family : 8;
unsigned archrev : 8;
unsigned reserved : 24;
/* id 4: */
u64 features;
} field;
} cpuid;
pal_vm_info_1_u_t vm1;
pal_vm_info_2_u_t vm2;
pal_status_t status;
unsigned long impl_va_msb = 50, phys_addr_size = 44; /* Itanium defaults */
int i;
for (i = 0; i < 5; ++i)
cpuid.bits[i] = ia64_get_cpuid(i);
memcpy(c->vendor, cpuid.field.vendor, 16);
#ifdef CONFIG_SMP
c->cpu = smp_processor_id();
/* below default values will be overwritten by identify_siblings()
* for Multi-Threading/Multi-Core capable CPUs
*/
c->threads_per_core = c->cores_per_socket = c->num_log = 1;
c->socket_id = -1;
identify_siblings(c);
if (c->threads_per_core > smp_num_siblings)
smp_num_siblings = c->threads_per_core;
#endif
c->ppn = cpuid.field.ppn;
c->number = cpuid.field.number;
c->revision = cpuid.field.revision;
c->model = cpuid.field.model;
c->family = cpuid.field.family;
c->archrev = cpuid.field.archrev;
c->features = cpuid.field.features;
c->model_name = get_model_name(c->family, c->model);
status = ia64_pal_vm_summary(&vm1, &vm2);
if (status == PAL_STATUS_SUCCESS) {
impl_va_msb = vm2.pal_vm_info_2_s.impl_va_msb;
phys_addr_size = vm1.pal_vm_info_1_s.phys_add_size;
}
c->unimpl_va_mask = ~((7L<<61) | ((1L << (impl_va_msb + 1)) - 1));
c->unimpl_pa_mask = ~((1L<<63) | ((1L << phys_addr_size) - 1));
}
void __init
setup_per_cpu_areas (void)
{
/* start_kernel() requires this... */
#ifdef CONFIG_ACPI_HOTPLUG_CPU
prefill_possible_map();
#endif
}
/*
* Calculate the max. cache line size.
*
* In addition, the minimum of the i-cache stride sizes is calculated for
* "flush_icache_range()".
*/
static void __cpuinit
get_max_cacheline_size (void)
{
unsigned long line_size, max = 1;
u64 l, levels, unique_caches;
pal_cache_config_info_t cci;
s64 status;
status = ia64_pal_cache_summary(&levels, &unique_caches);
if (status != 0) {
printk(KERN_ERR "%s: ia64_pal_cache_summary() failed (status=%ld)\n",
__func__, status);
max = SMP_CACHE_BYTES;
/* Safest setup for "flush_icache_range()" */
ia64_i_cache_stride_shift = I_CACHE_STRIDE_SHIFT;
goto out;
}
for (l = 0; l < levels; ++l) {
status = ia64_pal_cache_config_info(l, /* cache_type (data_or_unified)= */ 2,
&cci);
if (status != 0) {
printk(KERN_ERR
"%s: ia64_pal_cache_config_info(l=%lu, 2) failed (status=%ld)\n",
__func__, l, status);
max = SMP_CACHE_BYTES;
/* The safest setup for "flush_icache_range()" */
cci.pcci_stride = I_CACHE_STRIDE_SHIFT;
cci.pcci_unified = 1;
}
line_size = 1 << cci.pcci_line_size;
if (line_size > max)
max = line_size;
if (!cci.pcci_unified) {
status = ia64_pal_cache_config_info(l,
/* cache_type (instruction)= */ 1,
&cci);
if (status != 0) {
printk(KERN_ERR
"%s: ia64_pal_cache_config_info(l=%lu, 1) failed (status=%ld)\n",
__func__, l, status);
/* The safest setup for "flush_icache_range()" */
cci.pcci_stride = I_CACHE_STRIDE_SHIFT;
}
}
if (cci.pcci_stride < ia64_i_cache_stride_shift)
ia64_i_cache_stride_shift = cci.pcci_stride;
}
out:
if (max > ia64_max_cacheline_size)
ia64_max_cacheline_size = max;
}
/*
* cpu_init() initializes state that is per-CPU. This function acts
* as a 'CPU state barrier', nothing should get across.
*/
void __cpuinit
cpu_init (void)
{
extern void __cpuinit ia64_mmu_init (void *);
static unsigned long max_num_phys_stacked = IA64_NUM_PHYS_STACK_REG;
unsigned long num_phys_stacked;
pal_vm_info_2_u_t vmi;
unsigned int max_ctx;
struct cpuinfo_ia64 *cpu_info;
void *cpu_data;
cpu_data = per_cpu_init();
#ifdef CONFIG_SMP
/*
* insert boot cpu into sibling and core mapes
* (must be done after per_cpu area is setup)
*/
if (smp_processor_id() == 0) {
cpu_set(0, per_cpu(cpu_sibling_map, 0));
cpu_set(0, cpu_core_map[0]);
}
#endif
/*
* We set ar.k3 so that assembly code in MCA handler can compute
* physical addresses of per cpu variables with a simple:
* phys = ar.k3 + &per_cpu_var
*/
ia64_set_kr(IA64_KR_PER_CPU_DATA,
ia64_tpa(cpu_data) - (long) __per_cpu_start);
get_max_cacheline_size();
/*
* We can't pass "local_cpu_data" to identify_cpu() because we haven't called
* ia64_mmu_init() yet. And we can't call ia64_mmu_init() first because it
* depends on the data returned by identify_cpu(). We break the dependency by
* accessing cpu_data() through the canonical per-CPU address.
*/
cpu_info = cpu_data + ((char *) &__ia64_per_cpu_var(cpu_info) - __per_cpu_start);
identify_cpu(cpu_info);
#ifdef CONFIG_MCKINLEY
{
# define FEATURE_SET 16
struct ia64_pal_retval iprv;
if (cpu_info->family == 0x1f) {
PAL_CALL_PHYS(iprv, PAL_PROC_GET_FEATURES, 0, FEATURE_SET, 0);
if ((iprv.status == 0) && (iprv.v0 & 0x80) && (iprv.v2 & 0x80))
PAL_CALL_PHYS(iprv, PAL_PROC_SET_FEATURES,
(iprv.v1 | 0x80), FEATURE_SET, 0);
}
}
#endif
/* Clear the stack memory reserved for pt_regs: */
memset(task_pt_regs(current), 0, sizeof(struct pt_regs));
ia64_set_kr(IA64_KR_FPU_OWNER, 0);
/*
* Initialize the page-table base register to a global
* directory with all zeroes. This ensure that we can handle
* TLB-misses to user address-space even before we created the
* first user address-space. This may happen, e.g., due to
* aggressive use of lfetch.fault.
*/
ia64_set_kr(IA64_KR_PT_BASE, __pa(ia64_imva(empty_zero_page)));
/*
* Initialize default control register to defer speculative faults except
* for those arising from TLB misses, which are not deferred. The
* kernel MUST NOT depend on a particular setting of these bits (in other words,
* the kernel must have recovery code for all speculative accesses). Turn on
* dcr.lc as per recommendation by the architecture team. Most IA-32 apps
* shouldn't be affected by this (moral: keep your ia32 locks aligned and you'll
* be fine).
*/
ia64_setreg(_IA64_REG_CR_DCR, ( IA64_DCR_DP | IA64_DCR_DK | IA64_DCR_DX | IA64_DCR_DR
| IA64_DCR_DA | IA64_DCR_DD | IA64_DCR_LC));
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
if (current->mm)
BUG();
ia64_mmu_init(ia64_imva(cpu_data));
ia64_mca_cpu_init(ia64_imva(cpu_data));
#ifdef CONFIG_IA32_SUPPORT
ia32_cpu_init();
#endif
/* Clear ITC to eliminate sched_clock() overflows in human time. */
ia64_set_itc(0);
/* disable all local interrupt sources: */
ia64_set_itv(1 << 16);
ia64_set_lrr0(1 << 16);
ia64_set_lrr1(1 << 16);
ia64_setreg(_IA64_REG_CR_PMV, 1 << 16);
ia64_setreg(_IA64_REG_CR_CMCV, 1 << 16);
/* clear TPR & XTP to enable all interrupt classes: */
ia64_setreg(_IA64_REG_CR_TPR, 0);
/* Clear any pending interrupts left by SAL/EFI */
while (ia64_get_ivr() != IA64_SPURIOUS_INT_VECTOR)
ia64_eoi();
#ifdef CONFIG_SMP
normal_xtp();
#endif
/* set ia64_ctx.max_rid to the maximum RID that is supported by all CPUs: */
if (ia64_pal_vm_summary(NULL, &vmi) == 0) {
max_ctx = (1U << (vmi.pal_vm_info_2_s.rid_size - 3)) - 1;
setup_ptcg_sem(vmi.pal_vm_info_2_s.max_purges, NPTCG_FROM_PAL);
} else {
printk(KERN_WARNING "cpu_init: PAL VM summary failed, assuming 18 RID bits\n");
max_ctx = (1U << 15) - 1; /* use architected minimum */
}
while (max_ctx < ia64_ctx.max_ctx) {
unsigned int old = ia64_ctx.max_ctx;
if (cmpxchg(&ia64_ctx.max_ctx, old, max_ctx) == old)
break;
}
if (ia64_pal_rse_info(&num_phys_stacked, NULL) != 0) {
printk(KERN_WARNING "cpu_init: PAL RSE info failed; assuming 96 physical "
"stacked regs\n");
num_phys_stacked = 96;
}
/* size of physical stacked register partition plus 8 bytes: */
if (num_phys_stacked > max_num_phys_stacked) {
ia64_patch_phys_stack_reg(num_phys_stacked*8 + 8);
max_num_phys_stacked = num_phys_stacked;
}
platform_cpu_init();
pm_idle = default_idle;
}
void __init
check_bugs (void)
{
ia64_patch_mckinley_e9((unsigned long) __start___mckinley_e9_bundles,
(unsigned long) __end___mckinley_e9_bundles);
}
static int __init run_dmi_scan(void)
{
dmi_scan_machine();
return 0;
}
core_initcall(run_dmi_scan);
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2483_3 |
crossvul-cpp_data_good_2273_0 |
#include <linux/ceph/ceph_debug.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/ceph/decode.h>
#include <linux/ceph/auth.h>
#include "crypto.h"
#include "auth_x.h"
#include "auth_x_protocol.h"
static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed);
static int ceph_x_is_authenticated(struct ceph_auth_client *ac)
{
struct ceph_x_info *xi = ac->private;
int need;
ceph_x_validate_tickets(ac, &need);
dout("ceph_x_is_authenticated want=%d need=%d have=%d\n",
ac->want_keys, need, xi->have_keys);
return (ac->want_keys & xi->have_keys) == ac->want_keys;
}
static int ceph_x_should_authenticate(struct ceph_auth_client *ac)
{
struct ceph_x_info *xi = ac->private;
int need;
ceph_x_validate_tickets(ac, &need);
dout("ceph_x_should_authenticate want=%d need=%d have=%d\n",
ac->want_keys, need, xi->have_keys);
return need != 0;
}
static int ceph_x_encrypt_buflen(int ilen)
{
return sizeof(struct ceph_x_encrypt_header) + ilen + 16 +
sizeof(u32);
}
static int ceph_x_encrypt(struct ceph_crypto_key *secret,
void *ibuf, int ilen, void *obuf, size_t olen)
{
struct ceph_x_encrypt_header head = {
.struct_v = 1,
.magic = cpu_to_le64(CEPHX_ENC_MAGIC)
};
size_t len = olen - sizeof(u32);
int ret;
ret = ceph_encrypt2(secret, obuf + sizeof(u32), &len,
&head, sizeof(head), ibuf, ilen);
if (ret)
return ret;
ceph_encode_32(&obuf, len);
return len + sizeof(u32);
}
static int ceph_x_decrypt(struct ceph_crypto_key *secret,
void **p, void *end, void **obuf, size_t olen)
{
struct ceph_x_encrypt_header head;
size_t head_len = sizeof(head);
int len, ret;
len = ceph_decode_32(p);
if (*p + len > end)
return -EINVAL;
dout("ceph_x_decrypt len %d\n", len);
if (*obuf == NULL) {
*obuf = kmalloc(len, GFP_NOFS);
if (!*obuf)
return -ENOMEM;
olen = len;
}
ret = ceph_decrypt2(secret, &head, &head_len, *obuf, &olen, *p, len);
if (ret)
return ret;
if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)
return -EPERM;
*p += len;
return olen;
}
/*
* get existing (or insert new) ticket handler
*/
static struct ceph_x_ticket_handler *
get_ticket_handler(struct ceph_auth_client *ac, int service)
{
struct ceph_x_ticket_handler *th;
struct ceph_x_info *xi = ac->private;
struct rb_node *parent = NULL, **p = &xi->ticket_handlers.rb_node;
while (*p) {
parent = *p;
th = rb_entry(parent, struct ceph_x_ticket_handler, node);
if (service < th->service)
p = &(*p)->rb_left;
else if (service > th->service)
p = &(*p)->rb_right;
else
return th;
}
/* add it */
th = kzalloc(sizeof(*th), GFP_NOFS);
if (!th)
return ERR_PTR(-ENOMEM);
th->service = service;
rb_link_node(&th->node, parent, p);
rb_insert_color(&th->node, &xi->ticket_handlers);
return th;
}
static void remove_ticket_handler(struct ceph_auth_client *ac,
struct ceph_x_ticket_handler *th)
{
struct ceph_x_info *xi = ac->private;
dout("remove_ticket_handler %p %d\n", th, th->service);
rb_erase(&th->node, &xi->ticket_handlers);
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
kfree(th);
}
static int process_one_ticket(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void **p, void *end)
{
struct ceph_x_info *xi = ac->private;
int type;
u8 tkt_struct_v, blob_struct_v;
struct ceph_x_ticket_handler *th;
void *dbuf = NULL;
void *dp, *dend;
int dlen;
char is_enc;
struct timespec validity;
struct ceph_crypto_key old_key;
void *ticket_buf = NULL;
void *tp, *tpend;
struct ceph_timespec new_validity;
struct ceph_crypto_key new_session_key;
struct ceph_buffer *new_ticket_blob;
unsigned long new_expires, new_renew_after;
u64 new_secret_id;
int ret;
ceph_decode_need(p, end, sizeof(u32) + 1, bad);
type = ceph_decode_32(p);
dout(" ticket type %d %s\n", type, ceph_entity_type_name(type));
tkt_struct_v = ceph_decode_8(p);
if (tkt_struct_v != 1)
goto bad;
th = get_ticket_handler(ac, type);
if (IS_ERR(th)) {
ret = PTR_ERR(th);
goto out;
}
/* blob for me */
dlen = ceph_x_decrypt(secret, p, end, &dbuf, 0);
if (dlen <= 0) {
ret = dlen;
goto out;
}
dout(" decrypted %d bytes\n", dlen);
dp = dbuf;
dend = dp + dlen;
tkt_struct_v = ceph_decode_8(&dp);
if (tkt_struct_v != 1)
goto bad;
memcpy(&old_key, &th->session_key, sizeof(old_key));
ret = ceph_crypto_key_decode(&new_session_key, &dp, dend);
if (ret)
goto out;
ceph_decode_copy(&dp, &new_validity, sizeof(new_validity));
ceph_decode_timespec(&validity, &new_validity);
new_expires = get_seconds() + validity.tv_sec;
new_renew_after = new_expires - (validity.tv_sec / 4);
dout(" expires=%lu renew_after=%lu\n", new_expires,
new_renew_after);
/* ticket blob for service */
ceph_decode_8_safe(p, end, is_enc, bad);
if (is_enc) {
/* encrypted */
dout(" encrypted ticket\n");
dlen = ceph_x_decrypt(&old_key, p, end, &ticket_buf, 0);
if (dlen < 0) {
ret = dlen;
goto out;
}
tp = ticket_buf;
dlen = ceph_decode_32(&tp);
} else {
/* unencrypted */
ceph_decode_32_safe(p, end, dlen, bad);
ticket_buf = kmalloc(dlen, GFP_NOFS);
if (!ticket_buf) {
ret = -ENOMEM;
goto out;
}
tp = ticket_buf;
ceph_decode_need(p, end, dlen, bad);
ceph_decode_copy(p, ticket_buf, dlen);
}
tpend = tp + dlen;
dout(" ticket blob is %d bytes\n", dlen);
ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad);
blob_struct_v = ceph_decode_8(&tp);
new_secret_id = ceph_decode_64(&tp);
ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend);
if (ret)
goto out;
/* all is well, update our ticket */
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
th->session_key = new_session_key;
th->ticket_blob = new_ticket_blob;
th->validity = new_validity;
th->secret_id = new_secret_id;
th->expires = new_expires;
th->renew_after = new_renew_after;
dout(" got ticket service %d (%s) secret_id %lld len %d\n",
type, ceph_entity_type_name(type), th->secret_id,
(int)th->ticket_blob->vec.iov_len);
xi->have_keys |= th->service;
out:
kfree(ticket_buf);
kfree(dbuf);
return ret;
bad:
ret = -EINVAL;
goto out;
}
static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void *buf, void *end)
{
void *p = buf;
u8 reply_struct_v;
u32 num;
int ret;
ceph_decode_8_safe(&p, end, reply_struct_v, bad);
if (reply_struct_v != 1)
return -EINVAL;
ceph_decode_32_safe(&p, end, num, bad);
dout("%d tickets\n", num);
while (num--) {
ret = process_one_ticket(ac, secret, &p, end);
if (ret)
return ret;
}
return 0;
bad:
return -EINVAL;
}
static int ceph_x_build_authorizer(struct ceph_auth_client *ac,
struct ceph_x_ticket_handler *th,
struct ceph_x_authorizer *au)
{
int maxlen;
struct ceph_x_authorize_a *msg_a;
struct ceph_x_authorize_b msg_b;
void *p, *end;
int ret;
int ticket_blob_len =
(th->ticket_blob ? th->ticket_blob->vec.iov_len : 0);
dout("build_authorizer for %s %p\n",
ceph_entity_type_name(th->service), au);
maxlen = sizeof(*msg_a) + sizeof(msg_b) +
ceph_x_encrypt_buflen(ticket_blob_len);
dout(" need len %d\n", maxlen);
if (au->buf && au->buf->alloc_len < maxlen) {
ceph_buffer_put(au->buf);
au->buf = NULL;
}
if (!au->buf) {
au->buf = ceph_buffer_new(maxlen, GFP_NOFS);
if (!au->buf)
return -ENOMEM;
}
au->service = th->service;
au->secret_id = th->secret_id;
msg_a = au->buf->vec.iov_base;
msg_a->struct_v = 1;
msg_a->global_id = cpu_to_le64(ac->global_id);
msg_a->service_id = cpu_to_le32(th->service);
msg_a->ticket_blob.struct_v = 1;
msg_a->ticket_blob.secret_id = cpu_to_le64(th->secret_id);
msg_a->ticket_blob.blob_len = cpu_to_le32(ticket_blob_len);
if (ticket_blob_len) {
memcpy(msg_a->ticket_blob.blob, th->ticket_blob->vec.iov_base,
th->ticket_blob->vec.iov_len);
}
dout(" th %p secret_id %lld %lld\n", th, th->secret_id,
le64_to_cpu(msg_a->ticket_blob.secret_id));
p = msg_a + 1;
p += ticket_blob_len;
end = au->buf->vec.iov_base + au->buf->vec.iov_len;
get_random_bytes(&au->nonce, sizeof(au->nonce));
msg_b.struct_v = 1;
msg_b.nonce = cpu_to_le64(au->nonce);
ret = ceph_x_encrypt(&th->session_key, &msg_b, sizeof(msg_b),
p, end - p);
if (ret < 0)
goto out_buf;
p += ret;
au->buf->vec.iov_len = p - au->buf->vec.iov_base;
dout(" built authorizer nonce %llx len %d\n", au->nonce,
(int)au->buf->vec.iov_len);
BUG_ON(au->buf->vec.iov_len > maxlen);
return 0;
out_buf:
ceph_buffer_put(au->buf);
au->buf = NULL;
return ret;
}
static int ceph_x_encode_ticket(struct ceph_x_ticket_handler *th,
void **p, void *end)
{
ceph_decode_need(p, end, 1 + sizeof(u64), bad);
ceph_encode_8(p, 1);
ceph_encode_64(p, th->secret_id);
if (th->ticket_blob) {
const char *buf = th->ticket_blob->vec.iov_base;
u32 len = th->ticket_blob->vec.iov_len;
ceph_encode_32_safe(p, end, len, bad);
ceph_encode_copy_safe(p, end, buf, len, bad);
} else {
ceph_encode_32_safe(p, end, 0, bad);
}
return 0;
bad:
return -ERANGE;
}
static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed)
{
int want = ac->want_keys;
struct ceph_x_info *xi = ac->private;
int service;
*pneed = ac->want_keys & ~(xi->have_keys);
for (service = 1; service <= want; service <<= 1) {
struct ceph_x_ticket_handler *th;
if (!(ac->want_keys & service))
continue;
if (*pneed & service)
continue;
th = get_ticket_handler(ac, service);
if (IS_ERR(th)) {
*pneed |= service;
continue;
}
if (get_seconds() >= th->renew_after)
*pneed |= service;
if (get_seconds() >= th->expires)
xi->have_keys &= ~service;
}
}
static int ceph_x_build_request(struct ceph_auth_client *ac,
void *buf, void *end)
{
struct ceph_x_info *xi = ac->private;
int need;
struct ceph_x_request_header *head = buf;
int ret;
struct ceph_x_ticket_handler *th =
get_ticket_handler(ac, CEPH_ENTITY_TYPE_AUTH);
if (IS_ERR(th))
return PTR_ERR(th);
ceph_x_validate_tickets(ac, &need);
dout("build_request want %x have %x need %x\n",
ac->want_keys, xi->have_keys, need);
if (need & CEPH_ENTITY_TYPE_AUTH) {
struct ceph_x_authenticate *auth = (void *)(head + 1);
void *p = auth + 1;
struct ceph_x_challenge_blob tmp;
char tmp_enc[40];
u64 *u;
if (p > end)
return -ERANGE;
dout(" get_auth_session_key\n");
head->op = cpu_to_le16(CEPHX_GET_AUTH_SESSION_KEY);
/* encrypt and hash */
get_random_bytes(&auth->client_challenge, sizeof(u64));
tmp.client_challenge = auth->client_challenge;
tmp.server_challenge = cpu_to_le64(xi->server_challenge);
ret = ceph_x_encrypt(&xi->secret, &tmp, sizeof(tmp),
tmp_enc, sizeof(tmp_enc));
if (ret < 0)
return ret;
auth->struct_v = 1;
auth->key = 0;
for (u = (u64 *)tmp_enc; u + 1 <= (u64 *)(tmp_enc + ret); u++)
auth->key ^= *(__le64 *)u;
dout(" server_challenge %llx client_challenge %llx key %llx\n",
xi->server_challenge, le64_to_cpu(auth->client_challenge),
le64_to_cpu(auth->key));
/* now encode the old ticket if exists */
ret = ceph_x_encode_ticket(th, &p, end);
if (ret < 0)
return ret;
return p - buf;
}
if (need) {
void *p = head + 1;
struct ceph_x_service_ticket_request *req;
if (p > end)
return -ERANGE;
head->op = cpu_to_le16(CEPHX_GET_PRINCIPAL_SESSION_KEY);
ret = ceph_x_build_authorizer(ac, th, &xi->auth_authorizer);
if (ret)
return ret;
ceph_encode_copy(&p, xi->auth_authorizer.buf->vec.iov_base,
xi->auth_authorizer.buf->vec.iov_len);
req = p;
req->keys = cpu_to_le32(need);
p += sizeof(*req);
return p - buf;
}
return 0;
}
static int ceph_x_handle_reply(struct ceph_auth_client *ac, int result,
void *buf, void *end)
{
struct ceph_x_info *xi = ac->private;
struct ceph_x_reply_header *head = buf;
struct ceph_x_ticket_handler *th;
int len = end - buf;
int op;
int ret;
if (result)
return result; /* XXX hmm? */
if (xi->starting) {
/* it's a hello */
struct ceph_x_server_challenge *sc = buf;
if (len != sizeof(*sc))
return -EINVAL;
xi->server_challenge = le64_to_cpu(sc->server_challenge);
dout("handle_reply got server challenge %llx\n",
xi->server_challenge);
xi->starting = false;
xi->have_keys &= ~CEPH_ENTITY_TYPE_AUTH;
return -EAGAIN;
}
op = le16_to_cpu(head->op);
result = le32_to_cpu(head->result);
dout("handle_reply op %d result %d\n", op, result);
switch (op) {
case CEPHX_GET_AUTH_SESSION_KEY:
/* verify auth key */
ret = ceph_x_proc_ticket_reply(ac, &xi->secret,
buf + sizeof(*head), end);
break;
case CEPHX_GET_PRINCIPAL_SESSION_KEY:
th = get_ticket_handler(ac, CEPH_ENTITY_TYPE_AUTH);
if (IS_ERR(th))
return PTR_ERR(th);
ret = ceph_x_proc_ticket_reply(ac, &th->session_key,
buf + sizeof(*head), end);
break;
default:
return -EINVAL;
}
if (ret)
return ret;
if (ac->want_keys == xi->have_keys)
return 0;
return -EAGAIN;
}
static int ceph_x_create_authorizer(
struct ceph_auth_client *ac, int peer_type,
struct ceph_auth_handshake *auth)
{
struct ceph_x_authorizer *au;
struct ceph_x_ticket_handler *th;
int ret;
th = get_ticket_handler(ac, peer_type);
if (IS_ERR(th))
return PTR_ERR(th);
au = kzalloc(sizeof(*au), GFP_NOFS);
if (!au)
return -ENOMEM;
ret = ceph_x_build_authorizer(ac, th, au);
if (ret) {
kfree(au);
return ret;
}
auth->authorizer = (struct ceph_authorizer *) au;
auth->authorizer_buf = au->buf->vec.iov_base;
auth->authorizer_buf_len = au->buf->vec.iov_len;
auth->authorizer_reply_buf = au->reply_buf;
auth->authorizer_reply_buf_len = sizeof (au->reply_buf);
return 0;
}
static int ceph_x_update_authorizer(
struct ceph_auth_client *ac, int peer_type,
struct ceph_auth_handshake *auth)
{
struct ceph_x_authorizer *au;
struct ceph_x_ticket_handler *th;
th = get_ticket_handler(ac, peer_type);
if (IS_ERR(th))
return PTR_ERR(th);
au = (struct ceph_x_authorizer *)auth->authorizer;
if (au->secret_id < th->secret_id) {
dout("ceph_x_update_authorizer service %u secret %llu < %llu\n",
au->service, au->secret_id, th->secret_id);
return ceph_x_build_authorizer(ac, th, au);
}
return 0;
}
static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,
struct ceph_authorizer *a, size_t len)
{
struct ceph_x_authorizer *au = (void *)a;
struct ceph_x_ticket_handler *th;
int ret = 0;
struct ceph_x_authorize_reply reply;
void *preply = &reply;
void *p = au->reply_buf;
void *end = p + sizeof(au->reply_buf);
th = get_ticket_handler(ac, au->service);
if (IS_ERR(th))
return PTR_ERR(th);
ret = ceph_x_decrypt(&th->session_key, &p, end, &preply, sizeof(reply));
if (ret < 0)
return ret;
if (ret != sizeof(reply))
return -EPERM;
if (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one))
ret = -EPERM;
else
ret = 0;
dout("verify_authorizer_reply nonce %llx got %llx ret %d\n",
au->nonce, le64_to_cpu(reply.nonce_plus_one), ret);
return ret;
}
static void ceph_x_destroy_authorizer(struct ceph_auth_client *ac,
struct ceph_authorizer *a)
{
struct ceph_x_authorizer *au = (void *)a;
ceph_buffer_put(au->buf);
kfree(au);
}
static void ceph_x_reset(struct ceph_auth_client *ac)
{
struct ceph_x_info *xi = ac->private;
dout("reset\n");
xi->starting = true;
xi->server_challenge = 0;
}
static void ceph_x_destroy(struct ceph_auth_client *ac)
{
struct ceph_x_info *xi = ac->private;
struct rb_node *p;
dout("ceph_x_destroy %p\n", ac);
ceph_crypto_key_destroy(&xi->secret);
while ((p = rb_first(&xi->ticket_handlers)) != NULL) {
struct ceph_x_ticket_handler *th =
rb_entry(p, struct ceph_x_ticket_handler, node);
remove_ticket_handler(ac, th);
}
if (xi->auth_authorizer.buf)
ceph_buffer_put(xi->auth_authorizer.buf);
kfree(ac->private);
ac->private = NULL;
}
static void ceph_x_invalidate_authorizer(struct ceph_auth_client *ac,
int peer_type)
{
struct ceph_x_ticket_handler *th;
th = get_ticket_handler(ac, peer_type);
if (!IS_ERR(th))
memset(&th->validity, 0, sizeof(th->validity));
}
static const struct ceph_auth_client_ops ceph_x_ops = {
.name = "x",
.is_authenticated = ceph_x_is_authenticated,
.should_authenticate = ceph_x_should_authenticate,
.build_request = ceph_x_build_request,
.handle_reply = ceph_x_handle_reply,
.create_authorizer = ceph_x_create_authorizer,
.update_authorizer = ceph_x_update_authorizer,
.verify_authorizer_reply = ceph_x_verify_authorizer_reply,
.destroy_authorizer = ceph_x_destroy_authorizer,
.invalidate_authorizer = ceph_x_invalidate_authorizer,
.reset = ceph_x_reset,
.destroy = ceph_x_destroy,
};
int ceph_x_init(struct ceph_auth_client *ac)
{
struct ceph_x_info *xi;
int ret;
dout("ceph_x_init %p\n", ac);
ret = -ENOMEM;
xi = kzalloc(sizeof(*xi), GFP_NOFS);
if (!xi)
goto out;
ret = -EINVAL;
if (!ac->key) {
pr_err("no secret set (for auth_x protocol)\n");
goto out_nomem;
}
ret = ceph_crypto_key_clone(&xi->secret, ac->key);
if (ret < 0) {
pr_err("cannot clone key: %d\n", ret);
goto out_nomem;
}
xi->starting = true;
xi->ticket_handlers = RB_ROOT;
ac->protocol = CEPH_AUTH_CEPHX;
ac->private = xi;
ac->ops = &ceph_x_ops;
return 0;
out_nomem:
kfree(xi);
out:
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2273_0 |
crossvul-cpp_data_bad_5289_0 | /*
*******************************************************************************
** O.S : Linux
** FILE NAME : arcmsr_hba.c
** BY : Nick Cheng, C.L. Huang
** Description: SCSI RAID Device Driver for Areca RAID Controller
*******************************************************************************
** Copyright (C) 2002 - 2014, Areca Technology Corporation All rights reserved
**
** Web site: www.areca.com.tw
** E-mail: support@areca.com.tw
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License version 2 as
** published by the Free Software Foundation.
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
*******************************************************************************
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING,BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
** For history of changes, see Documentation/scsi/ChangeLog.arcmsr
** Firmware Specification, see Documentation/scsi/arcmsr_spec.txt
*******************************************************************************
*/
#include <linux/module.h>
#include <linux/reboot.h>
#include <linux/spinlock.h>
#include <linux/pci_ids.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/aer.h>
#include <linux/circ_buf.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsicam.h>
#include "arcmsr.h"
MODULE_AUTHOR("Nick Cheng, C.L. Huang <support@areca.com.tw>");
MODULE_DESCRIPTION("Areca ARC11xx/12xx/16xx/188x SAS/SATA RAID Controller Driver");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(ARCMSR_DRIVER_VERSION);
#define ARCMSR_SLEEPTIME 10
#define ARCMSR_RETRYCOUNT 12
static wait_queue_head_t wait_q;
static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd);
static int arcmsr_iop_confirm(struct AdapterControlBlock *acb);
static int arcmsr_abort(struct scsi_cmnd *);
static int arcmsr_bus_reset(struct scsi_cmnd *);
static int arcmsr_bios_param(struct scsi_device *sdev,
struct block_device *bdev, sector_t capacity, int *info);
static int arcmsr_queue_command(struct Scsi_Host *h, struct scsi_cmnd *cmd);
static int arcmsr_probe(struct pci_dev *pdev,
const struct pci_device_id *id);
static int arcmsr_suspend(struct pci_dev *pdev, pm_message_t state);
static int arcmsr_resume(struct pci_dev *pdev);
static void arcmsr_remove(struct pci_dev *pdev);
static void arcmsr_shutdown(struct pci_dev *pdev);
static void arcmsr_iop_init(struct AdapterControlBlock *acb);
static void arcmsr_free_ccb_pool(struct AdapterControlBlock *acb);
static u32 arcmsr_disable_outbound_ints(struct AdapterControlBlock *acb);
static void arcmsr_enable_outbound_ints(struct AdapterControlBlock *acb,
u32 intmask_org);
static void arcmsr_stop_adapter_bgrb(struct AdapterControlBlock *acb);
static void arcmsr_hbaA_flush_cache(struct AdapterControlBlock *acb);
static void arcmsr_hbaB_flush_cache(struct AdapterControlBlock *acb);
static void arcmsr_request_device_map(unsigned long pacb);
static void arcmsr_hbaA_request_device_map(struct AdapterControlBlock *acb);
static void arcmsr_hbaB_request_device_map(struct AdapterControlBlock *acb);
static void arcmsr_hbaC_request_device_map(struct AdapterControlBlock *acb);
static void arcmsr_message_isr_bh_fn(struct work_struct *work);
static bool arcmsr_get_firmware_spec(struct AdapterControlBlock *acb);
static void arcmsr_start_adapter_bgrb(struct AdapterControlBlock *acb);
static void arcmsr_hbaC_message_isr(struct AdapterControlBlock *pACB);
static void arcmsr_hbaD_message_isr(struct AdapterControlBlock *acb);
static void arcmsr_hardware_reset(struct AdapterControlBlock *acb);
static const char *arcmsr_info(struct Scsi_Host *);
static irqreturn_t arcmsr_interrupt(struct AdapterControlBlock *acb);
static void arcmsr_free_irq(struct pci_dev *, struct AdapterControlBlock *);
static void arcmsr_wait_firmware_ready(struct AdapterControlBlock *acb);
static int arcmsr_adjust_disk_queue_depth(struct scsi_device *sdev, int queue_depth)
{
if (queue_depth > ARCMSR_MAX_CMD_PERLUN)
queue_depth = ARCMSR_MAX_CMD_PERLUN;
return scsi_change_queue_depth(sdev, queue_depth);
}
static struct scsi_host_template arcmsr_scsi_host_template = {
.module = THIS_MODULE,
.name = "Areca SAS/SATA RAID driver",
.info = arcmsr_info,
.queuecommand = arcmsr_queue_command,
.eh_abort_handler = arcmsr_abort,
.eh_bus_reset_handler = arcmsr_bus_reset,
.bios_param = arcmsr_bios_param,
.change_queue_depth = arcmsr_adjust_disk_queue_depth,
.can_queue = ARCMSR_MAX_OUTSTANDING_CMD,
.this_id = ARCMSR_SCSI_INITIATOR_ID,
.sg_tablesize = ARCMSR_DEFAULT_SG_ENTRIES,
.max_sectors = ARCMSR_MAX_XFER_SECTORS_C,
.cmd_per_lun = ARCMSR_MAX_CMD_PERLUN,
.use_clustering = ENABLE_CLUSTERING,
.shost_attrs = arcmsr_host_attrs,
.no_write_same = 1,
};
static struct pci_device_id arcmsr_device_id_table[] = {
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1110),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1120),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1130),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1160),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1170),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1200),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1201),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1202),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1203),
.driver_data = ACB_ADAPTER_TYPE_B},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1210),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1214),
.driver_data = ACB_ADAPTER_TYPE_D},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1220),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1230),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1260),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1270),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1280),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1380),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1381),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1680),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1681),
.driver_data = ACB_ADAPTER_TYPE_A},
{PCI_DEVICE(PCI_VENDOR_ID_ARECA, PCI_DEVICE_ID_ARECA_1880),
.driver_data = ACB_ADAPTER_TYPE_C},
{0, 0}, /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, arcmsr_device_id_table);
static struct pci_driver arcmsr_pci_driver = {
.name = "arcmsr",
.id_table = arcmsr_device_id_table,
.probe = arcmsr_probe,
.remove = arcmsr_remove,
.suspend = arcmsr_suspend,
.resume = arcmsr_resume,
.shutdown = arcmsr_shutdown,
};
/*
****************************************************************************
****************************************************************************
*/
static void arcmsr_free_mu(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_B:
case ACB_ADAPTER_TYPE_D: {
dma_free_coherent(&acb->pdev->dev, acb->roundup_ccbsize,
acb->dma_coherent2, acb->dma_coherent_handle2);
break;
}
}
}
static bool arcmsr_remap_pciregion(struct AdapterControlBlock *acb)
{
struct pci_dev *pdev = acb->pdev;
switch (acb->adapter_type){
case ACB_ADAPTER_TYPE_A:{
acb->pmuA = ioremap(pci_resource_start(pdev,0), pci_resource_len(pdev,0));
if (!acb->pmuA) {
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
break;
}
case ACB_ADAPTER_TYPE_B:{
void __iomem *mem_base0, *mem_base1;
mem_base0 = ioremap(pci_resource_start(pdev, 0), pci_resource_len(pdev, 0));
if (!mem_base0) {
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
mem_base1 = ioremap(pci_resource_start(pdev, 2), pci_resource_len(pdev, 2));
if (!mem_base1) {
iounmap(mem_base0);
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
acb->mem_base0 = mem_base0;
acb->mem_base1 = mem_base1;
break;
}
case ACB_ADAPTER_TYPE_C:{
acb->pmuC = ioremap_nocache(pci_resource_start(pdev, 1), pci_resource_len(pdev, 1));
if (!acb->pmuC) {
printk(KERN_NOTICE "arcmsr%d: memory mapping region fail \n", acb->host->host_no);
return false;
}
if (readl(&acb->pmuC->outbound_doorbell) & ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR, &acb->pmuC->outbound_doorbell_clear);/*clear interrupt*/
return true;
}
break;
}
case ACB_ADAPTER_TYPE_D: {
void __iomem *mem_base0;
unsigned long addr, range, flags;
addr = (unsigned long)pci_resource_start(pdev, 0);
range = pci_resource_len(pdev, 0);
flags = pci_resource_flags(pdev, 0);
mem_base0 = ioremap(addr, range);
if (!mem_base0) {
pr_notice("arcmsr%d: memory mapping region fail\n",
acb->host->host_no);
return false;
}
acb->mem_base0 = mem_base0;
break;
}
}
return true;
}
static void arcmsr_unmap_pciregion(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:{
iounmap(acb->pmuA);
}
break;
case ACB_ADAPTER_TYPE_B:{
iounmap(acb->mem_base0);
iounmap(acb->mem_base1);
}
break;
case ACB_ADAPTER_TYPE_C:{
iounmap(acb->pmuC);
}
break;
case ACB_ADAPTER_TYPE_D:
iounmap(acb->mem_base0);
break;
}
}
static irqreturn_t arcmsr_do_interrupt(int irq, void *dev_id)
{
irqreturn_t handle_state;
struct AdapterControlBlock *acb = dev_id;
handle_state = arcmsr_interrupt(acb);
return handle_state;
}
static int arcmsr_bios_param(struct scsi_device *sdev,
struct block_device *bdev, sector_t capacity, int *geom)
{
int ret, heads, sectors, cylinders, total_capacity;
unsigned char *buffer;/* return copy of block device's partition table */
buffer = scsi_bios_ptable(bdev);
if (buffer) {
ret = scsi_partsize(buffer, capacity, &geom[2], &geom[0], &geom[1]);
kfree(buffer);
if (ret != -1)
return ret;
}
total_capacity = capacity;
heads = 64;
sectors = 32;
cylinders = total_capacity / (heads * sectors);
if (cylinders > 1024) {
heads = 255;
sectors = 63;
cylinders = total_capacity / (heads * sectors);
}
geom[0] = heads;
geom[1] = sectors;
geom[2] = cylinders;
return 0;
}
static uint8_t arcmsr_hbaA_wait_msgint_ready(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
int i;
for (i = 0; i < 2000; i++) {
if (readl(®->outbound_intstatus) &
ARCMSR_MU_OUTBOUND_MESSAGE0_INT) {
writel(ARCMSR_MU_OUTBOUND_MESSAGE0_INT,
®->outbound_intstatus);
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static uint8_t arcmsr_hbaB_wait_msgint_ready(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
int i;
for (i = 0; i < 2000; i++) {
if (readl(reg->iop2drv_doorbell)
& ARCMSR_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_MESSAGE_INT_CLEAR_PATTERN,
reg->iop2drv_doorbell);
writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT,
reg->drv2iop_doorbell);
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static uint8_t arcmsr_hbaC_wait_msgint_ready(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
int i;
for (i = 0; i < 2000; i++) {
if (readl(&phbcmu->outbound_doorbell)
& ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR,
&phbcmu->outbound_doorbell_clear); /*clear interrupt*/
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static bool arcmsr_hbaD_wait_msgint_ready(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *reg = pACB->pmuD;
int i;
for (i = 0; i < 2000; i++) {
if (readl(reg->outbound_doorbell)
& ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE,
reg->outbound_doorbell);
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
static void arcmsr_hbaA_flush_cache(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
int retry_count = 30;
writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, ®->inbound_msgaddr0);
do {
if (arcmsr_hbaA_wait_msgint_ready(acb))
break;
else {
retry_count--;
printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \
timeout, retry count down = %d \n", acb->host->host_no, retry_count);
}
} while (retry_count != 0);
}
static void arcmsr_hbaB_flush_cache(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
int retry_count = 30;
writel(ARCMSR_MESSAGE_FLUSH_CACHE, reg->drv2iop_doorbell);
do {
if (arcmsr_hbaB_wait_msgint_ready(acb))
break;
else {
retry_count--;
printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \
timeout,retry count down = %d \n", acb->host->host_no, retry_count);
}
} while (retry_count != 0);
}
static void arcmsr_hbaC_flush_cache(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *reg = pACB->pmuC;
int retry_count = 30;/* enlarge wait flush adapter cache time: 10 minute */
writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
do {
if (arcmsr_hbaC_wait_msgint_ready(pACB)) {
break;
} else {
retry_count--;
printk(KERN_NOTICE "arcmsr%d: wait 'flush adapter cache' \
timeout,retry count down = %d \n", pACB->host->host_no, retry_count);
}
} while (retry_count != 0);
return;
}
static void arcmsr_hbaD_flush_cache(struct AdapterControlBlock *pACB)
{
int retry_count = 15;
struct MessageUnit_D *reg = pACB->pmuD;
writel(ARCMSR_INBOUND_MESG0_FLUSH_CACHE, reg->inbound_msgaddr0);
do {
if (arcmsr_hbaD_wait_msgint_ready(pACB))
break;
retry_count--;
pr_notice("arcmsr%d: wait 'flush adapter "
"cache' timeout, retry count down = %d\n",
pACB->host->host_no, retry_count);
} while (retry_count != 0);
}
static void arcmsr_flush_adapter_cache(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
arcmsr_hbaA_flush_cache(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
arcmsr_hbaB_flush_cache(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
arcmsr_hbaC_flush_cache(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_flush_cache(acb);
break;
}
}
static bool arcmsr_alloc_io_queue(struct AdapterControlBlock *acb)
{
bool rtn = true;
void *dma_coherent;
dma_addr_t dma_coherent_handle;
struct pci_dev *pdev = acb->pdev;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg;
acb->roundup_ccbsize = roundup(sizeof(struct MessageUnit_B), 32);
dma_coherent = dma_zalloc_coherent(&pdev->dev, acb->roundup_ccbsize,
&dma_coherent_handle, GFP_KERNEL);
if (!dma_coherent) {
pr_notice("arcmsr%d: DMA allocation failed\n", acb->host->host_no);
return false;
}
acb->dma_coherent_handle2 = dma_coherent_handle;
acb->dma_coherent2 = dma_coherent;
reg = (struct MessageUnit_B *)dma_coherent;
acb->pmuB = reg;
if (acb->pdev->device == PCI_DEVICE_ID_ARECA_1203) {
reg->drv2iop_doorbell = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL_1203);
reg->drv2iop_doorbell_mask = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL_MASK_1203);
reg->iop2drv_doorbell = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL_1203);
reg->iop2drv_doorbell_mask = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL_MASK_1203);
} else {
reg->drv2iop_doorbell = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL);
reg->drv2iop_doorbell_mask = MEM_BASE0(ARCMSR_DRV2IOP_DOORBELL_MASK);
reg->iop2drv_doorbell = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL);
reg->iop2drv_doorbell_mask = MEM_BASE0(ARCMSR_IOP2DRV_DOORBELL_MASK);
}
reg->message_wbuffer = MEM_BASE1(ARCMSR_MESSAGE_WBUFFER);
reg->message_rbuffer = MEM_BASE1(ARCMSR_MESSAGE_RBUFFER);
reg->message_rwbuffer = MEM_BASE1(ARCMSR_MESSAGE_RWBUFFER);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg;
acb->roundup_ccbsize = roundup(sizeof(struct MessageUnit_D), 32);
dma_coherent = dma_zalloc_coherent(&pdev->dev, acb->roundup_ccbsize,
&dma_coherent_handle, GFP_KERNEL);
if (!dma_coherent) {
pr_notice("arcmsr%d: DMA allocation failed\n", acb->host->host_no);
return false;
}
acb->dma_coherent_handle2 = dma_coherent_handle;
acb->dma_coherent2 = dma_coherent;
reg = (struct MessageUnit_D *)dma_coherent;
acb->pmuD = reg;
reg->chip_id = MEM_BASE0(ARCMSR_ARC1214_CHIP_ID);
reg->cpu_mem_config = MEM_BASE0(ARCMSR_ARC1214_CPU_MEMORY_CONFIGURATION);
reg->i2o_host_interrupt_mask = MEM_BASE0(ARCMSR_ARC1214_I2_HOST_INTERRUPT_MASK);
reg->sample_at_reset = MEM_BASE0(ARCMSR_ARC1214_SAMPLE_RESET);
reg->reset_request = MEM_BASE0(ARCMSR_ARC1214_RESET_REQUEST);
reg->host_int_status = MEM_BASE0(ARCMSR_ARC1214_MAIN_INTERRUPT_STATUS);
reg->pcief0_int_enable = MEM_BASE0(ARCMSR_ARC1214_PCIE_F0_INTERRUPT_ENABLE);
reg->inbound_msgaddr0 = MEM_BASE0(ARCMSR_ARC1214_INBOUND_MESSAGE0);
reg->inbound_msgaddr1 = MEM_BASE0(ARCMSR_ARC1214_INBOUND_MESSAGE1);
reg->outbound_msgaddr0 = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_MESSAGE0);
reg->outbound_msgaddr1 = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_MESSAGE1);
reg->inbound_doorbell = MEM_BASE0(ARCMSR_ARC1214_INBOUND_DOORBELL);
reg->outbound_doorbell = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_DOORBELL);
reg->outbound_doorbell_enable = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_DOORBELL_ENABLE);
reg->inboundlist_base_low = MEM_BASE0(ARCMSR_ARC1214_INBOUND_LIST_BASE_LOW);
reg->inboundlist_base_high = MEM_BASE0(ARCMSR_ARC1214_INBOUND_LIST_BASE_HIGH);
reg->inboundlist_write_pointer = MEM_BASE0(ARCMSR_ARC1214_INBOUND_LIST_WRITE_POINTER);
reg->outboundlist_base_low = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_BASE_LOW);
reg->outboundlist_base_high = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_BASE_HIGH);
reg->outboundlist_copy_pointer = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_COPY_POINTER);
reg->outboundlist_read_pointer = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_LIST_READ_POINTER);
reg->outboundlist_interrupt_cause = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_INTERRUPT_CAUSE);
reg->outboundlist_interrupt_enable = MEM_BASE0(ARCMSR_ARC1214_OUTBOUND_INTERRUPT_ENABLE);
reg->message_wbuffer = MEM_BASE0(ARCMSR_ARC1214_MESSAGE_WBUFFER);
reg->message_rbuffer = MEM_BASE0(ARCMSR_ARC1214_MESSAGE_RBUFFER);
reg->msgcode_rwbuffer = MEM_BASE0(ARCMSR_ARC1214_MESSAGE_RWBUFFER);
}
break;
default:
break;
}
return rtn;
}
static int arcmsr_alloc_ccb_pool(struct AdapterControlBlock *acb)
{
struct pci_dev *pdev = acb->pdev;
void *dma_coherent;
dma_addr_t dma_coherent_handle;
struct CommandControlBlock *ccb_tmp;
int i = 0, j = 0;
dma_addr_t cdb_phyaddr;
unsigned long roundup_ccbsize;
unsigned long max_xfer_len;
unsigned long max_sg_entrys;
uint32_t firm_config_version;
for (i = 0; i < ARCMSR_MAX_TARGETID; i++)
for (j = 0; j < ARCMSR_MAX_TARGETLUN; j++)
acb->devstate[i][j] = ARECA_RAID_GONE;
max_xfer_len = ARCMSR_MAX_XFER_LEN;
max_sg_entrys = ARCMSR_DEFAULT_SG_ENTRIES;
firm_config_version = acb->firm_cfg_version;
if((firm_config_version & 0xFF) >= 3){
max_xfer_len = (ARCMSR_CDB_SG_PAGE_LENGTH << ((firm_config_version >> 8) & 0xFF)) * 1024;/* max 4M byte */
max_sg_entrys = (max_xfer_len/4096);
}
acb->host->max_sectors = max_xfer_len/512;
acb->host->sg_tablesize = max_sg_entrys;
roundup_ccbsize = roundup(sizeof(struct CommandControlBlock) + (max_sg_entrys - 1) * sizeof(struct SG64ENTRY), 32);
acb->uncache_size = roundup_ccbsize * ARCMSR_MAX_FREECCB_NUM;
dma_coherent = dma_alloc_coherent(&pdev->dev, acb->uncache_size, &dma_coherent_handle, GFP_KERNEL);
if(!dma_coherent){
printk(KERN_NOTICE "arcmsr%d: dma_alloc_coherent got error\n", acb->host->host_no);
return -ENOMEM;
}
acb->dma_coherent = dma_coherent;
acb->dma_coherent_handle = dma_coherent_handle;
memset(dma_coherent, 0, acb->uncache_size);
ccb_tmp = dma_coherent;
acb->vir2phy_offset = (unsigned long)dma_coherent - (unsigned long)dma_coherent_handle;
for(i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++){
cdb_phyaddr = dma_coherent_handle + offsetof(struct CommandControlBlock, arcmsr_cdb);
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
case ACB_ADAPTER_TYPE_B:
ccb_tmp->cdb_phyaddr = cdb_phyaddr >> 5;
break;
case ACB_ADAPTER_TYPE_C:
case ACB_ADAPTER_TYPE_D:
ccb_tmp->cdb_phyaddr = cdb_phyaddr;
break;
}
acb->pccb_pool[i] = ccb_tmp;
ccb_tmp->acb = acb;
INIT_LIST_HEAD(&ccb_tmp->list);
list_add_tail(&ccb_tmp->list, &acb->ccb_free_list);
ccb_tmp = (struct CommandControlBlock *)((unsigned long)ccb_tmp + roundup_ccbsize);
dma_coherent_handle = dma_coherent_handle + roundup_ccbsize;
}
return 0;
}
static void arcmsr_message_isr_bh_fn(struct work_struct *work)
{
struct AdapterControlBlock *acb = container_of(work,
struct AdapterControlBlock, arcmsr_do_message_isr_bh);
char *acb_dev_map = (char *)acb->device_map;
uint32_t __iomem *signature = NULL;
char __iomem *devicemap = NULL;
int target, lun;
struct scsi_device *psdev;
char diff, temp;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
signature = (uint32_t __iomem *)(®->message_rwbuffer[0]);
devicemap = (char __iomem *)(®->message_rwbuffer[21]);
break;
}
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
signature = (uint32_t __iomem *)(®->message_rwbuffer[0]);
devicemap = (char __iomem *)(®->message_rwbuffer[21]);
break;
}
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
signature = (uint32_t __iomem *)(®->msgcode_rwbuffer[0]);
devicemap = (char __iomem *)(®->msgcode_rwbuffer[21]);
break;
}
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
signature = (uint32_t __iomem *)(®->msgcode_rwbuffer[0]);
devicemap = (char __iomem *)(®->msgcode_rwbuffer[21]);
break;
}
}
atomic_inc(&acb->rq_map_token);
if (readl(signature) != ARCMSR_SIGNATURE_GET_CONFIG)
return;
for (target = 0; target < ARCMSR_MAX_TARGETID - 1;
target++) {
temp = readb(devicemap);
diff = (*acb_dev_map) ^ temp;
if (diff != 0) {
*acb_dev_map = temp;
for (lun = 0; lun < ARCMSR_MAX_TARGETLUN;
lun++) {
if ((diff & 0x01) == 1 &&
(temp & 0x01) == 1) {
scsi_add_device(acb->host,
0, target, lun);
} else if ((diff & 0x01) == 1
&& (temp & 0x01) == 0) {
psdev = scsi_device_lookup(acb->host,
0, target, lun);
if (psdev != NULL) {
scsi_remove_device(psdev);
scsi_device_put(psdev);
}
}
temp >>= 1;
diff >>= 1;
}
}
devicemap++;
acb_dev_map++;
}
}
static int
arcmsr_request_irq(struct pci_dev *pdev, struct AdapterControlBlock *acb)
{
int i, j, r;
struct msix_entry entries[ARCMST_NUM_MSIX_VECTORS];
for (i = 0; i < ARCMST_NUM_MSIX_VECTORS; i++)
entries[i].entry = i;
r = pci_enable_msix_range(pdev, entries, 1, ARCMST_NUM_MSIX_VECTORS);
if (r < 0)
goto msi_int;
acb->msix_vector_count = r;
for (i = 0; i < r; i++) {
if (request_irq(entries[i].vector,
arcmsr_do_interrupt, 0, "arcmsr", acb)) {
pr_warn("arcmsr%d: request_irq =%d failed!\n",
acb->host->host_no, entries[i].vector);
for (j = 0 ; j < i ; j++)
free_irq(entries[j].vector, acb);
pci_disable_msix(pdev);
goto msi_int;
}
acb->entries[i] = entries[i];
}
acb->acb_flags |= ACB_F_MSIX_ENABLED;
pr_info("arcmsr%d: msi-x enabled\n", acb->host->host_no);
return SUCCESS;
msi_int:
if (pci_enable_msi_exact(pdev, 1) < 0)
goto legacy_int;
if (request_irq(pdev->irq, arcmsr_do_interrupt,
IRQF_SHARED, "arcmsr", acb)) {
pr_warn("arcmsr%d: request_irq =%d failed!\n",
acb->host->host_no, pdev->irq);
pci_disable_msi(pdev);
goto legacy_int;
}
acb->acb_flags |= ACB_F_MSI_ENABLED;
pr_info("arcmsr%d: msi enabled\n", acb->host->host_no);
return SUCCESS;
legacy_int:
if (request_irq(pdev->irq, arcmsr_do_interrupt,
IRQF_SHARED, "arcmsr", acb)) {
pr_warn("arcmsr%d: request_irq = %d failed!\n",
acb->host->host_no, pdev->irq);
return FAILED;
}
return SUCCESS;
}
static int arcmsr_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct Scsi_Host *host;
struct AdapterControlBlock *acb;
uint8_t bus,dev_fun;
int error;
error = pci_enable_device(pdev);
if(error){
return -ENODEV;
}
host = scsi_host_alloc(&arcmsr_scsi_host_template, sizeof(struct AdapterControlBlock));
if(!host){
goto pci_disable_dev;
}
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if(error){
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if(error){
printk(KERN_WARNING
"scsi%d: No suitable DMA mask available\n",
host->host_no);
goto scsi_host_release;
}
}
init_waitqueue_head(&wait_q);
bus = pdev->bus->number;
dev_fun = pdev->devfn;
acb = (struct AdapterControlBlock *) host->hostdata;
memset(acb,0,sizeof(struct AdapterControlBlock));
acb->pdev = pdev;
acb->host = host;
host->max_lun = ARCMSR_MAX_TARGETLUN;
host->max_id = ARCMSR_MAX_TARGETID; /*16:8*/
host->max_cmd_len = 16; /*this is issue of 64bit LBA ,over 2T byte*/
host->can_queue = ARCMSR_MAX_OUTSTANDING_CMD;
host->cmd_per_lun = ARCMSR_MAX_CMD_PERLUN;
host->this_id = ARCMSR_SCSI_INITIATOR_ID;
host->unique_id = (bus << 8) | dev_fun;
pci_set_drvdata(pdev, host);
pci_set_master(pdev);
error = pci_request_regions(pdev, "arcmsr");
if(error){
goto scsi_host_release;
}
spin_lock_init(&acb->eh_lock);
spin_lock_init(&acb->ccblist_lock);
spin_lock_init(&acb->postq_lock);
spin_lock_init(&acb->doneq_lock);
spin_lock_init(&acb->rqbuffer_lock);
spin_lock_init(&acb->wqbuffer_lock);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_RQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->acb_flags &= ~ACB_F_SCSISTOPADAPTER;
INIT_LIST_HEAD(&acb->ccb_free_list);
acb->adapter_type = id->driver_data;
error = arcmsr_remap_pciregion(acb);
if(!error){
goto pci_release_regs;
}
error = arcmsr_alloc_io_queue(acb);
if (!error)
goto unmap_pci_region;
error = arcmsr_get_firmware_spec(acb);
if(!error){
goto free_hbb_mu;
}
error = arcmsr_alloc_ccb_pool(acb);
if(error){
goto free_hbb_mu;
}
error = scsi_add_host(host, &pdev->dev);
if(error){
goto free_ccb_pool;
}
if (arcmsr_request_irq(pdev, acb) == FAILED)
goto scsi_host_remove;
arcmsr_iop_init(acb);
INIT_WORK(&acb->arcmsr_do_message_isr_bh, arcmsr_message_isr_bh_fn);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
init_timer(&acb->eternal_timer);
acb->eternal_timer.expires = jiffies + msecs_to_jiffies(6 * HZ);
acb->eternal_timer.data = (unsigned long) acb;
acb->eternal_timer.function = &arcmsr_request_device_map;
add_timer(&acb->eternal_timer);
if(arcmsr_alloc_sysfs_attr(acb))
goto out_free_sysfs;
scsi_scan_host(host);
return 0;
out_free_sysfs:
del_timer_sync(&acb->eternal_timer);
flush_work(&acb->arcmsr_do_message_isr_bh);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
arcmsr_free_irq(pdev, acb);
scsi_host_remove:
scsi_remove_host(host);
free_ccb_pool:
arcmsr_free_ccb_pool(acb);
free_hbb_mu:
arcmsr_free_mu(acb);
unmap_pci_region:
arcmsr_unmap_pciregion(acb);
pci_release_regs:
pci_release_regions(pdev);
scsi_host_release:
scsi_host_put(host);
pci_disable_dev:
pci_disable_device(pdev);
return -ENODEV;
}
static void arcmsr_free_irq(struct pci_dev *pdev,
struct AdapterControlBlock *acb)
{
int i;
if (acb->acb_flags & ACB_F_MSI_ENABLED) {
free_irq(pdev->irq, acb);
pci_disable_msi(pdev);
} else if (acb->acb_flags & ACB_F_MSIX_ENABLED) {
for (i = 0; i < acb->msix_vector_count; i++)
free_irq(acb->entries[i].vector, acb);
pci_disable_msix(pdev);
} else
free_irq(pdev->irq, acb);
}
static int arcmsr_suspend(struct pci_dev *pdev, pm_message_t state)
{
uint32_t intmask_org;
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)host->hostdata;
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_free_irq(pdev, acb);
del_timer_sync(&acb->eternal_timer);
flush_work(&acb->arcmsr_do_message_isr_bh);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
pci_set_drvdata(pdev, host);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int arcmsr_resume(struct pci_dev *pdev)
{
int error;
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)host->hostdata;
pci_set_power_state(pdev, PCI_D0);
pci_enable_wake(pdev, PCI_D0, 0);
pci_restore_state(pdev);
if (pci_enable_device(pdev)) {
pr_warn("%s: pci_enable_device error\n", __func__);
return -ENODEV;
}
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (error) {
error = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (error) {
pr_warn("scsi%d: No suitable DMA mask available\n",
host->host_no);
goto controller_unregister;
}
}
pci_set_master(pdev);
if (arcmsr_request_irq(pdev, acb) == FAILED)
goto controller_stop;
arcmsr_iop_init(acb);
INIT_WORK(&acb->arcmsr_do_message_isr_bh, arcmsr_message_isr_bh_fn);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
init_timer(&acb->eternal_timer);
acb->eternal_timer.expires = jiffies + msecs_to_jiffies(6 * HZ);
acb->eternal_timer.data = (unsigned long) acb;
acb->eternal_timer.function = &arcmsr_request_device_map;
add_timer(&acb->eternal_timer);
return 0;
controller_stop:
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
controller_unregister:
scsi_remove_host(host);
arcmsr_free_ccb_pool(acb);
arcmsr_unmap_pciregion(acb);
pci_release_regions(pdev);
scsi_host_put(host);
pci_disable_device(pdev);
return -ENODEV;
}
static uint8_t arcmsr_hbaA_abort_allcmd(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
writel(ARCMSR_INBOUND_MESG0_ABORT_CMD, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'abort all outstanding command' timeout\n"
, acb->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_hbaB_abort_allcmd(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
writel(ARCMSR_MESSAGE_ABORT_CMD, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'abort all outstanding command' timeout\n"
, acb->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_hbaC_abort_allcmd(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *reg = pACB->pmuC;
writel(ARCMSR_INBOUND_MESG0_ABORT_CMD, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(pACB)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'abort all outstanding command' timeout\n"
, pACB->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_hbaD_abort_allcmd(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *reg = pACB->pmuD;
writel(ARCMSR_INBOUND_MESG0_ABORT_CMD, reg->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(pACB)) {
pr_notice("arcmsr%d: wait 'abort all outstanding "
"command' timeout\n", pACB->host->host_no);
return false;
}
return true;
}
static uint8_t arcmsr_abort_allcmd(struct AdapterControlBlock *acb)
{
uint8_t rtnval = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
rtnval = arcmsr_hbaA_abort_allcmd(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
rtnval = arcmsr_hbaB_abort_allcmd(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
rtnval = arcmsr_hbaC_abort_allcmd(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
rtnval = arcmsr_hbaD_abort_allcmd(acb);
break;
}
return rtnval;
}
static void arcmsr_pci_unmap_dma(struct CommandControlBlock *ccb)
{
struct scsi_cmnd *pcmd = ccb->pcmd;
scsi_dma_unmap(pcmd);
}
static void arcmsr_ccb_complete(struct CommandControlBlock *ccb)
{
struct AdapterControlBlock *acb = ccb->acb;
struct scsi_cmnd *pcmd = ccb->pcmd;
unsigned long flags;
atomic_dec(&acb->ccboutstandingcount);
arcmsr_pci_unmap_dma(ccb);
ccb->startdone = ARCMSR_CCB_DONE;
spin_lock_irqsave(&acb->ccblist_lock, flags);
list_add_tail(&ccb->list, &acb->ccb_free_list);
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
pcmd->scsi_done(pcmd);
}
static void arcmsr_report_sense_info(struct CommandControlBlock *ccb)
{
struct scsi_cmnd *pcmd = ccb->pcmd;
struct SENSE_DATA *sensebuffer = (struct SENSE_DATA *)pcmd->sense_buffer;
pcmd->result = DID_OK << 16;
if (sensebuffer) {
int sense_data_length =
sizeof(struct SENSE_DATA) < SCSI_SENSE_BUFFERSIZE
? sizeof(struct SENSE_DATA) : SCSI_SENSE_BUFFERSIZE;
memset(sensebuffer, 0, SCSI_SENSE_BUFFERSIZE);
memcpy(sensebuffer, ccb->arcmsr_cdb.SenseData, sense_data_length);
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->Valid = 1;
}
}
static u32 arcmsr_disable_outbound_ints(struct AdapterControlBlock *acb)
{
u32 orig_mask = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A : {
struct MessageUnit_A __iomem *reg = acb->pmuA;
orig_mask = readl(®->outbound_intmask);
writel(orig_mask|ARCMSR_MU_OUTBOUND_ALL_INTMASKENABLE, \
®->outbound_intmask);
}
break;
case ACB_ADAPTER_TYPE_B : {
struct MessageUnit_B *reg = acb->pmuB;
orig_mask = readl(reg->iop2drv_doorbell_mask);
writel(0, reg->iop2drv_doorbell_mask);
}
break;
case ACB_ADAPTER_TYPE_C:{
struct MessageUnit_C __iomem *reg = acb->pmuC;
/* disable all outbound interrupt */
orig_mask = readl(®->host_int_mask); /* disable outbound message0 int */
writel(orig_mask|ARCMSR_HBCMU_ALL_INTMASKENABLE, ®->host_int_mask);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
/* disable all outbound interrupt */
writel(ARCMSR_ARC1214_ALL_INT_DISABLE, reg->pcief0_int_enable);
}
break;
}
return orig_mask;
}
static void arcmsr_report_ccb_state(struct AdapterControlBlock *acb,
struct CommandControlBlock *ccb, bool error)
{
uint8_t id, lun;
id = ccb->pcmd->device->id;
lun = ccb->pcmd->device->lun;
if (!error) {
if (acb->devstate[id][lun] == ARECA_RAID_GONE)
acb->devstate[id][lun] = ARECA_RAID_GOOD;
ccb->pcmd->result = DID_OK << 16;
arcmsr_ccb_complete(ccb);
}else{
switch (ccb->arcmsr_cdb.DeviceStatus) {
case ARCMSR_DEV_SELECT_TIMEOUT: {
acb->devstate[id][lun] = ARECA_RAID_GONE;
ccb->pcmd->result = DID_NO_CONNECT << 16;
arcmsr_ccb_complete(ccb);
}
break;
case ARCMSR_DEV_ABORTED:
case ARCMSR_DEV_INIT_FAIL: {
acb->devstate[id][lun] = ARECA_RAID_GONE;
ccb->pcmd->result = DID_BAD_TARGET << 16;
arcmsr_ccb_complete(ccb);
}
break;
case ARCMSR_DEV_CHECK_CONDITION: {
acb->devstate[id][lun] = ARECA_RAID_GOOD;
arcmsr_report_sense_info(ccb);
arcmsr_ccb_complete(ccb);
}
break;
default:
printk(KERN_NOTICE
"arcmsr%d: scsi id = %d lun = %d isr get command error done, \
but got unknown DeviceStatus = 0x%x \n"
, acb->host->host_no
, id
, lun
, ccb->arcmsr_cdb.DeviceStatus);
acb->devstate[id][lun] = ARECA_RAID_GONE;
ccb->pcmd->result = DID_NO_CONNECT << 16;
arcmsr_ccb_complete(ccb);
break;
}
}
}
static void arcmsr_drain_donequeue(struct AdapterControlBlock *acb, struct CommandControlBlock *pCCB, bool error)
{
int id, lun;
if ((pCCB->acb != acb) || (pCCB->startdone != ARCMSR_CCB_START)) {
if (pCCB->startdone == ARCMSR_CCB_ABORTED) {
struct scsi_cmnd *abortcmd = pCCB->pcmd;
if (abortcmd) {
id = abortcmd->device->id;
lun = abortcmd->device->lun;
abortcmd->result |= DID_ABORT << 16;
arcmsr_ccb_complete(pCCB);
printk(KERN_NOTICE "arcmsr%d: pCCB ='0x%p' isr got aborted command \n",
acb->host->host_no, pCCB);
}
return;
}
printk(KERN_NOTICE "arcmsr%d: isr get an illegal ccb command \
done acb = '0x%p'"
"ccb = '0x%p' ccbacb = '0x%p' startdone = 0x%x"
" ccboutstandingcount = %d \n"
, acb->host->host_no
, acb
, pCCB
, pCCB->acb
, pCCB->startdone
, atomic_read(&acb->ccboutstandingcount));
return;
}
arcmsr_report_ccb_state(acb, pCCB, error);
}
static void arcmsr_done4abort_postqueue(struct AdapterControlBlock *acb)
{
int i = 0;
uint32_t flag_ccb, ccb_cdb_phy;
struct ARCMSR_CDB *pARCMSR_CDB;
bool error;
struct CommandControlBlock *pCCB;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
uint32_t outbound_intstatus;
outbound_intstatus = readl(®->outbound_intstatus) &
acb->outbound_int_enable;
/*clear and abort all outbound posted Q*/
writel(outbound_intstatus, ®->outbound_intstatus);/*clear interrupt*/
while(((flag_ccb = readl(®->outbound_queueport)) != 0xFFFFFFFF)
&& (i++ < ARCMSR_MAX_OUTSTANDING_CMD)) {
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
/*clear all outbound posted Q*/
writel(ARCMSR_DOORBELL_INT_CLEAR_PATTERN, reg->iop2drv_doorbell); /* clear doorbell interrupt */
for (i = 0; i < ARCMSR_MAX_HBB_POSTQUEUE; i++) {
flag_ccb = reg->done_qbuffer[i];
if (flag_ccb != 0) {
reg->done_qbuffer[i] = 0;
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+(flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
reg->post_qbuffer[i] = 0;
}
reg->doneq_index = 0;
reg->postq_index = 0;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
while ((readl(®->host_int_status) & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR) && (i++ < ARCMSR_MAX_OUTSTANDING_CMD)) {
/*need to do*/
flag_ccb = readl(®->outbound_queueport_low);
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+ccb_cdb_phy);/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *pmu = acb->pmuD;
uint32_t outbound_write_pointer;
uint32_t doneq_index, index_stripped, addressLow, residual, toggle;
unsigned long flags;
residual = atomic_read(&acb->ccboutstandingcount);
for (i = 0; i < residual; i++) {
spin_lock_irqsave(&acb->doneq_lock, flags);
outbound_write_pointer =
pmu->done_qbuffer[0].addressLow + 1;
doneq_index = pmu->doneq_index;
if ((doneq_index & 0xFFF) !=
(outbound_write_pointer & 0xFFF)) {
toggle = doneq_index & 0x4000;
index_stripped = (doneq_index & 0xFFF) + 1;
index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE;
pmu->doneq_index = index_stripped ? (index_stripped | toggle) :
((toggle ^ 0x4000) + 1);
doneq_index = pmu->doneq_index;
spin_unlock_irqrestore(&acb->doneq_lock, flags);
addressLow = pmu->done_qbuffer[doneq_index &
0xFFF].addressLow;
ccb_cdb_phy = (addressLow & 0xFFFFFFF0);
pARCMSR_CDB = (struct ARCMSR_CDB *)
(acb->vir2phy_offset + ccb_cdb_phy);
pCCB = container_of(pARCMSR_CDB,
struct CommandControlBlock, arcmsr_cdb);
error = (addressLow &
ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ?
true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
writel(doneq_index,
pmu->outboundlist_read_pointer);
} else {
spin_unlock_irqrestore(&acb->doneq_lock, flags);
mdelay(10);
}
}
pmu->postq_index = 0;
pmu->doneq_index = 0x40FF;
}
break;
}
}
static void arcmsr_remove(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *) host->hostdata;
int poll_count = 0;
arcmsr_free_sysfs_attr(acb);
scsi_remove_host(host);
flush_work(&acb->arcmsr_do_message_isr_bh);
del_timer_sync(&acb->eternal_timer);
arcmsr_disable_outbound_ints(acb);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
acb->acb_flags |= ACB_F_SCSISTOPADAPTER;
acb->acb_flags &= ~ACB_F_IOP_INITED;
for (poll_count = 0; poll_count < ARCMSR_MAX_OUTSTANDING_CMD; poll_count++){
if (!atomic_read(&acb->ccboutstandingcount))
break;
arcmsr_interrupt(acb);/* FIXME: need spinlock */
msleep(25);
}
if (atomic_read(&acb->ccboutstandingcount)) {
int i;
arcmsr_abort_allcmd(acb);
arcmsr_done4abort_postqueue(acb);
for (i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++) {
struct CommandControlBlock *ccb = acb->pccb_pool[i];
if (ccb->startdone == ARCMSR_CCB_START) {
ccb->startdone = ARCMSR_CCB_ABORTED;
ccb->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(ccb);
}
}
}
arcmsr_free_irq(pdev, acb);
arcmsr_free_ccb_pool(acb);
arcmsr_free_mu(acb);
arcmsr_unmap_pciregion(acb);
pci_release_regions(pdev);
scsi_host_put(host);
pci_disable_device(pdev);
}
static void arcmsr_shutdown(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)host->hostdata;
del_timer_sync(&acb->eternal_timer);
arcmsr_disable_outbound_ints(acb);
arcmsr_free_irq(pdev, acb);
flush_work(&acb->arcmsr_do_message_isr_bh);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
}
static int arcmsr_module_init(void)
{
int error = 0;
error = pci_register_driver(&arcmsr_pci_driver);
return error;
}
static void arcmsr_module_exit(void)
{
pci_unregister_driver(&arcmsr_pci_driver);
}
module_init(arcmsr_module_init);
module_exit(arcmsr_module_exit);
static void arcmsr_enable_outbound_ints(struct AdapterControlBlock *acb,
u32 intmask_org)
{
u32 mask;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
mask = intmask_org & ~(ARCMSR_MU_OUTBOUND_POSTQUEUE_INTMASKENABLE |
ARCMSR_MU_OUTBOUND_DOORBELL_INTMASKENABLE|
ARCMSR_MU_OUTBOUND_MESSAGE0_INTMASKENABLE);
writel(mask, ®->outbound_intmask);
acb->outbound_int_enable = ~(intmask_org & mask) & 0x000000ff;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
mask = intmask_org | (ARCMSR_IOP2DRV_DATA_WRITE_OK |
ARCMSR_IOP2DRV_DATA_READ_OK |
ARCMSR_IOP2DRV_CDB_DONE |
ARCMSR_IOP2DRV_MESSAGE_CMD_DONE);
writel(mask, reg->iop2drv_doorbell_mask);
acb->outbound_int_enable = (intmask_org | mask) & 0x0000000f;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
mask = ~(ARCMSR_HBCMU_UTILITY_A_ISR_MASK | ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR_MASK|ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR_MASK);
writel(intmask_org & mask, ®->host_int_mask);
acb->outbound_int_enable = ~(intmask_org & mask) & 0x0000000f;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
mask = ARCMSR_ARC1214_ALL_INT_ENABLE;
writel(intmask_org | mask, reg->pcief0_int_enable);
break;
}
}
}
static int arcmsr_build_ccb(struct AdapterControlBlock *acb,
struct CommandControlBlock *ccb, struct scsi_cmnd *pcmd)
{
struct ARCMSR_CDB *arcmsr_cdb = (struct ARCMSR_CDB *)&ccb->arcmsr_cdb;
int8_t *psge = (int8_t *)&arcmsr_cdb->u;
__le32 address_lo, address_hi;
int arccdbsize = 0x30;
__le32 length = 0;
int i;
struct scatterlist *sg;
int nseg;
ccb->pcmd = pcmd;
memset(arcmsr_cdb, 0, sizeof(struct ARCMSR_CDB));
arcmsr_cdb->TargetID = pcmd->device->id;
arcmsr_cdb->LUN = pcmd->device->lun;
arcmsr_cdb->Function = 1;
arcmsr_cdb->msgContext = 0;
memcpy(arcmsr_cdb->Cdb, pcmd->cmnd, pcmd->cmd_len);
nseg = scsi_dma_map(pcmd);
if (unlikely(nseg > acb->host->sg_tablesize || nseg < 0))
return FAILED;
scsi_for_each_sg(pcmd, sg, nseg, i) {
/* Get the physical address of the current data pointer */
length = cpu_to_le32(sg_dma_len(sg));
address_lo = cpu_to_le32(dma_addr_lo32(sg_dma_address(sg)));
address_hi = cpu_to_le32(dma_addr_hi32(sg_dma_address(sg)));
if (address_hi == 0) {
struct SG32ENTRY *pdma_sg = (struct SG32ENTRY *)psge;
pdma_sg->address = address_lo;
pdma_sg->length = length;
psge += sizeof (struct SG32ENTRY);
arccdbsize += sizeof (struct SG32ENTRY);
} else {
struct SG64ENTRY *pdma_sg = (struct SG64ENTRY *)psge;
pdma_sg->addresshigh = address_hi;
pdma_sg->address = address_lo;
pdma_sg->length = length|cpu_to_le32(IS_SG64_ADDR);
psge += sizeof (struct SG64ENTRY);
arccdbsize += sizeof (struct SG64ENTRY);
}
}
arcmsr_cdb->sgcount = (uint8_t)nseg;
arcmsr_cdb->DataLength = scsi_bufflen(pcmd);
arcmsr_cdb->msgPages = arccdbsize/0x100 + (arccdbsize % 0x100 ? 1 : 0);
if ( arccdbsize > 256)
arcmsr_cdb->Flags |= ARCMSR_CDB_FLAG_SGL_BSIZE;
if (pcmd->sc_data_direction == DMA_TO_DEVICE)
arcmsr_cdb->Flags |= ARCMSR_CDB_FLAG_WRITE;
ccb->arc_cdb_size = arccdbsize;
return SUCCESS;
}
static void arcmsr_post_ccb(struct AdapterControlBlock *acb, struct CommandControlBlock *ccb)
{
uint32_t cdb_phyaddr = ccb->cdb_phyaddr;
struct ARCMSR_CDB *arcmsr_cdb = (struct ARCMSR_CDB *)&ccb->arcmsr_cdb;
atomic_inc(&acb->ccboutstandingcount);
ccb->startdone = ARCMSR_CCB_START;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
if (arcmsr_cdb->Flags & ARCMSR_CDB_FLAG_SGL_BSIZE)
writel(cdb_phyaddr | ARCMSR_CCBPOST_FLAG_SGL_BSIZE,
®->inbound_queueport);
else
writel(cdb_phyaddr, ®->inbound_queueport);
break;
}
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
uint32_t ending_index, index = reg->postq_index;
ending_index = ((index + 1) % ARCMSR_MAX_HBB_POSTQUEUE);
reg->post_qbuffer[ending_index] = 0;
if (arcmsr_cdb->Flags & ARCMSR_CDB_FLAG_SGL_BSIZE) {
reg->post_qbuffer[index] =
cdb_phyaddr | ARCMSR_CCBPOST_FLAG_SGL_BSIZE;
} else {
reg->post_qbuffer[index] = cdb_phyaddr;
}
index++;
index %= ARCMSR_MAX_HBB_POSTQUEUE;/*if last index number set it to 0 */
reg->postq_index = index;
writel(ARCMSR_DRV2IOP_CDB_POSTED, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *phbcmu = acb->pmuC;
uint32_t ccb_post_stamp, arc_cdb_size;
arc_cdb_size = (ccb->arc_cdb_size > 0x300) ? 0x300 : ccb->arc_cdb_size;
ccb_post_stamp = (cdb_phyaddr | ((arc_cdb_size - 1) >> 6) | 1);
if (acb->cdb_phyaddr_hi32) {
writel(acb->cdb_phyaddr_hi32, &phbcmu->inbound_queueport_high);
writel(ccb_post_stamp, &phbcmu->inbound_queueport_low);
} else {
writel(ccb_post_stamp, &phbcmu->inbound_queueport_low);
}
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *pmu = acb->pmuD;
u16 index_stripped;
u16 postq_index, toggle;
unsigned long flags;
struct InBound_SRB *pinbound_srb;
spin_lock_irqsave(&acb->postq_lock, flags);
postq_index = pmu->postq_index;
pinbound_srb = (struct InBound_SRB *)&(pmu->post_qbuffer[postq_index & 0xFF]);
pinbound_srb->addressHigh = dma_addr_hi32(cdb_phyaddr);
pinbound_srb->addressLow = dma_addr_lo32(cdb_phyaddr);
pinbound_srb->length = ccb->arc_cdb_size >> 2;
arcmsr_cdb->msgContext = dma_addr_lo32(cdb_phyaddr);
toggle = postq_index & 0x4000;
index_stripped = postq_index + 1;
index_stripped &= (ARCMSR_MAX_ARC1214_POSTQUEUE - 1);
pmu->postq_index = index_stripped ? (index_stripped | toggle) :
(toggle ^ 0x4000);
writel(postq_index, pmu->inboundlist_write_pointer);
spin_unlock_irqrestore(&acb->postq_lock, flags);
break;
}
}
}
static void arcmsr_hbaA_stop_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
acb->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_STOP_BGRB, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'stop adapter background rebulid' timeout\n"
, acb->host->host_no);
}
}
static void arcmsr_hbaB_stop_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
acb->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_MESSAGE_STOP_BGRB, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'stop adapter background rebulid' timeout\n"
, acb->host->host_no);
}
}
static void arcmsr_hbaC_stop_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *reg = pACB->pmuC;
pACB->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_STOP_BGRB, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(pACB)) {
printk(KERN_NOTICE
"arcmsr%d: wait 'stop adapter background rebulid' timeout\n"
, pACB->host->host_no);
}
return;
}
static void arcmsr_hbaD_stop_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *reg = pACB->pmuD;
pACB->acb_flags &= ~ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_STOP_BGRB, reg->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(pACB))
pr_notice("arcmsr%d: wait 'stop adapter background rebulid' "
"timeout\n", pACB->host->host_no);
}
static void arcmsr_stop_adapter_bgrb(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
arcmsr_hbaA_stop_bgrb(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
arcmsr_hbaB_stop_bgrb(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
arcmsr_hbaC_stop_bgrb(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_stop_bgrb(acb);
break;
}
}
static void arcmsr_free_ccb_pool(struct AdapterControlBlock *acb)
{
dma_free_coherent(&acb->pdev->dev, acb->uncache_size, acb->dma_coherent, acb->dma_coherent_handle);
}
static void arcmsr_iop_message_read(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
writel(ARCMSR_INBOUND_DRIVER_DATA_READ_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
writel(ARCMSR_DRV2IOP_DATA_READ_OK, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
writel(ARCMSR_HBCMU_DRV2IOP_DATA_READ_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
writel(ARCMSR_ARC1214_DRV2IOP_DATA_OUT_READ,
reg->inbound_doorbell);
}
break;
}
}
static void arcmsr_iop_message_wrote(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
/*
** push inbound doorbell tell iop, driver data write ok
** and wait reply on next hwinterrupt for next Qbuffer post
*/
writel(ARCMSR_INBOUND_DRIVER_DATA_WRITE_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
/*
** push inbound doorbell tell iop, driver data write ok
** and wait reply on next hwinterrupt for next Qbuffer post
*/
writel(ARCMSR_DRV2IOP_DATA_WRITE_OK, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
/*
** push inbound doorbell tell iop, driver data write ok
** and wait reply on next hwinterrupt for next Qbuffer post
*/
writel(ARCMSR_HBCMU_DRV2IOP_DATA_WRITE_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
writel(ARCMSR_ARC1214_DRV2IOP_DATA_IN_READY,
reg->inbound_doorbell);
}
break;
}
}
struct QBUFFER __iomem *arcmsr_get_iop_rqbuffer(struct AdapterControlBlock *acb)
{
struct QBUFFER __iomem *qbuffer = NULL;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
qbuffer = (struct QBUFFER __iomem *)®->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
qbuffer = (struct QBUFFER __iomem *)reg->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *phbcmu = acb->pmuC;
qbuffer = (struct QBUFFER __iomem *)&phbcmu->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
qbuffer = (struct QBUFFER __iomem *)reg->message_rbuffer;
}
break;
}
return qbuffer;
}
static struct QBUFFER __iomem *arcmsr_get_iop_wqbuffer(struct AdapterControlBlock *acb)
{
struct QBUFFER __iomem *pqbuffer = NULL;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
pqbuffer = (struct QBUFFER __iomem *) ®->message_wbuffer;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
pqbuffer = (struct QBUFFER __iomem *)reg->message_wbuffer;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
pqbuffer = (struct QBUFFER __iomem *)®->message_wbuffer;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
pqbuffer = (struct QBUFFER __iomem *)reg->message_wbuffer;
}
break;
}
return pqbuffer;
}
static uint32_t
arcmsr_Read_iop_rqbuffer_in_DWORD(struct AdapterControlBlock *acb,
struct QBUFFER __iomem *prbuffer)
{
uint8_t *pQbuffer;
uint8_t *buf1 = NULL;
uint32_t __iomem *iop_data;
uint32_t iop_len, data_len, *buf2 = NULL;
iop_data = (uint32_t __iomem *)prbuffer->data;
iop_len = readl(&prbuffer->data_len);
if (iop_len > 0) {
buf1 = kmalloc(128, GFP_ATOMIC);
buf2 = (uint32_t *)buf1;
if (buf1 == NULL)
return 0;
data_len = iop_len;
while (data_len >= 4) {
*buf2++ = readl(iop_data);
iop_data++;
data_len -= 4;
}
if (data_len)
*buf2 = readl(iop_data);
buf2 = (uint32_t *)buf1;
}
while (iop_len > 0) {
pQbuffer = &acb->rqbuffer[acb->rqbuf_putIndex];
*pQbuffer = *buf1;
acb->rqbuf_putIndex++;
/* if last, index number set it to 0 */
acb->rqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
buf1++;
iop_len--;
}
kfree(buf2);
/* let IOP know data has been read */
arcmsr_iop_message_read(acb);
return 1;
}
uint32_t
arcmsr_Read_iop_rqbuffer_data(struct AdapterControlBlock *acb,
struct QBUFFER __iomem *prbuffer) {
uint8_t *pQbuffer;
uint8_t __iomem *iop_data;
uint32_t iop_len;
if (acb->adapter_type & (ACB_ADAPTER_TYPE_C | ACB_ADAPTER_TYPE_D))
return arcmsr_Read_iop_rqbuffer_in_DWORD(acb, prbuffer);
iop_data = (uint8_t __iomem *)prbuffer->data;
iop_len = readl(&prbuffer->data_len);
while (iop_len > 0) {
pQbuffer = &acb->rqbuffer[acb->rqbuf_putIndex];
*pQbuffer = readb(iop_data);
acb->rqbuf_putIndex++;
acb->rqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
iop_data++;
iop_len--;
}
arcmsr_iop_message_read(acb);
return 1;
}
static void arcmsr_iop2drv_data_wrote_handle(struct AdapterControlBlock *acb)
{
unsigned long flags;
struct QBUFFER __iomem *prbuffer;
int32_t buf_empty_len;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
prbuffer = arcmsr_get_iop_rqbuffer(acb);
buf_empty_len = (acb->rqbuf_putIndex - acb->rqbuf_getIndex - 1) &
(ARCMSR_MAX_QBUFFER - 1);
if (buf_empty_len >= readl(&prbuffer->data_len)) {
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
} else
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
}
static void arcmsr_write_ioctldata2iop_in_DWORD(struct AdapterControlBlock *acb)
{
uint8_t *pQbuffer;
struct QBUFFER __iomem *pwbuffer;
uint8_t *buf1 = NULL;
uint32_t __iomem *iop_data;
uint32_t allxfer_len = 0, data_len, *buf2 = NULL, data;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_READED) {
buf1 = kmalloc(128, GFP_ATOMIC);
buf2 = (uint32_t *)buf1;
if (buf1 == NULL)
return;
acb->acb_flags &= (~ACB_F_MESSAGE_WQBUFFER_READED);
pwbuffer = arcmsr_get_iop_wqbuffer(acb);
iop_data = (uint32_t __iomem *)pwbuffer->data;
while ((acb->wqbuf_getIndex != acb->wqbuf_putIndex)
&& (allxfer_len < 124)) {
pQbuffer = &acb->wqbuffer[acb->wqbuf_getIndex];
*buf1 = *pQbuffer;
acb->wqbuf_getIndex++;
acb->wqbuf_getIndex %= ARCMSR_MAX_QBUFFER;
buf1++;
allxfer_len++;
}
data_len = allxfer_len;
buf1 = (uint8_t *)buf2;
while (data_len >= 4) {
data = *buf2++;
writel(data, iop_data);
iop_data++;
data_len -= 4;
}
if (data_len) {
data = *buf2;
writel(data, iop_data);
}
writel(allxfer_len, &pwbuffer->data_len);
kfree(buf1);
arcmsr_iop_message_wrote(acb);
}
}
void
arcmsr_write_ioctldata2iop(struct AdapterControlBlock *acb)
{
uint8_t *pQbuffer;
struct QBUFFER __iomem *pwbuffer;
uint8_t __iomem *iop_data;
int32_t allxfer_len = 0;
if (acb->adapter_type & (ACB_ADAPTER_TYPE_C | ACB_ADAPTER_TYPE_D)) {
arcmsr_write_ioctldata2iop_in_DWORD(acb);
return;
}
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_READED) {
acb->acb_flags &= (~ACB_F_MESSAGE_WQBUFFER_READED);
pwbuffer = arcmsr_get_iop_wqbuffer(acb);
iop_data = (uint8_t __iomem *)pwbuffer->data;
while ((acb->wqbuf_getIndex != acb->wqbuf_putIndex)
&& (allxfer_len < 124)) {
pQbuffer = &acb->wqbuffer[acb->wqbuf_getIndex];
writeb(*pQbuffer, iop_data);
acb->wqbuf_getIndex++;
acb->wqbuf_getIndex %= ARCMSR_MAX_QBUFFER;
iop_data++;
allxfer_len++;
}
writel(allxfer_len, &pwbuffer->data_len);
arcmsr_iop_message_wrote(acb);
}
}
static void arcmsr_iop2drv_data_read_handle(struct AdapterControlBlock *acb)
{
unsigned long flags;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_WQBUFFER_READED;
if (acb->wqbuf_getIndex != acb->wqbuf_putIndex)
arcmsr_write_ioctldata2iop(acb);
if (acb->wqbuf_getIndex == acb->wqbuf_putIndex)
acb->acb_flags |= ACB_F_MESSAGE_WQBUFFER_CLEARED;
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
}
static void arcmsr_hbaA_doorbell_isr(struct AdapterControlBlock *acb)
{
uint32_t outbound_doorbell;
struct MessageUnit_A __iomem *reg = acb->pmuA;
outbound_doorbell = readl(®->outbound_doorbell);
do {
writel(outbound_doorbell, ®->outbound_doorbell);
if (outbound_doorbell & ARCMSR_OUTBOUND_IOP331_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(acb);
if (outbound_doorbell & ARCMSR_OUTBOUND_IOP331_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(acb);
outbound_doorbell = readl(®->outbound_doorbell);
} while (outbound_doorbell & (ARCMSR_OUTBOUND_IOP331_DATA_WRITE_OK
| ARCMSR_OUTBOUND_IOP331_DATA_READ_OK));
}
static void arcmsr_hbaC_doorbell_isr(struct AdapterControlBlock *pACB)
{
uint32_t outbound_doorbell;
struct MessageUnit_C __iomem *reg = pACB->pmuC;
/*
*******************************************************************
** Maybe here we need to check wrqbuffer_lock is lock or not
** DOORBELL: din! don!
** check if there are any mail need to pack from firmware
*******************************************************************
*/
outbound_doorbell = readl(®->outbound_doorbell);
do {
writel(outbound_doorbell, ®->outbound_doorbell_clear);
readl(®->outbound_doorbell_clear);
if (outbound_doorbell & ARCMSR_HBCMU_IOP2DRV_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(pACB);
if (outbound_doorbell & ARCMSR_HBCMU_IOP2DRV_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(pACB);
if (outbound_doorbell & ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE)
arcmsr_hbaC_message_isr(pACB);
outbound_doorbell = readl(®->outbound_doorbell);
} while (outbound_doorbell & (ARCMSR_HBCMU_IOP2DRV_DATA_WRITE_OK
| ARCMSR_HBCMU_IOP2DRV_DATA_READ_OK
| ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE));
}
static void arcmsr_hbaD_doorbell_isr(struct AdapterControlBlock *pACB)
{
uint32_t outbound_doorbell;
struct MessageUnit_D *pmu = pACB->pmuD;
outbound_doorbell = readl(pmu->outbound_doorbell);
do {
writel(outbound_doorbell, pmu->outbound_doorbell);
if (outbound_doorbell & ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE)
arcmsr_hbaD_message_isr(pACB);
if (outbound_doorbell & ARCMSR_ARC1214_IOP2DRV_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(pACB);
if (outbound_doorbell & ARCMSR_ARC1214_IOP2DRV_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(pACB);
outbound_doorbell = readl(pmu->outbound_doorbell);
} while (outbound_doorbell & (ARCMSR_ARC1214_IOP2DRV_DATA_WRITE_OK
| ARCMSR_ARC1214_IOP2DRV_DATA_READ_OK
| ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE));
}
static void arcmsr_hbaA_postqueue_isr(struct AdapterControlBlock *acb)
{
uint32_t flag_ccb;
struct MessageUnit_A __iomem *reg = acb->pmuA;
struct ARCMSR_CDB *pARCMSR_CDB;
struct CommandControlBlock *pCCB;
bool error;
while ((flag_ccb = readl(®->outbound_queueport)) != 0xFFFFFFFF) {
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
}
}
static void arcmsr_hbaB_postqueue_isr(struct AdapterControlBlock *acb)
{
uint32_t index;
uint32_t flag_ccb;
struct MessageUnit_B *reg = acb->pmuB;
struct ARCMSR_CDB *pARCMSR_CDB;
struct CommandControlBlock *pCCB;
bool error;
index = reg->doneq_index;
while ((flag_ccb = reg->done_qbuffer[index]) != 0) {
reg->done_qbuffer[index] = 0;
pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+(flag_ccb << 5));/*frame must be 32 bytes aligned*/
pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_drain_donequeue(acb, pCCB, error);
index++;
index %= ARCMSR_MAX_HBB_POSTQUEUE;
reg->doneq_index = index;
}
}
static void arcmsr_hbaC_postqueue_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_C __iomem *phbcmu;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *ccb;
uint32_t flag_ccb, ccb_cdb_phy, throttling = 0;
int error;
phbcmu = acb->pmuC;
/* areca cdb command done */
/* Use correct offset and size for syncing */
while ((flag_ccb = readl(&phbcmu->outbound_queueport_low)) !=
0xFFFFFFFF) {
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset
+ ccb_cdb_phy);
ccb = container_of(arcmsr_cdb, struct CommandControlBlock,
arcmsr_cdb);
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1)
? true : false;
/* check if command done with no error */
arcmsr_drain_donequeue(acb, ccb, error);
throttling++;
if (throttling == ARCMSR_HBC_ISR_THROTTLING_LEVEL) {
writel(ARCMSR_HBCMU_DRV2IOP_POSTQUEUE_THROTTLING,
&phbcmu->inbound_doorbell);
throttling = 0;
}
}
}
static void arcmsr_hbaD_postqueue_isr(struct AdapterControlBlock *acb)
{
u32 outbound_write_pointer, doneq_index, index_stripped, toggle;
uint32_t addressLow, ccb_cdb_phy;
int error;
struct MessageUnit_D *pmu;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *ccb;
unsigned long flags;
spin_lock_irqsave(&acb->doneq_lock, flags);
pmu = acb->pmuD;
outbound_write_pointer = pmu->done_qbuffer[0].addressLow + 1;
doneq_index = pmu->doneq_index;
if ((doneq_index & 0xFFF) != (outbound_write_pointer & 0xFFF)) {
do {
toggle = doneq_index & 0x4000;
index_stripped = (doneq_index & 0xFFF) + 1;
index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE;
pmu->doneq_index = index_stripped ? (index_stripped | toggle) :
((toggle ^ 0x4000) + 1);
doneq_index = pmu->doneq_index;
addressLow = pmu->done_qbuffer[doneq_index &
0xFFF].addressLow;
ccb_cdb_phy = (addressLow & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset
+ ccb_cdb_phy);
ccb = container_of(arcmsr_cdb,
struct CommandControlBlock, arcmsr_cdb);
error = (addressLow & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1)
? true : false;
arcmsr_drain_donequeue(acb, ccb, error);
writel(doneq_index, pmu->outboundlist_read_pointer);
} while ((doneq_index & 0xFFF) !=
(outbound_write_pointer & 0xFFF));
}
writel(ARCMSR_ARC1214_OUTBOUND_LIST_INTERRUPT_CLEAR,
pmu->outboundlist_interrupt_cause);
readl(pmu->outboundlist_interrupt_cause);
spin_unlock_irqrestore(&acb->doneq_lock, flags);
}
/*
**********************************************************************************
** Handle a message interrupt
**
** The only message interrupt we expect is in response to a query for the current adapter config.
** We want this in order to compare the drivemap so that we can detect newly-attached drives.
**********************************************************************************
*/
static void arcmsr_hbaA_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
/*clear interrupt and message state*/
writel(ARCMSR_MU_OUTBOUND_MESSAGE0_INT, ®->outbound_intstatus);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
static void arcmsr_hbaB_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
/*clear interrupt and message state*/
writel(ARCMSR_MESSAGE_INT_CLEAR_PATTERN, reg->iop2drv_doorbell);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
/*
**********************************************************************************
** Handle a message interrupt
**
** The only message interrupt we expect is in response to a query for the
** current adapter config.
** We want this in order to compare the drivemap so that we can detect newly-attached drives.
**********************************************************************************
*/
static void arcmsr_hbaC_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_C __iomem *reg = acb->pmuC;
/*clear interrupt and message state*/
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR, ®->outbound_doorbell_clear);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
static void arcmsr_hbaD_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_D *reg = acb->pmuD;
writel(ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE, reg->outbound_doorbell);
readl(reg->outbound_doorbell);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
static int arcmsr_hbaA_handle_isr(struct AdapterControlBlock *acb)
{
uint32_t outbound_intstatus;
struct MessageUnit_A __iomem *reg = acb->pmuA;
outbound_intstatus = readl(®->outbound_intstatus) &
acb->outbound_int_enable;
if (!(outbound_intstatus & ARCMSR_MU_OUTBOUND_HANDLE_INT))
return IRQ_NONE;
do {
writel(outbound_intstatus, ®->outbound_intstatus);
if (outbound_intstatus & ARCMSR_MU_OUTBOUND_DOORBELL_INT)
arcmsr_hbaA_doorbell_isr(acb);
if (outbound_intstatus & ARCMSR_MU_OUTBOUND_POSTQUEUE_INT)
arcmsr_hbaA_postqueue_isr(acb);
if (outbound_intstatus & ARCMSR_MU_OUTBOUND_MESSAGE0_INT)
arcmsr_hbaA_message_isr(acb);
outbound_intstatus = readl(®->outbound_intstatus) &
acb->outbound_int_enable;
} while (outbound_intstatus & (ARCMSR_MU_OUTBOUND_DOORBELL_INT
| ARCMSR_MU_OUTBOUND_POSTQUEUE_INT
| ARCMSR_MU_OUTBOUND_MESSAGE0_INT));
return IRQ_HANDLED;
}
static int arcmsr_hbaB_handle_isr(struct AdapterControlBlock *acb)
{
uint32_t outbound_doorbell;
struct MessageUnit_B *reg = acb->pmuB;
outbound_doorbell = readl(reg->iop2drv_doorbell) &
acb->outbound_int_enable;
if (!outbound_doorbell)
return IRQ_NONE;
do {
writel(~outbound_doorbell, reg->iop2drv_doorbell);
writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT, reg->drv2iop_doorbell);
if (outbound_doorbell & ARCMSR_IOP2DRV_DATA_WRITE_OK)
arcmsr_iop2drv_data_wrote_handle(acb);
if (outbound_doorbell & ARCMSR_IOP2DRV_DATA_READ_OK)
arcmsr_iop2drv_data_read_handle(acb);
if (outbound_doorbell & ARCMSR_IOP2DRV_CDB_DONE)
arcmsr_hbaB_postqueue_isr(acb);
if (outbound_doorbell & ARCMSR_IOP2DRV_MESSAGE_CMD_DONE)
arcmsr_hbaB_message_isr(acb);
outbound_doorbell = readl(reg->iop2drv_doorbell) &
acb->outbound_int_enable;
} while (outbound_doorbell & (ARCMSR_IOP2DRV_DATA_WRITE_OK
| ARCMSR_IOP2DRV_DATA_READ_OK
| ARCMSR_IOP2DRV_CDB_DONE
| ARCMSR_IOP2DRV_MESSAGE_CMD_DONE));
return IRQ_HANDLED;
}
static int arcmsr_hbaC_handle_isr(struct AdapterControlBlock *pACB)
{
uint32_t host_interrupt_status;
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
/*
*********************************************
** check outbound intstatus
*********************************************
*/
host_interrupt_status = readl(&phbcmu->host_int_status) &
(ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR);
if (!host_interrupt_status)
return IRQ_NONE;
do {
if (host_interrupt_status & ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR)
arcmsr_hbaC_doorbell_isr(pACB);
/* MU post queue interrupts*/
if (host_interrupt_status & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR)
arcmsr_hbaC_postqueue_isr(pACB);
host_interrupt_status = readl(&phbcmu->host_int_status);
} while (host_interrupt_status & (ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_HBCMU_OUTBOUND_DOORBELL_ISR));
return IRQ_HANDLED;
}
static irqreturn_t arcmsr_hbaD_handle_isr(struct AdapterControlBlock *pACB)
{
u32 host_interrupt_status;
struct MessageUnit_D *pmu = pACB->pmuD;
host_interrupt_status = readl(pmu->host_int_status) &
(ARCMSR_ARC1214_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_ARC1214_OUTBOUND_DOORBELL_ISR);
if (!host_interrupt_status)
return IRQ_NONE;
do {
/* MU post queue interrupts*/
if (host_interrupt_status &
ARCMSR_ARC1214_OUTBOUND_POSTQUEUE_ISR)
arcmsr_hbaD_postqueue_isr(pACB);
if (host_interrupt_status &
ARCMSR_ARC1214_OUTBOUND_DOORBELL_ISR)
arcmsr_hbaD_doorbell_isr(pACB);
host_interrupt_status = readl(pmu->host_int_status);
} while (host_interrupt_status &
(ARCMSR_ARC1214_OUTBOUND_POSTQUEUE_ISR |
ARCMSR_ARC1214_OUTBOUND_DOORBELL_ISR));
return IRQ_HANDLED;
}
static irqreturn_t arcmsr_interrupt(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
return arcmsr_hbaA_handle_isr(acb);
break;
case ACB_ADAPTER_TYPE_B:
return arcmsr_hbaB_handle_isr(acb);
break;
case ACB_ADAPTER_TYPE_C:
return arcmsr_hbaC_handle_isr(acb);
case ACB_ADAPTER_TYPE_D:
return arcmsr_hbaD_handle_isr(acb);
default:
return IRQ_NONE;
}
}
static void arcmsr_iop_parking(struct AdapterControlBlock *acb)
{
if (acb) {
/* stop adapter background rebuild */
if (acb->acb_flags & ACB_F_MSG_START_BGRB) {
uint32_t intmask_org;
acb->acb_flags &= ~ACB_F_MSG_START_BGRB;
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_stop_adapter_bgrb(acb);
arcmsr_flush_adapter_cache(acb);
arcmsr_enable_outbound_ints(acb, intmask_org);
}
}
}
void arcmsr_clear_iop2drv_rqueue_buffer(struct AdapterControlBlock *acb)
{
uint32_t i;
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
for (i = 0; i < 15; i++) {
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
arcmsr_iop_message_read(acb);
mdelay(30);
} else if (acb->rqbuf_getIndex !=
acb->rqbuf_putIndex) {
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
mdelay(30);
} else
break;
}
}
}
static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
char *buffer;
unsigned short use_sg;
int retvalue = 0, transfer_len = 0;
unsigned long flags;
struct CMD_MESSAGE_FIELD *pcmdmessagefld;
uint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |
(uint32_t)cmd->cmnd[6] << 16 |
(uint32_t)cmd->cmnd[7] << 8 |
(uint32_t)cmd->cmnd[8];
struct scatterlist *sg;
use_sg = scsi_sg_count(cmd);
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
if (use_sg > 1) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
transfer_len += sg->length;
if (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: ARCMSR_MESSAGE_FAIL!\n", __func__);
goto message_out;
}
pcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;
switch (controlcode) {
case ARCMSR_MESSAGE_READ_RQBUFFER: {
unsigned char *ver_addr;
uint8_t *ptmpQbuffer;
uint32_t allxfer_len = 0;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: memory not enough!\n", __func__);
goto message_out;
}
ptmpQbuffer = ver_addr;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
if (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {
unsigned int tail = acb->rqbuf_getIndex;
unsigned int head = acb->rqbuf_putIndex;
unsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);
allxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);
if (allxfer_len > ARCMSR_API_DATA_BUFLEN)
allxfer_len = ARCMSR_API_DATA_BUFLEN;
if (allxfer_len <= cnt_to_end)
memcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);
else {
memcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);
memcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);
}
acb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;
}
memcpy(pcmdmessagefld->messagedatabuffer, ver_addr,
allxfer_len);
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
struct QBUFFER __iomem *prbuffer;
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
prbuffer = arcmsr_get_iop_rqbuffer(acb);
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
}
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
kfree(ver_addr);
pcmdmessagefld->cmdmessage.Length = allxfer_len;
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_WRITE_WQBUFFER: {
unsigned char *ver_addr;
int32_t user_len, cnt2end;
uint8_t *pQbuffer, *ptmpuserbuffer;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
ptmpuserbuffer = ver_addr;
user_len = pcmdmessagefld->cmdmessage.Length;
memcpy(ptmpuserbuffer,
pcmdmessagefld->messagedatabuffer, user_len);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
if (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {
struct SENSE_DATA *sensebuffer =
(struct SENSE_DATA *)cmd->sense_buffer;
arcmsr_write_ioctldata2iop(acb);
/* has error report sensedata */
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->SenseKey = ILLEGAL_REQUEST;
sensebuffer->AdditionalSenseLength = 0x0A;
sensebuffer->AdditionalSenseCode = 0x20;
sensebuffer->Valid = 1;
retvalue = ARCMSR_MESSAGE_FAIL;
} else {
pQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];
cnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;
if (user_len > cnt2end) {
memcpy(pQbuffer, ptmpuserbuffer, cnt2end);
ptmpuserbuffer += cnt2end;
user_len -= cnt2end;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
}
memcpy(pQbuffer, ptmpuserbuffer, user_len);
acb->wqbuf_putIndex += user_len;
acb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {
acb->acb_flags &=
~ACB_F_MESSAGE_WQBUFFER_CLEARED;
arcmsr_write_ioctldata2iop(acb);
}
}
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
kfree(ver_addr);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_RQBUFFER: {
uint8_t *pQbuffer = acb->rqbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_WQBUFFER: {
uint8_t *pQbuffer = acb->wqbuffer;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {
uint8_t *pQbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
pQbuffer = acb->rqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_RETURN_CODE_3F: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_3F;
break;
}
case ARCMSR_MESSAGE_SAY_HELLO: {
int8_t *hello_string = "Hello! I am ARCMSR";
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
memcpy(pcmdmessagefld->messagedatabuffer,
hello_string, (int16_t)strlen(hello_string));
break;
}
case ARCMSR_MESSAGE_SAY_GOODBYE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_iop_parking(acb);
break;
}
case ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_flush_adapter_cache(acb);
break;
}
default:
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: unknown controlcode!\n", __func__);
}
message_out:
if (use_sg) {
struct scatterlist *sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
}
return retvalue;
}
static struct CommandControlBlock *arcmsr_get_freeccb(struct AdapterControlBlock *acb)
{
struct list_head *head = &acb->ccb_free_list;
struct CommandControlBlock *ccb = NULL;
unsigned long flags;
spin_lock_irqsave(&acb->ccblist_lock, flags);
if (!list_empty(head)) {
ccb = list_entry(head->next, struct CommandControlBlock, list);
list_del_init(&ccb->list);
}else{
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
return NULL;
}
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
return ccb;
}
static void arcmsr_handle_virtual_command(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
switch (cmd->cmnd[0]) {
case INQUIRY: {
unsigned char inqdata[36];
char *buffer;
struct scatterlist *sg;
if (cmd->device->lun) {
cmd->result = (DID_TIME_OUT << 16);
cmd->scsi_done(cmd);
return;
}
inqdata[0] = TYPE_PROCESSOR;
/* Periph Qualifier & Periph Dev Type */
inqdata[1] = 0;
/* rem media bit & Dev Type Modifier */
inqdata[2] = 0;
/* ISO, ECMA, & ANSI versions */
inqdata[4] = 31;
/* length of additional data */
strncpy(&inqdata[8], "Areca ", 8);
/* Vendor Identification */
strncpy(&inqdata[16], "RAID controller ", 16);
/* Product Identification */
strncpy(&inqdata[32], "R001", 4); /* Product Revision */
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
memcpy(buffer, inqdata, sizeof(inqdata));
sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
cmd->scsi_done(cmd);
}
break;
case WRITE_BUFFER:
case READ_BUFFER: {
if (arcmsr_iop_message_xfer(acb, cmd))
cmd->result = (DID_ERROR << 16);
cmd->scsi_done(cmd);
}
break;
default:
cmd->scsi_done(cmd);
}
}
static int arcmsr_queue_command_lck(struct scsi_cmnd *cmd,
void (* done)(struct scsi_cmnd *))
{
struct Scsi_Host *host = cmd->device->host;
struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata;
struct CommandControlBlock *ccb;
int target = cmd->device->id;
int lun = cmd->device->lun;
uint8_t scsicmd = cmd->cmnd[0];
cmd->scsi_done = done;
cmd->host_scribble = NULL;
cmd->result = 0;
if ((scsicmd == SYNCHRONIZE_CACHE) ||(scsicmd == SEND_DIAGNOSTIC)){
if(acb->devstate[target][lun] == ARECA_RAID_GONE) {
cmd->result = (DID_NO_CONNECT << 16);
}
cmd->scsi_done(cmd);
return 0;
}
if (target == 16) {
/* virtual device for iop message transfer */
arcmsr_handle_virtual_command(acb, cmd);
return 0;
}
ccb = arcmsr_get_freeccb(acb);
if (!ccb)
return SCSI_MLQUEUE_HOST_BUSY;
if (arcmsr_build_ccb( acb, ccb, cmd ) == FAILED) {
cmd->result = (DID_ERROR << 16) | (RESERVATION_CONFLICT << 1);
cmd->scsi_done(cmd);
return 0;
}
arcmsr_post_ccb(acb, ccb);
return 0;
}
static DEF_SCSI_QCMD(arcmsr_queue_command)
static bool arcmsr_hbaA_get_config(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
char *acb_firm_model = acb->firm_model;
char *acb_firm_version = acb->firm_version;
char *acb_device_map = acb->device_map;
char __iomem *iop_firm_model = (char __iomem *)(®->message_rwbuffer[15]);
char __iomem *iop_firm_version = (char __iomem *)(®->message_rwbuffer[17]);
char __iomem *iop_device_map = (char __iomem *)(®->message_rwbuffer[21]);
int count;
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'get adapter firmware \
miscellaneous data' timeout \n", acb->host->host_no);
return false;
}
count = 8;
while (count){
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count){
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
count=16;
while(count){
*acb_device_map = readb(iop_device_map);
acb_device_map++;
iop_device_map++;
count--;
}
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
acb->host->host_no,
acb->firm_model,
acb->firm_version);
acb->signature = readl(®->message_rwbuffer[0]);
acb->firm_request_len = readl(®->message_rwbuffer[1]);
acb->firm_numbers_queue = readl(®->message_rwbuffer[2]);
acb->firm_sdram_size = readl(®->message_rwbuffer[3]);
acb->firm_hd_channels = readl(®->message_rwbuffer[4]);
acb->firm_cfg_version = readl(®->message_rwbuffer[25]); /*firm_cfg_version,25,100-103*/
return true;
}
static bool arcmsr_hbaB_get_config(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
char *acb_firm_model = acb->firm_model;
char *acb_firm_version = acb->firm_version;
char *acb_device_map = acb->device_map;
char __iomem *iop_firm_model;
/*firm_model,15,60-67*/
char __iomem *iop_firm_version;
/*firm_version,17,68-83*/
char __iomem *iop_device_map;
/*firm_version,21,84-99*/
int count;
iop_firm_model = (char __iomem *)(®->message_rwbuffer[15]); /*firm_model,15,60-67*/
iop_firm_version = (char __iomem *)(®->message_rwbuffer[17]); /*firm_version,17,68-83*/
iop_device_map = (char __iomem *)(®->message_rwbuffer[21]); /*firm_version,21,84-99*/
arcmsr_wait_firmware_ready(acb);
writel(ARCMSR_MESSAGE_START_DRIVER_MODE, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_ERR "arcmsr%d: can't set driver mode.\n", acb->host->host_no);
return false;
}
writel(ARCMSR_MESSAGE_GET_CONFIG, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'get adapter firmware \
miscellaneous data' timeout \n", acb->host->host_no);
return false;
}
count = 8;
while (count){
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count){
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
count = 16;
while(count){
*acb_device_map = readb(iop_device_map);
acb_device_map++;
iop_device_map++;
count--;
}
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
acb->host->host_no,
acb->firm_model,
acb->firm_version);
acb->signature = readl(®->message_rwbuffer[0]);
/*firm_signature,1,00-03*/
acb->firm_request_len = readl(®->message_rwbuffer[1]);
/*firm_request_len,1,04-07*/
acb->firm_numbers_queue = readl(®->message_rwbuffer[2]);
/*firm_numbers_queue,2,08-11*/
acb->firm_sdram_size = readl(®->message_rwbuffer[3]);
/*firm_sdram_size,3,12-15*/
acb->firm_hd_channels = readl(®->message_rwbuffer[4]);
/*firm_ide_channels,4,16-19*/
acb->firm_cfg_version = readl(®->message_rwbuffer[25]); /*firm_cfg_version,25,100-103*/
/*firm_ide_channels,4,16-19*/
return true;
}
static bool arcmsr_hbaC_get_config(struct AdapterControlBlock *pACB)
{
uint32_t intmask_org, Index, firmware_state = 0;
struct MessageUnit_C __iomem *reg = pACB->pmuC;
char *acb_firm_model = pACB->firm_model;
char *acb_firm_version = pACB->firm_version;
char __iomem *iop_firm_model = (char __iomem *)(®->msgcode_rwbuffer[15]); /*firm_model,15,60-67*/
char __iomem *iop_firm_version = (char __iomem *)(®->msgcode_rwbuffer[17]); /*firm_version,17,68-83*/
int count;
/* disable all outbound interrupt */
intmask_org = readl(®->host_int_mask); /* disable outbound message0 int */
writel(intmask_org|ARCMSR_HBCMU_ALL_INTMASKENABLE, ®->host_int_mask);
/* wait firmware ready */
do {
firmware_state = readl(®->outbound_msgaddr1);
} while ((firmware_state & ARCMSR_HBCMU_MESSAGE_FIRMWARE_OK) == 0);
/* post "get config" instruction */
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
/* wait message ready */
for (Index = 0; Index < 2000; Index++) {
if (readl(®->outbound_doorbell) & ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR, ®->outbound_doorbell_clear);/*clear interrupt*/
break;
}
udelay(10);
} /*max 1 seconds*/
if (Index >= 2000) {
printk(KERN_NOTICE "arcmsr%d: wait 'get adapter firmware \
miscellaneous data' timeout \n", pACB->host->host_no);
return false;
}
count = 8;
while (count) {
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count) {
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
pACB->host->host_no,
pACB->firm_model,
pACB->firm_version);
pACB->firm_request_len = readl(®->msgcode_rwbuffer[1]); /*firm_request_len,1,04-07*/
pACB->firm_numbers_queue = readl(®->msgcode_rwbuffer[2]); /*firm_numbers_queue,2,08-11*/
pACB->firm_sdram_size = readl(®->msgcode_rwbuffer[3]); /*firm_sdram_size,3,12-15*/
pACB->firm_hd_channels = readl(®->msgcode_rwbuffer[4]); /*firm_ide_channels,4,16-19*/
pACB->firm_cfg_version = readl(®->msgcode_rwbuffer[25]); /*firm_cfg_version,25,100-103*/
/*all interrupt service will be enable at arcmsr_iop_init*/
return true;
}
static bool arcmsr_hbaD_get_config(struct AdapterControlBlock *acb)
{
char *acb_firm_model = acb->firm_model;
char *acb_firm_version = acb->firm_version;
char *acb_device_map = acb->device_map;
char __iomem *iop_firm_model;
char __iomem *iop_firm_version;
char __iomem *iop_device_map;
u32 count;
struct MessageUnit_D *reg = acb->pmuD;
iop_firm_model = (char __iomem *)(®->msgcode_rwbuffer[15]);
iop_firm_version = (char __iomem *)(®->msgcode_rwbuffer[17]);
iop_device_map = (char __iomem *)(®->msgcode_rwbuffer[21]);
if (readl(acb->pmuD->outbound_doorbell) &
ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_ARC1214_IOP2DRV_MESSAGE_CMD_DONE,
acb->pmuD->outbound_doorbell);/*clear interrupt*/
}
/* post "get config" instruction */
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, reg->inbound_msgaddr0);
/* wait message ready */
if (!arcmsr_hbaD_wait_msgint_ready(acb)) {
pr_notice("arcmsr%d: wait get adapter firmware "
"miscellaneous data timeout\n", acb->host->host_no);
return false;
}
count = 8;
while (count) {
*acb_firm_model = readb(iop_firm_model);
acb_firm_model++;
iop_firm_model++;
count--;
}
count = 16;
while (count) {
*acb_firm_version = readb(iop_firm_version);
acb_firm_version++;
iop_firm_version++;
count--;
}
count = 16;
while (count) {
*acb_device_map = readb(iop_device_map);
acb_device_map++;
iop_device_map++;
count--;
}
acb->signature = readl(®->msgcode_rwbuffer[0]);
/*firm_signature,1,00-03*/
acb->firm_request_len = readl(®->msgcode_rwbuffer[1]);
/*firm_request_len,1,04-07*/
acb->firm_numbers_queue = readl(®->msgcode_rwbuffer[2]);
/*firm_numbers_queue,2,08-11*/
acb->firm_sdram_size = readl(®->msgcode_rwbuffer[3]);
/*firm_sdram_size,3,12-15*/
acb->firm_hd_channels = readl(®->msgcode_rwbuffer[4]);
/*firm_hd_channels,4,16-19*/
acb->firm_cfg_version = readl(®->msgcode_rwbuffer[25]);
pr_notice("Areca RAID Controller%d: Model %s, F/W %s\n",
acb->host->host_no,
acb->firm_model,
acb->firm_version);
return true;
}
static bool arcmsr_get_firmware_spec(struct AdapterControlBlock *acb)
{
bool rtn = false;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
rtn = arcmsr_hbaA_get_config(acb);
break;
case ACB_ADAPTER_TYPE_B:
rtn = arcmsr_hbaB_get_config(acb);
break;
case ACB_ADAPTER_TYPE_C:
rtn = arcmsr_hbaC_get_config(acb);
break;
case ACB_ADAPTER_TYPE_D:
rtn = arcmsr_hbaD_get_config(acb);
break;
default:
break;
}
if (acb->firm_numbers_queue > ARCMSR_MAX_OUTSTANDING_CMD)
acb->maxOutstanding = ARCMSR_MAX_OUTSTANDING_CMD;
else
acb->maxOutstanding = acb->firm_numbers_queue - 1;
acb->host->can_queue = acb->maxOutstanding;
return rtn;
}
static int arcmsr_hbaA_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
struct CommandControlBlock *ccb;
struct ARCMSR_CDB *arcmsr_cdb;
uint32_t flag_ccb, outbound_intstatus, poll_ccb_done = 0, poll_count = 0;
int rtn;
bool error;
polling_hba_ccb_retry:
poll_count++;
outbound_intstatus = readl(®->outbound_intstatus) & acb->outbound_int_enable;
writel(outbound_intstatus, ®->outbound_intstatus);/*clear interrupt*/
while (1) {
if ((flag_ccb = readl(®->outbound_queueport)) == 0xFFFFFFFF) {
if (poll_ccb_done){
rtn = SUCCESS;
break;
}else {
msleep(25);
if (poll_count > 100){
rtn = FAILED;
break;
}
goto polling_hba_ccb_retry;
}
}
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));
ccb = container_of(arcmsr_cdb, struct CommandControlBlock, arcmsr_cdb);
poll_ccb_done |= (ccb == poll_ccb) ? 1 : 0;
if ((ccb->acb != acb) || (ccb->startdone != ARCMSR_CCB_START)) {
if ((ccb->startdone == ARCMSR_CCB_ABORTED) || (ccb == poll_ccb)) {
printk(KERN_NOTICE "arcmsr%d: scsi id = %d lun = %d ccb = '0x%p'"
" poll command abort successfully \n"
, acb->host->host_no
, ccb->pcmd->device->id
, (u32)ccb->pcmd->device->lun
, ccb);
ccb->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(ccb);
continue;
}
printk(KERN_NOTICE "arcmsr%d: polling get an illegal ccb"
" command done ccb = '0x%p'"
"ccboutstandingcount = %d \n"
, acb->host->host_no
, ccb
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_report_ccb_state(acb, ccb, error);
}
return rtn;
}
static int arcmsr_hbaB_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
struct MessageUnit_B *reg = acb->pmuB;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *ccb;
uint32_t flag_ccb, poll_ccb_done = 0, poll_count = 0;
int index, rtn;
bool error;
polling_hbb_ccb_retry:
poll_count++;
/* clear doorbell interrupt */
writel(ARCMSR_DOORBELL_INT_CLEAR_PATTERN, reg->iop2drv_doorbell);
while(1){
index = reg->doneq_index;
flag_ccb = reg->done_qbuffer[index];
if (flag_ccb == 0) {
if (poll_ccb_done){
rtn = SUCCESS;
break;
}else {
msleep(25);
if (poll_count > 100){
rtn = FAILED;
break;
}
goto polling_hbb_ccb_retry;
}
}
reg->done_qbuffer[index] = 0;
index++;
/*if last index number set it to 0 */
index %= ARCMSR_MAX_HBB_POSTQUEUE;
reg->doneq_index = index;
/* check if command done with no error*/
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));
ccb = container_of(arcmsr_cdb, struct CommandControlBlock, arcmsr_cdb);
poll_ccb_done |= (ccb == poll_ccb) ? 1 : 0;
if ((ccb->acb != acb) || (ccb->startdone != ARCMSR_CCB_START)) {
if ((ccb->startdone == ARCMSR_CCB_ABORTED) || (ccb == poll_ccb)) {
printk(KERN_NOTICE "arcmsr%d: scsi id = %d lun = %d ccb = '0x%p'"
" poll command abort successfully \n"
,acb->host->host_no
,ccb->pcmd->device->id
,(u32)ccb->pcmd->device->lun
,ccb);
ccb->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(ccb);
continue;
}
printk(KERN_NOTICE "arcmsr%d: polling get an illegal ccb"
" command done ccb = '0x%p'"
"ccboutstandingcount = %d \n"
, acb->host->host_no
, ccb
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false;
arcmsr_report_ccb_state(acb, ccb, error);
}
return rtn;
}
static int arcmsr_hbaC_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
struct MessageUnit_C __iomem *reg = acb->pmuC;
uint32_t flag_ccb, ccb_cdb_phy;
struct ARCMSR_CDB *arcmsr_cdb;
bool error;
struct CommandControlBlock *pCCB;
uint32_t poll_ccb_done = 0, poll_count = 0;
int rtn;
polling_hbc_ccb_retry:
poll_count++;
while (1) {
if ((readl(®->host_int_status) & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR) == 0) {
if (poll_ccb_done) {
rtn = SUCCESS;
break;
} else {
msleep(25);
if (poll_count > 100) {
rtn = FAILED;
break;
}
goto polling_hbc_ccb_retry;
}
}
flag_ccb = readl(®->outbound_queueport_low);
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset + ccb_cdb_phy);/*frame must be 32 bytes aligned*/
pCCB = container_of(arcmsr_cdb, struct CommandControlBlock, arcmsr_cdb);
poll_ccb_done |= (pCCB == poll_ccb) ? 1 : 0;
/* check ifcommand done with no error*/
if ((pCCB->acb != acb) || (pCCB->startdone != ARCMSR_CCB_START)) {
if (pCCB->startdone == ARCMSR_CCB_ABORTED) {
printk(KERN_NOTICE "arcmsr%d: scsi id = %d lun = %d ccb = '0x%p'"
" poll command abort successfully \n"
, acb->host->host_no
, pCCB->pcmd->device->id
, (u32)pCCB->pcmd->device->lun
, pCCB);
pCCB->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(pCCB);
continue;
}
printk(KERN_NOTICE "arcmsr%d: polling get an illegal ccb"
" command done ccb = '0x%p'"
"ccboutstandingcount = %d \n"
, acb->host->host_no
, pCCB
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ? true : false;
arcmsr_report_ccb_state(acb, pCCB, error);
}
return rtn;
}
static int arcmsr_hbaD_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
bool error;
uint32_t poll_ccb_done = 0, poll_count = 0, flag_ccb, ccb_cdb_phy;
int rtn, doneq_index, index_stripped, outbound_write_pointer, toggle;
unsigned long flags;
struct ARCMSR_CDB *arcmsr_cdb;
struct CommandControlBlock *pCCB;
struct MessageUnit_D *pmu = acb->pmuD;
polling_hbaD_ccb_retry:
poll_count++;
while (1) {
spin_lock_irqsave(&acb->doneq_lock, flags);
outbound_write_pointer = pmu->done_qbuffer[0].addressLow + 1;
doneq_index = pmu->doneq_index;
if ((outbound_write_pointer & 0xFFF) == (doneq_index & 0xFFF)) {
spin_unlock_irqrestore(&acb->doneq_lock, flags);
if (poll_ccb_done) {
rtn = SUCCESS;
break;
} else {
msleep(25);
if (poll_count > 40) {
rtn = FAILED;
break;
}
goto polling_hbaD_ccb_retry;
}
}
toggle = doneq_index & 0x4000;
index_stripped = (doneq_index & 0xFFF) + 1;
index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE;
pmu->doneq_index = index_stripped ? (index_stripped | toggle) :
((toggle ^ 0x4000) + 1);
doneq_index = pmu->doneq_index;
spin_unlock_irqrestore(&acb->doneq_lock, flags);
flag_ccb = pmu->done_qbuffer[doneq_index & 0xFFF].addressLow;
ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0);
arcmsr_cdb = (struct ARCMSR_CDB *)(acb->vir2phy_offset +
ccb_cdb_phy);
pCCB = container_of(arcmsr_cdb, struct CommandControlBlock,
arcmsr_cdb);
poll_ccb_done |= (pCCB == poll_ccb) ? 1 : 0;
if ((pCCB->acb != acb) ||
(pCCB->startdone != ARCMSR_CCB_START)) {
if (pCCB->startdone == ARCMSR_CCB_ABORTED) {
pr_notice("arcmsr%d: scsi id = %d "
"lun = %d ccb = '0x%p' poll command "
"abort successfully\n"
, acb->host->host_no
, pCCB->pcmd->device->id
, (u32)pCCB->pcmd->device->lun
, pCCB);
pCCB->pcmd->result = DID_ABORT << 16;
arcmsr_ccb_complete(pCCB);
continue;
}
pr_notice("arcmsr%d: polling an illegal "
"ccb command done ccb = '0x%p' "
"ccboutstandingcount = %d\n"
, acb->host->host_no
, pCCB
, atomic_read(&acb->ccboutstandingcount));
continue;
}
error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1)
? true : false;
arcmsr_report_ccb_state(acb, pCCB, error);
}
return rtn;
}
static int arcmsr_polling_ccbdone(struct AdapterControlBlock *acb,
struct CommandControlBlock *poll_ccb)
{
int rtn = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
rtn = arcmsr_hbaA_polling_ccbdone(acb, poll_ccb);
}
break;
case ACB_ADAPTER_TYPE_B: {
rtn = arcmsr_hbaB_polling_ccbdone(acb, poll_ccb);
}
break;
case ACB_ADAPTER_TYPE_C: {
rtn = arcmsr_hbaC_polling_ccbdone(acb, poll_ccb);
}
break;
case ACB_ADAPTER_TYPE_D:
rtn = arcmsr_hbaD_polling_ccbdone(acb, poll_ccb);
break;
}
return rtn;
}
static int arcmsr_iop_confirm(struct AdapterControlBlock *acb)
{
uint32_t cdb_phyaddr, cdb_phyaddr_hi32;
dma_addr_t dma_coherent_handle;
/*
********************************************************************
** here we need to tell iop 331 our freeccb.HighPart
** if freeccb.HighPart is not zero
********************************************************************
*/
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_B:
case ACB_ADAPTER_TYPE_D:
dma_coherent_handle = acb->dma_coherent_handle2;
break;
default:
dma_coherent_handle = acb->dma_coherent_handle;
break;
}
cdb_phyaddr = lower_32_bits(dma_coherent_handle);
cdb_phyaddr_hi32 = upper_32_bits(dma_coherent_handle);
acb->cdb_phyaddr_hi32 = cdb_phyaddr_hi32;
/*
***********************************************************************
** if adapter type B, set window of "post command Q"
***********************************************************************
*/
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
if (cdb_phyaddr_hi32 != 0) {
struct MessageUnit_A __iomem *reg = acb->pmuA;
writel(ARCMSR_SIGNATURE_SET_CONFIG, \
®->message_rwbuffer[0]);
writel(cdb_phyaddr_hi32, ®->message_rwbuffer[1]);
writel(ARCMSR_INBOUND_MESG0_SET_CONFIG, \
®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: ""set ccb high \
part physical address timeout\n",
acb->host->host_no);
return 1;
}
}
}
break;
case ACB_ADAPTER_TYPE_B: {
uint32_t __iomem *rwbuffer;
struct MessageUnit_B *reg = acb->pmuB;
reg->postq_index = 0;
reg->doneq_index = 0;
writel(ARCMSR_MESSAGE_SET_POST_WINDOW, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: cannot set driver mode\n", \
acb->host->host_no);
return 1;
}
rwbuffer = reg->message_rwbuffer;
/* driver "set config" signature */
writel(ARCMSR_SIGNATURE_SET_CONFIG, rwbuffer++);
/* normal should be zero */
writel(cdb_phyaddr_hi32, rwbuffer++);
/* postQ size (256 + 8)*4 */
writel(cdb_phyaddr, rwbuffer++);
/* doneQ size (256 + 8)*4 */
writel(cdb_phyaddr + 1056, rwbuffer++);
/* ccb maxQ size must be --> [(256 + 8)*4]*/
writel(1056, rwbuffer);
writel(ARCMSR_MESSAGE_SET_CONFIG, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: 'set command Q window' \
timeout \n",acb->host->host_no);
return 1;
}
writel(ARCMSR_MESSAGE_START_DRIVER_MODE, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
pr_err("arcmsr%d: can't set driver mode.\n",
acb->host->host_no);
return 1;
}
}
break;
case ACB_ADAPTER_TYPE_C: {
if (cdb_phyaddr_hi32 != 0) {
struct MessageUnit_C __iomem *reg = acb->pmuC;
printk(KERN_NOTICE "arcmsr%d: cdb_phyaddr_hi32=0x%x\n",
acb->adapter_index, cdb_phyaddr_hi32);
writel(ARCMSR_SIGNATURE_SET_CONFIG, ®->msgcode_rwbuffer[0]);
writel(cdb_phyaddr_hi32, ®->msgcode_rwbuffer[1]);
writel(ARCMSR_INBOUND_MESG0_SET_CONFIG, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: 'set command Q window' \
timeout \n", acb->host->host_no);
return 1;
}
}
}
break;
case ACB_ADAPTER_TYPE_D: {
uint32_t __iomem *rwbuffer;
struct MessageUnit_D *reg = acb->pmuD;
reg->postq_index = 0;
reg->doneq_index = 0;
rwbuffer = reg->msgcode_rwbuffer;
writel(ARCMSR_SIGNATURE_SET_CONFIG, rwbuffer++);
writel(cdb_phyaddr_hi32, rwbuffer++);
writel(cdb_phyaddr, rwbuffer++);
writel(cdb_phyaddr + (ARCMSR_MAX_ARC1214_POSTQUEUE *
sizeof(struct InBound_SRB)), rwbuffer++);
writel(0x100, rwbuffer);
writel(ARCMSR_INBOUND_MESG0_SET_CONFIG, reg->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(acb)) {
pr_notice("arcmsr%d: 'set command Q window' timeout\n",
acb->host->host_no);
return 1;
}
}
break;
}
return 0;
}
static void arcmsr_wait_firmware_ready(struct AdapterControlBlock *acb)
{
uint32_t firmware_state = 0;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
do {
firmware_state = readl(®->outbound_msgaddr1);
} while ((firmware_state & ARCMSR_OUTBOUND_MESG1_FIRMWARE_OK) == 0);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
do {
firmware_state = readl(reg->iop2drv_doorbell);
} while ((firmware_state & ARCMSR_MESSAGE_FIRMWARE_OK) == 0);
writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT, reg->drv2iop_doorbell);
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
do {
firmware_state = readl(®->outbound_msgaddr1);
} while ((firmware_state & ARCMSR_HBCMU_MESSAGE_FIRMWARE_OK) == 0);
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
do {
firmware_state = readl(reg->outbound_msgaddr1);
} while ((firmware_state &
ARCMSR_ARC1214_MESSAGE_FIRMWARE_OK) == 0);
}
break;
}
}
static void arcmsr_hbaA_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) || ((acb->acb_flags & ACB_F_BUS_RESET) != 0 ) || ((acb->acb_flags & ACB_F_ABORT) != 0 )){
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) == atomic_read(&acb->rq_map_token)){
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value, atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
}
return;
}
static void arcmsr_hbaB_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) || ((acb->acb_flags & ACB_F_BUS_RESET) != 0 ) || ((acb->acb_flags & ACB_F_ABORT) != 0 )){
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) == atomic_read(&acb->rq_map_token)) {
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value, atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_MESSAGE_GET_CONFIG, reg->drv2iop_doorbell);
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
}
return;
}
static void arcmsr_hbaC_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_C __iomem *reg = acb->pmuC;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) || ((acb->acb_flags & ACB_F_BUS_RESET) != 0) || ((acb->acb_flags & ACB_F_ABORT) != 0)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) == atomic_read(&acb->rq_map_token)) {
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value, atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG, ®->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, ®->inbound_doorbell);
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
}
return;
}
static void arcmsr_hbaD_request_device_map(struct AdapterControlBlock *acb)
{
struct MessageUnit_D *reg = acb->pmuD;
if (unlikely(atomic_read(&acb->rq_map_token) == 0) ||
((acb->acb_flags & ACB_F_BUS_RESET) != 0) ||
((acb->acb_flags & ACB_F_ABORT) != 0)) {
mod_timer(&acb->eternal_timer,
jiffies + msecs_to_jiffies(6 * HZ));
} else {
acb->fw_flag = FW_NORMAL;
if (atomic_read(&acb->ante_token_value) ==
atomic_read(&acb->rq_map_token)) {
atomic_set(&acb->rq_map_token, 16);
}
atomic_set(&acb->ante_token_value,
atomic_read(&acb->rq_map_token));
if (atomic_dec_and_test(&acb->rq_map_token)) {
mod_timer(&acb->eternal_timer, jiffies +
msecs_to_jiffies(6 * HZ));
return;
}
writel(ARCMSR_INBOUND_MESG0_GET_CONFIG,
reg->inbound_msgaddr0);
mod_timer(&acb->eternal_timer, jiffies +
msecs_to_jiffies(6 * HZ));
}
}
static void arcmsr_request_device_map(unsigned long pacb)
{
struct AdapterControlBlock *acb = (struct AdapterControlBlock *)pacb;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
arcmsr_hbaA_request_device_map(acb);
}
break;
case ACB_ADAPTER_TYPE_B: {
arcmsr_hbaB_request_device_map(acb);
}
break;
case ACB_ADAPTER_TYPE_C: {
arcmsr_hbaC_request_device_map(acb);
}
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_request_device_map(acb);
break;
}
}
static void arcmsr_hbaA_start_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
acb->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_START_BGRB, ®->inbound_msgaddr0);
if (!arcmsr_hbaA_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'start adapter background \
rebulid' timeout \n", acb->host->host_no);
}
}
static void arcmsr_hbaB_start_bgrb(struct AdapterControlBlock *acb)
{
struct MessageUnit_B *reg = acb->pmuB;
acb->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_MESSAGE_START_BGRB, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "arcmsr%d: wait 'start adapter background \
rebulid' timeout \n",acb->host->host_no);
}
}
static void arcmsr_hbaC_start_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
pACB->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_START_BGRB, &phbcmu->inbound_msgaddr0);
writel(ARCMSR_HBCMU_DRV2IOP_MESSAGE_CMD_DONE, &phbcmu->inbound_doorbell);
if (!arcmsr_hbaC_wait_msgint_ready(pACB)) {
printk(KERN_NOTICE "arcmsr%d: wait 'start adapter background \
rebulid' timeout \n", pACB->host->host_no);
}
return;
}
static void arcmsr_hbaD_start_bgrb(struct AdapterControlBlock *pACB)
{
struct MessageUnit_D *pmu = pACB->pmuD;
pACB->acb_flags |= ACB_F_MSG_START_BGRB;
writel(ARCMSR_INBOUND_MESG0_START_BGRB, pmu->inbound_msgaddr0);
if (!arcmsr_hbaD_wait_msgint_ready(pACB)) {
pr_notice("arcmsr%d: wait 'start adapter "
"background rebulid' timeout\n", pACB->host->host_no);
}
}
static void arcmsr_start_adapter_bgrb(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
arcmsr_hbaA_start_bgrb(acb);
break;
case ACB_ADAPTER_TYPE_B:
arcmsr_hbaB_start_bgrb(acb);
break;
case ACB_ADAPTER_TYPE_C:
arcmsr_hbaC_start_bgrb(acb);
break;
case ACB_ADAPTER_TYPE_D:
arcmsr_hbaD_start_bgrb(acb);
break;
}
}
static void arcmsr_clear_doorbell_queue_buffer(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
uint32_t outbound_doorbell;
/* empty doorbell Qbuffer if door bell ringed */
outbound_doorbell = readl(®->outbound_doorbell);
/*clear doorbell interrupt */
writel(outbound_doorbell, ®->outbound_doorbell);
writel(ARCMSR_INBOUND_DRIVER_DATA_READ_OK, ®->inbound_doorbell);
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
/*clear interrupt and message state*/
writel(ARCMSR_MESSAGE_INT_CLEAR_PATTERN, reg->iop2drv_doorbell);
writel(ARCMSR_DRV2IOP_DATA_READ_OK, reg->drv2iop_doorbell);
/* let IOP know data has been read */
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *reg = acb->pmuC;
uint32_t outbound_doorbell, i;
/* empty doorbell Qbuffer if door bell ringed */
outbound_doorbell = readl(®->outbound_doorbell);
writel(outbound_doorbell, ®->outbound_doorbell_clear);
writel(ARCMSR_HBCMU_DRV2IOP_DATA_READ_OK, ®->inbound_doorbell);
for (i = 0; i < 200; i++) {
msleep(20);
outbound_doorbell = readl(®->outbound_doorbell);
if (outbound_doorbell &
ARCMSR_HBCMU_IOP2DRV_DATA_WRITE_OK) {
writel(outbound_doorbell,
®->outbound_doorbell_clear);
writel(ARCMSR_HBCMU_DRV2IOP_DATA_READ_OK,
®->inbound_doorbell);
} else
break;
}
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
uint32_t outbound_doorbell, i;
/* empty doorbell Qbuffer if door bell ringed */
outbound_doorbell = readl(reg->outbound_doorbell);
writel(outbound_doorbell, reg->outbound_doorbell);
writel(ARCMSR_ARC1214_DRV2IOP_DATA_OUT_READ,
reg->inbound_doorbell);
for (i = 0; i < 200; i++) {
msleep(20);
outbound_doorbell = readl(reg->outbound_doorbell);
if (outbound_doorbell &
ARCMSR_ARC1214_IOP2DRV_DATA_WRITE_OK) {
writel(outbound_doorbell,
reg->outbound_doorbell);
writel(ARCMSR_ARC1214_DRV2IOP_DATA_OUT_READ,
reg->inbound_doorbell);
} else
break;
}
}
break;
}
}
static void arcmsr_enable_eoi_mode(struct AdapterControlBlock *acb)
{
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A:
return;
case ACB_ADAPTER_TYPE_B:
{
struct MessageUnit_B *reg = acb->pmuB;
writel(ARCMSR_MESSAGE_ACTIVE_EOI_MODE, reg->drv2iop_doorbell);
if (!arcmsr_hbaB_wait_msgint_ready(acb)) {
printk(KERN_NOTICE "ARCMSR IOP enables EOI_MODE TIMEOUT");
return;
}
}
break;
case ACB_ADAPTER_TYPE_C:
return;
}
return;
}
static void arcmsr_hardware_reset(struct AdapterControlBlock *acb)
{
uint8_t value[64];
int i, count = 0;
struct MessageUnit_A __iomem *pmuA = acb->pmuA;
struct MessageUnit_C __iomem *pmuC = acb->pmuC;
struct MessageUnit_D *pmuD = acb->pmuD;
/* backup pci config data */
printk(KERN_NOTICE "arcmsr%d: executing hw bus reset .....\n", acb->host->host_no);
for (i = 0; i < 64; i++) {
pci_read_config_byte(acb->pdev, i, &value[i]);
}
/* hardware reset signal */
if ((acb->dev_id == 0x1680)) {
writel(ARCMSR_ARC1680_BUS_RESET, &pmuA->reserved1[0]);
} else if ((acb->dev_id == 0x1880)) {
do {
count++;
writel(0xF, &pmuC->write_sequence);
writel(0x4, &pmuC->write_sequence);
writel(0xB, &pmuC->write_sequence);
writel(0x2, &pmuC->write_sequence);
writel(0x7, &pmuC->write_sequence);
writel(0xD, &pmuC->write_sequence);
} while (((readl(&pmuC->host_diagnostic) & ARCMSR_ARC1880_DiagWrite_ENABLE) == 0) && (count < 5));
writel(ARCMSR_ARC1880_RESET_ADAPTER, &pmuC->host_diagnostic);
} else if ((acb->dev_id == 0x1214)) {
writel(0x20, pmuD->reset_request);
} else {
pci_write_config_byte(acb->pdev, 0x84, 0x20);
}
msleep(2000);
/* write back pci config data */
for (i = 0; i < 64; i++) {
pci_write_config_byte(acb->pdev, i, value[i]);
}
msleep(1000);
return;
}
static void arcmsr_iop_init(struct AdapterControlBlock *acb)
{
uint32_t intmask_org;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_wait_firmware_ready(acb);
arcmsr_iop_confirm(acb);
/*start background rebuild*/
arcmsr_start_adapter_bgrb(acb);
/* empty doorbell Qbuffer if door bell ringed */
arcmsr_clear_doorbell_queue_buffer(acb);
arcmsr_enable_eoi_mode(acb);
/* enable outbound Post Queue,outbound doorbell Interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
acb->acb_flags |= ACB_F_IOP_INITED;
}
static uint8_t arcmsr_iop_reset(struct AdapterControlBlock *acb)
{
struct CommandControlBlock *ccb;
uint32_t intmask_org;
uint8_t rtnval = 0x00;
int i = 0;
unsigned long flags;
if (atomic_read(&acb->ccboutstandingcount) != 0) {
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
/* talk to iop 331 outstanding command aborted */
rtnval = arcmsr_abort_allcmd(acb);
/* clear all outbound posted Q */
arcmsr_done4abort_postqueue(acb);
for (i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++) {
ccb = acb->pccb_pool[i];
if (ccb->startdone == ARCMSR_CCB_START) {
scsi_dma_unmap(ccb->pcmd);
ccb->startdone = ARCMSR_CCB_DONE;
ccb->ccb_flags = 0;
spin_lock_irqsave(&acb->ccblist_lock, flags);
list_add_tail(&ccb->list, &acb->ccb_free_list);
spin_unlock_irqrestore(&acb->ccblist_lock, flags);
}
}
atomic_set(&acb->ccboutstandingcount, 0);
/* enable all outbound interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
return rtnval;
}
return rtnval;
}
static int arcmsr_bus_reset(struct scsi_cmnd *cmd)
{
struct AdapterControlBlock *acb;
uint32_t intmask_org, outbound_doorbell;
int retry_count = 0;
int rtn = FAILED;
acb = (struct AdapterControlBlock *) cmd->device->host->hostdata;
printk(KERN_ERR "arcmsr: executing bus reset eh.....num_resets = %d, num_aborts = %d \n", acb->num_resets, acb->num_aborts);
acb->num_resets++;
switch(acb->adapter_type){
case ACB_ADAPTER_TYPE_A:{
if (acb->acb_flags & ACB_F_BUS_RESET){
long timeout;
printk(KERN_ERR "arcmsr: there is an bus reset eh proceeding.......\n");
timeout = wait_event_timeout(wait_q, (acb->acb_flags & ACB_F_BUS_RESET) == 0, 220*HZ);
if (timeout) {
return SUCCESS;
}
}
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
struct MessageUnit_A __iomem *reg;
reg = acb->pmuA;
arcmsr_hardware_reset(acb);
acb->acb_flags &= ~ACB_F_IOP_INITED;
sleep_again:
ssleep(ARCMSR_SLEEPTIME);
if ((readl(®->outbound_msgaddr1) & ARCMSR_OUTBOUND_MESG1_FIRMWARE_OK) == 0) {
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, retry=%d\n", acb->host->host_no, retry_count);
if (retry_count > ARCMSR_RETRYCOUNT) {
acb->fw_flag = FW_DEADLOCK;
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, RETRY TERMINATED!!\n", acb->host->host_no);
return FAILED;
}
retry_count++;
goto sleep_again;
}
acb->acb_flags |= ACB_F_IOP_INITED;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_get_firmware_spec(acb);
arcmsr_start_adapter_bgrb(acb);
/* clear Qbuffer if door bell ringed */
outbound_doorbell = readl(®->outbound_doorbell);
writel(outbound_doorbell, ®->outbound_doorbell); /*clear interrupt */
writel(ARCMSR_INBOUND_DRIVER_DATA_READ_OK, ®->inbound_doorbell);
/* enable outbound Post Queue,outbound doorbell Interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = SUCCESS;
printk(KERN_ERR "arcmsr: scsi bus reset eh returns with success\n");
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6*HZ));
rtn = SUCCESS;
}
break;
}
case ACB_ADAPTER_TYPE_B:{
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = FAILED;
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
rtn = SUCCESS;
}
break;
}
case ACB_ADAPTER_TYPE_C:{
if (acb->acb_flags & ACB_F_BUS_RESET) {
long timeout;
printk(KERN_ERR "arcmsr: there is an bus reset eh proceeding.......\n");
timeout = wait_event_timeout(wait_q, (acb->acb_flags & ACB_F_BUS_RESET) == 0, 220*HZ);
if (timeout) {
return SUCCESS;
}
}
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
struct MessageUnit_C __iomem *reg;
reg = acb->pmuC;
arcmsr_hardware_reset(acb);
acb->acb_flags &= ~ACB_F_IOP_INITED;
sleep:
ssleep(ARCMSR_SLEEPTIME);
if ((readl(®->host_diagnostic) & 0x04) != 0) {
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, retry=%d\n", acb->host->host_no, retry_count);
if (retry_count > ARCMSR_RETRYCOUNT) {
acb->fw_flag = FW_DEADLOCK;
printk(KERN_ERR "arcmsr%d: waiting for hw bus reset return, RETRY TERMINATED!!\n", acb->host->host_no);
return FAILED;
}
retry_count++;
goto sleep;
}
acb->acb_flags |= ACB_F_IOP_INITED;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_get_firmware_spec(acb);
arcmsr_start_adapter_bgrb(acb);
/* clear Qbuffer if door bell ringed */
arcmsr_clear_doorbell_queue_buffer(acb);
/* enable outbound Post Queue,outbound doorbell Interrupt */
arcmsr_enable_outbound_ints(acb, intmask_org);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6 * HZ));
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = SUCCESS;
printk(KERN_ERR "arcmsr: scsi bus reset eh returns with success\n");
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer, jiffies + msecs_to_jiffies(6*HZ));
rtn = SUCCESS;
}
break;
}
case ACB_ADAPTER_TYPE_D: {
if (acb->acb_flags & ACB_F_BUS_RESET) {
long timeout;
pr_notice("arcmsr: there is an bus reset"
" eh proceeding.......\n");
timeout = wait_event_timeout(wait_q, (acb->acb_flags
& ACB_F_BUS_RESET) == 0, 220 * HZ);
if (timeout)
return SUCCESS;
}
acb->acb_flags |= ACB_F_BUS_RESET;
if (!arcmsr_iop_reset(acb)) {
struct MessageUnit_D *reg;
reg = acb->pmuD;
arcmsr_hardware_reset(acb);
acb->acb_flags &= ~ACB_F_IOP_INITED;
nap:
ssleep(ARCMSR_SLEEPTIME);
if ((readl(reg->sample_at_reset) & 0x80) != 0) {
pr_err("arcmsr%d: waiting for "
"hw bus reset return, retry=%d\n",
acb->host->host_no, retry_count);
if (retry_count > ARCMSR_RETRYCOUNT) {
acb->fw_flag = FW_DEADLOCK;
pr_err("arcmsr%d: waiting for hw bus"
" reset return, "
"RETRY TERMINATED!!\n",
acb->host->host_no);
return FAILED;
}
retry_count++;
goto nap;
}
acb->acb_flags |= ACB_F_IOP_INITED;
/* disable all outbound interrupt */
intmask_org = arcmsr_disable_outbound_ints(acb);
arcmsr_get_firmware_spec(acb);
arcmsr_start_adapter_bgrb(acb);
arcmsr_clear_doorbell_queue_buffer(acb);
arcmsr_enable_outbound_ints(acb, intmask_org);
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer,
jiffies + msecs_to_jiffies(6 * HZ));
acb->acb_flags &= ~ACB_F_BUS_RESET;
rtn = SUCCESS;
pr_err("arcmsr: scsi bus reset "
"eh returns with success\n");
} else {
acb->acb_flags &= ~ACB_F_BUS_RESET;
atomic_set(&acb->rq_map_token, 16);
atomic_set(&acb->ante_token_value, 16);
acb->fw_flag = FW_NORMAL;
mod_timer(&acb->eternal_timer,
jiffies + msecs_to_jiffies(6 * HZ));
rtn = SUCCESS;
}
break;
}
}
return rtn;
}
static int arcmsr_abort_one_cmd(struct AdapterControlBlock *acb,
struct CommandControlBlock *ccb)
{
int rtn;
rtn = arcmsr_polling_ccbdone(acb, ccb);
return rtn;
}
static int arcmsr_abort(struct scsi_cmnd *cmd)
{
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *)cmd->device->host->hostdata;
int i = 0;
int rtn = FAILED;
uint32_t intmask_org;
printk(KERN_NOTICE
"arcmsr%d: abort device command of scsi id = %d lun = %d\n",
acb->host->host_no, cmd->device->id, (u32)cmd->device->lun);
acb->acb_flags |= ACB_F_ABORT;
acb->num_aborts++;
/*
************************************************
** the all interrupt service routine is locked
** we need to handle it as soon as possible and exit
************************************************
*/
if (!atomic_read(&acb->ccboutstandingcount)) {
acb->acb_flags &= ~ACB_F_ABORT;
return rtn;
}
intmask_org = arcmsr_disable_outbound_ints(acb);
for (i = 0; i < ARCMSR_MAX_FREECCB_NUM; i++) {
struct CommandControlBlock *ccb = acb->pccb_pool[i];
if (ccb->startdone == ARCMSR_CCB_START && ccb->pcmd == cmd) {
ccb->startdone = ARCMSR_CCB_ABORTED;
rtn = arcmsr_abort_one_cmd(acb, ccb);
break;
}
}
acb->acb_flags &= ~ACB_F_ABORT;
arcmsr_enable_outbound_ints(acb, intmask_org);
return rtn;
}
static const char *arcmsr_info(struct Scsi_Host *host)
{
struct AdapterControlBlock *acb =
(struct AdapterControlBlock *) host->hostdata;
static char buf[256];
char *type;
int raid6 = 1;
switch (acb->pdev->device) {
case PCI_DEVICE_ID_ARECA_1110:
case PCI_DEVICE_ID_ARECA_1200:
case PCI_DEVICE_ID_ARECA_1202:
case PCI_DEVICE_ID_ARECA_1210:
raid6 = 0;
/*FALLTHRU*/
case PCI_DEVICE_ID_ARECA_1120:
case PCI_DEVICE_ID_ARECA_1130:
case PCI_DEVICE_ID_ARECA_1160:
case PCI_DEVICE_ID_ARECA_1170:
case PCI_DEVICE_ID_ARECA_1201:
case PCI_DEVICE_ID_ARECA_1203:
case PCI_DEVICE_ID_ARECA_1220:
case PCI_DEVICE_ID_ARECA_1230:
case PCI_DEVICE_ID_ARECA_1260:
case PCI_DEVICE_ID_ARECA_1270:
case PCI_DEVICE_ID_ARECA_1280:
type = "SATA";
break;
case PCI_DEVICE_ID_ARECA_1214:
case PCI_DEVICE_ID_ARECA_1380:
case PCI_DEVICE_ID_ARECA_1381:
case PCI_DEVICE_ID_ARECA_1680:
case PCI_DEVICE_ID_ARECA_1681:
case PCI_DEVICE_ID_ARECA_1880:
type = "SAS/SATA";
break;
default:
type = "unknown";
raid6 = 0;
break;
}
sprintf(buf, "Areca %s RAID Controller %s\narcmsr version %s\n",
type, raid6 ? "(RAID6 capable)" : "", ARCMSR_DRIVER_VERSION);
return buf;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5289_0 |
crossvul-cpp_data_bad_1436_0 | /*
Copyright (C) 2013-2015 Yubico AB
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "internal.h"
#include <stdlib.h>
#ifdef _WIN32
#include <windows.h>
#include <winternl.h>
#include <winerror.h>
#include <stdio.h>
#include <bcrypt.h>
#include <sal.h>
#pragma comment(lib, "bcrypt.lib")
#else
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#endif
#ifdef __linux
#include <linux/hidraw.h>
#endif
#ifdef __linux
static uint32_t
get_bytes (uint8_t * rpt, size_t len, size_t num_bytes, size_t cur)
{
/* Return if there aren't enough bytes. */
if (cur + num_bytes >= len)
return 0;
if (num_bytes == 0)
return 0;
else if (num_bytes == 1)
{
return rpt[cur + 1];
}
else if (num_bytes == 2)
{
return (rpt[cur + 2] * 256 + rpt[cur + 1]);
}
else
return 0;
}
static int
get_usage (uint8_t * report_descriptor, size_t size,
unsigned short *usage_page, unsigned short *usage)
{
size_t i = 0;
int size_code;
int data_len, key_size;
int usage_found = 0, usage_page_found = 0;
while (i < size)
{
int key = report_descriptor[i];
int key_cmd = key & 0xfc;
if ((key & 0xf0) == 0xf0)
{
fprintf (stderr, "invalid data received.\n");
return -1;
}
else
{
size_code = key & 0x3;
switch (size_code)
{
case 0:
case 1:
case 2:
data_len = size_code;
break;
case 3:
data_len = 4;
break;
default:
/* Can't ever happen since size_code is & 0x3 */
data_len = 0;
break;
};
key_size = 1;
}
if (key_cmd == 0x4)
{
*usage_page = get_bytes (report_descriptor, size, data_len, i);
usage_page_found = 1;
}
if (key_cmd == 0x8)
{
*usage = get_bytes (report_descriptor, size, data_len, i);
usage_found = 1;
}
if (usage_page_found && usage_found)
return 0; /* success */
i += data_len + key_size;
}
return -1; /* failure */
}
#endif
static int
get_usages (struct hid_device_info *dev, unsigned short *usage_page,
unsigned short *usage)
{
#ifdef __linux
int res, desc_size;
int ret = U2FH_TRANSPORT_ERROR;
struct hidraw_report_descriptor rpt_desc;
int handle = open (dev->path, O_RDWR);
if (handle > 0)
{
memset (&rpt_desc, 0, sizeof (rpt_desc));
res = ioctl (handle, HIDIOCGRDESCSIZE, &desc_size);
if (res >= 0)
{
rpt_desc.size = desc_size;
res = ioctl (handle, HIDIOCGRDESC, &rpt_desc);
if (res >= 0)
{
res =
get_usage (rpt_desc.value, rpt_desc.size, usage_page, usage);
if (res >= 0)
{
ret = U2FH_OK;
}
}
}
close (handle);
}
return ret;
#else
*usage_page = dev->usage_page;
*usage = dev->usage;
return U2FH_OK;
#endif
}
static struct u2fdevice *
close_device (u2fh_devs * devs, struct u2fdevice *dev)
{
struct u2fdevice *next = dev->next;
hid_close (dev->devh);
free (dev->device_path);
free (dev->device_string);
if (dev == devs->first)
{
devs->first = next;
free (dev);
}
else
{
struct u2fdevice *d;
for (d = devs->first; d != NULL; d = d->next)
{
if (d->next == dev)
{
d->next = next;
free (dev);
break;
}
}
}
return next;
}
struct u2fdevice *
get_device (u2fh_devs * devs, unsigned id)
{
struct u2fdevice *dev;
for (dev = devs->first; dev != NULL; dev = dev->next)
{
if (dev->id == id)
{
return dev;
}
}
return NULL;
}
static struct u2fdevice *
new_device (u2fh_devs * devs)
{
struct u2fdevice *new = malloc (sizeof (struct u2fdevice));
if (new == NULL)
{
return NULL;
}
memset (new, 0, sizeof (struct u2fdevice));
new->id = devs->max_id++;
if (devs->first == NULL)
{
devs->first = new;
}
else
{
struct u2fdevice *dev;
for (dev = devs->first; dev != NULL; dev = dev->next)
{
if (dev->next == NULL)
{
break;
}
}
dev->next = new;
}
return new;
}
static void
close_devices (u2fh_devs * devs)
{
struct u2fdevice *dev;
if (devs == NULL)
{
return;
}
dev = devs->first;
while (dev)
{
dev = close_device (devs, dev);
}
}
#if defined(_WIN32)
static int
obtain_nonce(unsigned char* nonce)
{
NTSTATUS status;
status = BCryptGenRandom(NULL, nonce, 8,
BCRYPT_USE_SYSTEM_PREFERRED_RNG);
if (!NT_SUCCESS(status))
return (-1);
return (0);
}
#elif defined(HAVE_DEV_URANDOM)
static int
obtain_nonce(unsigned char* nonce)
{
int fd = -1;
int ok = -1;
ssize_t r;
if ((fd = open("/dev/urandom", O_RDONLY)) < 0)
goto fail;
if ((r = read(fd, nonce, 8)) < 0 || r != 8)
goto fail;
ok = 0;
fail:
if (fd != -1)
close(fd);
return (ok);
}
#else
#error "please provide an implementation of obtain_nonce() for your platform"
#endif /* _WIN32 */
static int
init_device (u2fh_devs * devs, struct u2fdevice *dev)
{
unsigned char resp[1024];
unsigned char nonce[8];
if (obtain_nonce(nonce) != 0)
{
return U2FH_TRANSPORT_ERROR;
}
size_t resplen = sizeof (resp);
dev->cid = CID_BROADCAST;
if (u2fh_sendrecv
(devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp,
&resplen) == U2FH_OK)
{
U2FHID_INIT_RESP initresp;
if (resplen > sizeof (initresp))
{
return U2FH_MEMORY_ERROR;
}
memcpy (&initresp, resp, resplen);
dev->cid = initresp.cid;
dev->versionInterface = initresp.versionInterface;
dev->versionMajor = initresp.versionMajor;
dev->versionMinor = initresp.versionMinor;
dev->capFlags = initresp.capFlags;
}
else
{
return U2FH_TRANSPORT_ERROR;
}
return U2FH_OK;
}
static int
ping_device (u2fh_devs * devs, unsigned index)
{
unsigned char data[1] = { 0 };
unsigned char resp[1024];
size_t resplen = sizeof (resp);
return u2fh_sendrecv (devs, index, U2FHID_PING, data, sizeof (data), resp,
&resplen);
}
/**
* u2fh_devs_init:
* @devs: pointer to #u2fh_devs type to initialize.
*
* Initialize device handle.
*
* Returns: On success %U2FH_OK (integer 0) is returned, on memory
* allocation errors %U2FH_MEMORY_ERROR is returned, or another
* #u2fh_rc error code is returned.
*/
u2fh_rc
u2fh_devs_init (u2fh_devs ** devs)
{
u2fh_devs *d;
int rc;
d = malloc (sizeof (*d));
if (d == NULL)
return U2FH_MEMORY_ERROR;
memset (d, 0, sizeof (*d));
rc = hid_init ();
if (rc != 0)
{
free (d);
return U2FH_TRANSPORT_ERROR;
}
*devs = d;
return U2FH_OK;
}
/**
* u2fh_devs_discover:
* @devs: device handle, from u2fh_devs_init().
* @max_index: will on return be set to the maximum index, may be NULL; if
* there is 1 device this will be 0, if there are 2 devices this
* will be 1, and so on.
*
* Discover and open new devices. This function can safely be called
* several times and will free resources associated with unplugged
* devices and open new.
*
* Returns: On success, %U2FH_OK (integer 0) is returned, when no U2F
* device could be found %U2FH_NO_U2F_DEVICE is returned, or another
* #u2fh_rc error code.
*/
u2fh_rc
u2fh_devs_discover (u2fh_devs * devs, unsigned *max_index)
{
struct hid_device_info *di, *cur_dev;
u2fh_rc res = U2FH_NO_U2F_DEVICE;
struct u2fdevice *dev;
di = hid_enumerate (0, 0);
for (cur_dev = di; cur_dev; cur_dev = cur_dev->next)
{
int found = 0;
unsigned short usage_page = 0, usage = 0;
/* check if we already opened this device */
for (dev = devs->first; dev != NULL; dev = dev->next)
{
if (strcmp (dev->device_path, cur_dev->path) == 0)
{
if (ping_device (devs, dev->id) == U2FH_OK)
{
found = 1;
res = U2FH_OK;
}
else
{
if (debug)
{
fprintf (stderr, "Device %s failed ping, dead.\n",
dev->device_path);
}
close_device (devs, dev);
}
break;
}
}
if (found)
{
continue;
}
get_usages (cur_dev, &usage_page, &usage);
if (usage_page == FIDO_USAGE_PAGE && usage == FIDO_USAGE_U2FHID)
{
dev = new_device (devs);
dev->devh = hid_open_path (cur_dev->path);
if (dev->devh != NULL)
{
dev->device_path = strdup (cur_dev->path);
if (dev->device_path == NULL)
{
close_device (devs, dev);
goto out;
}
if (init_device (devs, dev) == U2FH_OK)
{
if (cur_dev->product_string)
{
size_t len =
wcstombs (NULL, cur_dev->product_string, 0);
dev->device_string = malloc (len + 1);
if (dev->device_string == NULL)
{
close_device (devs, dev);
goto out;
}
memset (dev->device_string, 0, len + 1);
wcstombs (dev->device_string, cur_dev->product_string,
len);
if (debug)
{
fprintf (stderr, "device %s discovered as '%s'\n",
dev->device_path, dev->device_string);
fprintf (stderr,
" version (Interface, Major, "
"Minor, Build): %d, %d, "
"%d, %d capFlags: %d\n",
dev->versionInterface,
dev->versionMajor,
dev->versionMinor,
dev->versionBuild, dev->capFlags);
}
}
res = U2FH_OK;
continue;
}
}
close_device (devs, dev);
}
}
/* loop through all open devices and make sure we find them in the enumeration */
dev = devs->first;
while (dev)
{
int found = 0;
for (cur_dev = di; cur_dev; cur_dev = cur_dev->next)
{
if (strcmp (cur_dev->path, dev->device_path) == 0)
{
found = 1;
dev = dev->next;
break;
}
}
if (!found)
{
if (debug)
{
fprintf (stderr, "device %s looks dead.\n", dev->device_path);
}
dev = close_device (devs, dev);
}
}
out:
hid_free_enumeration (di);
if (res == U2FH_OK && max_index)
*max_index = devs->max_id - 1;
return res;
}
/**
* u2fh_devs_done:
* @devs: device handle, from u2fh_devs_init().
*
* Release all resources associated with @devs. This function must be
* called when you are finished with a device handle.
*/
void
u2fh_devs_done (u2fh_devs * devs)
{
close_devices (devs);
hid_exit ();
free (devs);
}
/**
* u2fh_get_device_description:
* @devs: device_handle, from u2fh_devs_init().
* @index: index of device
* @out: buffer for storing device description
* @len: maximum amount of data to store in @out. Will be updated.
*
* Get the device description of the device at @index. Stores the
* string in @out.
*
* Returns: %U2FH_OK on success.
*/
u2fh_rc
u2fh_get_device_description (u2fh_devs * devs, unsigned index, char *out,
size_t * len)
{
size_t i;
struct u2fdevice *dev = get_device (devs, index);
if (!dev)
{
return U2FH_NO_U2F_DEVICE;
}
i = strlen (dev->device_string);
if (i < *len)
{
*len = i;
}
else
{
return U2FH_MEMORY_ERROR;
}
strcpy (out, dev->device_string);
return U2FH_OK;
}
/**
* u2fh_is_alive:
* @devs: device_handle, from u2fh_devs_init().
* @index: index of device
*
* Get the liveliness of the device @index.
*
* Returns: 1 if the device is considered alive, 0 otherwise.
*/
int
u2fh_is_alive (u2fh_devs * devs, unsigned index)
{
if (!get_device (devs, index))
return 0;
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1436_0 |
crossvul-cpp_data_bad_3418_1 | /*
* WebP (.webp) image decoder
* Copyright (c) 2013 Aneesh Dogra <aneesh@sugarlabs.org>
* Copyright (c) 2013 Justin Ruggles <justin.ruggles@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* WebP image decoder
*
* @author Aneesh Dogra <aneesh@sugarlabs.org>
* Container and Lossy decoding
*
* @author Justin Ruggles <justin.ruggles@gmail.com>
* Lossless decoder
* Compressed alpha for lossy
*
* @author James Almer <jamrial@gmail.com>
* Exif metadata
*
* Unimplemented:
* - Animation
* - ICC profile
* - XMP metadata
*/
#include "libavutil/imgutils.h"
#define BITSTREAM_READER_LE
#include "avcodec.h"
#include "bytestream.h"
#include "exif.h"
#include "get_bits.h"
#include "internal.h"
#include "thread.h"
#include "vp8.h"
#define VP8X_FLAG_ANIMATION 0x02
#define VP8X_FLAG_XMP_METADATA 0x04
#define VP8X_FLAG_EXIF_METADATA 0x08
#define VP8X_FLAG_ALPHA 0x10
#define VP8X_FLAG_ICC 0x20
#define MAX_PALETTE_SIZE 256
#define MAX_CACHE_BITS 11
#define NUM_CODE_LENGTH_CODES 19
#define HUFFMAN_CODES_PER_META_CODE 5
#define NUM_LITERAL_CODES 256
#define NUM_LENGTH_CODES 24
#define NUM_DISTANCE_CODES 40
#define NUM_SHORT_DISTANCES 120
#define MAX_HUFFMAN_CODE_LENGTH 15
static const uint16_t alphabet_sizes[HUFFMAN_CODES_PER_META_CODE] = {
NUM_LITERAL_CODES + NUM_LENGTH_CODES,
NUM_LITERAL_CODES, NUM_LITERAL_CODES, NUM_LITERAL_CODES,
NUM_DISTANCE_CODES
};
static const uint8_t code_length_code_order[NUM_CODE_LENGTH_CODES] = {
17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
};
static const int8_t lz77_distance_offsets[NUM_SHORT_DISTANCES][2] = {
{ 0, 1 }, { 1, 0 }, { 1, 1 }, { -1, 1 }, { 0, 2 }, { 2, 0 }, { 1, 2 }, { -1, 2 },
{ 2, 1 }, { -2, 1 }, { 2, 2 }, { -2, 2 }, { 0, 3 }, { 3, 0 }, { 1, 3 }, { -1, 3 },
{ 3, 1 }, { -3, 1 }, { 2, 3 }, { -2, 3 }, { 3, 2 }, { -3, 2 }, { 0, 4 }, { 4, 0 },
{ 1, 4 }, { -1, 4 }, { 4, 1 }, { -4, 1 }, { 3, 3 }, { -3, 3 }, { 2, 4 }, { -2, 4 },
{ 4, 2 }, { -4, 2 }, { 0, 5 }, { 3, 4 }, { -3, 4 }, { 4, 3 }, { -4, 3 }, { 5, 0 },
{ 1, 5 }, { -1, 5 }, { 5, 1 }, { -5, 1 }, { 2, 5 }, { -2, 5 }, { 5, 2 }, { -5, 2 },
{ 4, 4 }, { -4, 4 }, { 3, 5 }, { -3, 5 }, { 5, 3 }, { -5, 3 }, { 0, 6 }, { 6, 0 },
{ 1, 6 }, { -1, 6 }, { 6, 1 }, { -6, 1 }, { 2, 6 }, { -2, 6 }, { 6, 2 }, { -6, 2 },
{ 4, 5 }, { -4, 5 }, { 5, 4 }, { -5, 4 }, { 3, 6 }, { -3, 6 }, { 6, 3 }, { -6, 3 },
{ 0, 7 }, { 7, 0 }, { 1, 7 }, { -1, 7 }, { 5, 5 }, { -5, 5 }, { 7, 1 }, { -7, 1 },
{ 4, 6 }, { -4, 6 }, { 6, 4 }, { -6, 4 }, { 2, 7 }, { -2, 7 }, { 7, 2 }, { -7, 2 },
{ 3, 7 }, { -3, 7 }, { 7, 3 }, { -7, 3 }, { 5, 6 }, { -5, 6 }, { 6, 5 }, { -6, 5 },
{ 8, 0 }, { 4, 7 }, { -4, 7 }, { 7, 4 }, { -7, 4 }, { 8, 1 }, { 8, 2 }, { 6, 6 },
{ -6, 6 }, { 8, 3 }, { 5, 7 }, { -5, 7 }, { 7, 5 }, { -7, 5 }, { 8, 4 }, { 6, 7 },
{ -6, 7 }, { 7, 6 }, { -7, 6 }, { 8, 5 }, { 7, 7 }, { -7, 7 }, { 8, 6 }, { 8, 7 }
};
enum AlphaCompression {
ALPHA_COMPRESSION_NONE,
ALPHA_COMPRESSION_VP8L,
};
enum AlphaFilter {
ALPHA_FILTER_NONE,
ALPHA_FILTER_HORIZONTAL,
ALPHA_FILTER_VERTICAL,
ALPHA_FILTER_GRADIENT,
};
enum TransformType {
PREDICTOR_TRANSFORM = 0,
COLOR_TRANSFORM = 1,
SUBTRACT_GREEN = 2,
COLOR_INDEXING_TRANSFORM = 3,
};
enum PredictionMode {
PRED_MODE_BLACK,
PRED_MODE_L,
PRED_MODE_T,
PRED_MODE_TR,
PRED_MODE_TL,
PRED_MODE_AVG_T_AVG_L_TR,
PRED_MODE_AVG_L_TL,
PRED_MODE_AVG_L_T,
PRED_MODE_AVG_TL_T,
PRED_MODE_AVG_T_TR,
PRED_MODE_AVG_AVG_L_TL_AVG_T_TR,
PRED_MODE_SELECT,
PRED_MODE_ADD_SUBTRACT_FULL,
PRED_MODE_ADD_SUBTRACT_HALF,
};
enum HuffmanIndex {
HUFF_IDX_GREEN = 0,
HUFF_IDX_RED = 1,
HUFF_IDX_BLUE = 2,
HUFF_IDX_ALPHA = 3,
HUFF_IDX_DIST = 4
};
/* The structure of WebP lossless is an optional series of transformation data,
* followed by the primary image. The primary image also optionally contains
* an entropy group mapping if there are multiple entropy groups. There is a
* basic image type called an "entropy coded image" that is used for all of
* these. The type of each entropy coded image is referred to by the
* specification as its role. */
enum ImageRole {
/* Primary Image: Stores the actual pixels of the image. */
IMAGE_ROLE_ARGB,
/* Entropy Image: Defines which Huffman group to use for different areas of
* the primary image. */
IMAGE_ROLE_ENTROPY,
/* Predictors: Defines which predictor type to use for different areas of
* the primary image. */
IMAGE_ROLE_PREDICTOR,
/* Color Transform Data: Defines the color transformation for different
* areas of the primary image. */
IMAGE_ROLE_COLOR_TRANSFORM,
/* Color Index: Stored as an image of height == 1. */
IMAGE_ROLE_COLOR_INDEXING,
IMAGE_ROLE_NB,
};
typedef struct HuffReader {
VLC vlc; /* Huffman decoder context */
int simple; /* whether to use simple mode */
int nb_symbols; /* number of coded symbols */
uint16_t simple_symbols[2]; /* symbols for simple mode */
} HuffReader;
typedef struct ImageContext {
enum ImageRole role; /* role of this image */
AVFrame *frame; /* AVFrame for data */
int color_cache_bits; /* color cache size, log2 */
uint32_t *color_cache; /* color cache data */
int nb_huffman_groups; /* number of huffman groups */
HuffReader *huffman_groups; /* reader for each huffman group */
int size_reduction; /* relative size compared to primary image, log2 */
int is_alpha_primary;
} ImageContext;
typedef struct WebPContext {
VP8Context v; /* VP8 Context used for lossy decoding */
GetBitContext gb; /* bitstream reader for main image chunk */
AVFrame *alpha_frame; /* AVFrame for alpha data decompressed from VP8L */
AVCodecContext *avctx; /* parent AVCodecContext */
int initialized; /* set once the VP8 context is initialized */
int has_alpha; /* has a separate alpha chunk */
enum AlphaCompression alpha_compression; /* compression type for alpha chunk */
enum AlphaFilter alpha_filter; /* filtering method for alpha chunk */
uint8_t *alpha_data; /* alpha chunk data */
int alpha_data_size; /* alpha chunk data size */
int has_exif; /* set after an EXIF chunk has been processed */
int width; /* image width */
int height; /* image height */
int lossless; /* indicates lossless or lossy */
int nb_transforms; /* number of transforms */
enum TransformType transforms[4]; /* transformations used in the image, in order */
int reduced_width; /* reduced width for index image, if applicable */
int nb_huffman_groups; /* number of huffman groups in the primary image */
ImageContext image[IMAGE_ROLE_NB]; /* image context for each role */
} WebPContext;
#define GET_PIXEL(frame, x, y) \
((frame)->data[0] + (y) * frame->linesize[0] + 4 * (x))
#define GET_PIXEL_COMP(frame, x, y, c) \
(*((frame)->data[0] + (y) * frame->linesize[0] + 4 * (x) + c))
static void image_ctx_free(ImageContext *img)
{
int i, j;
av_free(img->color_cache);
if (img->role != IMAGE_ROLE_ARGB && !img->is_alpha_primary)
av_frame_free(&img->frame);
if (img->huffman_groups) {
for (i = 0; i < img->nb_huffman_groups; i++) {
for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; j++)
ff_free_vlc(&img->huffman_groups[i * HUFFMAN_CODES_PER_META_CODE + j].vlc);
}
av_free(img->huffman_groups);
}
memset(img, 0, sizeof(*img));
}
/* Differs from get_vlc2() in the following ways:
* - codes are bit-reversed
* - assumes 8-bit table to make reversal simpler
* - assumes max depth of 2 since the max code length for WebP is 15
*/
static av_always_inline int webp_get_vlc(GetBitContext *gb, VLC_TYPE (*table)[2])
{
int n, nb_bits;
unsigned int index;
int code;
OPEN_READER(re, gb);
UPDATE_CACHE(re, gb);
index = SHOW_UBITS(re, gb, 8);
index = ff_reverse[index];
code = table[index][0];
n = table[index][1];
if (n < 0) {
LAST_SKIP_BITS(re, gb, 8);
UPDATE_CACHE(re, gb);
nb_bits = -n;
index = SHOW_UBITS(re, gb, nb_bits);
index = (ff_reverse[index] >> (8 - nb_bits)) + code;
code = table[index][0];
n = table[index][1];
}
SKIP_BITS(re, gb, n);
CLOSE_READER(re, gb);
return code;
}
static int huff_reader_get_symbol(HuffReader *r, GetBitContext *gb)
{
if (r->simple) {
if (r->nb_symbols == 1)
return r->simple_symbols[0];
else
return r->simple_symbols[get_bits1(gb)];
} else
return webp_get_vlc(gb, r->vlc.table);
}
static int huff_reader_build_canonical(HuffReader *r, int *code_lengths,
int alphabet_size)
{
int len = 0, sym, code = 0, ret;
int max_code_length = 0;
uint16_t *codes;
/* special-case 1 symbol since the vlc reader cannot handle it */
for (sym = 0; sym < alphabet_size; sym++) {
if (code_lengths[sym] > 0) {
len++;
code = sym;
if (len > 1)
break;
}
}
if (len == 1) {
r->nb_symbols = 1;
r->simple_symbols[0] = code;
r->simple = 1;
return 0;
}
for (sym = 0; sym < alphabet_size; sym++)
max_code_length = FFMAX(max_code_length, code_lengths[sym]);
if (max_code_length == 0 || max_code_length > MAX_HUFFMAN_CODE_LENGTH)
return AVERROR(EINVAL);
codes = av_malloc_array(alphabet_size, sizeof(*codes));
if (!codes)
return AVERROR(ENOMEM);
code = 0;
r->nb_symbols = 0;
for (len = 1; len <= max_code_length; len++) {
for (sym = 0; sym < alphabet_size; sym++) {
if (code_lengths[sym] != len)
continue;
codes[sym] = code++;
r->nb_symbols++;
}
code <<= 1;
}
if (!r->nb_symbols) {
av_free(codes);
return AVERROR_INVALIDDATA;
}
ret = init_vlc(&r->vlc, 8, alphabet_size,
code_lengths, sizeof(*code_lengths), sizeof(*code_lengths),
codes, sizeof(*codes), sizeof(*codes), 0);
if (ret < 0) {
av_free(codes);
return ret;
}
r->simple = 0;
av_free(codes);
return 0;
}
static void read_huffman_code_simple(WebPContext *s, HuffReader *hc)
{
hc->nb_symbols = get_bits1(&s->gb) + 1;
if (get_bits1(&s->gb))
hc->simple_symbols[0] = get_bits(&s->gb, 8);
else
hc->simple_symbols[0] = get_bits1(&s->gb);
if (hc->nb_symbols == 2)
hc->simple_symbols[1] = get_bits(&s->gb, 8);
hc->simple = 1;
}
static int read_huffman_code_normal(WebPContext *s, HuffReader *hc,
int alphabet_size)
{
HuffReader code_len_hc = { { 0 }, 0, 0, { 0 } };
int *code_lengths = NULL;
int code_length_code_lengths[NUM_CODE_LENGTH_CODES] = { 0 };
int i, symbol, max_symbol, prev_code_len, ret;
int num_codes = 4 + get_bits(&s->gb, 4);
if (num_codes > NUM_CODE_LENGTH_CODES)
return AVERROR_INVALIDDATA;
for (i = 0; i < num_codes; i++)
code_length_code_lengths[code_length_code_order[i]] = get_bits(&s->gb, 3);
ret = huff_reader_build_canonical(&code_len_hc, code_length_code_lengths,
NUM_CODE_LENGTH_CODES);
if (ret < 0)
goto finish;
code_lengths = av_mallocz_array(alphabet_size, sizeof(*code_lengths));
if (!code_lengths) {
ret = AVERROR(ENOMEM);
goto finish;
}
if (get_bits1(&s->gb)) {
int bits = 2 + 2 * get_bits(&s->gb, 3);
max_symbol = 2 + get_bits(&s->gb, bits);
if (max_symbol > alphabet_size) {
av_log(s->avctx, AV_LOG_ERROR, "max symbol %d > alphabet size %d\n",
max_symbol, alphabet_size);
ret = AVERROR_INVALIDDATA;
goto finish;
}
} else {
max_symbol = alphabet_size;
}
prev_code_len = 8;
symbol = 0;
while (symbol < alphabet_size) {
int code_len;
if (!max_symbol--)
break;
code_len = huff_reader_get_symbol(&code_len_hc, &s->gb);
if (code_len < 16) {
/* Code length code [0..15] indicates literal code lengths. */
code_lengths[symbol++] = code_len;
if (code_len)
prev_code_len = code_len;
} else {
int repeat = 0, length = 0;
switch (code_len) {
case 16:
/* Code 16 repeats the previous non-zero value [3..6] times,
* i.e., 3 + ReadBits(2) times. If code 16 is used before a
* non-zero value has been emitted, a value of 8 is repeated. */
repeat = 3 + get_bits(&s->gb, 2);
length = prev_code_len;
break;
case 17:
/* Code 17 emits a streak of zeros [3..10], i.e.,
* 3 + ReadBits(3) times. */
repeat = 3 + get_bits(&s->gb, 3);
break;
case 18:
/* Code 18 emits a streak of zeros of length [11..138], i.e.,
* 11 + ReadBits(7) times. */
repeat = 11 + get_bits(&s->gb, 7);
break;
}
if (symbol + repeat > alphabet_size) {
av_log(s->avctx, AV_LOG_ERROR,
"invalid symbol %d + repeat %d > alphabet size %d\n",
symbol, repeat, alphabet_size);
ret = AVERROR_INVALIDDATA;
goto finish;
}
while (repeat-- > 0)
code_lengths[symbol++] = length;
}
}
ret = huff_reader_build_canonical(hc, code_lengths, alphabet_size);
finish:
ff_free_vlc(&code_len_hc.vlc);
av_free(code_lengths);
return ret;
}
static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role,
int w, int h);
#define PARSE_BLOCK_SIZE(w, h) do { \
block_bits = get_bits(&s->gb, 3) + 2; \
blocks_w = FFALIGN((w), 1 << block_bits) >> block_bits; \
blocks_h = FFALIGN((h), 1 << block_bits) >> block_bits; \
} while (0)
static int decode_entropy_image(WebPContext *s)
{
ImageContext *img;
int ret, block_bits, width, blocks_w, blocks_h, x, y, max;
width = s->width;
if (s->reduced_width > 0)
width = s->reduced_width;
PARSE_BLOCK_SIZE(width, s->height);
ret = decode_entropy_coded_image(s, IMAGE_ROLE_ENTROPY, blocks_w, blocks_h);
if (ret < 0)
return ret;
img = &s->image[IMAGE_ROLE_ENTROPY];
img->size_reduction = block_bits;
/* the number of huffman groups is determined by the maximum group number
* coded in the entropy image */
max = 0;
for (y = 0; y < img->frame->height; y++) {
for (x = 0; x < img->frame->width; x++) {
int p0 = GET_PIXEL_COMP(img->frame, x, y, 1);
int p1 = GET_PIXEL_COMP(img->frame, x, y, 2);
int p = p0 << 8 | p1;
max = FFMAX(max, p);
}
}
s->nb_huffman_groups = max + 1;
return 0;
}
static int parse_transform_predictor(WebPContext *s)
{
int block_bits, blocks_w, blocks_h, ret;
PARSE_BLOCK_SIZE(s->width, s->height);
ret = decode_entropy_coded_image(s, IMAGE_ROLE_PREDICTOR, blocks_w,
blocks_h);
if (ret < 0)
return ret;
s->image[IMAGE_ROLE_PREDICTOR].size_reduction = block_bits;
return 0;
}
static int parse_transform_color(WebPContext *s)
{
int block_bits, blocks_w, blocks_h, ret;
PARSE_BLOCK_SIZE(s->width, s->height);
ret = decode_entropy_coded_image(s, IMAGE_ROLE_COLOR_TRANSFORM, blocks_w,
blocks_h);
if (ret < 0)
return ret;
s->image[IMAGE_ROLE_COLOR_TRANSFORM].size_reduction = block_bits;
return 0;
}
static int parse_transform_color_indexing(WebPContext *s)
{
ImageContext *img;
int width_bits, index_size, ret, x;
uint8_t *ct;
index_size = get_bits(&s->gb, 8) + 1;
if (index_size <= 2)
width_bits = 3;
else if (index_size <= 4)
width_bits = 2;
else if (index_size <= 16)
width_bits = 1;
else
width_bits = 0;
ret = decode_entropy_coded_image(s, IMAGE_ROLE_COLOR_INDEXING,
index_size, 1);
if (ret < 0)
return ret;
img = &s->image[IMAGE_ROLE_COLOR_INDEXING];
img->size_reduction = width_bits;
if (width_bits > 0)
s->reduced_width = (s->width + ((1 << width_bits) - 1)) >> width_bits;
/* color index values are delta-coded */
ct = img->frame->data[0] + 4;
for (x = 4; x < img->frame->width * 4; x++, ct++)
ct[0] += ct[-4];
return 0;
}
static HuffReader *get_huffman_group(WebPContext *s, ImageContext *img,
int x, int y)
{
ImageContext *gimg = &s->image[IMAGE_ROLE_ENTROPY];
int group = 0;
if (gimg->size_reduction > 0) {
int group_x = x >> gimg->size_reduction;
int group_y = y >> gimg->size_reduction;
int g0 = GET_PIXEL_COMP(gimg->frame, group_x, group_y, 1);
int g1 = GET_PIXEL_COMP(gimg->frame, group_x, group_y, 2);
group = g0 << 8 | g1;
}
return &img->huffman_groups[group * HUFFMAN_CODES_PER_META_CODE];
}
static av_always_inline void color_cache_put(ImageContext *img, uint32_t c)
{
uint32_t cache_idx = (0x1E35A7BD * c) >> (32 - img->color_cache_bits);
img->color_cache[cache_idx] = c;
}
static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role,
int w, int h)
{
ImageContext *img;
HuffReader *hg;
int i, j, ret, x, y, width;
img = &s->image[role];
img->role = role;
if (!img->frame) {
img->frame = av_frame_alloc();
if (!img->frame)
return AVERROR(ENOMEM);
}
img->frame->format = AV_PIX_FMT_ARGB;
img->frame->width = w;
img->frame->height = h;
if (role == IMAGE_ROLE_ARGB && !img->is_alpha_primary) {
ThreadFrame pt = { .f = img->frame };
ret = ff_thread_get_buffer(s->avctx, &pt, 0);
} else
ret = av_frame_get_buffer(img->frame, 1);
if (ret < 0)
return ret;
if (get_bits1(&s->gb)) {
img->color_cache_bits = get_bits(&s->gb, 4);
if (img->color_cache_bits < 1 || img->color_cache_bits > 11) {
av_log(s->avctx, AV_LOG_ERROR, "invalid color cache bits: %d\n",
img->color_cache_bits);
return AVERROR_INVALIDDATA;
}
img->color_cache = av_mallocz_array(1 << img->color_cache_bits,
sizeof(*img->color_cache));
if (!img->color_cache)
return AVERROR(ENOMEM);
} else {
img->color_cache_bits = 0;
}
img->nb_huffman_groups = 1;
if (role == IMAGE_ROLE_ARGB && get_bits1(&s->gb)) {
ret = decode_entropy_image(s);
if (ret < 0)
return ret;
img->nb_huffman_groups = s->nb_huffman_groups;
}
img->huffman_groups = av_mallocz_array(img->nb_huffman_groups *
HUFFMAN_CODES_PER_META_CODE,
sizeof(*img->huffman_groups));
if (!img->huffman_groups)
return AVERROR(ENOMEM);
for (i = 0; i < img->nb_huffman_groups; i++) {
hg = &img->huffman_groups[i * HUFFMAN_CODES_PER_META_CODE];
for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; j++) {
int alphabet_size = alphabet_sizes[j];
if (!j && img->color_cache_bits > 0)
alphabet_size += 1 << img->color_cache_bits;
if (get_bits1(&s->gb)) {
read_huffman_code_simple(s, &hg[j]);
} else {
ret = read_huffman_code_normal(s, &hg[j], alphabet_size);
if (ret < 0)
return ret;
}
}
}
width = img->frame->width;
if (role == IMAGE_ROLE_ARGB && s->reduced_width > 0)
width = s->reduced_width;
x = 0; y = 0;
while (y < img->frame->height) {
int v;
hg = get_huffman_group(s, img, x, y);
v = huff_reader_get_symbol(&hg[HUFF_IDX_GREEN], &s->gb);
if (v < NUM_LITERAL_CODES) {
/* literal pixel values */
uint8_t *p = GET_PIXEL(img->frame, x, y);
p[2] = v;
p[1] = huff_reader_get_symbol(&hg[HUFF_IDX_RED], &s->gb);
p[3] = huff_reader_get_symbol(&hg[HUFF_IDX_BLUE], &s->gb);
p[0] = huff_reader_get_symbol(&hg[HUFF_IDX_ALPHA], &s->gb);
if (img->color_cache_bits)
color_cache_put(img, AV_RB32(p));
x++;
if (x == width) {
x = 0;
y++;
}
} else if (v < NUM_LITERAL_CODES + NUM_LENGTH_CODES) {
/* LZ77 backwards mapping */
int prefix_code, length, distance, ref_x, ref_y;
/* parse length and distance */
prefix_code = v - NUM_LITERAL_CODES;
if (prefix_code < 4) {
length = prefix_code + 1;
} else {
int extra_bits = (prefix_code - 2) >> 1;
int offset = 2 + (prefix_code & 1) << extra_bits;
length = offset + get_bits(&s->gb, extra_bits) + 1;
}
prefix_code = huff_reader_get_symbol(&hg[HUFF_IDX_DIST], &s->gb);
if (prefix_code > 39) {
av_log(s->avctx, AV_LOG_ERROR,
"distance prefix code too large: %d\n", prefix_code);
return AVERROR_INVALIDDATA;
}
if (prefix_code < 4) {
distance = prefix_code + 1;
} else {
int extra_bits = prefix_code - 2 >> 1;
int offset = 2 + (prefix_code & 1) << extra_bits;
distance = offset + get_bits(&s->gb, extra_bits) + 1;
}
/* find reference location */
if (distance <= NUM_SHORT_DISTANCES) {
int xi = lz77_distance_offsets[distance - 1][0];
int yi = lz77_distance_offsets[distance - 1][1];
distance = FFMAX(1, xi + yi * width);
} else {
distance -= NUM_SHORT_DISTANCES;
}
ref_x = x;
ref_y = y;
if (distance <= x) {
ref_x -= distance;
distance = 0;
} else {
ref_x = 0;
distance -= x;
}
while (distance >= width) {
ref_y--;
distance -= width;
}
if (distance > 0) {
ref_x = width - distance;
ref_y--;
}
ref_x = FFMAX(0, ref_x);
ref_y = FFMAX(0, ref_y);
/* copy pixels
* source and dest regions can overlap and wrap lines, so just
* copy per-pixel */
for (i = 0; i < length; i++) {
uint8_t *p_ref = GET_PIXEL(img->frame, ref_x, ref_y);
uint8_t *p = GET_PIXEL(img->frame, x, y);
AV_COPY32(p, p_ref);
if (img->color_cache_bits)
color_cache_put(img, AV_RB32(p));
x++;
ref_x++;
if (x == width) {
x = 0;
y++;
}
if (ref_x == width) {
ref_x = 0;
ref_y++;
}
if (y == img->frame->height || ref_y == img->frame->height)
break;
}
} else {
/* read from color cache */
uint8_t *p = GET_PIXEL(img->frame, x, y);
int cache_idx = v - (NUM_LITERAL_CODES + NUM_LENGTH_CODES);
if (!img->color_cache_bits) {
av_log(s->avctx, AV_LOG_ERROR, "color cache not found\n");
return AVERROR_INVALIDDATA;
}
if (cache_idx >= 1 << img->color_cache_bits) {
av_log(s->avctx, AV_LOG_ERROR,
"color cache index out-of-bounds\n");
return AVERROR_INVALIDDATA;
}
AV_WB32(p, img->color_cache[cache_idx]);
x++;
if (x == width) {
x = 0;
y++;
}
}
}
return 0;
}
/* PRED_MODE_BLACK */
static void inv_predict_0(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
AV_WB32(p, 0xFF000000);
}
/* PRED_MODE_L */
static void inv_predict_1(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
AV_COPY32(p, p_l);
}
/* PRED_MODE_T */
static void inv_predict_2(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
AV_COPY32(p, p_t);
}
/* PRED_MODE_TR */
static void inv_predict_3(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
AV_COPY32(p, p_tr);
}
/* PRED_MODE_TL */
static void inv_predict_4(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
AV_COPY32(p, p_tl);
}
/* PRED_MODE_AVG_T_AVG_L_TR */
static void inv_predict_5(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = p_t[0] + (p_l[0] + p_tr[0] >> 1) >> 1;
p[1] = p_t[1] + (p_l[1] + p_tr[1] >> 1) >> 1;
p[2] = p_t[2] + (p_l[2] + p_tr[2] >> 1) >> 1;
p[3] = p_t[3] + (p_l[3] + p_tr[3] >> 1) >> 1;
}
/* PRED_MODE_AVG_L_TL */
static void inv_predict_6(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = p_l[0] + p_tl[0] >> 1;
p[1] = p_l[1] + p_tl[1] >> 1;
p[2] = p_l[2] + p_tl[2] >> 1;
p[3] = p_l[3] + p_tl[3] >> 1;
}
/* PRED_MODE_AVG_L_T */
static void inv_predict_7(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = p_l[0] + p_t[0] >> 1;
p[1] = p_l[1] + p_t[1] >> 1;
p[2] = p_l[2] + p_t[2] >> 1;
p[3] = p_l[3] + p_t[3] >> 1;
}
/* PRED_MODE_AVG_TL_T */
static void inv_predict_8(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = p_tl[0] + p_t[0] >> 1;
p[1] = p_tl[1] + p_t[1] >> 1;
p[2] = p_tl[2] + p_t[2] >> 1;
p[3] = p_tl[3] + p_t[3] >> 1;
}
/* PRED_MODE_AVG_T_TR */
static void inv_predict_9(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = p_t[0] + p_tr[0] >> 1;
p[1] = p_t[1] + p_tr[1] >> 1;
p[2] = p_t[2] + p_tr[2] >> 1;
p[3] = p_t[3] + p_tr[3] >> 1;
}
/* PRED_MODE_AVG_AVG_L_TL_AVG_T_TR */
static void inv_predict_10(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = (p_l[0] + p_tl[0] >> 1) + (p_t[0] + p_tr[0] >> 1) >> 1;
p[1] = (p_l[1] + p_tl[1] >> 1) + (p_t[1] + p_tr[1] >> 1) >> 1;
p[2] = (p_l[2] + p_tl[2] >> 1) + (p_t[2] + p_tr[2] >> 1) >> 1;
p[3] = (p_l[3] + p_tl[3] >> 1) + (p_t[3] + p_tr[3] >> 1) >> 1;
}
/* PRED_MODE_SELECT */
static void inv_predict_11(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
int diff = (FFABS(p_l[0] - p_tl[0]) - FFABS(p_t[0] - p_tl[0])) +
(FFABS(p_l[1] - p_tl[1]) - FFABS(p_t[1] - p_tl[1])) +
(FFABS(p_l[2] - p_tl[2]) - FFABS(p_t[2] - p_tl[2])) +
(FFABS(p_l[3] - p_tl[3]) - FFABS(p_t[3] - p_tl[3]));
if (diff <= 0)
AV_COPY32(p, p_t);
else
AV_COPY32(p, p_l);
}
/* PRED_MODE_ADD_SUBTRACT_FULL */
static void inv_predict_12(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = av_clip_uint8(p_l[0] + p_t[0] - p_tl[0]);
p[1] = av_clip_uint8(p_l[1] + p_t[1] - p_tl[1]);
p[2] = av_clip_uint8(p_l[2] + p_t[2] - p_tl[2]);
p[3] = av_clip_uint8(p_l[3] + p_t[3] - p_tl[3]);
}
static av_always_inline uint8_t clamp_add_subtract_half(int a, int b, int c)
{
int d = a + b >> 1;
return av_clip_uint8(d + (d - c) / 2);
}
/* PRED_MODE_ADD_SUBTRACT_HALF */
static void inv_predict_13(uint8_t *p, const uint8_t *p_l, const uint8_t *p_tl,
const uint8_t *p_t, const uint8_t *p_tr)
{
p[0] = clamp_add_subtract_half(p_l[0], p_t[0], p_tl[0]);
p[1] = clamp_add_subtract_half(p_l[1], p_t[1], p_tl[1]);
p[2] = clamp_add_subtract_half(p_l[2], p_t[2], p_tl[2]);
p[3] = clamp_add_subtract_half(p_l[3], p_t[3], p_tl[3]);
}
typedef void (*inv_predict_func)(uint8_t *p, const uint8_t *p_l,
const uint8_t *p_tl, const uint8_t *p_t,
const uint8_t *p_tr);
static const inv_predict_func inverse_predict[14] = {
inv_predict_0, inv_predict_1, inv_predict_2, inv_predict_3,
inv_predict_4, inv_predict_5, inv_predict_6, inv_predict_7,
inv_predict_8, inv_predict_9, inv_predict_10, inv_predict_11,
inv_predict_12, inv_predict_13,
};
static void inverse_prediction(AVFrame *frame, enum PredictionMode m, int x, int y)
{
uint8_t *dec, *p_l, *p_tl, *p_t, *p_tr;
uint8_t p[4];
dec = GET_PIXEL(frame, x, y);
p_l = GET_PIXEL(frame, x - 1, y);
p_tl = GET_PIXEL(frame, x - 1, y - 1);
p_t = GET_PIXEL(frame, x, y - 1);
if (x == frame->width - 1)
p_tr = GET_PIXEL(frame, 0, y);
else
p_tr = GET_PIXEL(frame, x + 1, y - 1);
inverse_predict[m](p, p_l, p_tl, p_t, p_tr);
dec[0] += p[0];
dec[1] += p[1];
dec[2] += p[2];
dec[3] += p[3];
}
static int apply_predictor_transform(WebPContext *s)
{
ImageContext *img = &s->image[IMAGE_ROLE_ARGB];
ImageContext *pimg = &s->image[IMAGE_ROLE_PREDICTOR];
int x, y;
for (y = 0; y < img->frame->height; y++) {
for (x = 0; x < img->frame->width; x++) {
int tx = x >> pimg->size_reduction;
int ty = y >> pimg->size_reduction;
enum PredictionMode m = GET_PIXEL_COMP(pimg->frame, tx, ty, 2);
if (x == 0) {
if (y == 0)
m = PRED_MODE_BLACK;
else
m = PRED_MODE_T;
} else if (y == 0)
m = PRED_MODE_L;
if (m > 13) {
av_log(s->avctx, AV_LOG_ERROR,
"invalid predictor mode: %d\n", m);
return AVERROR_INVALIDDATA;
}
inverse_prediction(img->frame, m, x, y);
}
}
return 0;
}
static av_always_inline uint8_t color_transform_delta(uint8_t color_pred,
uint8_t color)
{
return (int)ff_u8_to_s8(color_pred) * ff_u8_to_s8(color) >> 5;
}
static int apply_color_transform(WebPContext *s)
{
ImageContext *img, *cimg;
int x, y, cx, cy;
uint8_t *p, *cp;
img = &s->image[IMAGE_ROLE_ARGB];
cimg = &s->image[IMAGE_ROLE_COLOR_TRANSFORM];
for (y = 0; y < img->frame->height; y++) {
for (x = 0; x < img->frame->width; x++) {
cx = x >> cimg->size_reduction;
cy = y >> cimg->size_reduction;
cp = GET_PIXEL(cimg->frame, cx, cy);
p = GET_PIXEL(img->frame, x, y);
p[1] += color_transform_delta(cp[3], p[2]);
p[3] += color_transform_delta(cp[2], p[2]) +
color_transform_delta(cp[1], p[1]);
}
}
return 0;
}
static int apply_subtract_green_transform(WebPContext *s)
{
int x, y;
ImageContext *img = &s->image[IMAGE_ROLE_ARGB];
for (y = 0; y < img->frame->height; y++) {
for (x = 0; x < img->frame->width; x++) {
uint8_t *p = GET_PIXEL(img->frame, x, y);
p[1] += p[2];
p[3] += p[2];
}
}
return 0;
}
static int apply_color_indexing_transform(WebPContext *s)
{
ImageContext *img;
ImageContext *pal;
int i, x, y;
uint8_t *p;
img = &s->image[IMAGE_ROLE_ARGB];
pal = &s->image[IMAGE_ROLE_COLOR_INDEXING];
if (pal->size_reduction > 0) {
GetBitContext gb_g;
uint8_t *line;
int pixel_bits = 8 >> pal->size_reduction;
line = av_malloc(img->frame->linesize[0]);
if (!line)
return AVERROR(ENOMEM);
for (y = 0; y < img->frame->height; y++) {
p = GET_PIXEL(img->frame, 0, y);
memcpy(line, p, img->frame->linesize[0]);
init_get_bits(&gb_g, line, img->frame->linesize[0] * 8);
skip_bits(&gb_g, 16);
i = 0;
for (x = 0; x < img->frame->width; x++) {
p = GET_PIXEL(img->frame, x, y);
p[2] = get_bits(&gb_g, pixel_bits);
i++;
if (i == 1 << pal->size_reduction) {
skip_bits(&gb_g, 24);
i = 0;
}
}
}
av_free(line);
}
// switch to local palette if it's worth initializing it
if (img->frame->height * img->frame->width > 300) {
uint8_t palette[256 * 4];
const int size = pal->frame->width * 4;
av_assert0(size <= 1024U);
memcpy(palette, GET_PIXEL(pal->frame, 0, 0), size); // copy palette
// set extra entries to transparent black
memset(palette + size, 0, 256 * 4 - size);
for (y = 0; y < img->frame->height; y++) {
for (x = 0; x < img->frame->width; x++) {
p = GET_PIXEL(img->frame, x, y);
i = p[2];
AV_COPY32(p, &palette[i * 4]);
}
}
} else {
for (y = 0; y < img->frame->height; y++) {
for (x = 0; x < img->frame->width; x++) {
p = GET_PIXEL(img->frame, x, y);
i = p[2];
if (i >= pal->frame->width) {
AV_WB32(p, 0x00000000);
} else {
const uint8_t *pi = GET_PIXEL(pal->frame, i, 0);
AV_COPY32(p, pi);
}
}
}
}
return 0;
}
static void update_canvas_size(AVCodecContext *avctx, int w, int h)
{
WebPContext *s = avctx->priv_data;
if (s->width && s->width != w) {
av_log(avctx, AV_LOG_WARNING, "Width mismatch. %d != %d\n",
s->width, w);
}
s->width = w;
if (s->height && s->height != h) {
av_log(avctx, AV_LOG_WARNING, "Height mismatch. %d != %d\n",
s->height, h);
}
s->height = h;
}
static int vp8_lossless_decode_frame(AVCodecContext *avctx, AVFrame *p,
int *got_frame, uint8_t *data_start,
unsigned int data_size, int is_alpha_chunk)
{
WebPContext *s = avctx->priv_data;
int w, h, ret, i, used;
if (!is_alpha_chunk) {
s->lossless = 1;
avctx->pix_fmt = AV_PIX_FMT_ARGB;
}
ret = init_get_bits8(&s->gb, data_start, data_size);
if (ret < 0)
return ret;
if (!is_alpha_chunk) {
if (get_bits(&s->gb, 8) != 0x2F) {
av_log(avctx, AV_LOG_ERROR, "Invalid WebP Lossless signature\n");
return AVERROR_INVALIDDATA;
}
w = get_bits(&s->gb, 14) + 1;
h = get_bits(&s->gb, 14) + 1;
update_canvas_size(avctx, w, h);
ret = ff_set_dimensions(avctx, s->width, s->height);
if (ret < 0)
return ret;
s->has_alpha = get_bits1(&s->gb);
if (get_bits(&s->gb, 3) != 0x0) {
av_log(avctx, AV_LOG_ERROR, "Invalid WebP Lossless version\n");
return AVERROR_INVALIDDATA;
}
} else {
if (!s->width || !s->height)
return AVERROR_BUG;
w = s->width;
h = s->height;
}
/* parse transformations */
s->nb_transforms = 0;
s->reduced_width = 0;
used = 0;
while (get_bits1(&s->gb)) {
enum TransformType transform = get_bits(&s->gb, 2);
if (used & (1 << transform)) {
av_log(avctx, AV_LOG_ERROR, "Transform %d used more than once\n",
transform);
ret = AVERROR_INVALIDDATA;
goto free_and_return;
}
used |= (1 << transform);
s->transforms[s->nb_transforms++] = transform;
switch (transform) {
case PREDICTOR_TRANSFORM:
ret = parse_transform_predictor(s);
break;
case COLOR_TRANSFORM:
ret = parse_transform_color(s);
break;
case COLOR_INDEXING_TRANSFORM:
ret = parse_transform_color_indexing(s);
break;
}
if (ret < 0)
goto free_and_return;
}
/* decode primary image */
s->image[IMAGE_ROLE_ARGB].frame = p;
if (is_alpha_chunk)
s->image[IMAGE_ROLE_ARGB].is_alpha_primary = 1;
ret = decode_entropy_coded_image(s, IMAGE_ROLE_ARGB, w, h);
if (ret < 0)
goto free_and_return;
/* apply transformations */
for (i = s->nb_transforms - 1; i >= 0; i--) {
switch (s->transforms[i]) {
case PREDICTOR_TRANSFORM:
ret = apply_predictor_transform(s);
break;
case COLOR_TRANSFORM:
ret = apply_color_transform(s);
break;
case SUBTRACT_GREEN:
ret = apply_subtract_green_transform(s);
break;
case COLOR_INDEXING_TRANSFORM:
ret = apply_color_indexing_transform(s);
break;
}
if (ret < 0)
goto free_and_return;
}
*got_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
p->key_frame = 1;
ret = data_size;
free_and_return:
for (i = 0; i < IMAGE_ROLE_NB; i++)
image_ctx_free(&s->image[i]);
return ret;
}
static void alpha_inverse_prediction(AVFrame *frame, enum AlphaFilter m)
{
int x, y, ls;
uint8_t *dec;
ls = frame->linesize[3];
/* filter first row using horizontal filter */
dec = frame->data[3] + 1;
for (x = 1; x < frame->width; x++, dec++)
*dec += *(dec - 1);
/* filter first column using vertical filter */
dec = frame->data[3] + ls;
for (y = 1; y < frame->height; y++, dec += ls)
*dec += *(dec - ls);
/* filter the rest using the specified filter */
switch (m) {
case ALPHA_FILTER_HORIZONTAL:
for (y = 1; y < frame->height; y++) {
dec = frame->data[3] + y * ls + 1;
for (x = 1; x < frame->width; x++, dec++)
*dec += *(dec - 1);
}
break;
case ALPHA_FILTER_VERTICAL:
for (y = 1; y < frame->height; y++) {
dec = frame->data[3] + y * ls + 1;
for (x = 1; x < frame->width; x++, dec++)
*dec += *(dec - ls);
}
break;
case ALPHA_FILTER_GRADIENT:
for (y = 1; y < frame->height; y++) {
dec = frame->data[3] + y * ls + 1;
for (x = 1; x < frame->width; x++, dec++)
dec[0] += av_clip_uint8(*(dec - 1) + *(dec - ls) - *(dec - ls - 1));
}
break;
}
}
static int vp8_lossy_decode_alpha(AVCodecContext *avctx, AVFrame *p,
uint8_t *data_start,
unsigned int data_size)
{
WebPContext *s = avctx->priv_data;
int x, y, ret;
if (s->alpha_compression == ALPHA_COMPRESSION_NONE) {
GetByteContext gb;
bytestream2_init(&gb, data_start, data_size);
for (y = 0; y < s->height; y++)
bytestream2_get_buffer(&gb, p->data[3] + p->linesize[3] * y,
s->width);
} else if (s->alpha_compression == ALPHA_COMPRESSION_VP8L) {
uint8_t *ap, *pp;
int alpha_got_frame = 0;
s->alpha_frame = av_frame_alloc();
if (!s->alpha_frame)
return AVERROR(ENOMEM);
ret = vp8_lossless_decode_frame(avctx, s->alpha_frame, &alpha_got_frame,
data_start, data_size, 1);
if (ret < 0) {
av_frame_free(&s->alpha_frame);
return ret;
}
if (!alpha_got_frame) {
av_frame_free(&s->alpha_frame);
return AVERROR_INVALIDDATA;
}
/* copy green component of alpha image to alpha plane of primary image */
for (y = 0; y < s->height; y++) {
ap = GET_PIXEL(s->alpha_frame, 0, y) + 2;
pp = p->data[3] + p->linesize[3] * y;
for (x = 0; x < s->width; x++) {
*pp = *ap;
pp++;
ap += 4;
}
}
av_frame_free(&s->alpha_frame);
}
/* apply alpha filtering */
if (s->alpha_filter)
alpha_inverse_prediction(p, s->alpha_filter);
return 0;
}
static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,
int *got_frame, uint8_t *data_start,
unsigned int data_size)
{
WebPContext *s = avctx->priv_data;
AVPacket pkt;
int ret;
if (!s->initialized) {
ff_vp8_decode_init(avctx);
s->initialized = 1;
if (s->has_alpha)
avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
}
s->lossless = 0;
if (data_size > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");
return AVERROR_PATCHWELCOME;
}
av_init_packet(&pkt);
pkt.data = data_start;
pkt.size = data_size;
ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);
if (ret < 0)
return ret;
update_canvas_size(avctx, avctx->width, avctx->height);
if (s->has_alpha) {
ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,
s->alpha_data_size);
if (ret < 0)
return ret;
}
return ret;
}
static int webp_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
AVFrame * const p = data;
WebPContext *s = avctx->priv_data;
GetByteContext gb;
int ret;
uint32_t chunk_type, chunk_size;
int vp8x_flags = 0;
s->avctx = avctx;
s->width = 0;
s->height = 0;
*got_frame = 0;
s->has_alpha = 0;
s->has_exif = 0;
bytestream2_init(&gb, avpkt->data, avpkt->size);
if (bytestream2_get_bytes_left(&gb) < 12)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
return AVERROR_INVALIDDATA;
}
chunk_size = bytestream2_get_le32(&gb);
if (bytestream2_get_bytes_left(&gb) < chunk_size)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le32(&gb) != MKTAG('W', 'E', 'B', 'P')) {
av_log(avctx, AV_LOG_ERROR, "missing WEBP tag\n");
return AVERROR_INVALIDDATA;
}
while (bytestream2_get_bytes_left(&gb) > 8) {
char chunk_str[5] = { 0 };
chunk_type = bytestream2_get_le32(&gb);
chunk_size = bytestream2_get_le32(&gb);
if (chunk_size == UINT32_MAX)
return AVERROR_INVALIDDATA;
chunk_size += chunk_size & 1;
if (bytestream2_get_bytes_left(&gb) < chunk_size)
return AVERROR_INVALIDDATA;
switch (chunk_type) {
case MKTAG('V', 'P', '8', ' '):
if (!*got_frame) {
ret = vp8_lossy_decode_frame(avctx, p, got_frame,
avpkt->data + bytestream2_tell(&gb),
chunk_size);
if (ret < 0)
return ret;
}
bytestream2_skip(&gb, chunk_size);
break;
case MKTAG('V', 'P', '8', 'L'):
if (!*got_frame) {
ret = vp8_lossless_decode_frame(avctx, p, got_frame,
avpkt->data + bytestream2_tell(&gb),
chunk_size, 0);
if (ret < 0)
return ret;
avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
}
bytestream2_skip(&gb, chunk_size);
break;
case MKTAG('V', 'P', '8', 'X'):
if (s->width || s->height || *got_frame) {
av_log(avctx, AV_LOG_ERROR, "Canvas dimensions are already set\n");
return AVERROR_INVALIDDATA;
}
vp8x_flags = bytestream2_get_byte(&gb);
bytestream2_skip(&gb, 3);
s->width = bytestream2_get_le24(&gb) + 1;
s->height = bytestream2_get_le24(&gb) + 1;
ret = av_image_check_size(s->width, s->height, 0, avctx);
if (ret < 0)
return ret;
break;
case MKTAG('A', 'L', 'P', 'H'): {
int alpha_header, filter_m, compression;
if (!(vp8x_flags & VP8X_FLAG_ALPHA)) {
av_log(avctx, AV_LOG_WARNING,
"ALPHA chunk present, but alpha bit not set in the "
"VP8X header\n");
}
if (chunk_size == 0) {
av_log(avctx, AV_LOG_ERROR, "invalid ALPHA chunk size\n");
return AVERROR_INVALIDDATA;
}
alpha_header = bytestream2_get_byte(&gb);
s->alpha_data = avpkt->data + bytestream2_tell(&gb);
s->alpha_data_size = chunk_size - 1;
bytestream2_skip(&gb, s->alpha_data_size);
filter_m = (alpha_header >> 2) & 0x03;
compression = alpha_header & 0x03;
if (compression > ALPHA_COMPRESSION_VP8L) {
av_log(avctx, AV_LOG_VERBOSE,
"skipping unsupported ALPHA chunk\n");
} else {
s->has_alpha = 1;
s->alpha_compression = compression;
s->alpha_filter = filter_m;
}
break;
}
case MKTAG('E', 'X', 'I', 'F'): {
int le, ifd_offset, exif_offset = bytestream2_tell(&gb);
AVDictionary *exif_metadata = NULL;
GetByteContext exif_gb;
if (s->has_exif) {
av_log(avctx, AV_LOG_VERBOSE, "Ignoring extra EXIF chunk\n");
goto exif_end;
}
if (!(vp8x_flags & VP8X_FLAG_EXIF_METADATA))
av_log(avctx, AV_LOG_WARNING,
"EXIF chunk present, but Exif bit not set in the "
"VP8X header\n");
s->has_exif = 1;
bytestream2_init(&exif_gb, avpkt->data + exif_offset,
avpkt->size - exif_offset);
if (ff_tdecode_header(&exif_gb, &le, &ifd_offset) < 0) {
av_log(avctx, AV_LOG_ERROR, "invalid TIFF header "
"in Exif data\n");
goto exif_end;
}
bytestream2_seek(&exif_gb, ifd_offset, SEEK_SET);
if (avpriv_exif_decode_ifd(avctx, &exif_gb, le, 0, &exif_metadata) < 0) {
av_log(avctx, AV_LOG_ERROR, "error decoding Exif data\n");
goto exif_end;
}
av_dict_copy(&((AVFrame *) data)->metadata, exif_metadata, 0);
exif_end:
av_dict_free(&exif_metadata);
bytestream2_skip(&gb, chunk_size);
break;
}
case MKTAG('I', 'C', 'C', 'P'):
case MKTAG('A', 'N', 'I', 'M'):
case MKTAG('A', 'N', 'M', 'F'):
case MKTAG('X', 'M', 'P', ' '):
AV_WL32(chunk_str, chunk_type);
av_log(avctx, AV_LOG_WARNING, "skipping unsupported chunk: %s\n",
chunk_str);
bytestream2_skip(&gb, chunk_size);
break;
default:
AV_WL32(chunk_str, chunk_type);
av_log(avctx, AV_LOG_VERBOSE, "skipping unknown chunk: %s\n",
chunk_str);
bytestream2_skip(&gb, chunk_size);
break;
}
}
if (!*got_frame) {
av_log(avctx, AV_LOG_ERROR, "image data not found\n");
return AVERROR_INVALIDDATA;
}
return avpkt->size;
}
static av_cold int webp_decode_close(AVCodecContext *avctx)
{
WebPContext *s = avctx->priv_data;
if (s->initialized)
return ff_vp8_decode_free(avctx);
return 0;
}
AVCodec ff_webp_decoder = {
.name = "webp",
.long_name = NULL_IF_CONFIG_SMALL("WebP image"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_WEBP,
.priv_data_size = sizeof(WebPContext),
.decode = webp_decode_frame,
.close = webp_decode_close,
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
};
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3418_1 |
crossvul-cpp_data_bad_4788_4 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M EEEEE M M OOO RRRR Y Y %
% MM MM E MM MM O O R R Y Y %
% M M M EEE M M M O O RRRR Y %
% M M E M M O O R R Y %
% M M EEEEE M M OOO R R Y %
% %
% %
% MagickCore Memory Allocation Methods %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Segregate our memory requirements from any program that calls our API. This
% should help reduce the risk of others changing our program state or causing
% memory corruption.
%
% Our custom memory allocation manager implements a best-fit allocation policy
% using segregated free lists. It uses a linear distribution of size classes
% for lower sizes and a power of two distribution of size classes at higher
% sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits."
% written by Yoo C. Chung.
%
% By default, ANSI memory methods are called (e.g. malloc). Use the
% custom memory allocator by defining MAGICKCORE_ZERO_CONFIGURATION_SUPPORT
% to allocate memory with private anonymous mapping rather than from the
% heap.
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/string_.h"
#include "magick/utility-private.h"
/*
Define declarations.
*/
#define BlockFooter(block,size) \
((size_t *) ((char *) (block)+(size)-2*sizeof(size_t)))
#define BlockHeader(block) ((size_t *) (block)-1)
#define BlockSize 4096
#define BlockThreshold 1024
#define MaxBlockExponent 16
#define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1)
#define MaxSegments 1024
#define MemoryGuard ((0xdeadbeef << 31)+0xdeafdeed)
#define NextBlock(block) ((char *) (block)+SizeOfBlock(block))
#define NextBlockInList(block) (*(void **) (block))
#define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2)))
#define PreviousBlockBit 0x01
#define PreviousBlockInList(block) (*((void **) (block)+1))
#define SegmentSize (2*1024*1024)
#define SizeMask (~0x01)
#define SizeOfBlock(block) (*BlockHeader(block) & SizeMask)
/*
Typedef declarations.
*/
typedef enum
{
UndefinedVirtualMemory,
AlignedVirtualMemory,
MapVirtualMemory,
UnalignedVirtualMemory
} VirtualMemoryType;
typedef struct _DataSegmentInfo
{
void
*allocation,
*bound;
MagickBooleanType
mapped;
size_t
length;
struct _DataSegmentInfo
*previous,
*next;
} DataSegmentInfo;
typedef struct _MagickMemoryMethods
{
AcquireMemoryHandler
acquire_memory_handler;
ResizeMemoryHandler
resize_memory_handler;
DestroyMemoryHandler
destroy_memory_handler;
} MagickMemoryMethods;
struct _MemoryInfo
{
char
filename[MaxTextExtent];
VirtualMemoryType
type;
size_t
length;
void
*blob;
size_t
signature;
};
typedef struct _MemoryPool
{
size_t
allocation;
void
*blocks[MaxBlocks+1];
size_t
number_segments;
DataSegmentInfo
*segments[MaxSegments],
segment_pool[MaxSegments];
} MemoryPool;
/*
Global declarations.
*/
#if defined _MSC_VER
static void* MSCMalloc(size_t size)
{
return malloc(size);
}
static void* MSCRealloc(void* ptr, size_t size)
{
return realloc(ptr, size);
}
static void MSCFree(void* ptr)
{
free(ptr);
}
#endif
static MagickMemoryMethods
memory_methods =
{
#if defined _MSC_VER
(AcquireMemoryHandler) MSCMalloc,
(ResizeMemoryHandler) MSCRealloc,
(DestroyMemoryHandler) MSCFree
#else
(AcquireMemoryHandler) malloc,
(ResizeMemoryHandler) realloc,
(DestroyMemoryHandler) free
#endif
};
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
static MemoryPool
memory_pool;
static SemaphoreInfo
*memory_semaphore = (SemaphoreInfo *) NULL;
static volatile DataSegmentInfo
*free_segments = (DataSegmentInfo *) NULL;
/*
Forward declarations.
*/
static MagickBooleanType
ExpandHeap(size_t);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e A l i g n e d M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireAlignedMemory() returns a pointer to a block of memory at least size
% bytes whose address is a multiple of 16*sizeof(void *).
%
% The format of the AcquireAlignedMemory method is:
%
% void *AcquireAlignedMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
static MagickBooleanType CheckMemoryOverflow(const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return(MagickTrue);
}
return(MagickFalse);
}
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)
{
#define AlignedExtent(size,alignment) \
(((size)+((alignment)-1)) & ~((alignment)-1))
size_t
alignment,
extent,
size;
void
*memory;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((void *) NULL);
memory=NULL;
alignment=CACHE_LINE_SIZE;
size=count*quantum;
extent=AlignedExtent(size,alignment);
if ((size == 0) || (alignment < sizeof(void *)) || (extent < size))
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
if (posix_memalign(&memory,alignment,extent) != 0)
memory=NULL;
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
memory=_aligned_malloc(extent,alignment);
#else
{
void
*p;
extent=(size+alignment-1)+sizeof(void *);
if (extent > size)
{
p=malloc(extent);
if (p != NULL)
{
memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment);
*((void **) memory-1)=p;
}
}
}
#endif
return(memory);
}
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e B l o c k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireBlock() returns a pointer to a block of memory at least size bytes
% suitably aligned for any use.
%
% The format of the AcquireBlock method is:
%
% void *AcquireBlock(const size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes to allocate.
%
*/
static inline size_t AllocationPolicy(size_t size)
{
register size_t
blocksize;
/*
The linear distribution.
*/
assert(size != 0);
assert(size % (4*sizeof(size_t)) == 0);
if (size <= BlockThreshold)
return(size/(4*sizeof(size_t)));
/*
Check for the largest block size.
*/
if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L))))
return(MaxBlocks-1L);
/*
Otherwise use a power of two distribution.
*/
blocksize=BlockThreshold/(4*sizeof(size_t));
for ( ; size > BlockThreshold; size/=2)
blocksize++;
assert(blocksize > (BlockThreshold/(4*sizeof(size_t))));
assert(blocksize < (MaxBlocks-1L));
return(blocksize);
}
static inline void InsertFreeBlock(void *block,const size_t i)
{
register void
*next,
*previous;
size_t
size;
size=SizeOfBlock(block);
previous=(void *) NULL;
next=memory_pool.blocks[i];
while ((next != (void *) NULL) && (SizeOfBlock(next) < size))
{
previous=next;
next=NextBlockInList(next);
}
PreviousBlockInList(block)=previous;
NextBlockInList(block)=next;
if (previous != (void *) NULL)
NextBlockInList(previous)=block;
else
memory_pool.blocks[i]=block;
if (next != (void *) NULL)
PreviousBlockInList(next)=block;
}
static inline void RemoveFreeBlock(void *block,const size_t i)
{
register void
*next,
*previous;
next=NextBlockInList(block);
previous=PreviousBlockInList(block);
if (previous == (void *) NULL)
memory_pool.blocks[i]=next;
else
NextBlockInList(previous)=next;
if (next != (void *) NULL)
PreviousBlockInList(next)=previous;
}
static void *AcquireBlock(size_t size)
{
register size_t
i;
register void
*block;
/*
Find free block.
*/
size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t));
i=AllocationPolicy(size);
block=memory_pool.blocks[i];
while ((block != (void *) NULL) && (SizeOfBlock(block) < size))
block=NextBlockInList(block);
if (block == (void *) NULL)
{
i++;
while (memory_pool.blocks[i] == (void *) NULL)
i++;
block=memory_pool.blocks[i];
if (i >= MaxBlocks)
return((void *) NULL);
}
assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0);
assert(SizeOfBlock(block) >= size);
RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block)));
if (SizeOfBlock(block) > size)
{
size_t
blocksize;
void
*next;
/*
Split block.
*/
next=(char *) block+size;
blocksize=SizeOfBlock(block)-size;
*BlockHeader(next)=blocksize;
*BlockFooter(next,blocksize)=blocksize;
InsertFreeBlock(next,AllocationPolicy(blocksize));
*BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask);
}
assert(size == SizeOfBlock(block));
*BlockHeader(NextBlock(block))|=PreviousBlockBit;
memory_pool.allocation+=size;
return(block);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireMagickMemory() returns a pointer to a block of memory at least size
% bytes suitably aligned for any use.
%
% The format of the AcquireMagickMemory method is:
%
% void *AcquireMagickMemory(const size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes to allocate.
%
*/
MagickExport void *AcquireMagickMemory(const size_t size)
{
register void
*memory;
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size);
#else
if (memory_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&memory_semaphore);
if (free_segments == (DataSegmentInfo *) NULL)
{
LockSemaphoreInfo(memory_semaphore);
if (free_segments == (DataSegmentInfo *) NULL)
{
register ssize_t
i;
assert(2*sizeof(size_t) > (size_t) (~SizeMask));
(void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
memory_pool.allocation=SegmentSize;
memory_pool.blocks[MaxBlocks]=(void *) (-1);
for (i=0; i < MaxSegments; i++)
{
if (i != 0)
memory_pool.segment_pool[i].previous=
(&memory_pool.segment_pool[i-1]);
if (i != (MaxSegments-1))
memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]);
}
free_segments=(&memory_pool.segment_pool[0]);
}
UnlockSemaphoreInfo(memory_semaphore);
}
LockSemaphoreInfo(memory_semaphore);
memory=AcquireBlock(size == 0 ? 1UL : size);
if (memory == (void *) NULL)
{
if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse)
memory=AcquireBlock(size == 0 ? 1UL : size);
}
UnlockSemaphoreInfo(memory_semaphore);
#endif
return(memory);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e Q u a n t u m M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantumMemory() returns a pointer to a block of memory at least
% count * quantum bytes suitably aligned for any use.
%
% The format of the AcquireQuantumMemory method is:
%
% void *AcquireQuantumMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum)
{
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((void *) NULL);
extent=count*quantum;
return(AcquireMagickMemory(extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e V i r t u a l M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireVirtualMemory() allocates a pointer to a block of memory at least size
% bytes suitably aligned for any use.
%
% The format of the AcquireVirtualMemory method is:
%
% MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum)
%
% A description of each parameter follows:
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((MemoryInfo *) NULL);
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
extent=count*quantum;
memory_info->length=extent;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,extent) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,extent);
if (memory_info->blob != NULL)
{
memory_info->type=AlignedVirtualMemory;
return(memory_info);
}
}
RelinquishMagickResource(MemoryResource,extent);
if (AcquireMagickResource(MapResource,extent) != MagickFalse)
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,extent);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
return(memory_info);
}
if (AcquireMagickResource(DiskResource,extent) != MagickFalse)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
If the MapResource request failed, there is no point in trying
file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
MagickOffsetType
offset;
offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET);
if ((offset == (MagickOffsetType) (extent-1)) &&
(write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,extent);
if (memory_info->blob != NULL)
{
(void) close(file);
memory_info->type=MapVirtualMemory;
return(memory_info);
}
}
/*
File-backed memory mapping failed, delete the temporary file.
*/
(void) close(file);
(void) RelinquishUniqueFileResource(memory_info->filename);
*memory_info->filename='\0';
}
}
RelinquishMagickResource(DiskResource,extent);
}
RelinquishMagickResource(MapResource,extent);
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(extent);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o p y M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CopyMagickMemory() copies size bytes from memory area source to the
% destination. Copying between objects that overlap will take place
% correctly. It returns destination.
%
% The format of the CopyMagickMemory method is:
%
% void *CopyMagickMemory(void *destination,const void *source,
% const size_t size)
%
% A description of each parameter follows:
%
% o destination: the destination.
%
% o source: the source.
%
% o size: the size of the memory in bytes to allocate.
%
*/
MagickExport void *CopyMagickMemory(void *destination,const void *source,
const size_t size)
{
register const unsigned char
*p;
register unsigned char
*q;
assert(destination != (void *) NULL);
assert(source != (const void *) NULL);
p=(const unsigned char *) source;
q=(unsigned char *) destination;
if (((q+size) < p) || (q > (p+size)))
switch (size)
{
default: return(memcpy(destination,source,size));
case 8: *q++=(*p++);
case 7: *q++=(*p++);
case 6: *q++=(*p++);
case 5: *q++=(*p++);
case 4: *q++=(*p++);
case 3: *q++=(*p++);
case 2: *q++=(*p++);
case 1: *q++=(*p++);
case 0: return(destination);
}
return(memmove(destination,source,size));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyMagickMemory() deallocates memory associated with the memory manager.
%
% The format of the DestroyMagickMemory method is:
%
% DestroyMagickMemory(void)
%
*/
MagickExport void DestroyMagickMemory(void)
{
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
register ssize_t
i;
if (memory_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&memory_semaphore);
LockSemaphoreInfo(memory_semaphore);
for (i=0; i < (ssize_t) memory_pool.number_segments; i++)
if (memory_pool.segments[i]->mapped == MagickFalse)
memory_methods.destroy_memory_handler(
memory_pool.segments[i]->allocation);
else
(void) UnmapBlob(memory_pool.segments[i]->allocation,
memory_pool.segments[i]->length);
free_segments=(DataSegmentInfo *) NULL;
(void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool));
UnlockSemaphoreInfo(memory_semaphore);
DestroySemaphoreInfo(&memory_semaphore);
#endif
}
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ E x p a n d H e a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExpandHeap() get more memory from the system. It returns MagickTrue on
% success otherwise MagickFalse.
%
% The format of the ExpandHeap method is:
%
% MagickBooleanType ExpandHeap(size_t size)
%
% A description of each parameter follows:
%
% o size: the size of the memory in bytes we require.
%
*/
static MagickBooleanType ExpandHeap(size_t size)
{
DataSegmentInfo
*segment_info;
MagickBooleanType
mapped;
register ssize_t
i;
register void
*block;
size_t
blocksize;
void
*segment;
blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize;
assert(memory_pool.number_segments < MaxSegments);
segment=MapBlob(-1,IOMode,0,blocksize);
mapped=segment != (void *) NULL ? MagickTrue : MagickFalse;
if (segment == (void *) NULL)
segment=(void *) memory_methods.acquire_memory_handler(blocksize);
if (segment == (void *) NULL)
return(MagickFalse);
segment_info=(DataSegmentInfo *) free_segments;
free_segments=segment_info->next;
segment_info->mapped=mapped;
segment_info->length=blocksize;
segment_info->allocation=segment;
segment_info->bound=(char *) segment+blocksize;
i=(ssize_t) memory_pool.number_segments-1;
for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--)
memory_pool.segments[i+1]=memory_pool.segments[i];
memory_pool.segments[i+1]=segment_info;
memory_pool.number_segments++;
size=blocksize-12*sizeof(size_t);
block=(char *) segment_info->allocation+4*sizeof(size_t);
*BlockHeader(block)=size | PreviousBlockBit;
*BlockFooter(block,size)=size;
InsertFreeBlock(block,AllocationPolicy(size));
block=NextBlock(block);
assert(block < segment_info->bound);
*BlockHeader(block)=2*sizeof(size_t);
*BlockHeader(NextBlock(block))=PreviousBlockBit;
return(MagickTrue);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M a g i c k M e m o r y M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy
% memory.
%
% The format of the GetMagickMemoryMethods() method is:
%
% void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler,
% ResizeMemoryHandler *resize_memory_handler,
% DestroyMemoryHandler *destroy_memory_handler)
%
% A description of each parameter follows:
%
% o acquire_memory_handler: method to acquire memory (e.g. malloc).
%
% o resize_memory_handler: method to resize memory (e.g. realloc).
%
% o destroy_memory_handler: method to destroy memory (e.g. free).
%
*/
MagickExport void GetMagickMemoryMethods(
AcquireMemoryHandler *acquire_memory_handler,
ResizeMemoryHandler *resize_memory_handler,
DestroyMemoryHandler *destroy_memory_handler)
{
assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL);
assert(resize_memory_handler != (ResizeMemoryHandler *) NULL);
assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL);
*acquire_memory_handler=memory_methods.acquire_memory_handler;
*resize_memory_handler=memory_methods.resize_memory_handler;
*destroy_memory_handler=memory_methods.destroy_memory_handler;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l M e m o r y B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualMemoryBlob() returns the virtual memory blob associated with the
% specified MemoryInfo structure.
%
% The format of the GetVirtualMemoryBlob method is:
%
% void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
%
% A description of each parameter follows:
%
% o memory_info: The MemoryInfo structure.
*/
MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info)
{
assert(memory_info != (const MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
return(memory_info->blob);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h A l i g n e d M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory()
% or reuse.
%
% The format of the RelinquishAlignedMemory method is:
%
% void *RelinquishAlignedMemory(void *memory)
%
% A description of each parameter follows:
%
% o memory: A pointer to a block of memory to free for reuse.
%
*/
MagickExport void *RelinquishAlignedMemory(void *memory)
{
if (memory == (void *) NULL)
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
free(memory);
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
_aligned_free(memory);
#else
free(*((void **) memory-1));
#endif
return(NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory()
% or AcquireQuantumMemory() for reuse.
%
% The format of the RelinquishMagickMemory method is:
%
% void *RelinquishMagickMemory(void *memory)
%
% A description of each parameter follows:
%
% o memory: A pointer to a block of memory to free for reuse.
%
*/
MagickExport void *RelinquishMagickMemory(void *memory)
{
if (memory == (void *) NULL)
return((void *) NULL);
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
memory_methods.destroy_memory_handler(memory);
#else
LockSemaphoreInfo(memory_semaphore);
assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0);
assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0);
if ((*BlockHeader(memory) & PreviousBlockBit) == 0)
{
void
*previous;
/*
Coalesce with previous adjacent block.
*/
previous=PreviousBlock(memory);
RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous)));
*BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) |
(*BlockHeader(previous) & ~SizeMask);
memory=previous;
}
if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0)
{
void
*next;
/*
Coalesce with next adjacent block.
*/
next=NextBlock(memory);
RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next)));
*BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) |
(*BlockHeader(memory) & ~SizeMask);
}
*BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory);
*BlockHeader(NextBlock(memory))&=(~PreviousBlockBit);
InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory)));
UnlockSemaphoreInfo(memory_semaphore);
#endif
return((void *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e l i n q u i s h V i r t u a l M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory().
%
% The format of the RelinquishVirtualMemory method is:
%
% MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
%
% A description of each parameter follows:
%
% o memory_info: A pointer to a block of memory to free for reuse.
%
*/
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info)
{
assert(memory_info != (MemoryInfo *) NULL);
assert(memory_info->signature == MagickSignature);
if (memory_info->blob != (void *) NULL)
switch (memory_info->type)
{
case AlignedVirtualMemory:
{
memory_info->blob=RelinquishAlignedMemory(memory_info->blob);
RelinquishMagickResource(MemoryResource,memory_info->length);
break;
}
case MapVirtualMemory:
{
(void) UnmapBlob(memory_info->blob,memory_info->length);
memory_info->blob=NULL;
RelinquishMagickResource(MapResource,memory_info->length);
if (*memory_info->filename != '\0')
{
(void) RelinquishUniqueFileResource(memory_info->filename);
RelinquishMagickResource(DiskResource,memory_info->length);
}
break;
}
case UnalignedVirtualMemory:
default:
{
memory_info->blob=RelinquishMagickMemory(memory_info->blob);
break;
}
}
memory_info->signature=(~MagickSignature);
memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info);
return(memory_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetMagickMemory() fills the first size bytes of the memory area pointed to
% by memory with the constant byte c.
%
% The format of the ResetMagickMemory method is:
%
% void *ResetMagickMemory(void *memory,int byte,const size_t size)
%
% A description of each parameter follows:
%
% o memory: a pointer to a memory allocation.
%
% o byte: set the memory to this value.
%
% o size: size of the memory to reset.
%
*/
MagickExport void *ResetMagickMemory(void *memory,int byte,const size_t size)
{
assert(memory != (void *) NULL);
return(memset(memory,byte,size));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e M a g i c k M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeMagickMemory() changes the size of the memory and returns a pointer to
% the (possibly moved) block. The contents will be unchanged up to the
% lesser of the new and old sizes.
%
% The format of the ResizeMagickMemory method is:
%
% void *ResizeMagickMemory(void *memory,const size_t size)
%
% A description of each parameter follows:
%
% o memory: A pointer to a memory allocation.
%
% o size: the new size of the allocated memory.
%
*/
#if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
static inline void *ResizeBlock(void *block,size_t size)
{
register void
*memory;
if (block == (void *) NULL)
return(AcquireBlock(size));
memory=AcquireBlock(size);
if (memory == (void *) NULL)
return((void *) NULL);
if (size <= (SizeOfBlock(block)-sizeof(size_t)))
(void) memcpy(memory,block,size);
else
(void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t));
memory_pool.allocation+=size;
return(memory);
}
#endif
MagickExport void *ResizeMagickMemory(void *memory,const size_t size)
{
register void
*block;
if (memory == (void *) NULL)
return(AcquireMagickMemory(size));
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size);
if (block == (void *) NULL)
memory=RelinquishMagickMemory(memory);
#else
LockSemaphoreInfo(memory_semaphore);
block=ResizeBlock(memory,size == 0 ? 1UL : size);
if (block == (void *) NULL)
{
if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse)
{
UnlockSemaphoreInfo(memory_semaphore);
memory=RelinquishMagickMemory(memory);
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
block=ResizeBlock(memory,size == 0 ? 1UL : size);
assert(block != (void *) NULL);
}
UnlockSemaphoreInfo(memory_semaphore);
memory=RelinquishMagickMemory(memory);
#endif
return(block);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e Q u a n t u m M e m o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeQuantumMemory() changes the size of the memory and returns a pointer
% to the (possibly moved) block. The contents will be unchanged up to the
% lesser of the new and old sizes.
%
% The format of the ResizeQuantumMemory method is:
%
% void *ResizeQuantumMemory(void *memory,const size_t count,
% const size_t quantum)
%
% A description of each parameter follows:
%
% o memory: A pointer to a memory allocation.
%
% o count: the number of quantum elements to allocate.
%
% o quantum: the number of bytes in each quantum.
%
*/
MagickExport void *ResizeQuantumMemory(void *memory,const size_t count,
const size_t quantum)
{
size_t
extent;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
{
memory=RelinquishMagickMemory(memory);
return((void *) NULL);
}
extent=count*quantum;
return(ResizeMagickMemory(memory,extent));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t M a g i c k M e m o r y M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy
% memory. Your custom memory methods must be set prior to the
% MagickCoreGenesis() method.
%
% The format of the SetMagickMemoryMethods() method is:
%
% SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler,
% ResizeMemoryHandler resize_memory_handler,
% DestroyMemoryHandler destroy_memory_handler)
%
% A description of each parameter follows:
%
% o acquire_memory_handler: method to acquire memory (e.g. malloc).
%
% o resize_memory_handler: method to resize memory (e.g. realloc).
%
% o destroy_memory_handler: method to destroy memory (e.g. free).
%
*/
MagickExport void SetMagickMemoryMethods(
AcquireMemoryHandler acquire_memory_handler,
ResizeMemoryHandler resize_memory_handler,
DestroyMemoryHandler destroy_memory_handler)
{
/*
Set memory methods.
*/
if (acquire_memory_handler != (AcquireMemoryHandler) NULL)
memory_methods.acquire_memory_handler=acquire_memory_handler;
if (resize_memory_handler != (ResizeMemoryHandler) NULL)
memory_methods.resize_memory_handler=resize_memory_handler;
if (destroy_memory_handler != (DestroyMemoryHandler) NULL)
memory_methods.destroy_memory_handler=destroy_memory_handler;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4788_4 |
crossvul-cpp_data_good_5475_4 | /* $Id$ */
/* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of
* the image data through additional options listed below
*
* Original code:
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
* Additions (c) Richard Nolde 2006-2010
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT
* HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
* DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND
* ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOFTWARE.
*
* Some portions of the current code are derived from tiffcp, primarly in
* the areas of lowlevel reading and writing of TAGS, scanlines and tiles though
* some of the original functions have been extended to support arbitrary bit
* depths. These functions are presented at the top of this file.
*
* Add support for the options below to extract sections of image(s)
* and to modify the whole image or selected portions of each image by
* rotations, mirroring, and colorscale/colormap inversion of selected
* types of TIFF images when appropriate. Some color model dependent
* functions are restricted to bilevel or 8 bit per sample data.
* See the man page for the full explanations.
*
* New Options:
* -h Display the syntax guide.
* -v Report the version and last build date for tiffcrop and libtiff.
* -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1
* Specify a series of coordinates to define rectangular
* regions by the top left and lower right corners.
* -e c|d|i|m|s export mode for images and selections from input images
* combined All images and selections are written to a single file (default)
* with multiple selections from one image combined into a single image
* divided All images and selections are written to a single file
* with each selection from one image written to a new image
* image Each input image is written to a new file (numeric filename sequence)
* with multiple selections from the image combined into one image
* multiple Each input image is written to a new file (numeric filename sequence)
* with each selection from the image written to a new image
* separated Individual selections from each image are written to separate files
* -U units [in, cm, px ] inches, centimeters or pixels
* -H # Set horizontal resolution of output images to #
* -V # Set vertical resolution of output images to #
* -J # Horizontal margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -K # Vertical margin of output page to # expressed in current
* units when sectioning image into columns x rows
* using the -S cols:rows option.
* -X # Horizontal dimension of region to extract expressed in current
* units
* -Y # Vertical dimension of region to extract expressed in current
* units
* -O orient Orientation for output image, portrait, landscape, auto
* -P page Page size for output image segments, eg letter, legal, tabloid,
* etc.
* -S cols:rows Divide the image into equal sized segments using cols across
* and rows down
* -E t|l|r|b Edge to use as origin
* -m #,#,#,# Margins from edges for selection: top, left, bottom, right
* (commas separated)
* -Z #:#,#:# Zones of the image designated as zone X of Y,
* eg 1:3 would be first of three equal portions measured
* from reference edge
* -N odd|even|#,#-#,#|last
* Select sequences and/or ranges of images within file
* to process. The words odd or even may be used to specify
* all odd or even numbered images the word last may be used
* in place of a number in the sequence to indicate the final
* image in the file without knowing how many images there are.
* -R # Rotate image or crop selection by 90,180,or 270 degrees
* clockwise
* -F h|v Flip (mirror) image or crop selection horizontally
* or vertically
* -I [black|white|data|both]
* Invert color space, eg dark to light for bilevel and grayscale images
* If argument is white or black, set the PHOTOMETRIC_INTERPRETATION
* tag to MinIsBlack or MinIsWhite without altering the image data
* If the argument is data or both, the image data are modified:
* both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,
* data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag
* -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N
* Dump raw data for input and/or output images to individual files
* in raw (binary) format or text (ASCII) representing binary data
* as strings of 1s and 0s. The filename arguments are used as stems
* from which individual files are created for each image. Text format
* includes annotations for image parameters and scanline info. Level
* selects which functions dump data, with higher numbers selecting
* lower level, scanline level routines. Debug reports a limited set
* of messages to monitor progess without enabling dump logs.
*/
static char tiffcrop_version_id[] = "2.4";
static char tiffcrop_rev_date[] = "12-13-2010";
#include "tif_config.h"
#include "tiffiop.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <sys/stat.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#ifndef HAVE_GETOPT
extern int getopt(int argc, char * const argv[], const char *optstring);
#endif
#ifdef NEED_LIBPORT
# include "libport.h"
#endif
#include "tiffio.h"
#if defined(VMS)
# define unlink delete
#endif
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#ifndef streq
#define streq(a,b) (strcmp((a),(b)) == 0)
#endif
#define strneq(a,b,n) (strncmp((a),(b),(n)) == 0)
#define TRUE 1
#define FALSE 0
#ifndef TIFFhowmany
#define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y)))
#define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)
#endif
/*
* Definitions and data structures required to support cropping and image
* manipulations.
*/
#define EDGE_TOP 1
#define EDGE_LEFT 2
#define EDGE_BOTTOM 3
#define EDGE_RIGHT 4
#define EDGE_CENTER 5
#define MIRROR_HORIZ 1
#define MIRROR_VERT 2
#define MIRROR_BOTH 3
#define ROTATECW_90 8
#define ROTATECW_180 16
#define ROTATECW_270 32
#define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270)
#define CROP_NONE 0
#define CROP_MARGINS 1
#define CROP_WIDTH 2
#define CROP_LENGTH 4
#define CROP_ZONES 8
#define CROP_REGIONS 16
#define CROP_ROTATE 32
#define CROP_MIRROR 64
#define CROP_INVERT 128
/* Modes for writing out images and selections */
#define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */
#define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */
#define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */
#define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */
#define FILE_PER_SELECTION 4 /* One file per selection */
#define COMPOSITE_IMAGES 0 /* Selections combined into one image */
#define SEPARATED_IMAGES 1 /* Selections saved to separate images */
#define STRIP 1
#define TILE 2
#define MAX_REGIONS 8 /* number of regions to extract from a single page */
#define MAX_OUTBUFFS 8 /* must match larger of zones or regions */
#define MAX_SECTIONS 32 /* number of sections per page to write to output */
#define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */
#define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */
#define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */
#define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */
#define DUMP_NONE 0
#define DUMP_TEXT 1
#define DUMP_RAW 2
/* Offsets into buffer for margins and fixed width and length segments */
struct offset {
uint32 tmargin;
uint32 lmargin;
uint32 bmargin;
uint32 rmargin;
uint32 crop_width;
uint32 crop_length;
uint32 startx;
uint32 endx;
uint32 starty;
uint32 endy;
};
/* Description of a zone within the image. Position 1 of 3 zones would be
* the first third of the image. These are computed after margins and
* width/length requests are applied so that you can extract multiple
* zones from within a larger region for OCR or barcode recognition.
*/
struct buffinfo {
uint32 size; /* size of this buffer */
unsigned char *buffer; /* address of the allocated buffer */
};
struct zone {
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
};
struct pageseg {
uint32 x1; /* index of left edge */
uint32 x2; /* index of right edge */
uint32 y1; /* index of top edge */
uint32 y2; /* index of bottom edge */
int position; /* ordinal of segment to be extracted */
int total; /* total equal sized divisions of crop area */
uint32 buffsize; /* size of buffer needed to hold the cropped zone */
};
struct coordpairs {
double X1; /* index of left edge in current units */
double X2; /* index of right edge in current units */
double Y1; /* index of top edge in current units */
double Y2; /* index of bottom edge in current units */
};
struct region {
uint32 x1; /* pixel offset of left edge */
uint32 x2; /* pixel offset of right edge */
uint32 y1; /* pixel offset of top edge */
uint32 y2; /* picel offset of bottom edge */
uint32 width; /* width in pixels */
uint32 length; /* length in pixels */
uint32 buffsize; /* size of buffer needed to hold the cropped region */
unsigned char *buffptr; /* address of start of the region */
};
/* Cropping parameters from command line and image data
* Note: This should be renamed to proc_opts and expanded to include all current globals
* if possible, but each function that accesses global variables will have to be redone.
*/
struct crop_mask {
double width; /* Selection width for master crop region in requested units */
double length; /* Selection length for master crop region in requesed units */
double margins[4]; /* Top, left, bottom, right margins */
float xres; /* Horizontal resolution read from image*/
float yres; /* Vertical resolution read from image */
uint32 combined_width; /* Width of combined cropped zones */
uint32 combined_length; /* Length of combined cropped zones */
uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */
uint16 img_mode; /* Composite or separate images created from zones or regions */
uint16 exp_mode; /* Export input images or selections to one or more files */
uint16 crop_mode; /* Crop options to be applied */
uint16 res_unit; /* Resolution unit for margins and selections */
uint16 edge_ref; /* Reference edge for sections extraction and combination */
uint16 rotation; /* Clockwise rotation of the extracted region or image */
uint16 mirror; /* Mirror extracted region or image horizontally or vertically */
uint16 invert; /* Invert the color map of image or region */
uint16 photometric; /* Status of photometric interpretation for inverted image */
uint16 selections; /* Number of regions or zones selected */
uint16 regions; /* Number of regions delimited by corner coordinates */
struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */
uint16 zones; /* Number of zones delimited by Ordinal:Total requested */
struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */
struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */
};
#define MAX_PAPERNAMES 49
#define MAX_PAPERNAME_LENGTH 15
#define DEFAULT_RESUNIT RESUNIT_INCH
#define DEFAULT_PAGE_HEIGHT 14.0
#define DEFAULT_PAGE_WIDTH 8.5
#define DEFAULT_RESOLUTION 300
#define DEFAULT_PAPER_SIZE "legal"
#define ORIENTATION_NONE 0
#define ORIENTATION_PORTRAIT 1
#define ORIENTATION_LANDSCAPE 2
#define ORIENTATION_SEASCAPE 4
#define ORIENTATION_AUTO 16
#define PAGE_MODE_NONE 0
#define PAGE_MODE_RESOLUTION 1
#define PAGE_MODE_PAPERSIZE 2
#define PAGE_MODE_MARGINS 4
#define PAGE_MODE_ROWSCOLS 8
#define INVERT_DATA_ONLY 10
#define INVERT_DATA_AND_TAG 11
struct paperdef {
char name[MAX_PAPERNAME_LENGTH];
double width;
double length;
double asratio;
};
/* European page sizes corrected from update sent by
* thomas . jarosch @ intra2net . com on 5/7/2010
* Paper Size Width Length Aspect Ratio */
struct paperdef PaperTable[MAX_PAPERNAMES] = {
{"default", 8.500, 14.000, 0.607},
{"pa4", 8.264, 11.000, 0.751},
{"letter", 8.500, 11.000, 0.773},
{"legal", 8.500, 14.000, 0.607},
{"half-letter", 8.500, 5.514, 1.542},
{"executive", 7.264, 10.528, 0.690},
{"tabloid", 11.000, 17.000, 0.647},
{"11x17", 11.000, 17.000, 0.647},
{"ledger", 17.000, 11.000, 1.545},
{"archa", 9.000, 12.000, 0.750},
{"archb", 12.000, 18.000, 0.667},
{"archc", 18.000, 24.000, 0.750},
{"archd", 24.000, 36.000, 0.667},
{"arche", 36.000, 48.000, 0.750},
{"csheet", 17.000, 22.000, 0.773},
{"dsheet", 22.000, 34.000, 0.647},
{"esheet", 34.000, 44.000, 0.773},
{"superb", 11.708, 17.042, 0.687},
{"commercial", 4.139, 9.528, 0.434},
{"monarch", 3.889, 7.528, 0.517},
{"envelope-dl", 4.333, 8.681, 0.499},
{"envelope-c5", 6.389, 9.028, 0.708},
{"europostcard", 4.139, 5.833, 0.710},
{"a0", 33.110, 46.811, 0.707},
{"a1", 23.386, 33.110, 0.706},
{"a2", 16.535, 23.386, 0.707},
{"a3", 11.693, 16.535, 0.707},
{"a4", 8.268, 11.693, 0.707},
{"a5", 5.827, 8.268, 0.705},
{"a6", 4.134, 5.827, 0.709},
{"a7", 2.913, 4.134, 0.705},
{"a8", 2.047, 2.913, 0.703},
{"a9", 1.457, 2.047, 0.712},
{"a10", 1.024, 1.457, 0.703},
{"b0", 39.370, 55.669, 0.707},
{"b1", 27.835, 39.370, 0.707},
{"b2", 19.685, 27.835, 0.707},
{"b3", 13.898, 19.685, 0.706},
{"b4", 9.843, 13.898, 0.708},
{"b5", 6.929, 9.843, 0.704},
{"b6", 4.921, 6.929, 0.710},
{"c0", 36.102, 51.063, 0.707},
{"c1", 25.512, 36.102, 0.707},
{"c2", 18.031, 25.512, 0.707},
{"c3", 12.756, 18.031, 0.707},
{"c4", 9.016, 12.756, 0.707},
{"c5", 6.378, 9.016, 0.707},
{"c6", 4.488, 6.378, 0.704},
{"", 0.000, 0.000, 1.000}
};
/* Structure to define input image parameters */
struct image_data {
float xres;
float yres;
uint32 width;
uint32 length;
uint16 res_unit;
uint16 bps;
uint16 spp;
uint16 planar;
uint16 photometric;
uint16 orientation;
uint16 compression;
uint16 adjustments;
};
/* Structure to define the output image modifiers */
struct pagedef {
char name[16];
double width; /* width in pixels */
double length; /* length in pixels */
double hmargin; /* margins to subtract from width of sections */
double vmargin; /* margins to subtract from height of sections */
double hres; /* horizontal resolution for output */
double vres; /* vertical resolution for output */
uint32 mode; /* bitmask of modifiers to page format */
uint16 res_unit; /* resolution unit for output image */
unsigned int rows; /* number of section rows */
unsigned int cols; /* number of section cols */
unsigned int orient; /* portrait, landscape, seascape, auto */
};
struct dump_opts {
int debug;
int format;
int level;
char mode[4];
char infilename[PATH_MAX + 1];
char outfilename[PATH_MAX + 1];
FILE *infile;
FILE *outfile;
};
/* globals */
static int outtiled = -1;
static uint32 tilewidth = 0;
static uint32 tilelength = 0;
static uint16 config = 0;
static uint16 compression = 0;
static uint16 predictor = 0;
static uint16 fillorder = 0;
static uint32 rowsperstrip = 0;
static uint32 g3opts = 0;
static int ignore = FALSE; /* if true, ignore read errors */
static uint32 defg3opts = (uint32) -1;
static int quality = 100; /* JPEG quality */
/* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */
static int jpegcolormode = JPEGCOLORMODE_RGB;
static uint16 defcompression = (uint16) -1;
static uint16 defpredictor = (uint16) -1;
static int pageNum = 0;
static int little_endian = 1;
/* Functions adapted from tiffcp with additions or significant modifications */
static int readContigStripsIntoBuffer (TIFF*, uint8*);
static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16);
static int writeBufferToContigStrips (TIFF*, uint8*, uint32);
static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *);
static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t,
uint16, uint16, struct dump_opts *);
static int processCompressOptions(char*);
static void usage(void);
/* All other functions by Richard Nolde, not found in tiffcp */
static void initImageData (struct image_data *);
static void initCropMasks (struct crop_mask *);
static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []);
static void initDumpOptions(struct dump_opts *);
/* Command line and file naming functions */
void process_command_opts (int, char *[], char *, char *, uint32 *,
uint16 *, uint16 *, uint32 *, uint32 *, uint32 *,
struct crop_mask *, struct pagedef *,
struct dump_opts *,
unsigned int *, unsigned int *);
static int update_output_file (TIFF **, char *, int, char *, unsigned int *);
/* * High level functions for whole image manipulation */
static int get_page_geometry (char *, struct pagedef*);
static int computeInputPixelOffsets(struct crop_mask *, struct image_data *,
struct offset *);
static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *);
static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **);
static int correct_orientation(struct image_data *, unsigned char **);
static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *);
static int processCropSelections(struct image_data *, struct crop_mask *,
unsigned char **, struct buffinfo []);
static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *,
struct dump_opts *, struct buffinfo [],
char *, char *, unsigned int*, unsigned int);
/* Section functions */
static int createImageSection(uint32, unsigned char **);
static int extractImageSection(struct image_data *, struct pageseg *,
unsigned char *, unsigned char *);
static int writeSingleSection(TIFF *, TIFF *, struct image_data *,
struct dump_opts *, uint32, uint32,
double, double, unsigned char *);
static int writeImageSections(TIFF *, TIFF *, struct image_data *,
struct pagedef *, struct pageseg *,
struct dump_opts *, unsigned char *,
unsigned char **);
/* Whole image functions */
static int createCroppedImage(struct image_data *, struct crop_mask *,
unsigned char **, unsigned char **);
static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image,
struct dump_opts * dump,
uint32, uint32, unsigned char *, int, int);
/* Image manipulation functions */
static int rotateContigSamples8bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples16bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples24bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateContigSamples32bits(uint16, uint16, uint16, uint32,
uint32, uint32, uint8 *, uint8 *);
static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *,
unsigned char **);
static int mirrorImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
static int invertImage(uint16, uint16, uint16, uint32, uint32,
unsigned char *);
/* Functions to reverse the sequence of samples in a scanline */
static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *);
static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *);
/* Functions for manipulating individual samples in an image */
static int extractSeparateRegion(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *, int);
static int extractCompositeRegions(struct image_data *, struct crop_mask *,
unsigned char *, unsigned char *);
static int extractContigSamples8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamples32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesBytes (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32);
static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32,
tsample_t, uint16, uint16,
tsample_t, uint32, uint32,
int);
static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32,
uint32, uint32, tsample_t, uint16,
uint16, uint16, struct dump_opts *);
/* Functions to combine separate planes into interleaved planes */
static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint16, uint16, FILE *, int, int);
static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, tsample_t, uint16,
FILE *, int, int);
static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32,
uint32, uint32, uint16, uint16,
FILE *, int, int);
static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *,
uint32, uint32, uint32, uint32,
tsample_t, uint16, FILE *, int, int);
/* Dump functions for debugging */
static void dump_info (FILE *, int, char *, char *, ...);
static int dump_data (FILE *, int, char *, unsigned char *, uint32);
static int dump_byte (FILE *, int, char *, unsigned char);
static int dump_short (FILE *, int, char *, uint16);
static int dump_long (FILE *, int, char *, uint32);
static int dump_wide (FILE *, int, char *, uint64);
static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *);
/* End function declarations */
/* Functions derived in whole or in part from tiffcp */
/* The following functions are taken largely intact from tiffcp */
static char* usage_info[] = {
"usage: tiffcrop [options] source1 ... sourceN destination",
"where options are:",
" -h Print this syntax listing",
" -v Print tiffcrop version identifier and last revision date",
" ",
" -a Append to output instead of overwriting",
" -d offset Set initial directory offset, counting first image as one, not zero",
" -p contig Pack samples contiguously (e.g. RGBRGB...)",
" -p separate Store samples separately (e.g. RRR...GGG...BBB...)",
" -s Write output in strips",
" -t Write output in tiles",
" -i Ignore read errors",
" ",
" -r # Make each strip have no more than # rows",
" -w # Set output tile width (pixels)",
" -l # Set output tile length (pixels)",
" ",
" -f lsb2msb Force lsb-to-msb FillOrder for output",
" -f msb2lsb Force msb-to-lsb FillOrder for output",
"",
" -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts] Compress output with deflate encoding",
" -c jpeg[:opts] Compress output with JPEG encoding",
" -c packbits Compress output with packbits encoding",
" -c g3[:opts] Compress output with CCITT Group 3 encoding",
" -c g4 Compress output with CCITT Group 4 encoding",
" -c none Use no compression algorithm on output",
" ",
"Group 3 options:",
" 1d Use default CCITT Group 3 1D-encoding",
" 2d Use optional CCITT Group 3 2D-encoding",
" fill Byte-align EOL codes",
"For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs",
" ",
"JPEG options:",
" # Set compression quality level (0-100, default 100)",
" raw Output color image as raw YCbCr",
" rgb Output color image as RGB",
"For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality",
" ",
"LZW and deflate options:",
" # Set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
" ",
"Page and selection options:",
" -N odd|even|#,#-#,#|last sequences and ranges of images within file to process",
" The words odd or even may be used to specify all odd or even numbered images.",
" The word last may be used in place of a number in the sequence to indicate.",
" The final image in the file without knowing how many images there are.",
" Numbers are counted from one even though TIFF IFDs are counted from zero.",
" ",
" -E t|l|r|b edge to use as origin for width and length of crop region",
" -U units [in, cm, px ] inches, centimeters or pixels",
" ",
" -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas",
" -X # horizontal dimension of region to extract expressed in current units",
" -Y # vertical dimension of region to extract expressed in current units",
" -Z #:#,#:# zones of the image designated as position X of Y,",
" eg 1:3 would be first of three equal portions measured from reference edge",
" -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1",
" regions of the image designated by upper left and lower right coordinates",
"",
"Export grouping options:",
" -e c|d|i|m|s export mode for images and selections from input images.",
" When exporting a composite image from multiple zones or regions",
" (combined and image modes), the selections must have equal sizes",
" for the axis perpendicular to the edge specified with -E.",
" c|combined All images and selections are written to a single file (default).",
" with multiple selections from one image combined into a single image.",
" d|divided All images and selections are written to a single file",
" with each selection from one image written to a new image.",
" i|image Each input image is written to a new file (numeric filename sequence)",
" with multiple selections from the image combined into one image.",
" m|multiple Each input image is written to a new file (numeric filename sequence)",
" with each selection from the image written to a new image.",
" s|separated Individual selections from each image are written to separate files.",
"",
"Output options:",
" -H # Set horizontal resolution of output images to #",
" -V # Set vertical resolution of output images to #",
" -J # Set horizontal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" -K # Set verticalal margin of output page to # expressed in current units",
" when sectioning image into columns x rows using the -S cols:rows option",
" ",
" -O orient orientation for output image, portrait, landscape, auto",
" -P page page size for output image segments, eg letter, legal, tabloid, etc",
" use #.#x#.# to specify a custom page size in the currently defined units",
" where #.# represents the width and length",
" -S cols:rows Divide the image into equal sized segments using cols across and rows down.",
" ",
" -F hor|vert|both",
" flip (mirror) image or region horizontally, vertically, or both",
" -R # [90,180,or 270] degrees clockwise rotation of image or extracted region",
" -I [black|white|data|both]",
" invert color space, eg dark to light for bilevel and grayscale images",
" If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ",
" tag to MinIsBlack or MinIsWhite without altering the image data",
" If the argument is data or both, the image data are modified:",
" both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,",
" data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag",
" ",
"-D opt1:value1,opt2:value2,opt3:value3:opt4:value4",
" Debug/dump program progress and/or data to non-TIFF files.",
" Options include the following and must be joined as a comma",
" separate list. The use of this option is generally limited to",
" program debugging and development of future options.",
" ",
" debug:N Display limited program progress indicators where larger N",
" increase the level of detail. Note: Tiffcrop may be compiled with",
" -DDEVELMODE to enable additional very low level debug reporting.",
"",
" Format:txt|raw Format any logged data as ASCII text or raw binary ",
" values. ASCII text dumps include strings of ones and zeroes",
" representing the binary values in the image data plus identifying headers.",
" ",
" level:N Specify the level of detail presented in the dump files.",
" This can vary from dumps of the entire input or output image data to dumps",
" of data processed by specific functions. Current range of levels is 1 to 3.",
" ",
" input:full-path-to-directory/input-dumpname",
" ",
" output:full-path-to-directory/output-dumpnaem",
" ",
" When dump files are being written, each image will be written to a separate",
" file with the name built by adding a numeric sequence value to the dumpname",
" and an extension of .txt for ASCII dumps or .bin for binary dumps.",
" ",
" The four debug/dump options are independent, though it makes little sense to",
" specify a dump file without specifying a detail level.",
" ",
NULL
};
/* This function could be modified to pass starting sample offset
* and number of samples as args to select fewer than spp
* from input image. These would then be passed to individual
* extractContigSampleXX routines.
*/
static int readContigTilesIntoBuffer (TIFF* in, uint8* buf,
uint32 imagelength,
uint32 imagewidth,
uint32 tw, uint32 tl,
tsample_t spp, uint16 bps)
{
int status = 1;
tsample_t sample = 0;
tsample_t count = spp;
uint32 row, col, trow;
uint32 nrow, ncol;
uint32 dst_rowsize, shift_width;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 trailing_bits, prev_trailing_bits;
uint32 tile_rowsize = TIFFTileRowSize(in);
uint32 src_offset, dst_offset;
uint32 row_offset, col_offset;
uint8 *bufp = (uint8*) buf;
unsigned char *src = NULL;
unsigned char *dst = NULL;
tsize_t tbytes = 0, tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(in);
unsigned char *tilebuf = NULL;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
tile_buffsize = tilesize;
if (tilesize == 0 || tile_rowsize == 0)
{
TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero");
exit(-1);
}
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("readContigTilesIntoBuffer",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != (tile_buffsize / tile_rowsize))
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
}
tilebuf = _TIFFmalloc(tile_buffsize);
if (tilebuf == 0)
return 0;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0);
if (tbytes < tilesize && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu",
(unsigned long) col, (unsigned long) row, (unsigned long)tbytes,
(unsigned long)tilesize);
status = 0;
_TIFFfree(tilebuf);
return status;
}
row_offset = row * dst_rowsize;
col_offset = ((col * bps * spp) + 7)/ 8;
bufp = buf + row_offset + col_offset;
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
/* Each tile scanline will start on a byte boundary but it
* has to be merged into the scanline for the entire
* image buffer and the previous segment may not have
* ended on a byte boundary
*/
/* Optimization for common bit depths, all samples */
if (((bps % 8) == 0) && (count == spp))
{
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
_TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8);
bufp += (imagewidth * bps * spp) / 8;
}
}
else
{
/* Bit depths not a multiple of 8 and/or extract fewer than spp samples */
prev_trailing_bits = trailing_bits = 0;
trailing_bits = (ncol * bps * spp) % 8;
/* for (trow = 0; tl < nrow; trow++) */
for (trow = 0; trow < nrow; trow++)
{
src_offset = trow * tile_rowsize;
src = tilebuf + src_offset;
dst_offset = (row + trow) * dst_rowsize;
dst = buf + dst_offset + col_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, ncol, sample,
spp, bps, count, 0, ncol))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, ncol,
sample, spp,
bps, count,
0, ncol,
prev_trailing_bits))
{
TIFFError("readContigTilesIntoBuffer",
"Unable to extract row %d from tile %lu",
row, (unsigned long)TIFFCurrentTile(in));
return 1;
}
break;
default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps);
return 1;
}
}
prev_trailing_bits += trailing_bits;
/* if (prev_trailing_bits > 7) */
/* prev_trailing_bits-= 8; */
}
}
}
_TIFFfree(tilebuf);
return status;
}
static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf,
uint32 imagelength, uint32 imagewidth,
uint32 tw, uint32 tl,
uint16 spp, uint16 bps)
{
int i, status = 1, sample;
int shift_width, bytes_per_pixel;
uint16 bytes_per_sample;
uint32 row, col; /* Current row and col of image */
uint32 nrow, ncol; /* Number of rows and cols in current tile */
uint32 row_offset, col_offset; /* Output buffer offsets */
tsize_t tbytes = 0, tilesize = TIFFTileSize(in);
tsample_t s;
uint8* bufp = (uint8*)obuf;
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *tbuff = NULL;
bytes_per_sample = (bps + 7) / 8;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
srcbuffs[sample] = NULL;
tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8);
if (!tbuff)
{
TIFFError ("readSeparateTilesIntoBuffer",
"Unable to allocate tile read buffer for sample %d", sample);
for (i = 0; i < sample; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[sample] = tbuff;
}
/* Each tile contains only the data for a single plane
* arranged in scanlines of tw * bytes_per_sample bytes.
*/
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
for (s = 0; s < spp && s < MAX_SAMPLES; s++)
{ /* Read each plane of a tile set into srcbuffs[s] */
tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s);
if (tbytes < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read tile for row %lu col %lu, "
"sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
status = 0;
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
}
/* Tiles on the right edge may be padded out to tw
* which must be a multiple of 16.
* Ncol represents the visible (non padding) portion.
*/
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
row_offset = row * (((imagewidth * spp * bps) + 7) / 8);
col_offset = ((col * spp * bps) + 7) / 8;
bufp = obuf + row_offset + col_offset;
if ((bps % 8) == 0)
{
if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth,
tw, spp, bps, NULL, 0, 0))
{
status = 0;
break;
}
}
else
{
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (shift_width)
{
case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow,
imagewidth, tw, spp, bps,
NULL, 0, 0))
{
status = 0;
break;
}
break;
default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps);
status = 0;
break;
}
}
}
}
for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++)
{
tbuff = srcbuffs[sample];
if (tbuff != NULL)
_TIFFfree(tbuff);
}
return status;
}
static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength)
{
uint32 row, nrows, rowsperstrip;
tstrip_t strip = 0;
tsize_t stripsize;
TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (row = 0; row < imagelength; row += rowsperstrip)
{
nrows = (row + rowsperstrip > imagelength) ?
imagelength - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
return 1;
}
buf += stripsize;
}
return 0;
}
/* Abandon plans to modify code so that plannar orientation separate images
* do not have all samples for each channel written before all samples
* for the next channel have been abandoned.
* Libtiff internals seem to depend on all data for a given sample
* being contiguous within a strip or tile when PLANAR_CONFIG is
* separate. All strips or tiles of a given plane are written
* before any strips or tiles of a different plane are stored.
*/
static int
writeBufferToSeparateStrips (TIFF* out, uint8* buf,
uint32 length, uint32 width, uint16 spp,
struct dump_opts *dump)
{
uint8 *src;
uint16 bps;
uint32 row, nrows, rowsize, rowsperstrip;
uint32 bytes_per_sample;
tsample_t s;
tstrip_t strip = 0;
tsize_t stripsize = TIFFStripSize(out);
tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out);
tsize_t total_bytes = 0;
tdata_t obuf;
(void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
(void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
bytes_per_sample = (bps + 7) / 8;
rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */
rowstripsize = rowsperstrip * bytes_per_sample * (width + 1);
obuf = _TIFFmalloc (rowstripsize);
if (obuf == NULL)
return 1;
for (s = 0; s < spp; s++)
{
for (row = 0; row < length; row += rowsperstrip)
{
nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
src = buf + (row * rowsize);
total_bytes += stripsize;
memset (obuf, '\0', rowstripsize);
if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump))
{
_TIFFfree(obuf);
return 1;
}
if ((dump->outfile != NULL) && (dump->level == 1))
{
dump_info(dump->outfile, dump->format,"",
"Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d",
s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf);
dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf);
}
if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
_TIFFfree(obuf);
return 1;
}
}
}
_TIFFfree(obuf);
return 0;
}
/* Extract all planes from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts* dump)
{
uint16 bps;
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint32 tile_rowsize = TIFFTileRowSize(out);
uint8* bufp = (uint8*) buf;
tsize_t tile_buffsize = 0;
tsize_t tilesize = TIFFTileSize(out);
unsigned char *tilebuf = NULL;
if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) ||
!TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) ||
!TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) )
return 1;
if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0)
{
TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero");
exit(-1);
}
tile_buffsize = tilesize;
if (tilesize < (tsize_t)(tl * tile_rowsize))
{
#ifdef DEBUG2
TIFFError("writeBufferToContigTiles",
"Tilesize %lu is too small, using alternate calculation %u",
tilesize, tl * tile_rowsize);
#endif
tile_buffsize = tl * tile_rowsize;
if (tl != tile_buffsize / tile_rowsize)
{
TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size");
exit(-1);
}
}
tilebuf = _TIFFmalloc(tile_buffsize);
if (tilebuf == 0)
return 1;
src_rowsize = ((imagewidth * spp * bps) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth,
tw, 0, spp, spp, bps, dump) > 0)
{
TIFFError("writeBufferToContigTiles",
"Unable to extract data to tile for row %lu, col %lu",
(unsigned long) row, (unsigned long)col);
_TIFFfree(tilebuf);
return 1;
}
if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0)
{
TIFFError("writeBufferToContigTiles",
"Cannot write tile at %lu %lu",
(unsigned long) col, (unsigned long) row);
_TIFFfree(tilebuf);
return 1;
}
}
}
_TIFFfree(tilebuf);
return 0;
} /* end writeBufferToContigTiles */
/* Extract each plane from contiguous buffer into a single tile buffer
* to be written out as a tile.
*/
static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts * dump)
{
tdata_t obuf = _TIFFmalloc(TIFFTileSize(out));
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint16 bps;
tsample_t s;
uint8* bufp = (uint8*) buf;
if (obuf == NULL)
return 1;
TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
src_rowsize = ((imagewidth * spp * bps) + 7) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
for (s = 0; s < spp; s++)
{
if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,
tw, s, 1, spp, bps, dump) > 0)
{
TIFFError("writeBufferToSeparateTiles",
"Unable to extract data to tile for row %lu, col %lu sample %d",
(unsigned long) row, (unsigned long)col, (int)s);
_TIFFfree(obuf);
return 1;
}
if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
{
TIFFError("writeBufferToseparateTiles",
"Cannot write tile at %lu %lu sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
_TIFFfree(obuf);
return 1;
}
}
}
}
_TIFFfree(obuf);
return 0;
} /* end writeBufferToSeparateTiles */
static void
processG3Options(char* cp)
{
if( (cp = strchr(cp, ':')) ) {
if (defg3opts == (uint32) -1)
defg3opts = 0;
do {
cp++;
if (strneq(cp, "1d", 2))
defg3opts &= ~GROUP3OPT_2DENCODING;
else if (strneq(cp, "2d", 2))
defg3opts |= GROUP3OPT_2DENCODING;
else if (strneq(cp, "fill", 4))
defg3opts |= GROUP3OPT_FILLBITS;
else
usage();
} while( (cp = strchr(cp, ':')) );
}
}
static int
processCompressOptions(char* opt)
{
char* cp = NULL;
if (strneq(opt, "none",4))
{
defcompression = COMPRESSION_NONE;
}
else if (streq(opt, "packbits"))
{
defcompression = COMPRESSION_PACKBITS;
}
else if (strneq(opt, "jpeg", 4))
{
cp = strchr(opt, ':');
defcompression = COMPRESSION_JPEG;
while (cp)
{
if (isdigit((int)cp[1]))
quality = atoi(cp + 1);
else if (strneq(cp + 1, "raw", 3 ))
jpegcolormode = JPEGCOLORMODE_RAW;
else if (strneq(cp + 1, "rgb", 3 ))
jpegcolormode = JPEGCOLORMODE_RGB;
else
usage();
cp = strchr(cp + 1, ':');
}
}
else if (strneq(opt, "g3", 2))
{
processG3Options(opt);
defcompression = COMPRESSION_CCITTFAX3;
}
else if (streq(opt, "g4"))
{
defcompression = COMPRESSION_CCITTFAX4;
}
else if (strneq(opt, "lzw", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_LZW;
}
else if (strneq(opt, "zip", 3))
{
cp = strchr(opt, ':');
if (cp)
defpredictor = atoi(cp+1);
defcompression = COMPRESSION_ADOBE_DEFLATE;
}
else
return (0);
return (1);
}
static void
usage(void)
{
int i;
fprintf(stderr, "\n%s\n", TIFFGetVersion());
for (i = 0; usage_info[i] != NULL; i++)
fprintf(stderr, "%s\n", usage_info[i]);
exit(-1);
}
#define CopyField(tag, v) \
if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
#define CopyField2(tag, v1, v2) \
if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
#define CopyField3(tag, v1, v2, v3) \
if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
#define CopyField4(tag, v1, v2, v3, v4) \
if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
static void
cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
{
switch (type) {
case TIFF_SHORT:
if (count == 1) {
uint16 shortv;
CopyField(tag, shortv);
} else if (count == 2) {
uint16 shortv1, shortv2;
CopyField2(tag, shortv1, shortv2);
} else if (count == 4) {
uint16 *tr, *tg, *tb, *ta;
CopyField4(tag, tr, tg, tb, ta);
} else if (count == (uint16) -1) {
uint16 shortv1;
uint16* shortav;
CopyField2(tag, shortv1, shortav);
}
break;
case TIFF_LONG:
{ uint32 longv;
CopyField(tag, longv);
}
break;
case TIFF_RATIONAL:
if (count == 1) {
float floatv;
CopyField(tag, floatv);
} else if (count == (uint16) -1) {
float* floatav;
CopyField(tag, floatav);
}
break;
case TIFF_ASCII:
{ char* stringv;
CopyField(tag, stringv);
}
break;
case TIFF_DOUBLE:
if (count == 1) {
double doublev;
CopyField(tag, doublev);
} else if (count == (uint16) -1) {
double* doubleav;
CopyField(tag, doubleav);
}
break;
default:
TIFFError(TIFFFileName(in),
"Data type %d is not supported, tag %d skipped",
tag, type);
}
}
static struct cpTag {
uint16 tag;
uint16 count;
TIFFDataType type;
} tags[] = {
{ TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
{ TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
{ TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
{ TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
{ TIFFTAG_MAKE, 1, TIFF_ASCII },
{ TIFFTAG_MODEL, 1, TIFF_ASCII },
{ TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
{ TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
{ TIFFTAG_PAGENAME, 1, TIFF_ASCII },
{ TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
{ TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
{ TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
{ TIFFTAG_DATETIME, 1, TIFF_ASCII },
{ TIFFTAG_ARTIST, 1, TIFF_ASCII },
{ TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
{ TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL },
{ TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
{ TIFFTAG_INKSET, 1, TIFF_SHORT },
{ TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
{ TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
{ TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
{ TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
{ TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
{ TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
{ TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
{ TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE },
{ TIFFTAG_STONITS, 1, TIFF_DOUBLE },
};
#define NTAGS (sizeof (tags) / sizeof (tags[0]))
#define CopyTag(tag, count, type) cpTag(in, out, tag, count, type)
/* Functions written by Richard Nolde, with exceptions noted. */
void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum,
uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth,
uint32 *deftilelength, uint32 *defrowsperstrip,
struct crop_mask *crop_data, struct pagedef *page,
struct dump_opts *dump,
unsigned int *imagelist, unsigned int *image_count )
{
int c, good_args = 0;
char *opt_offset = NULL; /* Position in string of value sought */
char *opt_ptr = NULL; /* Pointer to next token in option set */
char *sep = NULL; /* Pointer to a token separator */
unsigned int i, j, start, end;
#if !HAVE_DECL_OPTARG
extern int optind;
extern char* optarg;
#endif
*mp++ = 'w';
*mp = '\0';
while ((c = getopt(argc, argv,
"ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1)
{
good_args++;
switch (c) {
case 'a': mode[0] = 'a'; /* append to output */
break;
case 'c': if (!processCompressOptions(optarg)) /* compression scheme */
{
TIFFError ("Unknown compression option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */
if (start == 0)
{
TIFFError ("","Directory offset must be greater than zero");
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
*dirnum = start - 1;
break;
case 'e': switch (tolower((int) optarg[0])) /* image export modes*/
{
case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Composite */
case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Divided */
case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE;
crop_data->img_mode = COMPOSITE_IMAGES;
break; /* Image */
case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Multiple */
case 's': crop_data->exp_mode = FILE_PER_SELECTION;
crop_data->img_mode = SEPARATED_IMAGES;
break; /* Sections */
default: TIFFError ("Unknown export mode","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'f': if (streq(optarg, "lsb2msb")) /* fill order */
*deffillorder = FILLORDER_LSB2MSB;
else if (streq(optarg, "msb2lsb"))
*deffillorder = FILLORDER_MSB2LSB;
else
{
TIFFError ("Unknown fill order", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'h': usage();
break;
case 'i': ignore = TRUE; /* ignore errors */
break;
case 'l': outtiled = TRUE; /* tile length */
*deftilelength = atoi(optarg);
break;
case 'p': /* planar configuration */
if (streq(optarg, "separate"))
*defconfig = PLANARCONFIG_SEPARATE;
else if (streq(optarg, "contig"))
*defconfig = PLANARCONFIG_CONTIG;
else
{
TIFFError ("Unkown planar configuration", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'r': /* rows/strip */
*defrowsperstrip = atol(optarg);
break;
case 's': /* generate stripped output */
outtiled = FALSE;
break;
case 't': /* generate tiled output */
outtiled = TRUE;
break;
case 'v': TIFFError("Library Release", "%s", TIFFGetVersion());
TIFFError ("Tiffcrop version", "%s, last updated: %s",
tiffcrop_version_id, tiffcrop_rev_date);
TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler");
TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc");
TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde");
exit (0);
break;
case 'w': /* tile width */
outtiled = TRUE;
*deftilewidth = atoi(optarg);
break;
case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */
crop_data->crop_mode |= CROP_REGIONS;
for (i = 0, opt_ptr = strtok (optarg, ":");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ":")), i++)
{
crop_data->regions++;
if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf",
&crop_data->corners[i].X1, &crop_data->corners[i].Y1,
&crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4)
{
TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);;
}
break;
/* options for file open modes */
case 'B': *mp++ = 'b'; *mp = '\0';
break;
case 'L': *mp++ = 'l'; *mp = '\0';
break;
case 'M': *mp++ = 'm'; *mp = '\0';
break;
case 'C': *mp++ = 'c'; *mp = '\0';
break;
/* options for Debugging / data dump */
case 'D': for (i = 0, opt_ptr = strtok (optarg, ",");
(opt_ptr != NULL);
(opt_ptr = strtok (NULL, ",")), i++)
{
opt_offset = strpbrk(opt_ptr, ":=");
if (opt_offset == NULL)
{
TIFFError("Invalid dump option", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
*opt_offset = '\0';
/* convert option to lowercase */
end = strlen (opt_ptr);
for (i = 0; i < end; i++)
*(opt_ptr + i) = tolower((int) *(opt_ptr + i));
/* Look for dump format specification */
if (strncmp(opt_ptr, "for", 3) == 0)
{
/* convert value to lowercase */
end = strlen (opt_offset + 1);
for (i = 1; i <= end; i++)
*(opt_offset + i) = tolower((int) *(opt_offset + i));
/* check dump format value */
if (strncmp (opt_offset + 1, "txt", 3) == 0)
{
dump->format = DUMP_TEXT;
strcpy (dump->mode, "w");
}
else
{
if (strncmp(opt_offset + 1, "raw", 3) == 0)
{
dump->format = DUMP_RAW;
strcpy (dump->mode, "wb");
}
else
{
TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
}
else
{ /* Look for dump level specification */
if (strncmp (opt_ptr, "lev", 3) == 0)
dump->level = atoi(opt_offset + 1);
/* Look for input data dump file name */
if (strncmp (opt_ptr, "in", 2) == 0)
{
strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20);
dump->infilename[PATH_MAX - 20] = '\0';
}
/* Look for output data dump file name */
if (strncmp (opt_ptr, "out", 3) == 0)
{
strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20);
dump->outfilename[PATH_MAX - 20] = '\0';
}
if (strncmp (opt_ptr, "deb", 3) == 0)
dump->debug = atoi(opt_offset + 1);
}
}
if ((strlen(dump->infilename)) || (strlen(dump->outfilename)))
{
if (dump->level == 1)
TIFFError("","Defaulting to dump level 1, no data.");
if (dump->format == DUMP_NONE)
{
TIFFError("", "You must specify a dump format for dump files");
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
}
break;
/* image manipulation routine options */
case 'm': /* margins to exclude from selection, uppercase M was already used */
/* order of values must be TOP, LEFT, BOTTOM, RIGHT */
crop_data->crop_mode |= CROP_MARGINS;
for (i = 0, opt_ptr = strtok (optarg, ",:");
((opt_ptr != NULL) && (i < 4));
(opt_ptr = strtok (NULL, ",:")), i++)
{
crop_data->margins[i] = atof(opt_ptr);
}
break;
case 'E': /* edge reference */
switch (tolower((int) optarg[0]))
{
case 't': crop_data->edge_ref = EDGE_TOP;
break;
case 'b': crop_data->edge_ref = EDGE_BOTTOM;
break;
case 'l': crop_data->edge_ref = EDGE_LEFT;
break;
case 'r': crop_data->edge_ref = EDGE_RIGHT;
break;
default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'F': /* flip eg mirror image or cropped segment, M was already used */
crop_data->crop_mode |= CROP_MIRROR;
switch (tolower((int) optarg[0]))
{
case 'h': crop_data->mirror = MIRROR_HORIZ;
break;
case 'v': crop_data->mirror = MIRROR_VERT;
break;
case 'b': crop_data->mirror = MIRROR_BOTH;
break;
default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'H': /* set horizontal resolution to new value */
page->hres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'I': /* invert the color space, eg black to white */
crop_data->crop_mode |= CROP_INVERT;
/* The PHOTOMETIC_INTERPRETATION tag may be updated */
if (streq(optarg, "black"))
{
crop_data->photometric = PHOTOMETRIC_MINISBLACK;
continue;
}
if (streq(optarg, "white"))
{
crop_data->photometric = PHOTOMETRIC_MINISWHITE;
continue;
}
if (streq(optarg, "data"))
{
crop_data->photometric = INVERT_DATA_ONLY;
continue;
}
if (streq(optarg, "both"))
{
crop_data->photometric = INVERT_DATA_AND_TAG;
continue;
}
TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
break;
case 'J': /* horizontal margin for sectioned ouput pages */
page->hmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'K': /* vertical margin for sectioned ouput pages*/
page->vmargin = atof(optarg);
page->mode |= PAGE_MODE_MARGINS;
break;
case 'N': /* list of images to process */
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_IMAGES));
(opt_ptr = strtok (NULL, ",")))
{ /* We do not know how many images are in file yet
* so we build a list to include the maximum allowed
* and follow it until we hit the end of the file.
* Image count is not accurate for odd, even, last
* so page numbers won't be valid either.
*/
if (streq(opt_ptr, "odd"))
{
for (j = 1; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = (MAX_IMAGES - 1) / 2;
break;
}
else
{
if (streq(opt_ptr, "even"))
{
for (j = 2; j <= MAX_IMAGES; j += 2)
imagelist[i++] = j;
*image_count = MAX_IMAGES / 2;
break;
}
else
{
if (streq(opt_ptr, "last"))
imagelist[i++] = MAX_IMAGES;
else /* single value between commas */
{
sep = strpbrk(opt_ptr, ":-");
if (!sep)
imagelist[i++] = atoi(opt_ptr);
else
{
*sep = '\0';
start = atoi (opt_ptr);
if (!strcmp((sep + 1), "last"))
end = MAX_IMAGES;
else
end = atoi (sep + 1);
for (j = start; j <= end && j - start + i < MAX_IMAGES; j++)
imagelist[i++] = j;
}
}
}
}
}
*image_count = i;
break;
case 'O': /* page orientation */
switch (tolower((int) optarg[0]))
{
case 'a': page->orient = ORIENTATION_AUTO;
break;
case 'p': page->orient = ORIENTATION_PORTRAIT;
break;
case 'l': page->orient = ORIENTATION_LANDSCAPE;
break;
default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'P': /* page size selection */
if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2)
{
strcpy (page->name, "Custom");
page->mode |= PAGE_MODE_PAPERSIZE;
break;
}
if (get_page_geometry (optarg, page))
{
if (!strcmp(optarg, "list"))
{
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (-1);
}
TIFFError ("Invalid paper size", "%s", optarg);
TIFFError ("", "Select one of:");
TIFFError("", "Name Width Length (in inches)");
for (i = 0; i < MAX_PAPERNAMES - 1; i++)
TIFFError ("", "%-15.15s %5.2f %5.2f",
PaperTable[i].name, PaperTable[i].width,
PaperTable[i].length);
exit (-1);
}
else
{
page->mode |= PAGE_MODE_PAPERSIZE;
}
break;
case 'R': /* rotate image or cropped segment */
crop_data->crop_mode |= CROP_ROTATE;
switch (strtoul(optarg, NULL, 0))
{
case 90: crop_data->rotation = (uint16)90;
break;
case 180: crop_data->rotation = (uint16)180;
break;
case 270: crop_data->rotation = (uint16)270;
break;
default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */
sep = strpbrk(optarg, ",:");
if (sep)
{
*sep = '\0';
page->cols = atoi(optarg);
page->rows = atoi(sep +1);
}
else
{
page->cols = atoi(optarg);
page->rows = atoi(optarg);
}
if ((page->cols * page->rows) > MAX_SECTIONS)
{
TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS);
exit (-1);
}
page->mode |= PAGE_MODE_ROWSCOLS;
break;
case 'U': /* units for measurements and offsets */
if (streq(optarg, "in"))
{
crop_data->res_unit = RESUNIT_INCH;
page->res_unit = RESUNIT_INCH;
}
else if (streq(optarg, "cm"))
{
crop_data->res_unit = RESUNIT_CENTIMETER;
page->res_unit = RESUNIT_CENTIMETER;
}
else if (streq(optarg, "px"))
{
crop_data->res_unit = RESUNIT_NONE;
page->res_unit = RESUNIT_NONE;
}
else
{
TIFFError ("Illegal unit of measure","%s", optarg);
TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
}
break;
case 'V': /* set vertical resolution to new value */
page->vres = atof (optarg);
page->mode |= PAGE_MODE_RESOLUTION;
break;
case 'X': /* selection width */
crop_data->crop_mode |= CROP_WIDTH;
crop_data->width = atof(optarg);
break;
case 'Y': /* selection length */
crop_data->crop_mode |= CROP_LENGTH;
crop_data->length = atof(optarg);
break;
case 'Z': /* zones of an image X:Y read as zone X of Y */
crop_data->crop_mode |= CROP_ZONES;
for (i = 0, opt_ptr = strtok (optarg, ",");
((opt_ptr != NULL) && (i < MAX_REGIONS));
(opt_ptr = strtok (NULL, ",")), i++)
{
crop_data->zones++;
opt_offset = strchr(opt_ptr, ':');
if (!opt_offset) {
TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h");
exit(-1);
}
*opt_offset = '\0';
crop_data->zonelist[i].position = atoi(opt_ptr);
crop_data->zonelist[i].total = atoi(opt_offset + 1);
}
/* check for remaining elements over MAX_REGIONS */
if ((opt_ptr != NULL) && (i >= MAX_REGIONS))
{
TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS);
exit (-1);
}
break;
case '?': TIFFError ("For valid options type", "tiffcrop -h");
exit (-1);
/*NOTREACHED*/
}
}
} /* end process_command_opts */
/* Start a new output file if one has not been previously opened or
* autoindex is set to non-zero. Update page and file counters
* so TIFFTAG PAGENUM will be correct in image.
*/
static int
update_output_file (TIFF **tiffout, char *mode, int autoindex,
char *outname, unsigned int *page)
{
static int findex = 0; /* file sequence indicator */
char *sep;
char filenum[16];
char export_ext[16];
char exportname[PATH_MAX];
if (autoindex && (*tiffout != NULL))
{
/* Close any export file that was previously opened */
TIFFClose (*tiffout);
*tiffout = NULL;
}
strcpy (export_ext, ".tiff");
memset (exportname, '\0', PATH_MAX);
/* Leave room for page number portion of the new filename */
strncpy (exportname, outname, PATH_MAX - 16);
if (*tiffout == NULL) /* This is a new export file */
{
if (autoindex)
{ /* create a new filename for each export */
findex++;
if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF")))
{
strncpy (export_ext, sep, 5);
*sep = '\0';
}
else
strncpy (export_ext, ".tiff", 5);
export_ext[5] = '\0';
/* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */
if (findex > MAX_EXPORT_PAGES)
{
TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES);
return 1;
}
snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext);
filenum[14] = '\0';
strncat (exportname, filenum, 15);
}
exportname[PATH_MAX - 1] = '\0';
*tiffout = TIFFOpen(exportname, mode);
if (*tiffout == NULL)
{
TIFFError("update_output_file", "Unable to open output file %s", exportname);
return 1;
}
*page = 0;
return 0;
}
else
(*page)++;
return 0;
} /* end update_output_file */
int
main(int argc, char* argv[])
{
#if !HAVE_DECL_OPTARG
extern int optind;
#endif
uint16 defconfig = (uint16) -1;
uint16 deffillorder = 0;
uint32 deftilewidth = (uint32) 0;
uint32 deftilelength = (uint32) 0;
uint32 defrowsperstrip = (uint32) 0;
uint32 dirnum = 0;
TIFF *in = NULL;
TIFF *out = NULL;
char mode[10];
char *mp = mode;
/** RJN additions **/
struct image_data image; /* Image parameters for one image */
struct crop_mask crop; /* Cropping parameters for all images */
struct pagedef page; /* Page definition for output pages */
struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */
struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */
struct dump_opts dump; /* Data dump options */
unsigned char *read_buff = NULL; /* Input image data buffer */
unsigned char *crop_buff = NULL; /* Crop area buffer */
unsigned char *sect_buff = NULL; /* Image section buffer */
unsigned char *sect_src = NULL; /* Image section buffer pointer */
unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */
unsigned int image_count = 0;
unsigned int dump_images = 0;
unsigned int next_image = 0;
unsigned int next_page = 0;
unsigned int total_pages = 0;
unsigned int total_images = 0;
unsigned int end_of_input = FALSE;
int seg, length;
char temp_filename[PATH_MAX + 1];
little_endian = *((unsigned char *)&little_endian) & '1';
initImageData(&image);
initCropMasks(&crop);
initPageSetup(&page, sections, seg_buffs);
initDumpOptions(&dump);
process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig,
&deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip,
&crop, &page, &dump, imagelist, &image_count);
if (argc - optind < 2)
usage();
if ((argc - optind) == 2)
pageNum = -1;
else
total_images = 0;
/* read multiple input files and write to output file(s) */
while (optind < argc - 1)
{
in = TIFFOpen (argv[optind], "r");
if (in == NULL)
return (-3);
/* If only one input file is specified, we can use directory count */
total_images = TIFFNumberOfDirectories(in);
if (image_count == 0)
{
dirnum = 0;
total_pages = total_images; /* Only valid with single input file */
}
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
/* Total pages only valid for enumerated list of pages not derived
* using odd, even, or last keywords.
*/
if (image_count > total_images)
image_count = total_images;
total_pages = image_count;
}
/* MAX_IMAGES is used for special case "last" in selection list */
if (dirnum == (MAX_IMAGES - 1))
dirnum = total_images - 1;
if (dirnum > (total_images))
{
TIFFError (TIFFFileName(in),
"Invalid image number %d, File contains only %d images",
(int)dirnum + 1, total_images);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum))
{
TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum);
if (out != NULL)
(void) TIFFClose(out);
return (1);
}
end_of_input = FALSE;
while (end_of_input == FALSE)
{
config = defconfig;
compression = defcompression;
predictor = defpredictor;
fillorder = deffillorder;
rowsperstrip = defrowsperstrip;
tilewidth = deftilewidth;
tilelength = deftilelength;
g3opts = defg3opts;
if (dump.format != DUMP_NONE)
{
/* manage input and/or output dump files here */
dump_images++;
length = strlen(dump.infilename);
if (length > 0)
{
if (dump.infile != NULL)
fclose (dump.infile);
/* dump.infilename is guaranteed to be NUL termimated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s",
dump.infilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (-1);
}
dump_info(dump.infile, dump.format, "Reading image","%d from %s",
dump_images, TIFFFileName(in));
}
length = strlen(dump.outfilename);
if (length > 0)
{
if (dump.outfile != NULL)
fclose (dump.outfile);
/* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes
fewer than PATH_MAX */
snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s",
dump.outfilename, dump_images,
(dump.format == DUMP_TEXT) ? "txt" : "raw");
if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL)
{
TIFFError ("Unable to open dump file for writing", "%s", temp_filename);
exit (-1);
}
dump_info(dump.outfile, dump.format, "Writing image","%d from %s",
dump_images, TIFFFileName(in));
}
}
if (dump.debug)
TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages);
if (loadImage(in, &image, &dump, &read_buff))
{
TIFFError("main", "Unable to load source image");
exit (-1);
}
/* Correct the image orientation if it was not ORIENTATION_TOPLEFT.
*/
if (image.adjustments != 0)
{
if (correct_orientation(&image, &read_buff))
TIFFError("main", "Unable to correct image orientation");
}
if (getCropOffsets(&image, &crop, &dump))
{
TIFFError("main", "Unable to define crop regions");
exit (-1);
}
if (crop.selections > 0)
{
if (processCropSelections(&image, &crop, &read_buff, seg_buffs))
{
TIFFError("main", "Unable to process image selections");
exit (-1);
}
}
else /* Single image segment without zones or regions */
{
if (createCroppedImage(&image, &crop, &read_buff, &crop_buff))
{
TIFFError("main", "Unable to create output image");
exit (-1);
}
}
if (page.mode == PAGE_MODE_NONE)
{ /* Whole image or sections not based on output page size */
if (crop.selections > 0)
{
writeSelections(in, &out, &crop, &image, &dump, seg_buffs,
mp, argv[argc - 1], &next_page, total_pages);
}
else /* One file all images and sections */
{
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1],
&next_page))
exit (1);
if (writeCroppedImage(in, out, &image, &dump,crop.combined_width,
crop.combined_length, crop_buff, next_page, total_pages))
{
TIFFError("main", "Unable to write new image");
exit (-1);
}
}
}
else
{
/* If we used a crop buffer, our data is there, otherwise it is
* in the read_buffer
*/
if (crop_buff != NULL)
sect_src = crop_buff;
else
sect_src = read_buff;
/* Break input image into pages or rows and columns */
if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump))
{
TIFFError("main", "Unable to compute output section data");
exit (-1);
}
/* If there are multiple files on the command line, the final one is assumed
* to be the output filename into which the images are written.
*/
if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page))
exit (1);
if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, §_buff))
{
TIFFError("main", "Unable to write image sections");
exit (-1);
}
}
/* No image list specified, just read the next image */
if (image_count == 0)
dirnum++;
else
{
dirnum = (tdir_t)(imagelist[next_image] - 1);
next_image++;
}
if (dirnum == MAX_IMAGES - 1)
dirnum = TIFFNumberOfDirectories(in) - 1;
if (!TIFFSetDirectory(in, (tdir_t)dirnum))
end_of_input = TRUE;
}
TIFFClose(in);
optind++;
}
/* If we did not use the read buffer as the crop buffer */
if (read_buff)
_TIFFfree(read_buff);
if (crop_buff)
_TIFFfree(crop_buff);
if (sect_buff)
_TIFFfree(sect_buff);
/* Clean up any segment buffers used for zones or regions */
for (seg = 0; seg < crop.selections; seg++)
_TIFFfree (seg_buffs[seg].buffer);
if (dump.format != DUMP_NONE)
{
if (dump.infile != NULL)
fclose (dump.infile);
if (dump.outfile != NULL)
{
dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out));
fclose (dump.outfile);
}
}
TIFFClose(out);
return (0);
} /* end main */
/* Debugging functions */
static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count)
{
int j, k;
uint32 i;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (i = 0; i < count; i++)
{
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s", dump_array);
}
fprintf (dumpfile,"\n");
}
else
{
if ((fwrite (data, 1, count, dumpfile)) != count)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data)
{
int j, k;
char dump_array[10];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
}
dump_array[8] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 1, 1, dumpfile)) != 1)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data)
{
int j, k;
char dump_array[20];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 15; k >= 0; j++, k--)
{
bitset = data & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[17] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 2, 1, dumpfile)) != 2)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data)
{
int j, k;
char dump_array[40];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 31; k >= 0; j++, k--)
{
bitset = data & (((uint32)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[35] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 4, 1, dumpfile)) != 4)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data)
{
int j, k;
char dump_array[80];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 63; k >= 0; j++, k--)
{
bitset = data & (((uint64)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[71] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 8, 1, dumpfile)) != 8)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...)
{
if (format == DUMP_TEXT)
{
va_list ap;
va_start(ap, msg);
fprintf(dumpfile, "%s ", prefix);
vfprintf(dumpfile, msg, ap);
fprintf(dumpfile, "\n");
va_end(ap);
}
}
static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width,
uint32 row, unsigned char *buff)
{
int j, k;
uint32 i;
unsigned char * dump_ptr;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
for (i = 0; i < rows; i++)
{
dump_ptr = buff + (i * width);
if (format == DUMP_TEXT)
dump_info (dumpfile, format, "",
"Row %4d, %d bytes at offset %d",
row + i + 1, width, row * width);
for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10)
dump_data (dumpfile, format, "", dump_ptr, 10);
if (k > 0)
dump_data (dumpfile, format, "", dump_ptr, k);
}
return (0);
}
/* Extract one or more samples from an interleaved buffer. If count == 1,
* only the sample plane indicated by sample will be extracted. If count > 1,
* count samples beginning at sample will be extracted. Portions of a
* scanline can be extracted by specifying a start and end value.
*/
static int
extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int i, bytes_per_sample, sindex;
uint32 col, dst_rowsize, bit_offset;
uint32 src_byte /*, src_bit */;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesBytes","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesBytes",
"Invalid end column value %d ignored", end);
end = cols;
}
dst_rowsize = (bps * (end - start) * count) / 8;
bytes_per_sample = (bps + 7) / 8;
/* Optimize case for copying all samples */
if (count == spp)
{
src = in + (start * spp * bytes_per_sample);
_TIFFmemcpy (dst, src, dst_rowsize);
}
else
{
for (col = start; col < end; col++)
{
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
bit_offset = col * bps * spp;
if (sindex == 0)
{
src_byte = bit_offset / 8;
/* src_bit = bit_offset % 8; */
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
/* src_bit = (bit_offset + (sindex * bps)) % 8; */
}
src = in + src_byte;
for (i = 0; i < bytes_per_sample; i++)
*dst++ = *src++;
}
}
}
return (0);
} /* end extractContigSamplesBytes */
static int
extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = (buff2 | (buff1 >> ready_bits));
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples8bits */
static int
extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamples16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
{
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples16bits */
static int
extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = 0;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples24bits */
static int
extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamples32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamples32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = 0;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamples32bits */
static int
extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted8bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*src) & matchbits) << (src_bit);
if ((col == start) && (sindex == sample))
buff2 = *src & ((uint8)-1) << (shift);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ |= buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
buff2 = buff2 | (buff1 >> ready_bits);
ready_bits += bps;
}
}
while (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted8bits */
static int
extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *src = in;
uint8 *dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted16bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint16)-1 >> (16 - bps);
for (col = start; col < end; col++)
{ /* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint16)-1) << (8 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 8) /* add another bps bits to the buffer */
buff2 = buff2 | (buff1 >> ready_bits);
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted16bits */
static int
extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0;
uint32 col, src_byte, src_bit, bit_offset;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted24bits",
"Invalid end column value %d ignored", end);
end = cols;
}
ready_bits = shift;
maskbits = (uint32)-1 >> ( 32 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
if ((col == start) && (sindex == sample))
buff2 = buff1 & ((uint32)-1) << (16 - shift);
buff1 = (buff1 & matchbits) << (src_bit);
if (ready_bits < 16) /* add another bps bits to the buffer */
{
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted24bits */
static int
extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
tsample_t count, uint32 start, uint32 end,
int shift)
{
int ready_bits = 0, sindex = 0 /*, shift_width = 0 */;
uint32 col, src_byte, src_bit, bit_offset;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *src = in;
uint8 *dst = out;
if ((in == NULL) || (out == NULL))
{
TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer");
return (1);
}
if ((start > end) || (start > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid start column value %d ignored", start);
start = 0;
}
if ((end == 0) || (end > cols))
{
TIFFError ("extractContigSamplesShifted32bits",
"Invalid end column value %d ignored", end);
end = cols;
}
/* shift_width = ((bps + 7) / 8) + 1; */
ready_bits = shift;
maskbits = (uint64)-1 >> ( 64 - bps);
for (col = start; col < end; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps * spp;
for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++)
{
if (sindex == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sindex * bps)) / 8;
src_bit = (bit_offset + (sindex * bps)) % 8;
}
src = in + src_byte;
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
if ((col == start) && (sindex == sample))
buff2 = buff3 & ((uint64)-1) << (32 - shift);
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end extractContigSamplesShifted32bits */
static int
extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
tsample_t sample, uint16 spp, uint16 bps,
struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row, first_col = 0;
uint32 dst_rowsize, dst_offset;
tsample_t count = 1;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src_rowsize = ((bps * spp * cols) + 7) / 8;
dst_rowsize = ((bps * cols) + 7) / 8;
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, first_col, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToBuffer */
static int
extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols,
uint32 imagewidth, uint32 tilewidth, tsample_t sample,
uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, src_offset, row;
uint32 dst_rowsize, dst_offset;
uint8 *src, *dst;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
if ((dump->outfile != NULL) && (dump->level == 4))
{
dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer",
"Sample %d, %d rows", sample + 1, rows + 1);
}
src_rowsize = ((bps * spp * imagewidth) + 7) / 8;
dst_rowsize = ((bps * tilewidth * count) + 7) / 8;
for (row = 0; row < rows; row++)
{
src_offset = row * src_rowsize;
dst_offset = row * dst_rowsize;
src = in + src_offset;
dst = out + dst_offset;
/* pack the data into the scanline */
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 1: if (bps == 1)
{
if (extractContigSamples8bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
}
else
if (extractContigSamples16bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 2: if (extractContigSamples24bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
case 3:
case 4:
case 5: if (extractContigSamples32bits (src, dst, cols, sample,
spp, bps, count, 0, cols))
return (1);
break;
default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps);
return (1);
}
if ((dump->outfile != NULL) && (dump->level == 4))
dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst);
}
return (0);
} /* end extractContigSamplesToTileBuffer */
static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint16 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
static int
combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * spp * cols) + 7) / 8;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
row_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
col_offset = row_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
src += bytes_per_sample;
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamplesBytes */
static int
combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
/* int bytes_per_sample = 0; */
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples8bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples8bits */
static int
combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples16bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples16bits */
static int
combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0 */;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples24bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateSamples24bits */
static int
combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateSamples32bits","Invalid input or output buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
src_rowsize = ((bps * cols) + 7) / 8;
dst_rowsize = ((bps * cols * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateSamples32bits */
static int
combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out,
uint32 cols, uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int i, bytes_per_sample;
uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset;
unsigned char *src;
unsigned char *dst;
tsample_t s;
src = srcbuffs[0];
dst = out;
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address");
return (1);
}
bytes_per_sample = (bps + 7) / 8;
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = imagewidth * bytes_per_sample * spp;
for (row = 0; row < rows; row++)
{
if ((dumpfile != NULL) && (level == 2))
{
for (s = 0; s < spp; s++)
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s);
dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize));
}
}
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
#ifdef DEVELMODE
TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d",
row, src_offset, dst - out);
#endif
for (col = 0; col < cols; col++)
{
col_offset = src_offset + (col * (bps / 8));
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = srcbuffs[s] + col_offset;
for (i = 0; i < bytes_per_sample; i++)
*(dst + i) = *(src + i);
dst += bytes_per_sample;
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamplesBytes */
static int
combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize, src_offset;
uint32 bit_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint8 maskbits = 0, matchbits = 0;
uint8 buff1 = 0, buff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint8)-1 >> ( 8 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (8 - src_bit - bps);
/* load up next sample from each plane */
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
buff1 = ((*src) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
strcpy (action, "Flush");
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Match bits", matchbits);
dump_byte (dumpfile, format, "Src bits", *src);
dump_byte (dumpfile, format, "Buff1 bits", buff1);
dump_byte (dumpfile, format, "Buff2 bits", buff2);
dump_info (dumpfile, format, "","%s", action);
}
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", buff1);
}
}
if ((dumpfile != NULL) && (level >= 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples8bits */
static int
combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint16 maskbits = 0, matchbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint16)-1 >> (16 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (16 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_short (dumpfile, format, "Match bits", matchbits);
dump_data (dumpfile, format, "Src bits", src, 2);
dump_short (dumpfile, format, "Buff1 bits", buff1);
dump_short (dumpfile, format, "Buff2 bits", buff2);
dump_byte (dumpfile, format, "Write byte", bytebuff);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_byte (dumpfile, format, "Final bits", bytebuff);
}
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples16bits */
static int
combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0;
uint32 src_rowsize, dst_rowsize;
uint32 bit_offset, src_offset;
uint32 row, col, src_byte = 0, src_bit = 0;
uint32 maskbits = 0, matchbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint32)-1 >> ( 32 - bps);
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (32 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action);
}
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize));
}
}
return (0);
} /* end combineSeparateTileSamples24bits */
static int
combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols,
uint32 rows, uint32 imagewidth,
uint32 tw, uint16 spp, uint16 bps,
FILE *dumpfile, int format, int level)
{
int ready_bits = 0 /*, shift_width = 0 */;
uint32 src_rowsize, dst_rowsize, bit_offset, src_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 row, col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
tsample_t s;
unsigned char *src = in[0];
unsigned char *dst = out;
char action[8];
if ((src == NULL) || (dst == NULL))
{
TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer");
return (1);
}
src_rowsize = ((bps * tw) + 7) / 8;
dst_rowsize = ((imagewidth * bps * spp) + 7) / 8;
maskbits = (uint64)-1 >> ( 64 - bps);
/* shift_width = ((bps + 7) / 8) + 1; */
for (row = 0; row < rows; row++)
{
ready_bits = 0;
buff1 = buff2 = 0;
dst = out + (row * dst_rowsize);
src_offset = row * src_rowsize;
for (col = 0; col < cols; col++)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = col * bps;
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
matchbits = maskbits << (64 - src_bit - bps);
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
src = in[s] + src_offset + src_byte;
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 32)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
strcpy (action, "Flush");
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
strcpy (action, "Update");
}
ready_bits += bps;
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, s, src_byte, src_bit, dst - out);
dump_wide (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 8);
dump_wide (dumpfile, format, "Buff1 bits ", buff1);
dump_wide (dumpfile, format, "Buff2 bits ", buff2);
dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action);
}
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
if ((dumpfile != NULL) && (level == 3))
{
dump_info (dumpfile, format, "",
"Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d",
row + 1, col + 1, src_byte, src_bit, dst - out);
dump_long (dumpfile, format, "Match bits ", matchbits);
dump_data (dumpfile, format, "Src bits ", src, 4);
dump_long (dumpfile, format, "Buff1 bits ", buff1);
dump_long (dumpfile, format, "Buff2 bits ", buff2);
dump_byte (dumpfile, format, "Write bits1", bytebuff1);
dump_byte (dumpfile, format, "Write bits2", bytebuff2);
dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits);
}
if ((dumpfile != NULL) && (level == 2))
{
dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data");
dump_buffer(dumpfile, format, 1, dst_rowsize, row, out);
}
}
return (0);
} /* end combineSeparateTileSamples32bits */
static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length,
uint32 width, uint16 spp,
struct dump_opts *dump)
{
int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
int32 bytes_read = 0;
uint16 bps, nstrips, planar, strips_per_sample;
uint32 src_rowsize, dst_rowsize, rows_processed, rps;
uint32 rows_this_strip = 0;
tsample_t s;
tstrip_t strip;
tsize_t scanlinesize = TIFFScanlineSize(in);
tsize_t stripsize = TIFFStripSize(in);
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *buff = NULL;
unsigned char *dst = NULL;
if (obuf == NULL)
{
TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument");
return (0);
}
memset (srcbuffs, '\0', sizeof(srcbuffs));
TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
if (rps > length)
rps = length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
src_rowsize = ((bps * width) + 7) / 8;
dst_rowsize = ((bps * width * spp) + 7) / 8;
dst = obuf;
if ((dump->infile != NULL) && (dump->level == 3))
{
dump_info (dump->infile, dump->format, "",
"Image width %d, length %d, Scanline size, %4d bytes",
width, length, scanlinesize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d, Shift width %d",
bps, spp, shift_width);
}
/* Libtiff seems to assume/require that data for separate planes are
* written one complete plane after another and not interleaved in any way.
* Multiple scanlines and possibly strips of the same plane must be
* written before data for any other plane.
*/
nstrips = TIFFNumberOfStrips(in);
strips_per_sample = nstrips /spp;
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
srcbuffs[s] = NULL;
buff = _TIFFmalloc(stripsize);
if (!buff)
{
TIFFError ("readSeparateStripsIntoBuffer",
"Unable to allocate strip read buffer for sample %d", s);
for (i = 0; i < s; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[s] = buff;
}
rows_processed = 0;
for (j = 0; (j < strips_per_sample) && (result == 1); j++)
{
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
strip = (s * strips_per_sample) + j;
bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize);
rows_this_strip = bytes_read / src_rowsize;
if (bytes_read < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu for sample %d",
(unsigned long) strip, s + 1);
result = 0;
break;
}
#ifdef DEVELMODE
TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d",
strip, bytes_read, rows_this_strip, shift_width);
#endif
}
if (rps > rows_this_strip)
rps = rows_this_strip;
dst = obuf + (dst_rowsize * rows_processed);
if ((bps % 8) == 0)
{
if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
}
else
{
switch (shift_width)
{
case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps);
result = 0;
break;
}
}
if ((rows_processed + rps) > length)
{
rows_processed = length;
rps = length - rows_processed;
}
else
rows_processed += rps;
}
/* free any buffers allocated for each plane or scanline and
* any temporary buffers
*/
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
if (buff != NULL)
_TIFFfree(buff);
}
return (result);
} /* end readSeparateStripsIntoBuffer */
static int
get_page_geometry (char *name, struct pagedef *page)
{
char *ptr;
int n;
for (ptr = name; *ptr; ptr++)
*ptr = (char)tolower((int)*ptr);
for (n = 0; n < MAX_PAPERNAMES; n++)
{
if (strcmp(name, PaperTable[n].name) == 0)
{
page->width = PaperTable[n].width;
page->length = PaperTable[n].length;
strncpy (page->name, PaperTable[n].name, 15);
page->name[15] = '\0';
return (0);
}
}
return (1);
}
static void
initPageSetup (struct pagedef *page, struct pageseg *pagelist,
struct buffinfo seg_buffs[])
{
int i;
strcpy (page->name, "");
page->mode = PAGE_MODE_NONE;
page->res_unit = RESUNIT_NONE;
page->hres = 0.0;
page->vres = 0.0;
page->width = 0.0;
page->length = 0.0;
page->hmargin = 0.0;
page->vmargin = 0.0;
page->rows = 0;
page->cols = 0;
page->orient = ORIENTATION_NONE;
for (i = 0; i < MAX_SECTIONS; i++)
{
pagelist[i].x1 = (uint32)0;
pagelist[i].x2 = (uint32)0;
pagelist[i].y1 = (uint32)0;
pagelist[i].y2 = (uint32)0;
pagelist[i].buffsize = (uint32)0;
pagelist[i].position = 0;
pagelist[i].total = 0;
}
for (i = 0; i < MAX_OUTBUFFS; i++)
{
seg_buffs[i].size = 0;
seg_buffs[i].buffer = NULL;
}
}
static void
initImageData (struct image_data *image)
{
image->xres = 0.0;
image->yres = 0.0;
image->width = 0;
image->length = 0;
image->res_unit = RESUNIT_NONE;
image->bps = 0;
image->spp = 0;
image->planar = 0;
image->photometric = 0;
image->orientation = 0;
image->compression = COMPRESSION_NONE;
image->adjustments = 0;
}
static void
initCropMasks (struct crop_mask *cps)
{
int i;
cps->crop_mode = CROP_NONE;
cps->res_unit = RESUNIT_NONE;
cps->edge_ref = EDGE_TOP;
cps->width = 0;
cps->length = 0;
for (i = 0; i < 4; i++)
cps->margins[i] = 0.0;
cps->bufftotal = (uint32)0;
cps->combined_width = (uint32)0;
cps->combined_length = (uint32)0;
cps->rotation = (uint16)0;
cps->photometric = INVERT_DATA_AND_TAG;
cps->mirror = (uint16)0;
cps->invert = (uint16)0;
cps->zones = (uint32)0;
cps->regions = (uint32)0;
for (i = 0; i < MAX_REGIONS; i++)
{
cps->corners[i].X1 = 0.0;
cps->corners[i].X2 = 0.0;
cps->corners[i].Y1 = 0.0;
cps->corners[i].Y2 = 0.0;
cps->regionlist[i].x1 = 0;
cps->regionlist[i].x2 = 0;
cps->regionlist[i].y1 = 0;
cps->regionlist[i].y2 = 0;
cps->regionlist[i].width = 0;
cps->regionlist[i].length = 0;
cps->regionlist[i].buffsize = 0;
cps->regionlist[i].buffptr = NULL;
cps->zonelist[i].position = 0;
cps->zonelist[i].total = 0;
}
cps->exp_mode = ONE_FILE_COMPOSITE;
cps->img_mode = COMPOSITE_IMAGES;
}
static void initDumpOptions(struct dump_opts *dump)
{
dump->debug = 0;
dump->format = DUMP_NONE;
dump->level = 1;
sprintf (dump->mode, "w");
memset (dump->infilename, '\0', PATH_MAX + 1);
memset (dump->outfilename, '\0',PATH_MAX + 1);
dump->infile = NULL;
dump->outfile = NULL;
}
/* Compute pixel offsets into the image for margins and fixed regions */
static int
computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image,
struct offset *off)
{
double scale;
float xres, yres;
/* Values for these offsets are in pixels from start of image, not bytes,
* and are indexed from zero to width - 1 or length - 1 */
uint32 tmargin, bmargin, lmargin, rmargin;
uint32 startx, endx; /* offsets of first and last columns to extract */
uint32 starty, endy; /* offsets of first and last row to extract */
uint32 width, length, crop_width, crop_length;
uint32 i, max_width, max_length, zwidth, zlength, buffsize;
uint32 x1, x2, y1, y2;
if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER)
{
xres = 1.0;
yres = 1.0;
}
else
{
if (((image->xres == 0) || (image->yres == 0)) &&
(crop->res_unit != RESUNIT_NONE) &&
((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))
{
TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution");
TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again");
return (-1);
}
xres = image->xres;
yres = image->yres;
}
/* Translate user units to image units */
scale = 1.0;
switch (crop->res_unit) {
case RESUNIT_CENTIMETER:
if (image->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (image->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
if (crop->crop_mode & CROP_REGIONS)
{
max_width = max_length = 0;
for (i = 0; i < crop->regions; i++)
{
if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER))
{
x1 = (uint32) (crop->corners[i].X1 * scale * xres);
x2 = (uint32) (crop->corners[i].X2 * scale * xres);
y1 = (uint32) (crop->corners[i].Y1 * scale * yres);
y2 = (uint32) (crop->corners[i].Y2 * scale * yres);
}
else
{
x1 = (uint32) (crop->corners[i].X1);
x2 = (uint32) (crop->corners[i].X2);
y1 = (uint32) (crop->corners[i].Y1);
y2 = (uint32) (crop->corners[i].Y2);
}
if (x1 < 1)
crop->regionlist[i].x1 = 0;
else
crop->regionlist[i].x1 = (uint32) (x1 - 1);
if (x2 > image->width - 1)
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = (uint32) (x2 - 1);
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
if (y1 < 1)
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = (uint32) (y1 - 1);
if (y2 > image->length - 1)
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = (uint32) (y2 - 1);
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
if (zwidth > max_width)
max_width = zwidth;
if (zlength > max_length)
max_length = zlength;
buffsize = (uint32)
(((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (crop->img_mode == COMPOSITE_IMAGES)
{
switch (crop->edge_ref)
{
case EDGE_LEFT:
case EDGE_RIGHT:
crop->combined_length = zlength;
crop->combined_width += zwidth;
break;
case EDGE_BOTTOM:
case EDGE_TOP: /* width from left, length from top */
default:
crop->combined_width = zwidth;
crop->combined_length += zlength;
break;
}
}
}
return (0);
}
/* Convert crop margins into offsets into image
* Margins are expressed as pixel rows and columns, not bytes
*/
if (crop->crop_mode & CROP_MARGINS)
{
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{ /* User has specified pixels as reference unit */
tmargin = (uint32)(crop->margins[0]);
lmargin = (uint32)(crop->margins[1]);
bmargin = (uint32)(crop->margins[2]);
rmargin = (uint32)(crop->margins[3]);
}
else
{ /* inches or centimeters specified */
tmargin = (uint32)(crop->margins[0] * scale * yres);
lmargin = (uint32)(crop->margins[1] * scale * xres);
bmargin = (uint32)(crop->margins[2] * scale * yres);
rmargin = (uint32)(crop->margins[3] * scale * xres);
}
if ((lmargin + rmargin) > image->width)
{
TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width");
lmargin = (uint32) 0;
rmargin = (uint32) 0;
return (-1);
}
if ((tmargin + bmargin) > image->length)
{
TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length");
tmargin = (uint32) 0;
bmargin = (uint32) 0;
return (-1);
}
}
else
{ /* no margins requested */
tmargin = (uint32) 0;
lmargin = (uint32) 0;
bmargin = (uint32) 0;
rmargin = (uint32) 0;
}
/* Width, height, and margins are expressed as pixel offsets into image */
if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)
{
if (crop->crop_mode & CROP_WIDTH)
width = (uint32)crop->width;
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = (uint32)crop->length;
else
length = image->length - tmargin - bmargin;
}
else
{
if (crop->crop_mode & CROP_WIDTH)
width = (uint32)(crop->width * scale * image->xres);
else
width = image->width - lmargin - rmargin;
if (crop->crop_mode & CROP_LENGTH)
length = (uint32)(crop->length * scale * image->yres);
else
length = image->length - tmargin - bmargin;
}
off->tmargin = tmargin;
off->bmargin = bmargin;
off->lmargin = lmargin;
off->rmargin = rmargin;
/* Calculate regions defined by margins, width, and length.
* Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,
* since they are used to compute offsets into buffers */
switch (crop->edge_ref) {
case EDGE_BOTTOM:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
endy = image->length - bmargin - 1;
if ((endy - length) <= tmargin)
starty = tmargin;
else
starty = endy - length + 1;
break;
case EDGE_RIGHT:
endx = image->width - rmargin - 1;
if ((endx - width) <= lmargin)
startx = lmargin;
else
startx = endx - width + 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
case EDGE_TOP: /* width from left, length from top */
case EDGE_LEFT:
default:
startx = lmargin;
if ((startx + width) >= (image->width - rmargin))
endx = image->width - rmargin - 1;
else
endx = startx + width - 1;
starty = tmargin;
if ((starty + length) >= (image->length - bmargin))
endy = image->length - bmargin - 1;
else
endy = starty + length - 1;
break;
}
off->startx = startx;
off->starty = starty;
off->endx = endx;
off->endy = endy;
crop_width = endx - startx + 1;
crop_length = endy - starty + 1;
if (crop_width <= 0)
{
TIFFError("computeInputPixelOffsets",
"Invalid left/right margins and /or image crop width requested");
return (-1);
}
if (crop_width > image->width)
crop_width = image->width;
if (crop_length <= 0)
{
TIFFError("computeInputPixelOffsets",
"Invalid top/bottom margins and /or image crop length requested");
return (-1);
}
if (crop_length > image->length)
crop_length = image->length;
off->crop_width = crop_width;
off->crop_length = crop_length;
return (0);
} /* end computeInputPixelOffsets */
/*
* Translate crop options into pixel offsets for one or more regions of the image.
* Options are applied in this order: margins, specific width and length, zones,
* but all are optional. Margins are relative to each edge. Width, length and
* zones are relative to the specified reference edge. Zones are expressed as
* X:Y where X is the ordinal value in a set of Y equal sized portions. eg.
* 2:3 would indicate the middle third of the region qualified by margins and
* any explicit width and length specified. Regions are specified by coordinates
* of the top left and lower right corners with range 1 to width or height.
*/
static int
getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump)
{
struct offset offsets;
int i;
int32 test;
uint32 seg, total, need_buff = 0;
uint32 buffsize;
uint32 zwidth, zlength;
memset(&offsets, '\0', sizeof(struct offset));
crop->bufftotal = 0;
crop->combined_width = (uint32)0;
crop->combined_length = (uint32)0;
crop->selections = 0;
/* Compute pixel offsets if margins or fixed width or length specified */
if ((crop->crop_mode & CROP_MARGINS) ||
(crop->crop_mode & CROP_REGIONS) ||
(crop->crop_mode & CROP_LENGTH) ||
(crop->crop_mode & CROP_WIDTH))
{
if (computeInputPixelOffsets(crop, image, &offsets))
{
TIFFError ("getCropOffsets", "Unable to compute crop margins");
return (-1);
}
need_buff = TRUE;
crop->selections = crop->regions;
/* Regions are only calculated from top and left edges with no margins */
if (crop->crop_mode & CROP_REGIONS)
return (0);
}
else
{ /* cropped area is the full image */
offsets.tmargin = 0;
offsets.lmargin = 0;
offsets.bmargin = 0;
offsets.rmargin = 0;
offsets.crop_width = image->width;
offsets.crop_length = image->length;
offsets.startx = 0;
offsets.endx = image->width - 1;
offsets.starty = 0;
offsets.endy = image->length - 1;
need_buff = FALSE;
}
if (dump->outfile != NULL)
{
dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d",
offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin);
dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d",
offsets.crop_width, offsets.crop_length);
}
if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */
{
if (need_buff == FALSE) /* No margins or fixed width or length areas */
{
crop->selections = 0;
crop->combined_width = image->width;
crop->combined_length = image->length;
return (0);
}
else
{
/* Use one region for margins and fixed width or length areas
* even though it was not formally declared as a region.
*/
crop->selections = 1;
crop->zones = 1;
crop->zonelist[0].total = 1;
crop->zonelist[0].position = 1;
}
}
else
crop->selections = crop->zones;
for (i = 0; i < crop->zones; i++)
{
seg = crop->zonelist[i].position;
total = crop->zonelist[i].total;
switch (crop->edge_ref)
{
case EDGE_LEFT: /* zones from left to right, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * 1.0 * (seg - 1) / total);
test = (int32)offsets.startx +
(int32)(offsets.crop_width * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_BOTTOM: /* width from left, zones from bottom to top */
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y1 = 0;
else
crop->regionlist[i].y1 = test + 1;
test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
case EDGE_RIGHT: /* zones from right to left, length from top */
zlength = offsets.crop_length;
crop->regionlist[i].y1 = offsets.starty;
crop->regionlist[i].y2 = offsets.endy;
crop->regionlist[i].x1 = offsets.startx +
(uint32)(offsets.crop_width * (total - seg) * 1.0 / total);
test = offsets.startx +
(offsets.crop_width * (total - seg + 1) * 1.0 / total);
if (test < 1 )
crop->regionlist[i].x2 = 0;
else
{
if (test > (int32)(image->width - 1))
crop->regionlist[i].x2 = image->width - 1;
else
crop->regionlist[i].x2 = test - 1;
}
zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
crop->combined_length = (uint32)zlength;
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_width += (uint32)zwidth;
else
crop->combined_width = (uint32)zwidth;
break;
case EDGE_TOP: /* width from left, zones from top to bottom */
default:
zwidth = offsets.crop_width;
crop->regionlist[i].x1 = offsets.startx;
crop->regionlist[i].x2 = offsets.endx;
crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total);
test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total);
if (test < 1 )
crop->regionlist[i].y2 = 0;
else
{
if (test > (int32)(image->length - 1))
crop->regionlist[i].y2 = image->length - 1;
else
crop->regionlist[i].y2 = test - 1;
}
zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1;
/* This is passed to extractCropZone or extractCompositeZones */
if (crop->exp_mode == COMPOSITE_IMAGES)
crop->combined_length += (uint32)zlength;
else
crop->combined_length = (uint32)zlength;
crop->combined_width = (uint32)zwidth;
break;
} /* end switch statement */
buffsize = (uint32)
((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1));
crop->regionlist[i].width = (uint32) zwidth;
crop->regionlist[i].length = (uint32) zlength;
crop->regionlist[i].buffsize = buffsize;
crop->bufftotal += buffsize;
if (dump->outfile != NULL)
dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d",
i + 1, (uint32)zwidth, (uint32)zlength,
crop->regionlist[i].x1, crop->regionlist[i].x2,
crop->regionlist[i].y1, crop->regionlist[i].y2);
}
return (0);
} /* end getCropOffsets */
static int
computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts* dump)
{
double scale;
double pwidth, plength; /* Output page width and length in user units*/
uint32 iwidth, ilength; /* Input image width and length in pixels*/
uint32 owidth, olength; /* Output image width and length in pixels*/
uint32 orows, ocols; /* rows and cols for output */
uint32 hmargin, vmargin; /* Horizontal and vertical margins */
uint32 x1, x2, y1, y2, line_bytes;
/* unsigned int orientation; */
uint32 i, j, k;
scale = 1.0;
if (page->res_unit == RESUNIT_NONE)
page->res_unit = image->res_unit;
switch (image->res_unit) {
case RESUNIT_CENTIMETER:
if (page->res_unit == RESUNIT_INCH)
scale = 1.0/2.54;
break;
case RESUNIT_INCH:
if (page->res_unit == RESUNIT_CENTIMETER)
scale = 2.54;
break;
case RESUNIT_NONE: /* Dimensions in pixels */
default:
break;
}
/* get width, height, resolutions of input image selection */
if (crop->combined_width > 0)
iwidth = crop->combined_width;
else
iwidth = image->width;
if (crop->combined_length > 0)
ilength = crop->combined_length;
else
ilength = image->length;
if (page->hres <= 1.0)
page->hres = image->xres;
if (page->vres <= 1.0)
page->vres = image->yres;
if ((page->hres < 1.0) || (page->vres < 1.0))
{
TIFFError("computeOutputPixelOffsets",
"Invalid horizontal or vertical resolution specified or read from input image");
return (1);
}
/* If no page sizes are being specified, we just use the input image size to
* calculate maximum margins that can be taken from image.
*/
if (page->width <= 0)
pwidth = iwidth;
else
pwidth = page->width;
if (page->length <= 0)
plength = ilength;
else
plength = page->length;
if (dump->debug)
{
TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, "
"Hmargin: %3.2f, Vmargin: %3.2f",
page->name, page->vres, page->hres,
page->hmargin, page->vmargin);
TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f",
page->res_unit, scale, pwidth, plength);
}
/* compute margins at specified unit and resolution */
if (page->mode & PAGE_MODE_MARGINS)
{
if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER)
{ /* inches or centimeters specified */
hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8));
vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8));
}
else
{ /* Otherwise user has specified pixels as reference unit */
hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8));
vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8));
}
if ((hmargin * 2.0) > (pwidth * page->hres))
{
TIFFError("computeOutputPixelOffsets",
"Combined left and right margins exceed page width");
hmargin = (uint32) 0;
return (-1);
}
if ((vmargin * 2.0) > (plength * page->vres))
{
TIFFError("computeOutputPixelOffsets",
"Combined top and bottom margins exceed page length");
vmargin = (uint32) 0;
return (-1);
}
}
else
{
hmargin = 0;
vmargin = 0;
}
if (page->mode & PAGE_MODE_ROWSCOLS )
{
/* Maybe someday but not for now */
if (page->mode & PAGE_MODE_MARGINS)
TIFFError("computeOutputPixelOffsets",
"Output margins cannot be specified with rows and columns");
owidth = TIFFhowmany(iwidth, page->cols);
olength = TIFFhowmany(ilength, page->rows);
}
else
{
if (page->mode & PAGE_MODE_PAPERSIZE )
{
owidth = (uint32)((pwidth * page->hres) - (hmargin * 2));
olength = (uint32)((plength * page->vres) - (vmargin * 2));
}
else
{
owidth = (uint32)(iwidth - (hmargin * 2 * page->hres));
olength = (uint32)(ilength - (vmargin * 2 * page->vres));
}
}
if (owidth > iwidth)
owidth = iwidth;
if (olength > ilength)
olength = ilength;
/* Compute the number of pages required for Portrait or Landscape */
switch (page->orient)
{
case ORIENTATION_NONE:
case ORIENTATION_PORTRAIT:
ocols = TIFFhowmany(iwidth, owidth);
orows = TIFFhowmany(ilength, olength);
/* orientation = ORIENTATION_PORTRAIT; */
break;
case ORIENTATION_LANDSCAPE:
ocols = TIFFhowmany(iwidth, olength);
orows = TIFFhowmany(ilength, owidth);
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
break;
case ORIENTATION_AUTO:
default:
x1 = TIFFhowmany(iwidth, owidth);
x2 = TIFFhowmany(ilength, olength);
y1 = TIFFhowmany(iwidth, olength);
y2 = TIFFhowmany(ilength, owidth);
if ( (x1 * x2) < (y1 * y2))
{ /* Portrait */
ocols = x1;
orows = x2;
/* orientation = ORIENTATION_PORTRAIT; */
}
else
{ /* Landscape */
ocols = y1;
orows = y2;
x1 = olength;
olength = owidth;
owidth = x1;
/* orientation = ORIENTATION_LANDSCAPE; */
}
}
if (ocols < 1)
ocols = 1;
if (orows < 1)
orows = 1;
/* If user did not specify rows and cols, set them from calcuation */
if (page->rows < 1)
page->rows = orows;
if (page->cols < 1)
page->cols = ocols;
line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp;
if ((page->rows * page->cols) > MAX_SECTIONS)
{
TIFFError("computeOutputPixelOffsets",
"Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections");
return (-1);
}
/* build the list of offsets for each output section */
for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++)
{
y1 = (uint32)(olength * i);
y2 = (uint32)(olength * (i + 1) - 1);
if (y2 >= ilength)
y2 = ilength - 1;
for (j = 0; j < ocols; j++, k++)
{
x1 = (uint32)(owidth * j);
x2 = (uint32)(owidth * (j + 1) - 1);
if (x2 >= iwidth)
x2 = iwidth - 1;
sections[k].x1 = x1;
sections[k].x2 = x2;
sections[k].y1 = y1;
sections[k].y2 = y2;
sections[k].buffsize = line_bytes * olength;
sections[k].position = k + 1;
sections[k].total = orows * ocols;
}
}
return (0);
} /* end computeOutputPixelOffsets */
static int
loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
{
uint32 i;
float xres = 0.0, yres = 0.0;
uint32 nstrips = 0, ntiles = 0;
uint16 planar = 0;
uint16 bps = 0, spp = 0, res_unit = 0;
uint16 orientation = 0;
uint16 input_compression = 0, input_photometric = 0;
uint16 subsampling_horiz, subsampling_vert;
uint32 width = 0, length = 0;
uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0;
uint32 tw = 0, tl = 0; /* Tile width and length */
uint32 tile_rowsize = 0;
unsigned char *read_buff = NULL;
unsigned char *new_buff = NULL;
int readunit = 0;
static uint32 prev_readsize = 0;
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
TIFFError("loadImage","Image lacks Photometric interpreation tag");
if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
TIFFError("loadimage","Image lacks image width tag");
if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
TIFFError("loadimage","Image lacks image length tag");
TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = RESUNIT_INCH;
if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
char compressionid[16];
switch (input_compression)
{
case COMPRESSION_NONE: /* 1 dump mode */
strcpy (compressionid, "None/dump");
break;
case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
strcpy (compressionid, "Huffman RLE");
break;
case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
strcpy (compressionid, "Group3 Fax");
break;
case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
strcpy (compressionid, "Group4 Fax");
break;
case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
strcpy (compressionid, "LZW");
break;
case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
strcpy (compressionid, "Old Jpeg");
break;
case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
strcpy (compressionid, "New Jpeg");
break;
case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
strcpy (compressionid, "Next RLE");
break;
case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
strcpy (compressionid, "CITTRLEW");
break;
case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
strcpy (compressionid, "Mac Packbits");
break;
case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
strcpy (compressionid, "Thunderscan");
break;
case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
strcpy (compressionid, "IT8 padded");
break;
case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
strcpy (compressionid, "IT8 RLE");
break;
case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
strcpy (compressionid, "IT8 mono");
break;
case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
strcpy (compressionid, "IT8 lineart");
break;
case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
strcpy (compressionid, "Pixar 10 bit");
break;
case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
strcpy (compressionid, "Pixar 11bit");
break;
case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
strcpy (compressionid, "Deflate");
break;
case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
strcpy (compressionid, "Adobe deflate");
break;
default:
strcpy (compressionid, "None/unknown");
break;
}
TIFFError("loadImage", "Input compression %s", compressionid);
#endif
scanlinesize = TIFFScanlineSize(in);
image->bps = bps;
image->spp = spp;
image->planar = planar;
image->width = width;
image->length = length;
image->xres = xres;
image->yres = yres;
image->res_unit = res_unit;
image->compression = input_compression;
image->photometric = input_photometric;
#ifdef DEBUG2
char photometricid[12];
switch (input_photometric)
{
case PHOTOMETRIC_MINISWHITE:
strcpy (photometricid, "MinIsWhite");
break;
case PHOTOMETRIC_MINISBLACK:
strcpy (photometricid, "MinIsBlack");
break;
case PHOTOMETRIC_RGB:
strcpy (photometricid, "RGB");
break;
case PHOTOMETRIC_PALETTE:
strcpy (photometricid, "Palette");
break;
case PHOTOMETRIC_MASK:
strcpy (photometricid, "Mask");
break;
case PHOTOMETRIC_SEPARATED:
strcpy (photometricid, "Separated");
break;
case PHOTOMETRIC_YCBCR:
strcpy (photometricid, "YCBCR");
break;
case PHOTOMETRIC_CIELAB:
strcpy (photometricid, "CIELab");
break;
case PHOTOMETRIC_ICCLAB:
strcpy (photometricid, "ICCLab");
break;
case PHOTOMETRIC_ITULAB:
strcpy (photometricid, "ITULab");
break;
case PHOTOMETRIC_LOGL:
strcpy (photometricid, "LogL");
break;
case PHOTOMETRIC_LOGLUV:
strcpy (photometricid, "LOGLuv");
break;
default:
strcpy (photometricid, "Unknown");
break;
}
TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
#endif
image->orientation = orientation;
switch (orientation)
{
case 0:
case ORIENTATION_TOPLEFT:
image->adjustments = 0;
break;
case ORIENTATION_TOPRIGHT:
image->adjustments = MIRROR_HORIZ;
break;
case ORIENTATION_BOTRIGHT:
image->adjustments = ROTATECW_180;
break;
case ORIENTATION_BOTLEFT:
image->adjustments = MIRROR_VERT;
break;
case ORIENTATION_LEFTTOP:
image->adjustments = MIRROR_VERT | ROTATECW_90;
break;
case ORIENTATION_RIGHTTOP:
image->adjustments = ROTATECW_90;
break;
case ORIENTATION_RIGHTBOT:
image->adjustments = MIRROR_VERT | ROTATECW_270;
break;
case ORIENTATION_LEFTBOT:
image->adjustments = ROTATECW_270;
break;
default:
image->adjustments = 0;
image->orientation = ORIENTATION_TOPLEFT;
}
if ((bps == 0) || (spp == 0))
{
TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)",
spp, bps);
return (-1);
}
if (TIFFIsTiled(in))
{
readunit = TILE;
tlsize = TIFFTileSize(in);
ntiles = TIFFNumberOfTiles(in);
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
tile_rowsize = TIFFTileRowSize(in);
if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
{
TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
exit(-1);
}
buffsize = tlsize * ntiles;
if (tlsize != (buffsize / ntiles))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
if (buffsize < (uint32)(ntiles * tl * tile_rowsize))
{
buffsize = ntiles * tl * tile_rowsize;
if (ntiles != (buffsize / tl / tile_rowsize))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
#ifdef DEBUG2
TIFFError("loadImage",
"Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu",
tlsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Tilesize: %u, Number of Tiles: %u, Tile row size: %u",
tlsize, ntiles, tile_rowsize);
}
else
{
uint32 buffsize_check;
readunit = STRIP;
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
stsize = TIFFStripSize(in);
nstrips = TIFFNumberOfStrips(in);
if (nstrips == 0 || stsize == 0)
{
TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
exit(-1);
}
buffsize = stsize * nstrips;
if (stsize != (buffsize / nstrips))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
buffsize_check = ((length * width * spp * bps) + 7);
if (length != ((buffsize_check - 7) / width / spp / bps))
{
TIFFError("loadImage", "Integer overflow detected.");
exit(-1);
}
if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8))
{
buffsize = ((length * width * spp * bps) + 7) / 8;
#ifdef DEBUG2
TIFFError("loadImage",
"Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu",
stsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u",
stsize, nstrips, rowsperstrip, scanlinesize);
}
if (input_compression == COMPRESSION_JPEG)
{ /* Force conversion to RGB */
jpegcolormode = JPEGCOLORMODE_RGB;
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
/* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
else
{ /* Otherwise, can't handle subsampled input */
if (input_photometric == PHOTOMETRIC_YCBCR)
{
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsampling_horiz, &subsampling_vert);
if (subsampling_horiz != 1 || subsampling_vert != 1)
{
TIFFError("loadImage",
"Can't copy/convert subsampled image with subsampling %d horiz %d vert",
subsampling_horiz, subsampling_vert);
return (-1);
}
}
}
read_buff = *read_ptr;
/* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
/* outside buffer */
if (!read_buff)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
{
if (prev_readsize < buffsize)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
new_buff = _TIFFrealloc(read_buff, buffsize+3);
if (!new_buff)
{
free (read_buff);
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
read_buff = new_buff;
}
}
if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff[buffsize] = 0;
read_buff[buffsize+1] = 0;
read_buff[buffsize+2] = 0;
prev_readsize = buffsize;
*read_ptr = read_buff;
/* N.B. The read functions used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
*/
switch (readunit) {
case STRIP:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigStripsIntoBuffer(in, read_buff)))
{
TIFFError("loadImage", "Unable to read contiguous strips into buffer");
return (-1);
}
}
else
{
if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
{
TIFFError("loadImage", "Unable to read separate strips into buffer");
return (-1);
}
}
break;
case TILE:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
return (-1);
}
}
else
{
if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read separate tiles into buffer");
return (-1);
}
}
break;
default: TIFFError("loadImage", "Unsupported image file format");
return (-1);
break;
}
if ((dump->infile != NULL) && (dump->level == 2))
{
dump_info (dump->infile, dump->format, "loadImage",
"Image width %d, length %d, Raw image data, %4d bytes",
width, length, buffsize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d", bps, spp);
for (i = 0; i < length; i++)
dump_buffer(dump->infile, dump->format, 1, scanlinesize,
i, read_buff + (i * scanlinesize));
}
return (0);
} /* end loadImage */
static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr)
{
uint16 mirror, rotation;
unsigned char *work_buff;
work_buff = *work_buff_ptr;
if ((image == NULL) || (work_buff == NULL))
{
TIFFError ("correct_orientatin", "Invalid image or buffer pointer");
return (-1);
}
if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT))
{
mirror = (uint16)(image->adjustments & MIRROR_BOTH);
if (mirrorImage(image->spp, image->bps, mirror,
image->width, image->length, work_buff))
{
TIFFError ("correct_orientation", "Unable to mirror image");
return (-1);
}
}
if (image->adjustments & ROTATE_ANY)
{
if (image->adjustments & ROTATECW_90)
rotation = (uint16) 90;
else
if (image->adjustments & ROTATECW_180)
rotation = (uint16) 180;
else
if (image->adjustments & ROTATECW_270)
rotation = (uint16) 270;
else
{
TIFFError ("correct_orientation", "Invalid rotation value: %d",
image->adjustments & ROTATE_ANY);
return (-1);
}
if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr))
{
TIFFError ("correct_orientation", "Unable to rotate image");
return (-1);
}
image->orientation = ORIENTATION_TOPLEFT;
}
return (0);
} /* end correct_orientation */
/* Extract multiple zones from an image and combine into a single composite image */
static int
extractCompositeRegions(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff)
{
int shift_width, bytes_per_sample, bytes_per_pixel;
uint32 i, trailing_bits, prev_trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_rowsize, dst_rowsize, src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint32 prev_length, prev_width, composite_width;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract one or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0;
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
src = read_buff;
dst = crop_buff;
/* These are setup for adding additional sections */
prev_width = prev_length = 0;
prev_trailing_bits = trailing_bits = 0;
composite_width = crop->combined_width;
crop->combined_width = 0;
crop->combined_length = 0;
for (i = 0; i < crop->selections; i++)
{
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[i].y1;
last_row = crop->regionlist[i].y2;
first_col = crop->regionlist[i].x1;
last_col = crop->regionlist[i].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
/* These should not be needed for composite images */
crop->regionlist[i].width = crop_width;
crop->regionlist[i].length = crop_length;
crop->regionlist[i].buffptr = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * count) + 7) / 8);
switch (crop->edge_ref)
{
default:
case EDGE_TOP:
case EDGE_BOTTOM:
if ((i > 0) && (crop_width != crop->regionlist[i - 1].width))
{
TIFFError ("extractCompositeRegions",
"Only equal width regions can be combined for -E top or bottom");
return (1);
}
crop->combined_width = crop_width;
crop->combined_length += crop_length;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + (prev_length * dst_rowsize);
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_length += crop_length;
break;
case EDGE_LEFT: /* splice the pieces of each row together, side by side */
case EDGE_RIGHT:
if ((i > 0) && (crop_length != crop->regionlist[i - 1].length))
{
TIFFError ("extractCompositeRegions",
"Only equal length regions can be combined for -E left or right");
return (1);
}
crop->combined_width += crop_width;
crop->combined_length = crop_length;
dst_rowsize = (((composite_width * bps * count) + 7) / 8);
trailing_bits = (crop_width * bps * count) % 8;
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset + prev_width;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractCompositeRegions",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps);
return (1);
}
}
prev_width += (crop_width * bps * count) / 8;
prev_trailing_bits += trailing_bits;
if (prev_trailing_bits > 7)
prev_trailing_bits-= 8;
break;
}
}
if (crop->combined_width != composite_width)
TIFFError("combineSeparateRegions","Combined width does not match composite width");
return (0);
} /* end extractCompositeRegions */
/* Copy a single region of input buffer to an output buffer.
* The read functions used copy separate plane data into a buffer
* as interleaved samples rather than separate planes so the same
* logic works to extract regions regardless of the way the data
* are organized in the input file. This function can be used to
* extract one or more samples from the input image by updating the
* parameters for starting sample and number of samples to copy in the
* fifth and eighth arguments of the call to extractContigSamples.
* They would be passed as new elements of the crop_mask struct.
*/
static int
extractSeparateRegion(struct image_data *image, struct crop_mask *crop,
unsigned char *read_buff, unsigned char *crop_buff,
int region)
{
int shift_width, prev_trailing_bits = 0;
uint32 bytes_per_sample, bytes_per_pixel;
uint32 src_rowsize, dst_rowsize;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset;
uint32 crop_width, crop_length, img_width /*, img_length */;
uint16 bps, spp;
uint8 *src, *dst;
tsample_t count, sample = 0; /* Update to extract more or more samples */
img_width = image->width;
/* img_length = image->length; */
bps = image->bps;
spp = image->spp;
count = spp;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if ((bps % 8) == 0)
shift_width = 0; /* Byte aligned data only */
else
{
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
}
/* rows, columns, width, length are expressed in pixels */
first_row = crop->regionlist[region].y1;
last_row = crop->regionlist[region].y2;
first_col = crop->regionlist[region].x1;
last_col = crop->regionlist[region].x2;
crop_width = last_col - first_col + 1;
crop_length = last_row - first_row + 1;
crop->regionlist[region].width = crop_width;
crop->regionlist[region].length = crop_length;
crop->regionlist[region].buffptr = crop_buff;
src = read_buff;
dst = crop_buff;
src_rowsize = ((img_width * bps * spp) + 7) / 8;
dst_rowsize = (((crop_width * bps * spp) + 7) / 8);
for (row = first_row; row <= last_row; row++)
{
src_offset = row * src_rowsize;
dst_offset = (row - first_row) * dst_rowsize;
src = read_buff + src_offset;
dst = crop_buff + dst_offset;
switch (shift_width)
{
case 0: if (extractContigSamplesBytes (src, dst, img_width, sample,
spp, bps, count, first_col,
last_col + 1))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 1: if (bps == 1)
{
if (extractContigSamplesShifted8bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
}
else
if (extractContigSamplesShifted16bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 2: if (extractContigSamplesShifted24bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
case 3:
case 4:
case 5: if (extractContigSamplesShifted32bits (src, dst, img_width,
sample, spp, bps, count,
first_col, last_col + 1,
prev_trailing_bits))
{
TIFFError("extractSeparateRegion",
"Unable to extract row %d", row);
return (1);
}
break;
default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps);
return (1);
}
}
return (0);
} /* end extractSeparateRegion */
static int
extractImageSection(struct image_data *image, struct pageseg *section,
unsigned char *src_buff, unsigned char *sect_buff)
{
unsigned char bytebuff1, bytebuff2;
#ifdef DEVELMODE
/* unsigned char *src, *dst; */
#endif
uint32 img_width, img_rowsize;
#ifdef DEVELMODE
uint32 img_length;
#endif
uint32 j, shift1, shift2, trailing_bits;
uint32 row, first_row, last_row, first_col, last_col;
uint32 src_offset, dst_offset, row_offset, col_offset;
uint32 offset1, offset2, full_bytes;
uint32 sect_width;
#ifdef DEVELMODE
uint32 sect_length;
#endif
uint16 bps, spp;
#ifdef DEVELMODE
int k;
unsigned char bitset;
static char *bitarray = NULL;
#endif
img_width = image->width;
#ifdef DEVELMODE
img_length = image->length;
#endif
bps = image->bps;
spp = image->spp;
#ifdef DEVELMODE
/* src = src_buff; */
/* dst = sect_buff; */
#endif
src_offset = 0;
dst_offset = 0;
#ifdef DEVELMODE
if (bitarray == NULL)
{
if ((bitarray = (char *)malloc(img_width)) == NULL)
{
TIFFError ("", "DEBUG: Unable to allocate debugging bitarray");
return (-1);
}
}
#endif
/* rows, columns, width, length are expressed in pixels */
first_row = section->y1;
last_row = section->y2;
first_col = section->x1;
last_col = section->x2;
sect_width = last_col - first_col + 1;
#ifdef DEVELMODE
sect_length = last_row - first_row + 1;
#endif
img_rowsize = ((img_width * bps + 7) / 8) * spp;
full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */
trailing_bits = (sect_width * bps) % 8;
#ifdef DEVELMODE
TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n",
first_row, last_row, first_col, last_col);
TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n",
img_width, img_length, bps, spp);
TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n",
sect_width, sect_length, full_bytes, trailing_bits);
#endif
if ((bps % 8) == 0)
{
col_offset = first_col * spp * bps / 8;
for (row = first_row; row <= last_row; row++)
{
/* row_offset = row * img_width * spp * bps / 8; */
row_offset = row * img_rowsize;
src_offset = row_offset + col_offset;
#ifdef DEVELMODE
TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset);
#endif
_TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes);
dst_offset += full_bytes;
}
}
else
{ /* bps != 8 */
shift1 = spp * ((first_col * bps) % 8);
shift2 = spp * ((last_col * bps) % 8);
for (row = first_row; row <= last_row; row++)
{
/* pull out the first byte */
row_offset = row * img_rowsize;
offset1 = row_offset + (first_col * bps / 8);
offset2 = row_offset + (last_col * bps / 8);
#ifdef DEVELMODE
for (j = 0, k = 7; j < 8; j++, k--)
{
bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
sprintf(&bitarray[8], " ");
sprintf(&bitarray[9], " ");
for (j = 10, k = 7; j < 18; j++, k--)
{
bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[18] = '\0';
TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n",
row, offset1, shift1, offset2, shift2);
#endif
bytebuff1 = bytebuff2 = 0;
if (shift1 == 0) /* the region is byte and sample alligned */
{
_TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes);
#ifdef DEVELMODE
TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset);
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2));
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n",
offset2, dst_offset);
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
else /* each destination byte will have to be built from two source bytes*/
{
#ifdef DEVELMODE
TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset);
#endif
for (j = 0; j <= full_bytes; j++)
{
bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1);
bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1));
sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1));
}
#ifdef DEVELMODE
sprintf(&bitarray[18], "\n");
sprintf(&bitarray[19], "\t");
for (j = 20, k = 7; j < 28; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[28] = ' ';
bitarray[29] = ' ';
#endif
dst_offset += full_bytes;
if (trailing_bits != 0)
{
#ifdef DEVELMODE
TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset);
#endif
if (shift2 > shift1)
{
bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2));
bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1);
sect_buff[dst_offset] = bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Shift2 > Shift1\n");
#endif
}
else
{
if (shift2 < shift1)
{
bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1));
sect_buff[dst_offset] &= bytebuff2;
#ifdef DEVELMODE
TIFFError ("", " Shift2 < Shift1\n");
#endif
}
#ifdef DEVELMODE
else
TIFFError ("", " Shift2 == Shift1\n");
#endif
}
}
#ifdef DEVELMODE
sprintf(&bitarray[28], " ");
sprintf(&bitarray[29], " ");
for (j = 30, k = 7; j < 38; j++, k--)
{
bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0;
sprintf(&bitarray[j], (bitset) ? "1" : "0");
}
bitarray[38] = '\0';
TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray);
#endif
dst_offset++;
}
}
}
return (0);
} /* end extractImageSection */
static int
writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop,
struct image_data *image, struct dump_opts *dump,
struct buffinfo seg_buffs[], char *mp, char *filename,
unsigned int *page, unsigned int total_pages)
{
int i, page_count;
int autoindex = 0;
unsigned char *crop_buff = NULL;
/* Where we open a new file depends on the export mode */
switch (crop->exp_mode)
{
case ONE_FILE_COMPOSITE: /* Regions combined into single image */
autoindex = 0;
crop_buff = seg_buffs[0].buffer;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = total_pages;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case ONE_FILE_SEPARATED: /* Regions as separated images */
autoindex = 0;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
page_count = crop->selections * total_pages;
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */
autoindex = 1;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[0].buffer;
if (writeCroppedImage(in, *out, image, dump,
crop->combined_width,
crop->combined_length,
crop_buff, *page, total_pages))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
break;
case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */
autoindex = 1;
page_count = crop->selections;
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
for (i = 0; i < crop->selections; i++)
{
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
case FILE_PER_SELECTION:
autoindex = 1;
page_count = 1;
for (i = 0; i < crop->selections; i++)
{
if (update_output_file (out, mp, autoindex, filename, page))
return (1);
crop_buff = seg_buffs[i].buffer;
/* Write the current region to the current file */
if (writeCroppedImage(in, *out, image, dump,
crop->regionlist[i].width,
crop->regionlist[i].length,
crop_buff, *page, page_count))
{
TIFFError("writeRegions", "Unable to write new image");
return (-1);
}
}
break;
default: return (1);
}
return (0);
} /* end writeRegions */
static int
writeImageSections(TIFF *in, TIFF *out, struct image_data *image,
struct pagedef *page, struct pageseg *sections,
struct dump_opts * dump, unsigned char *src_buff,
unsigned char **sect_buff_ptr)
{
double hres, vres;
uint32 i, k, width, length, sectsize;
unsigned char *sect_buff = *sect_buff_ptr;
hres = page->hres;
vres = page->vres;
k = page->cols * page->rows;
if ((k < 1) || (k > MAX_SECTIONS))
{
TIFFError("writeImageSections",
"%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k);
return (-1);
}
for (i = 0; i < k; i++)
{
width = sections[i].x2 - sections[i].x1 + 1;
length = sections[i].y2 - sections[i].y1 + 1;
sectsize = (uint32)
ceil((width * image->bps + 7) / (double)8) * image->spp * length;
/* allocate a buffer if we don't have one already */
if (createImageSection(sectsize, sect_buff_ptr))
{
TIFFError("writeImageSections", "Unable to allocate section buffer");
exit (-1);
}
sect_buff = *sect_buff_ptr;
if (extractImageSection (image, §ions[i], src_buff, sect_buff))
{
TIFFError("writeImageSections", "Unable to extract image sections");
exit (-1);
}
/* call the write routine here instead of outside the loop */
if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff))
{
TIFFError("writeImageSections", "Unable to write image section");
exit (-1);
}
}
return (0);
} /* end writeImageSections */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
*/
static int
writeSingleSection(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
double hres, double vres,
unsigned char *sect_buff)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
/* Calling this seems to reset the compression mode on the TIFF *in file.
TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode);
*/
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
/* This is the global variable compression which is set
* if the user has specified a command line option for
* a compression option. Should be passed around in one
* of the parameters instead of as a global. If no user
* option specified it will still be (uint16) -1. */
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{ /* OJPEG is no longer supported for writing so upgrade to JPEG */
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else /* Use the compression from the input file */
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */
{
TIFFError ("writeSingleSection",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
#ifdef DEBUG2
TIFFError("writeSingleSection", "Input photometric: %s",
(input_photometric == PHOTOMETRIC_RGB) ? "RGB" :
((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr"));
#endif
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeSingleSection",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
/* These are references to GLOBAL variables set by defaults
* and /or the compression flag
*/
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeSingleSection",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += (strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
if (pageNum < 0) /* only one input file */
TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1);
else
TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Update these since they are overwritten from input res by loop above */
TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres);
TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigTiles (out, sect_buff, length, width, spp, dump);
else
writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump);
}
else
{
if (config == PLANARCONFIG_CONTIG)
writeBufferToContigStrips (out, sect_buff, length);
else
writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump);
}
if (!TIFFWriteDirectory(out))
{
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeSingleSection */
/* Create a buffer to write one section at a time */
static int
createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr)
{
unsigned char *sect_buff = NULL;
unsigned char *new_buff = NULL;
static uint32 prev_sectsize = 0;
sect_buff = *sect_buff_ptr;
if (!sect_buff)
{
sect_buff = (unsigned char *)_TIFFmalloc(sectsize);
*sect_buff_ptr = sect_buff;
_TIFFmemset(sect_buff, 0, sectsize);
}
else
{
if (prev_sectsize < sectsize)
{
new_buff = _TIFFrealloc(sect_buff, sectsize);
if (!new_buff)
{
free (sect_buff);
sect_buff = (unsigned char *)_TIFFmalloc(sectsize);
}
else
sect_buff = new_buff;
_TIFFmemset(sect_buff, 0, sectsize);
}
}
if (!sect_buff)
{
TIFFError("createImageSection", "Unable to allocate/reallocate section buffer");
return (-1);
}
prev_sectsize = sectsize;
*sect_buff_ptr = sect_buff;
return (0);
} /* end createImageSection */
/* Process selections defined by regions, zones, margins, or fixed sized areas */
static int
processCropSelections(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, struct buffinfo seg_buffs[])
{
int i;
uint32 width, length, total_width, total_length;
tsize_t cropsize;
unsigned char *crop_buff = NULL;
unsigned char *read_buff = NULL;
unsigned char *next_buff = NULL;
tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
if (crop->img_mode == COMPOSITE_IMAGES)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[0].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize);
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = cropsize;
/* Checks for matching width or length as required */
if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0)
return (1);
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for composite regions");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
/* Mirror and Rotate will not work with multiple regions unless they are the same width */
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror composite regions %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, &crop_buff))
{
TIFFError("processCropSelections",
"Failed to rotate composite regions by %d degrees", crop->rotation);
return (-1);
}
seg_buffs[0].buffer = crop_buff;
seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8)
* image->spp) * crop->combined_length;
}
}
else /* Separated Images */
{
total_width = total_length = 0;
for (i = 0; i < crop->selections; i++)
{
cropsize = crop->bufftotal;
crop_buff = seg_buffs[i].buffer;
if (!crop_buff)
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
else
{
prev_cropsize = seg_buffs[0].size;
if (prev_cropsize < cropsize)
{
next_buff = _TIFFrealloc(crop_buff, cropsize);
if (! next_buff)
{
_TIFFfree (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = next_buff;
}
}
if (!crop_buff)
{
TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer");
return (-1);
}
_TIFFmemset(crop_buff, 0, cropsize);
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = cropsize;
if (extractSeparateRegion(image, crop, read_buff, crop_buff, i))
{
TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i);
return (-1);
}
width = crop->regionlist[i].width;
length = crop->regionlist[i].length;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
width, length, crop_buff))
{
TIFFError("processCropSelections",
"Failed to invert colorspace for region");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
width, length, crop_buff))
{
TIFFError("processCropSelections", "Failed to mirror crop region %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->regionlist[i].width,
&crop->regionlist[i].length, &crop_buff))
{
TIFFError("processCropSelections",
"Failed to rotate crop region by %d degrees", crop->rotation);
return (-1);
}
total_width += crop->regionlist[i].width;
total_length += crop->regionlist[i].length;
crop->combined_width = total_width;
crop->combined_length = total_length;
seg_buffs[i].buffer = crop_buff;
seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8)
* image->spp) * crop->regionlist[i].length;
}
}
}
return (0);
} /* end processCropSelections */
/* Copy the crop section of the data from the current image into a buffer
* and adjust the IFD values to reflect the new size. If no cropping is
* required, use the origial read buffer as the crop buffer.
*
* There is quite a bit of redundancy between this routine and the more
* specialized processCropSelections, but this provides
* the most optimized path when no Zones or Regions are required.
*/
static int
createCroppedImage(struct image_data *image, struct crop_mask *crop,
unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr)
{
tsize_t cropsize;
unsigned char *read_buff = NULL;
unsigned char *crop_buff = NULL;
unsigned char *new_buff = NULL;
static tsize_t prev_cropsize = 0;
read_buff = *read_buff_ptr;
/* process full image, no crop buffer needed */
crop_buff = read_buff;
*crop_buff_ptr = read_buff;
crop->combined_width = image->width;
crop->combined_length = image->length;
cropsize = crop->bufftotal;
crop_buff = *crop_buff_ptr;
if (!crop_buff)
{
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
*crop_buff_ptr = crop_buff;
_TIFFmemset(crop_buff, 0, cropsize);
prev_cropsize = cropsize;
}
else
{
if (prev_cropsize < cropsize)
{
new_buff = _TIFFrealloc(crop_buff, cropsize);
if (!new_buff)
{
free (crop_buff);
crop_buff = (unsigned char *)_TIFFmalloc(cropsize);
}
else
crop_buff = new_buff;
_TIFFmemset(crop_buff, 0, cropsize);
}
}
if (!crop_buff)
{
TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer");
return (-1);
}
*crop_buff_ptr = crop_buff;
if (crop->crop_mode & CROP_INVERT)
{
switch (crop->photometric)
{
/* Just change the interpretation */
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
image->photometric = crop->photometric;
break;
case INVERT_DATA_ONLY:
case INVERT_DATA_AND_TAG:
if (invertImage(image->photometric, image->spp, image->bps,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage",
"Failed to invert colorspace for image or cropped selection");
return (-1);
}
if (crop->photometric == INVERT_DATA_AND_TAG)
{
switch (image->photometric)
{
case PHOTOMETRIC_MINISWHITE:
image->photometric = PHOTOMETRIC_MINISBLACK;
break;
case PHOTOMETRIC_MINISBLACK:
image->photometric = PHOTOMETRIC_MINISWHITE;
break;
default:
break;
}
}
break;
default: break;
}
}
if (crop->crop_mode & CROP_MIRROR)
{
if (mirrorImage(image->spp, image->bps, crop->mirror,
crop->combined_width, crop->combined_length, crop_buff))
{
TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s",
(crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically");
return (-1);
}
}
if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */
{
if (rotateImage(crop->rotation, image, &crop->combined_width,
&crop->combined_length, crop_buff_ptr))
{
TIFFError("createCroppedImage",
"Failed to rotate image or cropped selection by %d degrees", crop->rotation);
return (-1);
}
}
if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */
*read_buff_ptr = NULL; /* so we don't try to free it later */
return (0);
} /* end createCroppedImage */
/* Code in this function is heavily indebted to code in tiffcp
* with modifications by Richard Nolde to handle orientation correctly.
* It will have to be updated significantly if support is added to
* extract one or more samples from original image since the
* original code assumes we are always copying all samples.
* Use of global variables for config, compression and others
* should be replaced by addition to the crop_mask struct (which
* will be renamed to proc_opts indicating that is controlls
* user supplied processing options, not just cropping) and
* then passed in as an argument.
*/
static int
writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image,
struct dump_opts *dump, uint32 width, uint32 length,
unsigned char *crop_buff, int pagenum, int total_pages)
{
uint16 bps, spp;
uint16 input_compression, input_photometric;
uint16 input_planar;
struct cpTag* p;
input_compression = image->compression;
input_photometric = image->photometric;
spp = image->spp;
bps = image->bps;
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(out, TIFFTAG_IMAGELENGTH, length);
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
#ifdef DEBUG2
TIFFError("writeCroppedImage", "Input compression: %s",
(input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" :
((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg"));
#endif
if (compression != (uint16)-1)
TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
else
{
if (input_compression == COMPRESSION_OJPEG)
{
compression = COMPRESSION_JPEG;
jpegcolormode = JPEGCOLORMODE_RAW;
TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
}
else
CopyField(TIFFTAG_COMPRESSION, compression);
}
if (compression == COMPRESSION_JPEG)
{
if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */
(input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */
{
TIFFError ("writeCroppedImage",
"JPEG compression cannot be used with %s image data",
(input_photometric == PHOTOMETRIC_PALETTE) ?
"palette" : "mask");
return (-1);
}
if ((input_photometric == PHOTOMETRIC_RGB) &&
(jpegcolormode == JPEGCOLORMODE_RGB))
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric);
}
else
{
if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
{
if (input_compression == COMPRESSION_SGILOG ||
input_compression == COMPRESSION_SGILOG24)
{
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ?
PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV);
}
else
TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric);
}
}
if (((input_photometric == PHOTOMETRIC_LOGL) ||
(input_photometric == PHOTOMETRIC_LOGLUV)) &&
((compression != COMPRESSION_SGILOG) &&
(compression != COMPRESSION_SGILOG24)))
{
TIFFError("writeCroppedImage",
"LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression");
return (-1);
}
if (fillorder != 0)
TIFFSetField(out, TIFFTAG_FILLORDER, fillorder);
else
CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT);
/* The loadimage function reads input orientation and sets
* image->orientation. The correct_image_orientation function
* applies the required rotation and mirror operations to
* present the data in TOPLEFT orientation and updates
* image->orientation if any transforms are performed,
* as per EXIF standard.
*/
TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation);
/*
* Choose tiles/strip for the output image according to
* the command line arguments (-tiles, -strips) and the
* structure of the input image.
*/
if (outtiled == -1)
outtiled = TIFFIsTiled(in);
if (outtiled) {
/*
* Setup output file's tile width&height. If either
* is not specified, use either the value from the
* input image or, if nothing is defined, use the
* library default.
*/
if (tilewidth == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth);
if (tilelength == (uint32) 0)
TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength);
if (tilewidth == 0 || tilelength == 0)
TIFFDefaultTileSize(out, &tilewidth, &tilelength);
TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth);
TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength);
} else {
/*
* RowsPerStrip is left unspecified: use either the
* value from the input image or, if nothing is defined,
* use the library default.
*/
if (rowsperstrip == (uint32) 0)
{
if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip))
rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip);
if (compression != COMPRESSION_JPEG)
{
if (rowsperstrip > length)
rowsperstrip = length;
}
}
else
if (rowsperstrip == (uint32) -1)
rowsperstrip = length;
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
}
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar);
if (config != (uint16) -1)
TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
else
CopyField(TIFFTAG_PLANARCONFIG, config);
if (spp <= 4)
CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT);
CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT);
/* SMinSampleValue & SMaxSampleValue */
switch (compression) {
case COMPRESSION_JPEG:
if (((bps % 8) == 0) || ((bps % 12) == 0))
{
TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
else
{
TIFFError("writeCroppedImage",
"JPEG compression requires 8 or 12 bits per sample");
return (-1);
}
break;
case COMPRESSION_LZW:
case COMPRESSION_ADOBE_DEFLATE:
case COMPRESSION_DEFLATE:
if (predictor != (uint16)-1)
TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
else
CopyField(TIFFTAG_PREDICTOR, predictor);
break;
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
if (bps != 1)
{
TIFFError("writeCroppedImage",
"Group 3/4 compression is not usable with bps > 1");
return (-1);
}
if (compression == COMPRESSION_CCITTFAX3) {
if (g3opts != (uint32) -1)
TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts);
else
CopyField(TIFFTAG_GROUP3OPTIONS, g3opts);
} else {
CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG);
}
CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG);
CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG);
CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII);
break;
case COMPRESSION_NONE:
break;
default: break;
}
{ uint32 len32;
void** data;
if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data))
TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data);
}
{ uint16 ninks;
const char* inknames;
if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) {
TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks);
if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) {
int inknameslen = strlen(inknames) + 1;
const char* cp = inknames;
while (ninks > 1) {
cp = strchr(cp, '\0');
if (cp) {
cp++;
inknameslen += (strlen(cp) + 1);
}
ninks--;
}
TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames);
}
}
}
{
unsigned short pg0, pg1;
if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) {
TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages);
}
}
for (p = tags; p < &tags[NTAGS]; p++)
CopyTag(p->tag, p->count, p->type);
/* Compute the tile or strip dimensions and write to disk */
if (outtiled)
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write contiguous tile data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate tile data for page %d", pagenum);
}
}
else
{
if (config == PLANARCONFIG_CONTIG)
{
if (writeBufferToContigStrips (out, crop_buff, length))
TIFFError("","Unable to write contiguous strip data for page %d", pagenum);
}
else
{
if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump))
TIFFError("","Unable to write separate strip data for page %d", pagenum);
}
}
if (!TIFFWriteDirectory(out))
{
TIFFError("","Failed to write IFD for page number %d", pagenum);
TIFFClose(out);
return (-1);
}
return (0);
} /* end writeCroppedImage */
static int
rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 src_byte = 0, src_bit = 0;
uint32 row, rowsize = 0, bit_offset = 0;
uint8 matchbits = 0, maskbits = 0;
uint8 buff1 = 0, buff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples8bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint8)-1 >> ( 8 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length ; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (8 - src_bit - bps);
buff1 = ((*next) & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
else
{
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end rotateContigSamples8bits */
static int
rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint16 matchbits = 0, maskbits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples16bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint16)-1 >> (16 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (16 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 8) | next[1];
else
buff1 = (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 8)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end rotateContigSamples16bits */
static int
rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0;
uint32 row, rowsize, bit_offset;
uint32 src_byte = 0, src_bit = 0;
uint32 matchbits = 0, maskbits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint32)-1 >> (32 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (32 - src_bit - bps);
if (little_endian)
buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
else
buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
buff1 = (buff1 & matchbits) << (src_bit);
/* If we have a full buffer's worth, write it out */
if (ready_bits >= 16)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
else
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples24bits */
static int
rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width,
uint32 length, uint32 col, uint8 *src, uint8 *dst)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 row, rowsize, bit_offset;
uint32 src_byte, src_bit;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 maskbits = 0, matchbits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
uint8 *next;
tsample_t sample;
if ((src == NULL) || (dst == NULL))
{
TIFFError("rotateContigSamples24bits","Invalid src or destination buffer");
return (1);
}
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
rowsize = ((bps * spp * width) + 7) / 8;
ready_bits = 0;
maskbits = (uint64)-1 >> (64 - bps);
buff1 = buff2 = 0;
for (row = 0; row < length; row++)
{
bit_offset = col * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
switch (rotation)
{
case 90: next = src + src_byte - (row * rowsize);
break;
case 270: next = src + src_byte + (row * rowsize);
break;
default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation);
return (1);
}
matchbits = maskbits << (64 - src_bit - bps);
if (little_endian)
{
longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & matchbits) << (src_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end rotateContigSamples32bits */
/* Rotate an image by a multiple of 90 degrees clockwise */
static int
rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width,
uint32 *img_length, unsigned char **ibuff_ptr)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, src_offset, dst_offset;
uint32 i, col, width, length;
uint32 colsize, buffsize, col_offset, pix_offset;
unsigned char *ibuff;
unsigned char *src;
unsigned char *dst;
uint16 spp, bps;
float res_temp;
unsigned char *rbuff = NULL;
width = *img_width;
length = *img_length;
spp = image->spp;
bps = image->bps;
rowsize = ((bps * spp * width) + 7) / 8;
colsize = ((bps * spp * length) + 7) / 8;
if ((colsize * width) > (rowsize * length))
buffsize = (colsize + 1) * width;
else
buffsize = (rowsize + 1) * length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
switch (rotation)
{
case 0:
case 360: return (0);
case 90:
case 180:
case 270: break;
default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation);
return (-1);
}
if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize)))
{
TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize);
return (-1);
}
_TIFFmemset(rbuff, '\0', buffsize);
ibuff = *ibuff_ptr;
switch (rotation)
{
case 180: if ((bps % 8) == 0) /* byte alligned data */
{
src = ibuff;
pix_offset = (spp * bps) / 8;
for (row = 0; row < length; row++)
{
dst_offset = (length - row - 1) * rowsize;
for (col = 0; col < width; col++)
{
col_offset = (width - col - 1) * pix_offset;
dst = rbuff + dst_offset + col_offset;
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *src++;
}
}
}
else
{ /* non 8 bit per sample data */
for (row = 0; row < length; row++)
{
src_offset = row * rowsize;
dst_offset = (length - row - 1) * rowsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (reverseSamples8bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (reverseSamples16bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
break;
case 90: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel);
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src -= rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = (length - 1) * rowsize;
dst_offset = col * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
break;
case 270: if ((bps % 8) == 0) /* byte aligned data */
{
for (col = 0; col < width; col++)
{
src_offset = col * bytes_per_pixel;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
for (row = length; row > 0; row--)
{
for (i = 0; i < bytes_per_pixel; i++)
*dst++ = *(src + i);
src += rowsize;
}
}
}
else
{ /* non 8 bit per sample data */
for (col = 0; col < width; col++)
{
src_offset = 0;
dst_offset = (width - col - 1) * colsize;
src = ibuff + src_offset;
dst = rbuff + dst_offset;
switch (shift_width)
{
case 1: if (bps == 1)
{
if (rotateContigSamples8bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
}
if (rotateContigSamples16bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 2: if (rotateContigSamples24bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
case 3:
case 4:
case 5: if (rotateContigSamples32bits(rotation, spp, bps, width,
length, col, src, dst))
{
_TIFFfree(rbuff);
return (-1);
}
break;
default: TIFFError("rotateImage","Unsupported bit depth %d", bps);
_TIFFfree(rbuff);
return (-1);
}
}
}
_TIFFfree(ibuff);
*(ibuff_ptr) = rbuff;
*img_width = length;
*img_length = width;
image->width = length;
image->length = width;
res_temp = image->xres;
image->xres = image->yres;
image->yres = res_temp;
break;
default:
break;
}
return (0);
} /* end rotateImage */
static int
reverseSamples8bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte, src_bit;
uint32 bit_offset = 0;
uint8 match_bits = 0, mask_bits = 0;
uint8 buff1 = 0, buff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples8bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint8)-1 >> ( 8 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
src_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
src_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (8 - src_bit - bps);
buff1 = ((*src) & match_bits) << (src_bit);
if (ready_bits < 8)
buff2 = (buff2 | (buff1 >> ready_bits));
else /* If we have a full buffer's worth, write it out */
{
*dst++ = buff2;
buff2 = buff1;
ready_bits -= 8;
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits)));
*dst++ = buff1;
}
return (0);
} /* end reverseSamples8bits */
static int
reverseSamples16bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint16 match_bits = 0, mask_bits = 0;
uint16 buff1 = 0, buff2 = 0;
uint8 bytebuff = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSample16bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint16)-1 >> (16 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (16 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 8) | src[1];
else
buff1 = (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 8)
{ /* add another bps bits to the buffer */
bytebuff = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
ready_bits -= 8;
/* shift in new bits */
buff2 = ((buff2 << 8) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
if (ready_bits > 0)
{
bytebuff = (buff2 >> 8);
*dst++ = bytebuff;
}
return (0);
} /* end reverseSamples16bits */
static int
reverseSamples24bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0;
uint32 col;
uint32 src_byte = 0, high_bit = 0;
uint32 bit_offset = 0;
uint32 match_bits = 0, mask_bits = 0;
uint32 buff1 = 0, buff2 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples24bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint32)-1 >> (32 - bps);
dst = obuff;
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (32 - high_bit - bps);
if (little_endian)
buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
else
buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
buff1 = (buff1 & match_bits) << (high_bit);
if (ready_bits < 16)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 16);
*dst++ = bytebuff2;
ready_bits -= 16;
/* shift in new bits */
buff2 = ((buff2 << 16) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
/* catch any trailing bits at the end of the line */
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 24);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
bytebuff2 = bytebuff1;
ready_bits -= 8;
}
return (0);
} /* end reverseSamples24bits */
static int
reverseSamples32bits (uint16 spp, uint16 bps, uint32 width,
uint8 *ibuff, uint8 *obuff)
{
int ready_bits = 0 /*, shift_width = 0 */;
/* int bytes_per_sample, bytes_per_pixel; */
uint32 bit_offset;
uint32 src_byte = 0, high_bit = 0;
uint32 col;
uint32 longbuff1 = 0, longbuff2 = 0;
uint64 mask_bits = 0, match_bits = 0;
uint64 buff1 = 0, buff2 = 0, buff3 = 0;
uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0;
unsigned char *src;
unsigned char *dst;
tsample_t sample;
if ((ibuff == NULL) || (obuff == NULL))
{
TIFFError("reverseSamples32bits","Invalid image or work buffer");
return (1);
}
ready_bits = 0;
mask_bits = (uint64)-1 >> (64 - bps);
dst = obuff;
/* bytes_per_sample = (bps + 7) / 8; */
/* bytes_per_pixel = ((bps * spp) + 7) / 8; */
/* if (bytes_per_pixel < (bytes_per_sample + 1)) */
/* shift_width = bytes_per_pixel; */
/* else */
/* shift_width = bytes_per_sample + 1; */
for (col = width; col > 0; col--)
{
/* Compute src byte(s) and bits within byte(s) */
bit_offset = (col - 1) * bps * spp;
for (sample = 0; sample < spp; sample++)
{
if (sample == 0)
{
src_byte = bit_offset / 8;
high_bit = bit_offset % 8;
}
else
{
src_byte = (bit_offset + (sample * bps)) / 8;
high_bit = (bit_offset + (sample * bps)) % 8;
}
src = ibuff + src_byte;
match_bits = mask_bits << (64 - high_bit - bps);
if (little_endian)
{
longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
longbuff2 = longbuff1;
}
else
{
longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0];
longbuff2 = longbuff1;
}
buff3 = ((uint64)longbuff1 << 32) | longbuff2;
buff1 = (buff3 & match_bits) << (high_bit);
if (ready_bits < 32)
{ /* add another bps bits to the buffer */
bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0;
buff2 = (buff2 | (buff1 >> ready_bits));
}
else /* If we have a full buffer's worth, write it out */
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
bytebuff2 = (buff2 >> 48);
*dst++ = bytebuff2;
bytebuff3 = (buff2 >> 40);
*dst++ = bytebuff3;
bytebuff4 = (buff2 >> 32);
*dst++ = bytebuff4;
ready_bits -= 32;
/* shift in new bits */
buff2 = ((buff2 << 32) | (buff1 >> ready_bits));
}
ready_bits += bps;
}
}
while (ready_bits > 0)
{
bytebuff1 = (buff2 >> 56);
*dst++ = bytebuff1;
buff2 = (buff2 << 8);
ready_bits -= 8;
}
return (0);
} /* end reverseSamples32bits */
static int
reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
/* Mirror an image horizontally or vertically */
static int
mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff)
{
int shift_width;
uint32 bytes_per_pixel, bytes_per_sample;
uint32 row, rowsize, row_offset;
unsigned char *line_buff = NULL;
unsigned char *src;
unsigned char *dst;
src = ibuff;
rowsize = ((width * bps * spp) + 7) / 8;
switch (mirror)
{
case MIRROR_BOTH:
case MIRROR_VERT:
line_buff = (unsigned char *)_TIFFmalloc(rowsize);
if (line_buff == NULL)
{
TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize);
return (-1);
}
dst = ibuff + (rowsize * (length - 1));
for (row = 0; row < length / 2; row++)
{
_TIFFmemcpy(line_buff, src, rowsize);
_TIFFmemcpy(src, dst, rowsize);
_TIFFmemcpy(dst, line_buff, rowsize);
src += (rowsize);
dst -= (rowsize);
}
if (line_buff)
_TIFFfree(line_buff);
if (mirror == MIRROR_VERT)
break;
case MIRROR_HORIZ :
if ((bps % 8) == 0) /* byte alligned data */
{
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
dst = ibuff + row_offset + rowsize;
if (reverseSamplesBytes(spp, bps, width, src, dst))
{
return (-1);
}
}
}
else
{ /* non 8 bit per sample data */
if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1)))
{
TIFFError("mirrorImage", "Unable to allocate mirror line buffer");
return (-1);
}
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
for (row = 0; row < length; row++)
{
row_offset = row * rowsize;
src = ibuff + row_offset;
_TIFFmemset (line_buff, '\0', rowsize);
switch (shift_width)
{
case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
case 3:
case 4:
case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff))
{
_TIFFfree(line_buff);
return (-1);
}
_TIFFmemcpy (src, line_buff, rowsize);
break;
default: TIFFError("mirrorImage","Unsupported bit depth %d", bps);
_TIFFfree(line_buff);
return (-1);
}
}
if (line_buff)
_TIFFfree(line_buff);
}
break;
default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror);
return (-1);
break;
}
return (0);
}
/* Invert the light and dark values for a bilevel or grayscale image */
static int
invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff)
{
uint32 row, col;
unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4;
unsigned char *src;
uint16 *src_uint16;
uint32 *src_uint32;
if (spp != 1)
{
TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel");
return (-1);
}
if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK)
{
TIFFError("invertImage", "Only black and white and grayscale images can be inverted");
return (-1);
}
src = work_buff;
if (src == NULL)
{
TIFFError ("invertImage", "Invalid crop buffer passed to invertImage");
return (-1);
}
switch (bps)
{
case 32: src_uint32 = (uint32 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint32 = (uint32)0xFFFFFFFF - *src_uint32;
src_uint32++;
}
break;
case 16: src_uint16 = (uint16 *)src;
for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src_uint16 = (uint16)0xFFFF - *src_uint16;
src_uint16++;
}
break;
case 8: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
*src = (uint8)255 - *src;
src++;
}
break;
case 4: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
bytebuff1 = 16 - (uint8)(*src & 240 >> 4);
bytebuff2 = 16 - (*src & 15);
*src = bytebuff1 << 4 & bytebuff2;
src++;
}
break;
case 2: for (row = 0; row < length; row++)
for (col = 0; col < width; col++)
{
bytebuff1 = 4 - (uint8)(*src & 192 >> 6);
bytebuff2 = 4 - (uint8)(*src & 48 >> 4);
bytebuff3 = 4 - (uint8)(*src & 12 >> 2);
bytebuff4 = 4 - (uint8)(*src & 3);
*src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4;
src++;
}
break;
case 1: for (row = 0; row < length; row++)
for (col = 0; col < width; col += 8 /(spp * bps))
{
*src = ~(*src);
src++;
}
break;
default: TIFFError("invertImage", "Unsupported bit depth %d", bps);
return (-1);
}
return (0);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5475_4 |
crossvul-cpp_data_bad_5203_0 | /**
* collectd - src/network.c
* Copyright (C) 2005-2013 Florian octo Forster
* Copyright (C) 2009 Aman Gupta
*
* 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; only version 2.1 of the License is
* applicable.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors:
* Florian octo Forster <octo at collectd.org>
* Aman Gupta <aman at tmm1.net>
**/
#define _DEFAULT_SOURCE
#define _BSD_SOURCE /* For struct ip_mreq */
#include "collectd.h"
#include "plugin.h"
#include "common.h"
#include "configfile.h"
#include "utils_fbhash.h"
#include "utils_avltree.h"
#include "utils_cache.h"
#include "utils_complain.h"
#include "network.h"
#if HAVE_PTHREAD_H
# include <pthread.h>
#endif
#if HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#if HAVE_NETDB_H
# include <netdb.h>
#endif
#if HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#if HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#if HAVE_POLL_H
# include <poll.h>
#endif
#if HAVE_NET_IF_H
# include <net/if.h>
#endif
#if HAVE_LIBGCRYPT
# include <pthread.h>
# if defined __APPLE__
/* default xcode compiler throws warnings even when deprecated functionality
* is not used. -Werror breaks the build because of erroneous warnings.
* http://stackoverflow.com/questions/10556299/compiler-warnings-with-libgcrypt-v1-5-0/12830209#12830209
*/
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
# endif
/* FreeBSD's copy of libgcrypt extends the existing GCRYPT_NO_DEPRECATED
* to properly hide all deprecated functionality.
* http://svnweb.freebsd.org/ports/head/security/libgcrypt/files/patch-src__gcrypt.h.in
*/
# define GCRYPT_NO_DEPRECATED
# include <gcrypt.h>
# if defined __APPLE__
/* Re enable deprecation warnings */
# pragma GCC diagnostic warning "-Wdeprecated-declarations"
# endif
# if GCRYPT_VERSION_NUMBER < 0x010600
GCRY_THREAD_OPTION_PTHREAD_IMPL;
# endif
#endif
#ifndef IPV6_ADD_MEMBERSHIP
# ifdef IPV6_JOIN_GROUP
# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
# else
# error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
# endif
#endif /* !IP_ADD_MEMBERSHIP */
/*
* Maximum size required for encryption / signing:
*
* 42 bytes for the encryption header
* + 64 bytes for the username
* -----------
* = 106 bytes
*/
#define BUFF_SIG_SIZE 106
/*
* Private data types
*/
#define SECURITY_LEVEL_NONE 0
#if HAVE_LIBGCRYPT
# define SECURITY_LEVEL_SIGN 1
# define SECURITY_LEVEL_ENCRYPT 2
#endif
struct sockent_client
{
int fd;
struct sockaddr_storage *addr;
socklen_t addrlen;
#if HAVE_LIBGCRYPT
int security_level;
char *username;
char *password;
gcry_cipher_hd_t cypher;
unsigned char password_hash[32];
#endif
};
struct sockent_server
{
int *fd;
size_t fd_num;
#if HAVE_LIBGCRYPT
int security_level;
char *auth_file;
fbhash_t *userdb;
gcry_cipher_hd_t cypher;
#endif
};
typedef struct sockent
{
#define SOCKENT_TYPE_CLIENT 1
#define SOCKENT_TYPE_SERVER 2
int type;
char *node;
char *service;
int interface;
union
{
struct sockent_client client;
struct sockent_server server;
} data;
struct sockent *next;
} sockent_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------+-----------------------+-------------------------------+
* ! Ver. ! ! Length !
* +-------+-----------------------+-------------------------------+
*/
struct part_header_s
{
uint16_t type;
uint16_t length;
};
typedef struct part_header_s part_header_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* : (Length - 4) Bytes :
* +---------------------------------------------------------------+
*/
struct part_string_s
{
part_header_t *head;
char *value;
};
typedef struct part_string_s part_string_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* : (Length - 4 == 2 || 4 || 8) Bytes :
* +---------------------------------------------------------------+
*/
struct part_number_s
{
part_header_t *head;
uint64_t *value;
};
typedef struct part_number_s part_number_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+---------------+---------------+
* ! Num of values ! Type0 ! Type1 !
* +-------------------------------+---------------+---------------+
* ! Value0 !
* ! !
* +---------------------------------------------------------------+
* ! Value1 !
* ! !
* +---------------------------------------------------------------+
*/
struct part_values_s
{
part_header_t *head;
uint16_t *num_values;
uint8_t *values_types;
value_t *values;
};
typedef struct part_values_s part_values_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* ! Hash (Bits 0 - 31) !
* : : :
* ! Hash (Bits 224 - 255) !
* +---------------------------------------------------------------+
*/
/* Minimum size */
#define PART_SIGNATURE_SHA256_SIZE 36
struct part_signature_sha256_s
{
part_header_t head;
unsigned char hash[32];
char *username;
};
typedef struct part_signature_sha256_s part_signature_sha256_t;
/* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-------------------------------+-------------------------------+
* ! Type ! Length !
* +-------------------------------+-------------------------------+
* ! Original length ! Padding (0 - 15 bytes) !
* +-------------------------------+-------------------------------+
* ! Hash (Bits 0 - 31) !
* : : :
* ! Hash (Bits 128 - 159) !
* +---------------------------------------------------------------+
*/
/* Minimum size */
#define PART_ENCRYPTION_AES256_SIZE 42
struct part_encryption_aes256_s
{
part_header_t head;
uint16_t username_length;
char *username;
unsigned char iv[16];
/* <encrypted> */
unsigned char hash[20];
/* <payload /> */
/* </encrypted> */
};
typedef struct part_encryption_aes256_s part_encryption_aes256_t;
struct receive_list_entry_s
{
char *data;
int data_len;
int fd;
struct receive_list_entry_s *next;
};
typedef struct receive_list_entry_s receive_list_entry_t;
/*
* Private variables
*/
static int network_config_ttl = 0;
/* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
static size_t network_config_packet_size = 1452;
static int network_config_forward = 0;
static int network_config_stats = 0;
static sockent_t *sending_sockets = NULL;
static receive_list_entry_t *receive_list_head = NULL;
static receive_list_entry_t *receive_list_tail = NULL;
static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
static uint64_t receive_list_length = 0;
static sockent_t *listen_sockets = NULL;
static struct pollfd *listen_sockets_pollfd = NULL;
static size_t listen_sockets_num = 0;
/* The receive and dispatch threads will run as long as `listen_loop' is set to
* zero. */
static int listen_loop = 0;
static int receive_thread_running = 0;
static pthread_t receive_thread_id;
static int dispatch_thread_running = 0;
static pthread_t dispatch_thread_id;
/* Buffer in which to-be-sent network packets are constructed. */
static char *send_buffer;
static char *send_buffer_ptr;
static int send_buffer_fill;
static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
/* XXX: These counters are incremented from one place only. The spot in which
* the values are incremented is either only reachable by one thread (the
* dispatch thread, for example) or locked by some lock (send_buffer_lock for
* example). Only if neither is true, the stats_lock is acquired. The counters
* are always read without holding a lock in the hope that writing 8 bytes to
* memory is an atomic operation. */
static derive_t stats_octets_rx = 0;
static derive_t stats_octets_tx = 0;
static derive_t stats_packets_rx = 0;
static derive_t stats_packets_tx = 0;
static derive_t stats_values_dispatched = 0;
static derive_t stats_values_not_dispatched = 0;
static derive_t stats_values_sent = 0;
static derive_t stats_values_not_sent = 0;
static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
/*
* Private functions
*/
static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
{
uint64_t time_sent = 0;
int status;
status = uc_meta_data_get_unsigned_int (vl,
"network:time_sent", &time_sent);
/* This is a value we already sent. Don't allow it to be received again in
* order to avoid looping. */
if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
return (0);
return (1);
} /* }}} _Bool check_receive_okay */
static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
{
_Bool received = 0;
int status;
if (network_config_forward != 0)
return (1);
if (vl->meta == NULL)
return (1);
status = meta_data_get_boolean (vl->meta, "network:received", &received);
if (status == -ENOENT)
return (1);
else if (status != 0)
{
ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
"with status %i.", status);
return (1);
}
/* By default, only *send* value lists that were not *received* by the
* network plugin. */
return (!received);
} /* }}} _Bool check_send_okay */
static _Bool check_notify_received (const notification_t *n) /* {{{ */
{
notification_meta_t *ptr;
for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
if ((strcmp ("network:received", ptr->name) == 0)
&& (ptr->type == NM_TYPE_BOOLEAN))
return ((_Bool) ptr->nm_value.nm_boolean);
return (0);
} /* }}} _Bool check_notify_received */
static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
{
static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
_Bool received = 0;
if (n->meta == NULL)
return (1);
received = check_notify_received (n);
if (network_config_forward && received)
{
c_complain_once (LOG_ERR, &complain_forwarding,
"network plugin: A notification has been received via the network "
"and forwarding is enabled. Forwarding of notifications is currently "
"not supported, because there is not loop-deteciton available. "
"Please contact the collectd mailing list if you need this "
"feature.");
}
/* By default, only *send* value lists that were not *received* by the
* network plugin. */
return (!received);
} /* }}} _Bool check_send_notify_okay */
static int network_dispatch_values (value_list_t *vl, /* {{{ */
const char *username)
{
int status;
if ((vl->time <= 0)
|| (strlen (vl->host) <= 0)
|| (strlen (vl->plugin) <= 0)
|| (strlen (vl->type) <= 0))
return (-EINVAL);
if (!check_receive_okay (vl))
{
#if COLLECT_DEBUG
char name[6*DATA_MAX_NAME_LEN];
FORMAT_VL (name, sizeof (name), vl);
name[sizeof (name) - 1] = 0;
DEBUG ("network plugin: network_dispatch_values: "
"NOT dispatching %s.", name);
#endif
stats_values_not_dispatched++;
return (0);
}
assert (vl->meta == NULL);
vl->meta = meta_data_create ();
if (vl->meta == NULL)
{
ERROR ("network plugin: meta_data_create failed.");
return (-ENOMEM);
}
status = meta_data_add_boolean (vl->meta, "network:received", 1);
if (status != 0)
{
ERROR ("network plugin: meta_data_add_boolean failed.");
meta_data_destroy (vl->meta);
vl->meta = NULL;
return (status);
}
if (username != NULL)
{
status = meta_data_add_string (vl->meta, "network:username", username);
if (status != 0)
{
ERROR ("network plugin: meta_data_add_string failed.");
meta_data_destroy (vl->meta);
vl->meta = NULL;
return (status);
}
}
plugin_dispatch_values (vl);
stats_values_dispatched++;
meta_data_destroy (vl->meta);
vl->meta = NULL;
return (0);
} /* }}} int network_dispatch_values */
static int network_dispatch_notification (notification_t *n) /* {{{ */
{
int status;
assert (n->meta == NULL);
status = plugin_notification_meta_add_boolean (n, "network:received", 1);
if (status != 0)
{
ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
plugin_notification_meta_free (n->meta);
n->meta = NULL;
return (status);
}
status = plugin_dispatch_notification (n);
plugin_notification_meta_free (n->meta);
n->meta = NULL;
return (status);
} /* }}} int network_dispatch_notification */
#if HAVE_LIBGCRYPT
static void network_init_gcrypt (void) /* {{{ */
{
/* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
* Because you can't know in a library whether another library has
* already initialized the library */
if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
return;
/* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
* To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
* *before* initalizing Libgcrypt with gcry_check_version(), which itself must
* be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
* above doesn't count, as it doesn't implicitly initalize Libgcrypt.
*
* tl;dr: keep all these gry_* statements in this exact order please. */
# if GCRYPT_VERSION_NUMBER < 0x010600
gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
# endif
gcry_check_version (NULL);
gcry_control (GCRYCTL_INIT_SECMEM, 32768);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
} /* }}} void network_init_gcrypt */
static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
const void *iv, size_t iv_size, const char *username)
{
gcry_error_t err;
gcry_cipher_hd_t *cyper_ptr;
unsigned char password_hash[32];
if (se->type == SOCKENT_TYPE_CLIENT)
{
cyper_ptr = &se->data.client.cypher;
memcpy (password_hash, se->data.client.password_hash,
sizeof (password_hash));
}
else
{
char *secret;
cyper_ptr = &se->data.server.cypher;
if (username == NULL)
return (NULL);
secret = fbh_get (se->data.server.userdb, username);
if (secret == NULL)
return (NULL);
gcry_md_hash_buffer (GCRY_MD_SHA256,
password_hash,
secret, strlen (secret));
sfree (secret);
}
if (*cyper_ptr == NULL)
{
err = gcry_cipher_open (cyper_ptr,
GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_open returned: %s",
gcry_strerror (err));
*cyper_ptr = NULL;
return (NULL);
}
}
else
{
gcry_cipher_reset (*cyper_ptr);
}
assert (*cyper_ptr != NULL);
err = gcry_cipher_setkey (*cyper_ptr,
password_hash, sizeof (password_hash));
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_setkey returned: %s",
gcry_strerror (err));
gcry_cipher_close (*cyper_ptr);
*cyper_ptr = NULL;
return (NULL);
}
err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_setkey returned: %s",
gcry_strerror (err));
gcry_cipher_close (*cyper_ptr);
*cyper_ptr = NULL;
return (NULL);
}
return (*cyper_ptr);
} /* }}} int network_get_aes256_cypher */
#endif /* HAVE_LIBGCRYPT */
static int write_part_values (char **ret_buffer, int *ret_buffer_len,
const data_set_t *ds, const value_list_t *vl)
{
char *packet_ptr;
int packet_len;
int num_values;
part_header_t pkg_ph;
uint16_t pkg_num_values;
uint8_t *pkg_values_types;
value_t *pkg_values;
int offset;
int i;
num_values = vl->values_len;
packet_len = sizeof (part_header_t) + sizeof (uint16_t)
+ (num_values * sizeof (uint8_t))
+ (num_values * sizeof (value_t));
if (*ret_buffer_len < packet_len)
return (-1);
pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
if (pkg_values_types == NULL)
{
ERROR ("network plugin: write_part_values: malloc failed.");
return (-1);
}
pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
if (pkg_values == NULL)
{
free (pkg_values_types);
ERROR ("network plugin: write_part_values: malloc failed.");
return (-1);
}
pkg_ph.type = htons (TYPE_VALUES);
pkg_ph.length = htons (packet_len);
pkg_num_values = htons ((uint16_t) vl->values_len);
for (i = 0; i < num_values; i++)
{
pkg_values_types[i] = (uint8_t) ds->ds[i].type;
switch (ds->ds[i].type)
{
case DS_TYPE_COUNTER:
pkg_values[i].counter = htonll (vl->values[i].counter);
break;
case DS_TYPE_GAUGE:
pkg_values[i].gauge = htond (vl->values[i].gauge);
break;
case DS_TYPE_DERIVE:
pkg_values[i].derive = htonll (vl->values[i].derive);
break;
case DS_TYPE_ABSOLUTE:
pkg_values[i].absolute = htonll (vl->values[i].absolute);
break;
default:
free (pkg_values_types);
free (pkg_values);
ERROR ("network plugin: write_part_values: "
"Unknown data source type: %i",
ds->ds[i].type);
return (-1);
} /* switch (ds->ds[i].type) */
} /* for (num_values) */
/*
* Use `memcpy' to write everything to the buffer, because the pointer
* may be unaligned and some architectures, such as SPARC, can't handle
* that.
*/
packet_ptr = *ret_buffer;
offset = 0;
memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
offset += sizeof (pkg_ph);
memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
offset += sizeof (pkg_num_values);
memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
offset += num_values * sizeof (uint8_t);
memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
offset += num_values * sizeof (value_t);
assert (offset == packet_len);
*ret_buffer = packet_ptr + packet_len;
*ret_buffer_len -= packet_len;
free (pkg_values_types);
free (pkg_values);
return (0);
} /* int write_part_values */
static int write_part_number (char **ret_buffer, int *ret_buffer_len,
int type, uint64_t value)
{
char *packet_ptr;
int packet_len;
part_header_t pkg_head;
uint64_t pkg_value;
int offset;
packet_len = sizeof (pkg_head) + sizeof (pkg_value);
if (*ret_buffer_len < packet_len)
return (-1);
pkg_head.type = htons (type);
pkg_head.length = htons (packet_len);
pkg_value = htonll (value);
packet_ptr = *ret_buffer;
offset = 0;
memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
offset += sizeof (pkg_head);
memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
offset += sizeof (pkg_value);
assert (offset == packet_len);
*ret_buffer = packet_ptr + packet_len;
*ret_buffer_len -= packet_len;
return (0);
} /* int write_part_number */
static int write_part_string (char **ret_buffer, int *ret_buffer_len,
int type, const char *str, int str_len)
{
char *buffer;
int buffer_len;
uint16_t pkg_type;
uint16_t pkg_length;
int offset;
buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
if (*ret_buffer_len < buffer_len)
return (-1);
pkg_type = htons (type);
pkg_length = htons (buffer_len);
buffer = *ret_buffer;
offset = 0;
memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
offset += sizeof (pkg_type);
memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
offset += sizeof (pkg_length);
memcpy (buffer + offset, str, str_len);
offset += str_len;
memset (buffer + offset, '\0', 1);
offset += 1;
assert (offset == buffer_len);
*ret_buffer = buffer + buffer_len;
*ret_buffer_len -= buffer_len;
return (0);
} /* int write_part_string */
static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
value_t **ret_values, int *ret_num_values)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
uint16_t tmp16;
size_t exp_size;
int i;
uint16_t pkg_length;
uint16_t pkg_type;
uint16_t pkg_numval;
uint8_t *pkg_types;
value_t *pkg_values;
if (buffer_len < 15)
{
NOTICE ("network plugin: packet is too short: "
"buffer_len = %zu", buffer_len);
return (-1);
}
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_type = ntohs (tmp16);
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_length = ntohs (tmp16);
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_numval = ntohs (tmp16);
assert (pkg_type == TYPE_VALUES);
exp_size = 3 * sizeof (uint16_t)
+ pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
if (buffer_len < exp_size)
{
WARNING ("network plugin: parse_part_values: "
"Packet too short: "
"Chunk of size %zu expected, "
"but buffer has only %zu bytes left.",
exp_size, buffer_len);
return (-1);
}
if (pkg_length != exp_size)
{
WARNING ("network plugin: parse_part_values: "
"Length and number of values "
"in the packet don't match.");
return (-1);
}
pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
if ((pkg_types == NULL) || (pkg_values == NULL))
{
sfree (pkg_types);
sfree (pkg_values);
ERROR ("network plugin: parse_part_values: malloc failed.");
return (-1);
}
memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
buffer += pkg_numval * sizeof (uint8_t);
memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
buffer += pkg_numval * sizeof (value_t);
for (i = 0; i < pkg_numval; i++)
{
switch (pkg_types[i])
{
case DS_TYPE_COUNTER:
pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
break;
case DS_TYPE_GAUGE:
pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
break;
case DS_TYPE_DERIVE:
pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
break;
case DS_TYPE_ABSOLUTE:
pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
break;
default:
NOTICE ("network plugin: parse_part_values: "
"Don't know how to handle data source type %"PRIu8,
pkg_types[i]);
sfree (pkg_types);
sfree (pkg_values);
return (-1);
} /* switch (pkg_types[i]) */
}
*ret_buffer = buffer;
*ret_buffer_len = buffer_len - pkg_length;
*ret_num_values = pkg_numval;
*ret_values = pkg_values;
sfree (pkg_types);
return (0);
} /* int parse_part_values */
static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
uint64_t *value)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
uint16_t tmp16;
uint64_t tmp64;
size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
uint16_t pkg_length;
if (buffer_len < exp_size)
{
WARNING ("network plugin: parse_part_number: "
"Packet too short: "
"Chunk of size %zu expected, "
"but buffer has only %zu bytes left.",
exp_size, buffer_len);
return (-1);
}
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
/* pkg_type = ntohs (tmp16); */
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_length = ntohs (tmp16);
memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
buffer += sizeof (tmp64);
*value = ntohll (tmp64);
*ret_buffer = buffer;
*ret_buffer_len = buffer_len - pkg_length;
return (0);
} /* int parse_part_number */
static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
char *output, int output_len)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
uint16_t tmp16;
size_t header_size = 2 * sizeof (uint16_t);
uint16_t pkg_length;
if (buffer_len < header_size)
{
WARNING ("network plugin: parse_part_string: "
"Packet too short: "
"Chunk of at least size %zu expected, "
"but buffer has only %zu bytes left.",
header_size, buffer_len);
return (-1);
}
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
/* pkg_type = ntohs (tmp16); */
memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
buffer += sizeof (tmp16);
pkg_length = ntohs (tmp16);
/* Check that packet fits in the input buffer */
if (pkg_length > buffer_len)
{
WARNING ("network plugin: parse_part_string: "
"Packet too big: "
"Chunk of size %"PRIu16" received, "
"but buffer has only %zu bytes left.",
pkg_length, buffer_len);
return (-1);
}
/* Check that pkg_length is in the valid range */
if (pkg_length <= header_size)
{
WARNING ("network plugin: parse_part_string: "
"Packet too short: "
"Header claims this packet is only %hu "
"bytes long.", pkg_length);
return (-1);
}
/* Check that the package data fits into the output buffer.
* The previous if-statement ensures that:
* `pkg_length > header_size' */
if ((output_len < 0)
|| ((size_t) output_len < ((size_t) pkg_length - header_size)))
{
WARNING ("network plugin: parse_part_string: "
"Output buffer too small.");
return (-1);
}
/* All sanity checks successfull, let's copy the data over */
output_len = pkg_length - header_size;
memcpy ((void *) output, (void *) buffer, output_len);
buffer += output_len;
/* For some very weird reason '\0' doesn't do the trick on SPARC in
* this statement. */
if (output[output_len - 1] != 0)
{
WARNING ("network plugin: parse_part_string: "
"Received string does not end "
"with a NULL-byte.");
return (-1);
}
*ret_buffer = buffer;
*ret_buffer_len = buffer_len - pkg_length;
return (0);
} /* int parse_part_string */
/* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
* parse_packet and vice versa. */
#define PP_SIGNED 0x01
#define PP_ENCRYPTED 0x02
static int parse_packet (sockent_t *se,
void *buffer, size_t buffer_size, int flags,
const char *username);
#define BUFFER_READ(p,s) do { \
memcpy ((p), buffer + buffer_offset, (s)); \
buffer_offset += (s); \
} while (0)
#if HAVE_LIBGCRYPT
static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_len, int flags)
{
static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
char *buffer;
size_t buffer_len;
size_t buffer_offset;
size_t username_len;
char *secret;
part_signature_sha256_t pss;
uint16_t pss_head_length;
char hash[sizeof (pss.hash)];
gcry_md_hd_t hd;
gcry_error_t err;
unsigned char *hash_ptr;
buffer = *ret_buffer;
buffer_len = *ret_buffer_len;
buffer_offset = 0;
if (se->data.server.userdb == NULL)
{
c_complain (LOG_NOTICE, &complain_no_users,
"network plugin: Received signed network packet but can't verify it "
"because no user DB has been configured. Will accept it.");
return (0);
}
/* Check if the buffer has enough data for this structure. */
if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
return (-ENOMEM);
/* Read type and length header */
BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
pss_head_length = ntohs (pss.head.length);
/* Check if the `pss_head_length' is within bounds. */
if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
|| (pss_head_length > buffer_len))
{
ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
return (-1);
}
/* Copy the hash. */
BUFFER_READ (pss.hash, sizeof (pss.hash));
/* Calculate username length (without null byte) and allocate memory */
username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
pss.username = malloc (username_len + 1);
if (pss.username == NULL)
return (-ENOMEM);
/* Read the username */
BUFFER_READ (pss.username, username_len);
pss.username[username_len] = 0;
assert (buffer_offset == pss_head_length);
/* Query the password */
secret = fbh_get (se->data.server.userdb, pss.username);
if (secret == NULL)
{
ERROR ("network plugin: Unknown user: %s", pss.username);
sfree (pss.username);
return (-ENOENT);
}
/* Create a hash device and check the HMAC */
hd = NULL;
err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
if (err != 0)
{
ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
gcry_strerror (err));
sfree (secret);
sfree (pss.username);
return (-1);
}
err = gcry_md_setkey (hd, secret, strlen (secret));
if (err != 0)
{
ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
gcry_md_close (hd);
sfree (secret);
sfree (pss.username);
return (-1);
}
gcry_md_write (hd,
buffer + PART_SIGNATURE_SHA256_SIZE,
buffer_len - PART_SIGNATURE_SHA256_SIZE);
hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
if (hash_ptr == NULL)
{
ERROR ("network plugin: gcry_md_read failed.");
gcry_md_close (hd);
sfree (secret);
sfree (pss.username);
return (-1);
}
memcpy (hash, hash_ptr, sizeof (hash));
/* Clean up */
gcry_md_close (hd);
hd = NULL;
if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
{
WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
"Hash mismatch.");
}
else
{
parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
flags | PP_SIGNED, pss.username);
}
sfree (secret);
sfree (pss.username);
*ret_buffer = buffer + buffer_len;
*ret_buffer_len = 0;
return (0);
} /* }}} int parse_part_sign_sha256 */
/* #endif HAVE_LIBGCRYPT */
#else /* if !HAVE_LIBGCRYPT */
static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_size, int flags)
{
static int warning_has_been_printed = 0;
char *buffer;
size_t buffer_size;
size_t buffer_offset;
uint16_t part_len;
part_signature_sha256_t pss;
buffer = *ret_buffer;
buffer_size = *ret_buffer_size;
buffer_offset = 0;
if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
return (-ENOMEM);
BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
part_len = ntohs (pss.head.length);
if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
|| (part_len > buffer_size))
return (-EINVAL);
if (warning_has_been_printed == 0)
{
WARNING ("network plugin: Received signed packet, but the network "
"plugin was not linked with libgcrypt, so I cannot "
"verify the signature. The packet will be accepted.");
warning_has_been_printed = 1;
}
parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
/* username = */ NULL);
*ret_buffer = buffer + buffer_size;
*ret_buffer_size = 0;
return (0);
} /* }}} int parse_part_sign_sha256 */
#endif /* !HAVE_LIBGCRYPT */
#if HAVE_LIBGCRYPT
static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_len,
int flags)
{
char *buffer = *ret_buffer;
size_t buffer_len = *ret_buffer_len;
size_t payload_len;
size_t part_size;
size_t buffer_offset;
uint16_t username_len;
part_encryption_aes256_t pea;
unsigned char hash[sizeof (pea.hash)];
gcry_cipher_hd_t cypher;
gcry_error_t err;
/* Make sure at least the header if available. */
if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
{
NOTICE ("network plugin: parse_part_encr_aes256: "
"Discarding short packet.");
return (-1);
}
buffer_offset = 0;
/* Copy the unencrypted information into `pea'. */
BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
/* Check the `part size'. */
part_size = ntohs (pea.head.length);
if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
|| (part_size > buffer_len))
{
NOTICE ("network plugin: parse_part_encr_aes256: "
"Discarding part with invalid size.");
return (-1);
}
/* Read the username */
BUFFER_READ (&username_len, sizeof (username_len));
username_len = ntohs (username_len);
if ((username_len <= 0)
|| (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
{
NOTICE ("network plugin: parse_part_encr_aes256: "
"Discarding part with invalid username length.");
return (-1);
}
assert (username_len > 0);
pea.username = malloc (username_len + 1);
if (pea.username == NULL)
return (-ENOMEM);
BUFFER_READ (pea.username, username_len);
pea.username[username_len] = 0;
/* Last but not least, the initialization vector */
BUFFER_READ (pea.iv, sizeof (pea.iv));
/* Make sure we are at the right position */
assert (buffer_offset == (username_len +
PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
pea.username);
if (cypher == NULL)
{
sfree (pea.username);
return (-1);
}
payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
assert (payload_len > 0);
/* Decrypt the packet in-place */
err = gcry_cipher_decrypt (cypher,
buffer + buffer_offset,
part_size - buffer_offset,
/* in = */ NULL, /* in len = */ 0);
if (err != 0)
{
sfree (pea.username);
ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
gcry_strerror (err));
return (-1);
}
/* Read the hash */
BUFFER_READ (pea.hash, sizeof (pea.hash));
/* Make sure we're at the right position - again */
assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
assert (buffer_offset == (part_size - payload_len));
/* Check hash sum */
memset (hash, 0, sizeof (hash));
gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
buffer + buffer_offset, payload_len);
if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
{
sfree (pea.username);
ERROR ("network plugin: Decryption failed: Checksum mismatch.");
return (-1);
}
parse_packet (se, buffer + buffer_offset, payload_len,
flags | PP_ENCRYPTED, pea.username);
/* XXX: Free pea.username?!? */
/* Update return values */
*ret_buffer = buffer + part_size;
*ret_buffer_len = buffer_len - part_size;
sfree (pea.username);
return (0);
} /* }}} int parse_part_encr_aes256 */
/* #endif HAVE_LIBGCRYPT */
#else /* if !HAVE_LIBGCRYPT */
static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
void **ret_buffer, size_t *ret_buffer_size, int flags)
{
static int warning_has_been_printed = 0;
char *buffer;
size_t buffer_size;
size_t buffer_offset;
part_header_t ph;
size_t ph_length;
buffer = *ret_buffer;
buffer_size = *ret_buffer_size;
buffer_offset = 0;
/* parse_packet assures this minimum size. */
assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
BUFFER_READ (&ph.type, sizeof (ph.type));
BUFFER_READ (&ph.length, sizeof (ph.length));
ph_length = ntohs (ph.length);
if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
|| (ph_length > buffer_size))
{
ERROR ("network plugin: AES-256 encrypted part "
"with invalid length received.");
return (-1);
}
if (warning_has_been_printed == 0)
{
WARNING ("network plugin: Received encrypted packet, but the network "
"plugin was not linked with libgcrypt, so I cannot "
"decrypt it. The part will be discarded.");
warning_has_been_printed = 1;
}
*ret_buffer += ph_length;
*ret_buffer_size -= ph_length;
return (0);
} /* }}} int parse_part_encr_aes256 */
#endif /* !HAVE_LIBGCRYPT */
#undef BUFFER_READ
static int parse_packet (sockent_t *se, /* {{{ */
void *buffer, size_t buffer_size, int flags,
const char *username)
{
int status;
value_list_t vl = VALUE_LIST_INIT;
notification_t n;
#if HAVE_LIBGCRYPT
int packet_was_signed = (flags & PP_SIGNED);
int packet_was_encrypted = (flags & PP_ENCRYPTED);
int printed_ignore_warning = 0;
#endif /* HAVE_LIBGCRYPT */
memset (&vl, '\0', sizeof (vl));
memset (&n, '\0', sizeof (n));
status = 0;
while ((status == 0) && (0 < buffer_size)
&& ((unsigned int) buffer_size > sizeof (part_header_t)))
{
uint16_t pkg_length;
uint16_t pkg_type;
memcpy ((void *) &pkg_type,
(void *) buffer,
sizeof (pkg_type));
memcpy ((void *) &pkg_length,
(void *) (buffer + sizeof (pkg_type)),
sizeof (pkg_length));
pkg_length = ntohs (pkg_length);
pkg_type = ntohs (pkg_type);
if (pkg_length > buffer_size)
break;
/* Ensure that this loop terminates eventually */
if (pkg_length < (2 * sizeof (uint16_t)))
break;
if (pkg_type == TYPE_ENCR_AES256)
{
status = parse_part_encr_aes256 (se,
&buffer, &buffer_size, flags);
if (status != 0)
{
ERROR ("network plugin: Decrypting AES256 "
"part failed "
"with status %i.", status);
break;
}
}
#if HAVE_LIBGCRYPT
else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
&& (packet_was_encrypted == 0))
{
if (printed_ignore_warning == 0)
{
INFO ("network plugin: Unencrypted packet or "
"part has been ignored.");
printed_ignore_warning = 1;
}
buffer = ((char *) buffer) + pkg_length;
continue;
}
#endif /* HAVE_LIBGCRYPT */
else if (pkg_type == TYPE_SIGN_SHA256)
{
status = parse_part_sign_sha256 (se,
&buffer, &buffer_size, flags);
if (status != 0)
{
ERROR ("network plugin: Verifying HMAC-SHA-256 "
"signature failed "
"with status %i.", status);
break;
}
}
#if HAVE_LIBGCRYPT
else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
&& (packet_was_encrypted == 0)
&& (packet_was_signed == 0))
{
if (printed_ignore_warning == 0)
{
INFO ("network plugin: Unsigned packet or "
"part has been ignored.");
printed_ignore_warning = 1;
}
buffer = ((char *) buffer) + pkg_length;
continue;
}
#endif /* HAVE_LIBGCRYPT */
else if (pkg_type == TYPE_VALUES)
{
status = parse_part_values (&buffer, &buffer_size,
&vl.values, &vl.values_len);
if (status != 0)
break;
network_dispatch_values (&vl, username);
sfree (vl.values);
}
else if (pkg_type == TYPE_TIME)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
{
vl.time = TIME_T_TO_CDTIME_T (tmp);
n.time = TIME_T_TO_CDTIME_T (tmp);
}
}
else if (pkg_type == TYPE_TIME_HR)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
{
vl.time = (cdtime_t) tmp;
n.time = (cdtime_t) tmp;
}
}
else if (pkg_type == TYPE_INTERVAL)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
vl.interval = TIME_T_TO_CDTIME_T (tmp);
}
else if (pkg_type == TYPE_INTERVAL_HR)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
vl.interval = (cdtime_t) tmp;
}
else if (pkg_type == TYPE_HOST)
{
status = parse_part_string (&buffer, &buffer_size,
vl.host, sizeof (vl.host));
if (status == 0)
sstrncpy (n.host, vl.host, sizeof (n.host));
}
else if (pkg_type == TYPE_PLUGIN)
{
status = parse_part_string (&buffer, &buffer_size,
vl.plugin, sizeof (vl.plugin));
if (status == 0)
sstrncpy (n.plugin, vl.plugin,
sizeof (n.plugin));
}
else if (pkg_type == TYPE_PLUGIN_INSTANCE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.plugin_instance,
sizeof (vl.plugin_instance));
if (status == 0)
sstrncpy (n.plugin_instance,
vl.plugin_instance,
sizeof (n.plugin_instance));
}
else if (pkg_type == TYPE_TYPE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.type, sizeof (vl.type));
if (status == 0)
sstrncpy (n.type, vl.type, sizeof (n.type));
}
else if (pkg_type == TYPE_TYPE_INSTANCE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.type_instance,
sizeof (vl.type_instance));
if (status == 0)
sstrncpy (n.type_instance, vl.type_instance,
sizeof (n.type_instance));
}
else if (pkg_type == TYPE_MESSAGE)
{
status = parse_part_string (&buffer, &buffer_size,
n.message, sizeof (n.message));
if (status != 0)
{
/* do nothing */
}
else if ((n.severity != NOTIF_FAILURE)
&& (n.severity != NOTIF_WARNING)
&& (n.severity != NOTIF_OKAY))
{
INFO ("network plugin: "
"Ignoring notification with "
"unknown severity %i.",
n.severity);
}
else if (n.time <= 0)
{
INFO ("network plugin: "
"Ignoring notification with "
"time == 0.");
}
else if (strlen (n.message) <= 0)
{
INFO ("network plugin: "
"Ignoring notification with "
"an empty message.");
}
else
{
network_dispatch_notification (&n);
}
}
else if (pkg_type == TYPE_SEVERITY)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
n.severity = (int) tmp;
}
else
{
DEBUG ("network plugin: parse_packet: Unknown part"
" type: 0x%04hx", pkg_type);
buffer = ((char *) buffer) + pkg_length;
}
} /* while (buffer_size > sizeof (part_header_t)) */
if (status == 0 && buffer_size > 0)
WARNING ("network plugin: parse_packet: Received truncated "
"packet, try increasing `MaxPacketSize'");
return (status);
} /* }}} int parse_packet */
static void free_sockent_client (struct sockent_client *sec) /* {{{ */
{
if (sec->fd >= 0)
{
close (sec->fd);
sec->fd = -1;
}
sfree (sec->addr);
#if HAVE_LIBGCRYPT
sfree (sec->username);
sfree (sec->password);
if (sec->cypher != NULL)
gcry_cipher_close (sec->cypher);
#endif
} /* }}} void free_sockent_client */
static void free_sockent_server (struct sockent_server *ses) /* {{{ */
{
size_t i;
for (i = 0; i < ses->fd_num; i++)
{
if (ses->fd[i] >= 0)
{
close (ses->fd[i]);
ses->fd[i] = -1;
}
}
sfree (ses->fd);
#if HAVE_LIBGCRYPT
sfree (ses->auth_file);
fbh_destroy (ses->userdb);
if (ses->cypher != NULL)
gcry_cipher_close (ses->cypher);
#endif
} /* }}} void free_sockent_server */
static void sockent_destroy (sockent_t *se) /* {{{ */
{
sockent_t *next;
DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
while (se != NULL)
{
next = se->next;
sfree (se->node);
sfree (se->service);
if (se->type == SOCKENT_TYPE_CLIENT)
free_sockent_client (&se->data.client);
else
free_sockent_server (&se->data.server);
sfree (se);
se = next;
}
} /* }}} void sockent_destroy */
/*
* int network_set_ttl
*
* Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
* `IPV6_UNICAST_HOPS', depending on which option is applicable.
*
* The `struct addrinfo' is used to destinguish between unicast and multicast
* sockets.
*/
static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
{
DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
network_config_ttl);
assert (se->type == SOCKENT_TYPE_CLIENT);
if ((network_config_ttl < 1) || (network_config_ttl > 255))
return (-1);
if (ai->ai_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
int optname;
if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
optname = IP_MULTICAST_TTL;
else
optname = IP_TTL;
if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
&network_config_ttl,
sizeof (network_config_ttl)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
}
else if (ai->ai_family == AF_INET6)
{
/* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
int optname;
if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
optname = IPV6_MULTICAST_HOPS;
else
optname = IPV6_UNICAST_HOPS;
if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
&network_config_ttl,
sizeof (network_config_ttl)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
}
return (0);
} /* int network_set_ttl */
static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
{
DEBUG ("network plugin: network_set_interface: interface index = %i;",
se->interface);
assert (se->type == SOCKENT_TYPE_CLIENT);
if (ai->ai_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
{
#if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
/* If possible, use the "ip_mreqn" structure which has
* an "interface index" member. Using the interface
* index is preferred here, because of its similarity
* to the way IPv6 handles this. Unfortunately, it
* appears not to be portable. */
struct ip_mreqn mreq;
memset (&mreq, 0, sizeof (mreq));
mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
mreq.imr_address.s_addr = ntohl (INADDR_ANY);
mreq.imr_ifindex = se->interface;
#else
struct ip_mreq mreq;
memset (&mreq, 0, sizeof (mreq));
mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
#endif
if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
&mreq, sizeof (mreq)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
return (0);
}
}
else if (ai->ai_family == AF_INET6)
{
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
{
if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
&se->interface,
sizeof (se->interface)) != 0)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
return (0);
}
}
/* else: Not a multicast interface. */
if (se->interface != 0)
{
#if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
char interface_name[IFNAMSIZ];
if (if_indextoname (se->interface, interface_name) == NULL)
return (-1);
DEBUG ("network plugin: Binding socket to interface %s", interface_name);
if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
interface_name,
sizeof(interface_name)) == -1 )
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (bind-if): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
/* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
#else
WARNING ("network plugin: Cannot set the interface on a unicast "
"socket because "
# if !defined(SO_BINDTODEVICE)
"the \"SO_BINDTODEVICE\" socket option "
# else
"the \"if_indextoname\" function "
# endif
"is not available on your system.");
#endif
}
return (0);
} /* }}} network_set_interface */
static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
{
#if KERNEL_SOLARIS
char loop = 0;
#else
int loop = 0;
#endif
int yes = 1;
/* allow multiple sockets to use the same PORT number */
if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
&yes, sizeof(yes)) == -1) {
char errbuf[1024];
ERROR ("network plugin: setsockopt (reuseaddr): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
DEBUG ("fd = %i; calling `bind'", fd);
if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
{
char errbuf[1024];
ERROR ("bind: %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
if (ai->ai_family == AF_INET)
{
struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
{
#if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
struct ip_mreqn mreq;
#else
struct ip_mreq mreq;
#endif
DEBUG ("fd = %i; IPv4 multicast address found", fd);
mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
#if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
/* Set the interface using the interface index if
* possible (available). Unfortunately, the struct
* ip_mreqn is not portable. */
mreq.imr_address.s_addr = ntohl (INADDR_ANY);
mreq.imr_ifindex = interface_idx;
#else
mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
#endif
if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
&loop, sizeof (loop)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (multicast-loop): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&mreq, sizeof (mreq)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (add-membership): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
return (0);
}
}
else if (ai->ai_family == AF_INET6)
{
/* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
{
struct ipv6_mreq mreq;
DEBUG ("fd = %i; IPv6 multicast address found", fd);
memcpy (&mreq.ipv6mr_multiaddr,
&addr->sin6_addr,
sizeof (addr->sin6_addr));
/* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
* ipv6mr_interface may be set to zeroes to
* choose the default multicast interface or to
* the index of a particular multicast-capable
* interface if the host is multihomed.
* Membership is associ-associated with a
* single interface; programs running on
* multihomed hosts may need to join the same
* group on more than one interface.*/
mreq.ipv6mr_interface = interface_idx;
if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
&loop, sizeof (loop)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
&mreq, sizeof (mreq)) == -1)
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
return (-1);
}
return (0);
}
}
#if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
/* if a specific interface was set, bind the socket to it. But to avoid
* possible problems with multicast routing, only do that for non-multicast
* addresses */
if (interface_idx != 0)
{
char interface_name[IFNAMSIZ];
if (if_indextoname (interface_idx, interface_name) == NULL)
return (-1);
DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
interface_name,
sizeof(interface_name)) == -1 )
{
char errbuf[1024];
ERROR ("network plugin: setsockopt (bind-if): %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
return (-1);
}
}
#endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
return (0);
} /* int network_bind_socket */
/* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
* or `SOCKENT_TYPE_SERVER' */
static sockent_t *sockent_create (int type) /* {{{ */
{
sockent_t *se;
if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
return (NULL);
se = malloc (sizeof (*se));
if (se == NULL)
return (NULL);
memset (se, 0, sizeof (*se));
se->type = type;
se->node = NULL;
se->service = NULL;
se->interface = 0;
se->next = NULL;
if (type == SOCKENT_TYPE_SERVER)
{
se->data.server.fd = NULL;
se->data.server.fd_num = 0;
#if HAVE_LIBGCRYPT
se->data.server.security_level = SECURITY_LEVEL_NONE;
se->data.server.auth_file = NULL;
se->data.server.userdb = NULL;
se->data.server.cypher = NULL;
#endif
}
else
{
se->data.client.fd = -1;
se->data.client.addr = NULL;
#if HAVE_LIBGCRYPT
se->data.client.security_level = SECURITY_LEVEL_NONE;
se->data.client.username = NULL;
se->data.client.password = NULL;
se->data.client.cypher = NULL;
#endif
}
return (se);
} /* }}} sockent_t *sockent_create */
static int sockent_init_crypto (sockent_t *se) /* {{{ */
{
#if HAVE_LIBGCRYPT /* {{{ */
if (se->type == SOCKENT_TYPE_CLIENT)
{
if (se->data.client.security_level > SECURITY_LEVEL_NONE)
{
network_init_gcrypt ();
if ((se->data.client.username == NULL)
|| (se->data.client.password == NULL))
{
ERROR ("network plugin: Client socket with "
"security requested, but no "
"credentials are configured.");
return (-1);
}
gcry_md_hash_buffer (GCRY_MD_SHA256,
se->data.client.password_hash,
se->data.client.password,
strlen (se->data.client.password));
}
}
else /* (se->type == SOCKENT_TYPE_SERVER) */
{
if (se->data.server.security_level > SECURITY_LEVEL_NONE)
{
network_init_gcrypt ();
if (se->data.server.auth_file == NULL)
{
ERROR ("network plugin: Server socket with "
"security requested, but no "
"password file is configured.");
return (-1);
}
}
if (se->data.server.auth_file != NULL)
{
se->data.server.userdb = fbh_create (se->data.server.auth_file);
if (se->data.server.userdb == NULL)
{
ERROR ("network plugin: Reading password file "
"`%s' failed.",
se->data.server.auth_file);
if (se->data.server.security_level > SECURITY_LEVEL_NONE)
return (-1);
}
}
}
#endif /* }}} HAVE_LIBGCRYPT */
return (0);
} /* }}} int sockent_init_crypto */
static int sockent_client_connect (sockent_t *se) /* {{{ */
{
static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
struct sockent_client *client;
struct addrinfo ai_hints;
struct addrinfo *ai_list = NULL, *ai_ptr;
int status;
if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
return (EINVAL);
client = &se->data.client;
if (client->fd >= 0) /* already connected */
return (0);
memset (&ai_hints, 0, sizeof (ai_hints));
#ifdef AI_ADDRCONFIG
ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_DGRAM;
ai_hints.ai_protocol = IPPROTO_UDP;
status = getaddrinfo (se->node,
(se->service != NULL) ? se->service : NET_DEFAULT_PORT,
&ai_hints, &ai_list);
if (status != 0)
{
c_complain (LOG_ERR, &complaint,
"network plugin: getaddrinfo (%s, %s) failed: %s",
(se->node == NULL) ? "(null)" : se->node,
(se->service == NULL) ? "(null)" : se->service,
gai_strerror (status));
return (-1);
}
else
{
c_release (LOG_NOTICE, &complaint,
"network plugin: Successfully resolved \"%s\".",
se->node);
}
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
{
client->fd = socket (ai_ptr->ai_family,
ai_ptr->ai_socktype,
ai_ptr->ai_protocol);
if (client->fd < 0)
{
char errbuf[1024];
ERROR ("network plugin: socket(2) failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
continue;
}
client->addr = malloc (sizeof (*client->addr));
if (client->addr == NULL)
{
ERROR ("network plugin: malloc failed.");
close (client->fd);
client->fd = -1;
continue;
}
memset (client->addr, 0, sizeof (*client->addr));
assert (sizeof (*client->addr) >= ai_ptr->ai_addrlen);
memcpy (client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
client->addrlen = ai_ptr->ai_addrlen;
network_set_ttl (se, ai_ptr);
network_set_interface (se, ai_ptr);
/* We don't open more than one write-socket per
* node/service pair.. */
break;
}
freeaddrinfo (ai_list);
if (client->fd < 0)
return (-1);
return (0);
} /* }}} int sockent_client_connect */
static int sockent_client_disconnect (sockent_t *se) /* {{{ */
{
struct sockent_client *client;
if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
return (EINVAL);
client = &se->data.client;
if (client->fd >= 0) /* connected */
{
close (client->fd);
client->fd = -1;
}
sfree (client->addr);
client->addrlen = 0;
return (0);
} /* }}} int sockent_client_disconnect */
/* Open the file descriptors for a initialized sockent structure. */
static int sockent_server_listen (sockent_t *se) /* {{{ */
{
struct addrinfo ai_hints;
struct addrinfo *ai_list, *ai_ptr;
int status;
const char *node;
const char *service;
if (se == NULL)
return (-1);
assert (se->data.server.fd == NULL);
assert (se->data.server.fd_num == 0);
node = se->node;
service = se->service;
if (service == NULL)
service = NET_DEFAULT_PORT;
DEBUG ("network plugin: sockent_server_listen: node = %s; service = %s;",
node, service);
memset (&ai_hints, 0, sizeof (ai_hints));
ai_hints.ai_flags = 0;
#ifdef AI_PASSIVE
ai_hints.ai_flags |= AI_PASSIVE;
#endif
#ifdef AI_ADDRCONFIG
ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_DGRAM;
ai_hints.ai_protocol = IPPROTO_UDP;
status = getaddrinfo (node, service, &ai_hints, &ai_list);
if (status != 0)
{
ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
(se->node == NULL) ? "(null)" : se->node,
(se->service == NULL) ? "(null)" : se->service,
gai_strerror (status));
return (-1);
}
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
{
int *tmp;
tmp = realloc (se->data.server.fd,
sizeof (*tmp) * (se->data.server.fd_num + 1));
if (tmp == NULL)
{
ERROR ("network plugin: realloc failed.");
continue;
}
se->data.server.fd = tmp;
tmp = se->data.server.fd + se->data.server.fd_num;
*tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
ai_ptr->ai_protocol);
if (*tmp < 0)
{
char errbuf[1024];
ERROR ("network plugin: socket(2) failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
continue;
}
status = network_bind_socket (*tmp, ai_ptr, se->interface);
if (status != 0)
{
close (*tmp);
*tmp = -1;
continue;
}
se->data.server.fd_num++;
continue;
} /* for (ai_list) */
freeaddrinfo (ai_list);
if (se->data.server.fd_num <= 0)
return (-1);
return (0);
} /* }}} int sockent_server_listen */
/* Add a sockent to the global list of sockets */
static int sockent_add (sockent_t *se) /* {{{ */
{
sockent_t *last_ptr;
if (se == NULL)
return (-1);
if (se->type == SOCKENT_TYPE_SERVER)
{
struct pollfd *tmp;
size_t i;
tmp = realloc (listen_sockets_pollfd,
sizeof (*tmp) * (listen_sockets_num
+ se->data.server.fd_num));
if (tmp == NULL)
{
ERROR ("network plugin: realloc failed.");
return (-1);
}
listen_sockets_pollfd = tmp;
tmp = listen_sockets_pollfd + listen_sockets_num;
for (i = 0; i < se->data.server.fd_num; i++)
{
memset (tmp + i, 0, sizeof (*tmp));
tmp[i].fd = se->data.server.fd[i];
tmp[i].events = POLLIN | POLLPRI;
tmp[i].revents = 0;
}
listen_sockets_num += se->data.server.fd_num;
if (listen_sockets == NULL)
{
listen_sockets = se;
return (0);
}
last_ptr = listen_sockets;
}
else /* if (se->type == SOCKENT_TYPE_CLIENT) */
{
if (sending_sockets == NULL)
{
sending_sockets = se;
return (0);
}
last_ptr = sending_sockets;
}
while (last_ptr->next != NULL)
last_ptr = last_ptr->next;
last_ptr->next = se;
return (0);
} /* }}} int sockent_add */
static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
{
while (42)
{
receive_list_entry_t *ent;
sockent_t *se;
/* Lock and wait for more data to come in */
pthread_mutex_lock (&receive_list_lock);
while ((listen_loop == 0)
&& (receive_list_head == NULL))
pthread_cond_wait (&receive_list_cond, &receive_list_lock);
/* Remove the head entry and unlock */
ent = receive_list_head;
if (ent != NULL)
receive_list_head = ent->next;
receive_list_length--;
pthread_mutex_unlock (&receive_list_lock);
/* Check whether we are supposed to exit. We do NOT check `listen_loop'
* because we dispatch all missing packets before shutting down. */
if (ent == NULL)
break;
/* Look for the correct `sockent_t' */
se = listen_sockets;
while (se != NULL)
{
size_t i;
for (i = 0; i < se->data.server.fd_num; i++)
if (se->data.server.fd[i] == ent->fd)
break;
if (i < se->data.server.fd_num)
break;
se = se->next;
}
if (se == NULL)
{
ERROR ("network plugin: Got packet from FD %i, but can't "
"find an appropriate socket entry.",
ent->fd);
sfree (ent->data);
sfree (ent);
continue;
}
parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
/* username = */ NULL);
sfree (ent->data);
sfree (ent);
} /* while (42) */
return (NULL);
} /* }}} void *dispatch_thread */
static int network_receive (void) /* {{{ */
{
char buffer[network_config_packet_size];
int buffer_len;
int i;
int status = 0;
receive_list_entry_t *private_list_head;
receive_list_entry_t *private_list_tail;
uint64_t private_list_length;
assert (listen_sockets_num > 0);
private_list_head = NULL;
private_list_tail = NULL;
private_list_length = 0;
while (listen_loop == 0)
{
status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
if (status <= 0)
{
char errbuf[1024];
if (errno == EINTR)
continue;
ERROR ("network plugin: poll(2) failed: %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
break;
}
for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
{
receive_list_entry_t *ent;
if ((listen_sockets_pollfd[i].revents
& (POLLIN | POLLPRI)) == 0)
continue;
status--;
buffer_len = recv (listen_sockets_pollfd[i].fd,
buffer, sizeof (buffer),
0 /* no flags */);
if (buffer_len < 0)
{
char errbuf[1024];
status = (errno != 0) ? errno : -1;
ERROR ("network plugin: recv(2) failed: %s",
sstrerror (errno, errbuf, sizeof (errbuf)));
break;
}
stats_octets_rx += ((uint64_t) buffer_len);
stats_packets_rx++;
/* TODO: Possible performance enhancement: Do not free
* these entries in the dispatch thread but put them in
* another list, so we don't have to allocate more and
* more of these structures. */
ent = malloc (sizeof (receive_list_entry_t));
if (ent == NULL)
{
ERROR ("network plugin: malloc failed.");
status = ENOMEM;
break;
}
memset (ent, 0, sizeof (receive_list_entry_t));
ent->data = malloc (network_config_packet_size);
if (ent->data == NULL)
{
sfree (ent);
ERROR ("network plugin: malloc failed.");
status = ENOMEM;
break;
}
ent->fd = listen_sockets_pollfd[i].fd;
ent->next = NULL;
memcpy (ent->data, buffer, buffer_len);
ent->data_len = buffer_len;
if (private_list_head == NULL)
private_list_head = ent;
else
private_list_tail->next = ent;
private_list_tail = ent;
private_list_length++;
/* Do not block here. Blocking here has led to
* insufficient performance in the past. */
if (pthread_mutex_trylock (&receive_list_lock) == 0)
{
assert (((receive_list_head == NULL) && (receive_list_length == 0))
|| ((receive_list_head != NULL) && (receive_list_length != 0)));
if (receive_list_head == NULL)
receive_list_head = private_list_head;
else
receive_list_tail->next = private_list_head;
receive_list_tail = private_list_tail;
receive_list_length += private_list_length;
pthread_cond_signal (&receive_list_cond);
pthread_mutex_unlock (&receive_list_lock);
private_list_head = NULL;
private_list_tail = NULL;
private_list_length = 0;
}
status = 0;
} /* for (listen_sockets_pollfd) */
if (status != 0)
break;
} /* while (listen_loop == 0) */
/* Make sure everything is dispatched before exiting. */
if (private_list_head != NULL)
{
pthread_mutex_lock (&receive_list_lock);
if (receive_list_head == NULL)
receive_list_head = private_list_head;
else
receive_list_tail->next = private_list_head;
receive_list_tail = private_list_tail;
receive_list_length += private_list_length;
pthread_cond_signal (&receive_list_cond);
pthread_mutex_unlock (&receive_list_lock);
}
return (status);
} /* }}} int network_receive */
static void *receive_thread (void __attribute__((unused)) *arg)
{
return (network_receive () ? (void *) 1 : (void *) 0);
} /* void *receive_thread */
static void network_init_buffer (void)
{
memset (send_buffer, 0, network_config_packet_size);
send_buffer_ptr = send_buffer;
send_buffer_fill = 0;
memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
} /* int network_init_buffer */
static void networt_send_buffer_plain (sockent_t *se, /* {{{ */
const char *buffer, size_t buffer_size)
{
int status;
while (42)
{
status = sockent_client_connect (se);
if (status != 0)
return;
status = sendto (se->data.client.fd, buffer, buffer_size,
/* flags = */ 0,
(struct sockaddr *) se->data.client.addr,
se->data.client.addrlen);
if (status < 0)
{
char errbuf[1024];
if ((errno == EINTR) || (errno == EAGAIN))
continue;
ERROR ("network plugin: sendto failed: %s. Closing sending socket.",
sstrerror (errno, errbuf, sizeof (errbuf)));
sockent_client_disconnect (se);
return;
}
break;
} /* while (42) */
} /* }}} void networt_send_buffer_plain */
#if HAVE_LIBGCRYPT
#define BUFFER_ADD(p,s) do { \
memcpy (buffer + buffer_offset, (p), (s)); \
buffer_offset += (s); \
} while (0)
static void networt_send_buffer_signed (sockent_t *se, /* {{{ */
const char *in_buffer, size_t in_buffer_size)
{
part_signature_sha256_t ps;
char buffer[BUFF_SIG_SIZE + in_buffer_size];
size_t buffer_offset;
size_t username_len;
gcry_md_hd_t hd;
gcry_error_t err;
unsigned char *hash;
hd = NULL;
err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
if (err != 0)
{
ERROR ("network plugin: Creating HMAC object failed: %s",
gcry_strerror (err));
return;
}
err = gcry_md_setkey (hd, se->data.client.password,
strlen (se->data.client.password));
if (err != 0)
{
ERROR ("network plugin: gcry_md_setkey failed: %s",
gcry_strerror (err));
gcry_md_close (hd);
return;
}
username_len = strlen (se->data.client.username);
if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
{
ERROR ("network plugin: Username too long: %s",
se->data.client.username);
return;
}
memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
se->data.client.username, username_len);
memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
in_buffer, in_buffer_size);
/* Initialize the `ps' structure. */
memset (&ps, 0, sizeof (ps));
ps.head.type = htons (TYPE_SIGN_SHA256);
ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
/* Calculate the hash value. */
gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
username_len + in_buffer_size);
hash = gcry_md_read (hd, GCRY_MD_SHA256);
if (hash == NULL)
{
ERROR ("network plugin: gcry_md_read failed.");
gcry_md_close (hd);
return;
}
memcpy (ps.hash, hash, sizeof (ps.hash));
/* Add the header */
buffer_offset = 0;
BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
BUFFER_ADD (ps.hash, sizeof (ps.hash));
assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
gcry_md_close (hd);
hd = NULL;
buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
networt_send_buffer_plain (se, buffer, buffer_offset);
} /* }}} void networt_send_buffer_signed */
static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
const char *in_buffer, size_t in_buffer_size)
{
part_encryption_aes256_t pea;
char buffer[BUFF_SIG_SIZE + in_buffer_size];
size_t buffer_size;
size_t buffer_offset;
size_t header_size;
size_t username_len;
gcry_error_t err;
gcry_cipher_hd_t cypher;
/* Initialize the header fields */
memset (&pea, 0, sizeof (pea));
pea.head.type = htons (TYPE_ENCR_AES256);
pea.username = se->data.client.username;
username_len = strlen (pea.username);
if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
{
ERROR ("network plugin: Username too long: %s", pea.username);
return;
}
buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
header_size = PART_ENCRYPTION_AES256_SIZE + username_len
- sizeof (pea.hash);
assert (buffer_size <= sizeof (buffer));
DEBUG ("network plugin: networt_send_buffer_encrypted: "
"buffer_size = %zu;", buffer_size);
pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
+ username_len + in_buffer_size));
pea.username_length = htons ((uint16_t) username_len);
/* Chose a random initialization vector. */
gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
/* Create hash of the payload */
gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
/* Initialize the buffer */
buffer_offset = 0;
memset (buffer, 0, sizeof (buffer));
BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
BUFFER_ADD (pea.username, username_len);
BUFFER_ADD (pea.iv, sizeof (pea.iv));
assert (buffer_offset == header_size);
BUFFER_ADD (pea.hash, sizeof (pea.hash));
BUFFER_ADD (in_buffer, in_buffer_size);
assert (buffer_offset == buffer_size);
cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
se->data.client.password);
if (cypher == NULL)
return;
/* Encrypt the buffer in-place */
err = gcry_cipher_encrypt (cypher,
buffer + header_size,
buffer_size - header_size,
/* in = */ NULL, /* in len = */ 0);
if (err != 0)
{
ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
gcry_strerror (err));
return;
}
/* Send it out without further modifications */
networt_send_buffer_plain (se, buffer, buffer_size);
} /* }}} void networt_send_buffer_encrypted */
#undef BUFFER_ADD
#endif /* HAVE_LIBGCRYPT */
static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
{
sockent_t *se;
DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
for (se = sending_sockets; se != NULL; se = se->next)
{
#if HAVE_LIBGCRYPT
if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
networt_send_buffer_encrypted (se, buffer, buffer_len);
else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
networt_send_buffer_signed (se, buffer, buffer_len);
else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
#endif /* HAVE_LIBGCRYPT */
networt_send_buffer_plain (se, buffer, buffer_len);
} /* for (sending_sockets) */
} /* }}} void network_send_buffer */
static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
value_list_t *vl_def,
const data_set_t *ds, const value_list_t *vl)
{
char *buffer_orig = buffer;
if (strcmp (vl_def->host, vl->host) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
vl->host, strlen (vl->host)) != 0)
return (-1);
sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
}
if (vl_def->time != vl->time)
{
if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
(uint64_t) vl->time))
return (-1);
vl_def->time = vl->time;
}
if (vl_def->interval != vl->interval)
{
if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
(uint64_t) vl->interval))
return (-1);
vl_def->interval = vl->interval;
}
if (strcmp (vl_def->plugin, vl->plugin) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
vl->plugin, strlen (vl->plugin)) != 0)
return (-1);
sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
}
if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
vl->plugin_instance,
strlen (vl->plugin_instance)) != 0)
return (-1);
sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
}
if (strcmp (vl_def->type, vl->type) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
vl->type, strlen (vl->type)) != 0)
return (-1);
sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
}
if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
{
if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
vl->type_instance,
strlen (vl->type_instance)) != 0)
return (-1);
sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
}
if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
return (-1);
return (buffer - buffer_orig);
} /* }}} int add_to_buffer */
static void flush_buffer (void)
{
DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
send_buffer_fill);
network_send_buffer (send_buffer, (size_t) send_buffer_fill);
stats_octets_tx += ((uint64_t) send_buffer_fill);
stats_packets_tx++;
network_init_buffer ();
}
static int network_write (const data_set_t *ds, const value_list_t *vl,
user_data_t __attribute__((unused)) *user_data)
{
int status;
if (!check_send_okay (vl))
{
#if COLLECT_DEBUG
char name[6*DATA_MAX_NAME_LEN];
FORMAT_VL (name, sizeof (name), vl);
name[sizeof (name) - 1] = 0;
DEBUG ("network plugin: network_write: "
"NOT sending %s.", name);
#endif
/* Counter is not protected by another lock and may be reached by
* multiple threads */
pthread_mutex_lock (&stats_lock);
stats_values_not_sent++;
pthread_mutex_unlock (&stats_lock);
return (0);
}
uc_meta_data_add_unsigned_int (vl,
"network:time_sent", (uint64_t) vl->time);
pthread_mutex_lock (&send_buffer_lock);
status = add_to_buffer (send_buffer_ptr,
network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
&send_buffer_vl,
ds, vl);
if (status >= 0)
{
/* status == bytes added to the buffer */
send_buffer_fill += status;
send_buffer_ptr += status;
stats_values_sent++;
}
else
{
flush_buffer ();
status = add_to_buffer (send_buffer_ptr,
network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
&send_buffer_vl,
ds, vl);
if (status >= 0)
{
send_buffer_fill += status;
send_buffer_ptr += status;
stats_values_sent++;
}
}
if (status < 0)
{
ERROR ("network plugin: Unable to append to the "
"buffer for some weird reason");
}
else if ((network_config_packet_size - send_buffer_fill) < 15)
{
flush_buffer ();
}
pthread_mutex_unlock (&send_buffer_lock);
return ((status < 0) ? -1 : 0);
} /* int network_write */
static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
int *retval)
{
if ((ci->values_num != 1)
|| ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
&& (ci->values[0].type != OCONFIG_TYPE_STRING)))
{
ERROR ("network plugin: The `%s' config option needs "
"exactly one boolean argument.", ci->key);
return (-1);
}
if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
{
if (ci->values[0].value.boolean)
*retval = 1;
else
*retval = 0;
}
else
{
char *str = ci->values[0].value.string;
if (IS_TRUE (str))
*retval = 1;
else if (IS_FALSE (str))
*retval = 0;
else
{
ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
"option as boolean value.",
str, ci->key);
return (-1);
}
}
return (0);
} /* }}} int network_config_set_boolean */
static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
{
int tmp;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_NUMBER))
{
WARNING ("network plugin: The `TimeToLive' config option needs exactly "
"one numeric argument.");
return (-1);
}
tmp = (int) ci->values[0].value.number;
if ((tmp > 0) && (tmp <= 255))
network_config_ttl = tmp;
else {
WARNING ("network plugin: The `TimeToLive' must be between 1 and 255.");
return (-1);
}
return (0);
} /* }}} int network_config_set_ttl */
static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
int *interface)
{
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("network plugin: The `Interface' config option needs exactly "
"one string argument.");
return (-1);
}
if (interface == NULL)
return (-1);
*interface = if_nametoindex (ci->values[0].value.string);
return (0);
} /* }}} int network_config_set_interface */
static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
{
int tmp;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_NUMBER))
{
WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
"one numeric argument.");
return (-1);
}
tmp = (int) ci->values[0].value.number;
if ((tmp >= 1024) && (tmp <= 65535))
network_config_packet_size = tmp;
return (0);
} /* }}} int network_config_set_buffer_size */
#if HAVE_LIBGCRYPT
static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
char **ret_string)
{
char *tmp;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("network plugin: The `%s' config option needs exactly "
"one string argument.", ci->key);
return (-1);
}
tmp = strdup (ci->values[0].value.string);
if (tmp == NULL)
return (-1);
sfree (*ret_string);
*ret_string = tmp;
return (0);
} /* }}} int network_config_set_string */
#endif /* HAVE_LIBGCRYPT */
#if HAVE_LIBGCRYPT
static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
int *retval)
{
char *str;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
"one string argument.");
return (-1);
}
str = ci->values[0].value.string;
if (strcasecmp ("Encrypt", str) == 0)
*retval = SECURITY_LEVEL_ENCRYPT;
else if (strcasecmp ("Sign", str) == 0)
*retval = SECURITY_LEVEL_SIGN;
else if (strcasecmp ("None", str) == 0)
*retval = SECURITY_LEVEL_NONE;
else
{
WARNING ("network plugin: Unknown security level: %s.", str);
return (-1);
}
return (0);
} /* }}} int network_config_set_security_level */
#endif /* HAVE_LIBGCRYPT */
static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
{
sockent_t *se;
int status;
int i;
if ((ci->values_num < 1) || (ci->values_num > 2)
|| (ci->values[0].type != OCONFIG_TYPE_STRING)
|| ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
{
ERROR ("network plugin: The `%s' config option needs "
"one or two string arguments.", ci->key);
return (-1);
}
se = sockent_create (SOCKENT_TYPE_SERVER);
if (se == NULL)
{
ERROR ("network plugin: sockent_create failed.");
return (-1);
}
se->node = strdup (ci->values[0].value.string);
if (ci->values_num >= 2)
se->service = strdup (ci->values[1].value.string);
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
#if HAVE_LIBGCRYPT
if (strcasecmp ("AuthFile", child->key) == 0)
network_config_set_string (child, &se->data.server.auth_file);
else if (strcasecmp ("SecurityLevel", child->key) == 0)
network_config_set_security_level (child,
&se->data.server.security_level);
else
#endif /* HAVE_LIBGCRYPT */
if (strcasecmp ("Interface", child->key) == 0)
network_config_set_interface (child,
&se->interface);
else
{
WARNING ("network plugin: Option `%s' is not allowed here.",
child->key);
}
}
#if HAVE_LIBGCRYPT
if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
&& (se->data.server.auth_file == NULL))
{
ERROR ("network plugin: A security level higher than `none' was "
"requested, but no AuthFile option was given. Cowardly refusing to "
"open this socket!");
sockent_destroy (se);
return (-1);
}
#endif /* HAVE_LIBGCRYPT */
status = sockent_init_crypto (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_listen: sockent_init_crypto() failed.");
sockent_destroy (se);
return (-1);
}
status = sockent_server_listen (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_server: sockent_server_listen failed.");
sockent_destroy (se);
return (-1);
}
status = sockent_add (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
sockent_destroy (se);
return (-1);
}
return (0);
} /* }}} int network_config_add_listen */
static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
{
sockent_t *se;
int status;
int i;
if ((ci->values_num < 1) || (ci->values_num > 2)
|| (ci->values[0].type != OCONFIG_TYPE_STRING)
|| ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
{
ERROR ("network plugin: The `%s' config option needs "
"one or two string arguments.", ci->key);
return (-1);
}
se = sockent_create (SOCKENT_TYPE_CLIENT);
if (se == NULL)
{
ERROR ("network plugin: sockent_create failed.");
return (-1);
}
se->node = strdup (ci->values[0].value.string);
if (ci->values_num >= 2)
se->service = strdup (ci->values[1].value.string);
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
#if HAVE_LIBGCRYPT
if (strcasecmp ("Username", child->key) == 0)
network_config_set_string (child, &se->data.client.username);
else if (strcasecmp ("Password", child->key) == 0)
network_config_set_string (child, &se->data.client.password);
else if (strcasecmp ("SecurityLevel", child->key) == 0)
network_config_set_security_level (child,
&se->data.client.security_level);
else
#endif /* HAVE_LIBGCRYPT */
if (strcasecmp ("Interface", child->key) == 0)
network_config_set_interface (child,
&se->interface);
else
{
WARNING ("network plugin: Option `%s' is not allowed here.",
child->key);
}
}
#if HAVE_LIBGCRYPT
if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
&& ((se->data.client.username == NULL)
|| (se->data.client.password == NULL)))
{
ERROR ("network plugin: A security level higher than `none' was "
"requested, but no Username or Password option was given. "
"Cowardly refusing to open this socket!");
sockent_destroy (se);
return (-1);
}
#endif /* HAVE_LIBGCRYPT */
status = sockent_init_crypto (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_server: sockent_init_crypto() failed.");
sockent_destroy (se);
return (-1);
}
/* No call to sockent_client_connect() here -- it is called from
* networt_send_buffer_plain(). */
status = sockent_add (se);
if (status != 0)
{
ERROR ("network plugin: network_config_add_server: sockent_add failed.");
sockent_destroy (se);
return (-1);
}
return (0);
} /* }}} int network_config_add_server */
static int network_config (oconfig_item_t *ci) /* {{{ */
{
int i;
/* The options need to be applied first */
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("TimeToLive", child->key) == 0)
network_config_set_ttl (child);
}
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("Listen", child->key) == 0)
network_config_add_listen (child);
else if (strcasecmp ("Server", child->key) == 0)
network_config_add_server (child);
else if (strcasecmp ("TimeToLive", child->key) == 0) {
/* Handled earlier */
}
else if (strcasecmp ("MaxPacketSize", child->key) == 0)
network_config_set_buffer_size (child);
else if (strcasecmp ("Forward", child->key) == 0)
network_config_set_boolean (child, &network_config_forward);
else if (strcasecmp ("ReportStats", child->key) == 0)
network_config_set_boolean (child, &network_config_stats);
else
{
WARNING ("network plugin: Option `%s' is not allowed here.",
child->key);
}
}
return (0);
} /* }}} int network_config */
static int network_notification (const notification_t *n,
user_data_t __attribute__((unused)) *user_data)
{
char buffer[network_config_packet_size];
char *buffer_ptr = buffer;
int buffer_free = sizeof (buffer);
int status;
if (!check_send_notify_okay (n))
return (0);
memset (buffer, 0, sizeof (buffer));
status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
(uint64_t) n->time);
if (status != 0)
return (-1);
status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
(uint64_t) n->severity);
if (status != 0)
return (-1);
if (strlen (n->host) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
n->host, strlen (n->host));
if (status != 0)
return (-1);
}
if (strlen (n->plugin) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
n->plugin, strlen (n->plugin));
if (status != 0)
return (-1);
}
if (strlen (n->plugin_instance) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free,
TYPE_PLUGIN_INSTANCE,
n->plugin_instance, strlen (n->plugin_instance));
if (status != 0)
return (-1);
}
if (strlen (n->type) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
n->type, strlen (n->type));
if (status != 0)
return (-1);
}
if (strlen (n->type_instance) > 0)
{
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
n->type_instance, strlen (n->type_instance));
if (status != 0)
return (-1);
}
status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
n->message, strlen (n->message));
if (status != 0)
return (-1);
network_send_buffer (buffer, sizeof (buffer) - buffer_free);
return (0);
} /* int network_notification */
static int network_shutdown (void)
{
sockent_t *se;
listen_loop++;
/* Kill the listening thread */
if (receive_thread_running != 0)
{
INFO ("network plugin: Stopping receive thread.");
pthread_kill (receive_thread_id, SIGTERM);
pthread_join (receive_thread_id, NULL /* no return value */);
memset (&receive_thread_id, 0, sizeof (receive_thread_id));
receive_thread_running = 0;
}
/* Shutdown the dispatching thread */
if (dispatch_thread_running != 0)
{
INFO ("network plugin: Stopping dispatch thread.");
pthread_mutex_lock (&receive_list_lock);
pthread_cond_broadcast (&receive_list_cond);
pthread_mutex_unlock (&receive_list_lock);
pthread_join (dispatch_thread_id, /* ret = */ NULL);
dispatch_thread_running = 0;
}
sockent_destroy (listen_sockets);
if (send_buffer_fill > 0)
flush_buffer ();
sfree (send_buffer);
for (se = sending_sockets; se != NULL; se = se->next)
sockent_client_disconnect (se);
sockent_destroy (sending_sockets);
plugin_unregister_config ("network");
plugin_unregister_init ("network");
plugin_unregister_write ("network");
plugin_unregister_shutdown ("network");
return (0);
} /* int network_shutdown */
static int network_stats_read (void) /* {{{ */
{
derive_t copy_octets_rx;
derive_t copy_octets_tx;
derive_t copy_packets_rx;
derive_t copy_packets_tx;
derive_t copy_values_dispatched;
derive_t copy_values_not_dispatched;
derive_t copy_values_sent;
derive_t copy_values_not_sent;
derive_t copy_receive_list_length;
value_list_t vl = VALUE_LIST_INIT;
value_t values[2];
copy_octets_rx = stats_octets_rx;
copy_octets_tx = stats_octets_tx;
copy_packets_rx = stats_packets_rx;
copy_packets_tx = stats_packets_tx;
copy_values_dispatched = stats_values_dispatched;
copy_values_not_dispatched = stats_values_not_dispatched;
copy_values_sent = stats_values_sent;
copy_values_not_sent = stats_values_not_sent;
copy_receive_list_length = receive_list_length;
/* Initialize `vl' */
vl.values = values;
vl.values_len = 2;
vl.time = 0;
sstrncpy (vl.host, hostname_g, sizeof (vl.host));
sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
/* Octets received / sent */
vl.values[0].derive = (derive_t) copy_octets_rx;
vl.values[1].derive = (derive_t) copy_octets_tx;
sstrncpy (vl.type, "if_octets", sizeof (vl.type));
plugin_dispatch_values (&vl);
/* Packets received / send */
vl.values[0].derive = (derive_t) copy_packets_rx;
vl.values[1].derive = (derive_t) copy_packets_tx;
sstrncpy (vl.type, "if_packets", sizeof (vl.type));
plugin_dispatch_values (&vl);
/* Values (not) dispatched and (not) send */
sstrncpy (vl.type, "total_values", sizeof (vl.type));
vl.values_len = 1;
vl.values[0].derive = (derive_t) copy_values_dispatched;
sstrncpy (vl.type_instance, "dispatch-accepted",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
vl.values[0].derive = (derive_t) copy_values_not_dispatched;
sstrncpy (vl.type_instance, "dispatch-rejected",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
vl.values[0].derive = (derive_t) copy_values_sent;
sstrncpy (vl.type_instance, "send-accepted",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
vl.values[0].derive = (derive_t) copy_values_not_sent;
sstrncpy (vl.type_instance, "send-rejected",
sizeof (vl.type_instance));
plugin_dispatch_values (&vl);
/* Receive queue length */
vl.values[0].gauge = (gauge_t) copy_receive_list_length;
sstrncpy (vl.type, "queue_length", sizeof (vl.type));
vl.type_instance[0] = 0;
plugin_dispatch_values (&vl);
return (0);
} /* }}} int network_stats_read */
static int network_init (void)
{
static _Bool have_init = 0;
/* Check if we were already initialized. If so, just return - there's
* nothing more to do (for now, that is). */
if (have_init)
return (0);
have_init = 1;
#if HAVE_LIBGCRYPT
network_init_gcrypt ();
#endif
if (network_config_stats != 0)
plugin_register_read ("network", network_stats_read);
plugin_register_shutdown ("network", network_shutdown);
send_buffer = malloc (network_config_packet_size);
if (send_buffer == NULL)
{
ERROR ("network plugin: malloc failed.");
return (-1);
}
network_init_buffer ();
/* setup socket(s) and so on */
if (sending_sockets != NULL)
{
plugin_register_write ("network", network_write,
/* user_data = */ NULL);
plugin_register_notification ("network", network_notification,
/* user_data = */ NULL);
}
/* If no threads need to be started, return here. */
if ((listen_sockets_num == 0)
|| ((dispatch_thread_running != 0)
&& (receive_thread_running != 0)))
return (0);
if (dispatch_thread_running == 0)
{
int status;
status = plugin_thread_create (&dispatch_thread_id,
NULL /* no attributes */,
dispatch_thread,
NULL /* no argument */);
if (status != 0)
{
char errbuf[1024];
ERROR ("network: pthread_create failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
}
else
{
dispatch_thread_running = 1;
}
}
if (receive_thread_running == 0)
{
int status;
status = plugin_thread_create (&receive_thread_id,
NULL /* no attributes */,
receive_thread,
NULL /* no argument */);
if (status != 0)
{
char errbuf[1024];
ERROR ("network: pthread_create failed: %s",
sstrerror (errno, errbuf,
sizeof (errbuf)));
}
else
{
receive_thread_running = 1;
}
}
return (0);
} /* int network_init */
/*
* The flush option of the network plugin cannot flush individual identifiers.
* All the values are added to a buffer and sent when the buffer is full, the
* requested value may or may not be in there, it's not worth finding out. We
* just send the buffer if `flush' is called - if the requested value was in
* there, good. If not, well, then there is nothing to flush.. -octo
*/
static int network_flush (__attribute__((unused)) cdtime_t timeout,
__attribute__((unused)) const char *identifier,
__attribute__((unused)) user_data_t *user_data)
{
pthread_mutex_lock (&send_buffer_lock);
if (send_buffer_fill > 0)
flush_buffer ();
pthread_mutex_unlock (&send_buffer_lock);
return (0);
} /* int network_flush */
void module_register (void)
{
plugin_register_complex_config ("network", network_config);
plugin_register_init ("network", network_init);
plugin_register_flush ("network", network_flush,
/* user_data = */ NULL);
} /* void module_register */
/* vim: set fdm=marker : */
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5203_0 |
crossvul-cpp_data_good_346_9 | /*
* Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com>
*
* This file is part of OpenSC.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "egk-tool-cmdline.h"
#include "libopensc/log.h"
#include "libopensc/opensc.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#ifdef ENABLE_ZLIB
#include <zlib.h>
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
z_stream stream;
memset(&stream, 0, sizeof stream);
stream.total_in = compressed_len;
stream.avail_in = compressed_len;
stream.total_out = *uncompressed_len;
stream.avail_out = *uncompressed_len;
stream.next_in = (Bytef *) compressed;
stream.next_out = (Bytef *) uncompressed;
/* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */
if (Z_OK == inflateInit2(&stream, (15 + 32))
&& Z_STREAM_END == inflate(&stream, Z_FINISH)) {
*uncompressed_len = stream.total_out;
} else {
return SC_ERROR_INVALID_DATA;
}
inflateEnd(&stream);
return SC_SUCCESS;
}
#else
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif
#define PRINT(c) (isprint(c) ? c : '?')
void dump_binary(void *buf, size_t buf_len)
{
#ifdef _WIN32
_setmode(fileno(stdout), _O_BINARY);
#endif
fwrite(buf, 1, buf_len, stdout);
#ifdef _WIN32
_setmode(fileno(stdout), _O_TEXT);
#endif
}
const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02};
static int initialize(int reader_id, int verbose,
sc_context_t **ctx, sc_reader_t **reader)
{
unsigned int i, reader_count;
int r;
if (!ctx || !reader)
return SC_ERROR_INVALID_ARGUMENTS;
r = sc_establish_context(ctx, "");
if (r < 0 || !*ctx) {
fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r));
return r;
}
(*ctx)->debug = verbose;
(*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
reader_count = sc_ctx_get_reader_count(*ctx);
if (reader_count == 0) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n");
return SC_ERROR_NO_READERS_FOUND;
}
if (reader_id < 0) {
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < reader_count; i++) {
*reader = sc_ctx_get_reader(*ctx, i);
if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) {
reader_id = i;
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader"
" with a card: %s", (*reader)->name);
break;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader.");
reader_id = 0;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number "
"(%d), only %d available.\n", reader_id, reader_count);
return SC_ERROR_NO_READERS_FOUND;
}
*reader = sc_ctx_get_reader(*ctx, reader_id);
return SC_SUCCESS;
}
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file && file->size > 0 ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix)
{
*major = 0;
*minor = 0;
*fix = 0;
/* decode BCD to decimal */
if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) {
*major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4);
}
if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) {
*minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF);
}
if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10)
&& (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) {
*fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100
+ (bcd[4]>>4)*10 + (bcd[4]&0xF);
}
}
int
main (int argc, char **argv)
{
struct gengetopt_args_info cmdline;
struct sc_path path;
struct sc_context *ctx;
struct sc_reader *reader = NULL;
struct sc_card *card;
unsigned char *data = NULL;
size_t data_len = 0;
int r;
if (cmdline_parser(argc, argv, &cmdline) != 0)
exit(1);
r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader);
if (r < 0) {
fprintf(stderr, "Can't initialize reader\n");
exit(1);
}
if (sc_connect_card(reader, &card) < 0) {
fprintf(stderr, "Could not connect to card\n");
sc_release_context(ctx);
exit(1);
}
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0);
if (SC_SUCCESS != sc_select_file(card, &path, NULL))
goto err;
if (cmdline.pd_flag
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 2) {
size_t len_pd = (data[0] << 8) | data[1];
if (len_pd + 2 <= data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + 2, len_pd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + 2, len_pd);
}
}
}
if ((cmdline.vd_flag || cmdline.gvd_flag)
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 8) {
size_t off_vd = (data[0] << 8) | data[1];
size_t end_vd = (data[2] << 8) | data[3];
size_t off_gvd = (data[4] << 8) | data[5];
size_t end_gvd = (data[6] << 8) | data[7];
size_t len_vd = end_vd - off_vd + 1;
size_t len_gvd = end_gvd - off_gvd + 1;
if (off_vd <= end_vd && end_vd < data_len
&& off_gvd <= end_gvd && end_gvd < data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (cmdline.vd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_vd, len_vd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_vd, len_vd);
}
}
if (cmdline.gvd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_gvd, len_gvd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_gvd, len_gvd);
}
}
}
}
if (cmdline.vsd_status_flag
&& read_file(card, "D00C", &data, &data_len)
&& data_len >= 25) {
char *status;
unsigned int major, minor, fix;
switch (data[0]) {
case '0':
status = "Transactions pending";
break;
case '1':
status = "No transactions pending";
break;
default:
status = "Unknown";
break;
}
decode_version(data+15, &major, &minor, &fix);
printf(
"Status %s\n"
"Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n"
"Version %u.%u.%u\n",
status,
PRINT(data[7]), PRINT(data[8]),
PRINT(data[5]), PRINT(data[6]),
PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]),
PRINT(data[9]), PRINT(data[10]),
PRINT(data[11]), PRINT(data[12]),
PRINT(data[13]), PRINT(data[14]),
major, minor, fix);
}
err:
sc_disconnect_card(card);
sc_release_context(ctx);
cmdline_parser_free (&cmdline);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_346_9 |
crossvul-cpp_data_good_160_2 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Utilities and definitions for handling Pins
* ----------------------------------------------------------------------------
*/
#include "jspin.h"
#include "jspininfo.h" // auto-generated
#include "jsinteractive.h"
#include "jshardware.h"
// jshGetDeviceObjectFor
#include "jswrapper.h"
// NOTE: If PIN_NAMES_DIRECT is defined, pin names are worked out directly from port + pin in pinInfo
// ----------------------------------------------------------------------------
// Whether a pin's state has been set manually or not
BITFIELD_DECL(jshPinStateIsManual, JSH_PIN_COUNT);
// ----------------------------------------------------------------------------
bool jshIsPinValid(Pin pin) {
// Note, PIN_UNDEFINED is always > JSH_PIN_COUNT
return pin < JSH_PIN_COUNT && (pinInfo[pin].port&JSH_PORT_MASK) != JSH_PORT_NONE;
}
Pin jshGetPinFromString(const char *s) {
if (((s[0]>='A' && s[0]<='I') || s[0]=='V') && s[1]) {
int port = (s[0]=='V') ? JSH_PORTV : JSH_PORTA+s[0]-'A';
int pin = -1;
if (s[1]>='0' && s[1]<='9') {
if (!s[2]) { // D0-D9
pin = (s[1]-'0');
} else if (s[2]>='0' && s[2]<='9') {
if (!s[3]) {
pin = ((s[1]-'0')*10 + (s[2]-'0'));
#ifdef LINUX
} else if (!s[4] && s[3]>='0' && s[3]<='9') {
pin = ((s[1]-'0')*100 + (s[2]-'0')*10 + (s[3]-'0'));
#endif
}
}
}
if (pin>=0) {
#ifdef PIN_NAMES_DIRECT
int i;
for (i=0;i<JSH_PIN_COUNT;i++)
if ((pinInfo[i].port&JSH_PORT_MASK) == port && pinInfo[i].pin==pin)
return (Pin)i;
#else
if (0) {
#if JSH_PORTA_OFFSET!=-1
} else if (port == JSH_PORTA) {
if (pin<JSH_PORTA_COUNT) return (Pin)(JSH_PORTA_OFFSET + pin);
#endif
#if JSH_PORTB_OFFSET!=-1
} else if (port == JSH_PORTB) {
if (pin<JSH_PORTB_COUNT) return (Pin)(JSH_PORTB_OFFSET + pin);
#endif
#if JSH_PORTC_OFFSET!=-1
} else if (port == JSH_PORTC) {
if (pin<JSH_PORTC_COUNT) return (Pin)(JSH_PORTC_OFFSET + pin);
#endif
#if JSH_PORTD_OFFSET!=-1
} else if (port == JSH_PORTD) {
if (pin<JSH_PORTD_COUNT) return (Pin)(JSH_PORTD_OFFSET + pin);
#endif
#if JSH_PORTE_OFFSET!=-1
} else if (port == JSH_PORTE) {
if (pin<JSH_PORTE_COUNT) return (Pin)(JSH_PORTE_OFFSET + pin);
#endif
#if JSH_PORTF_OFFSET!=-1
} else if (port == JSH_PORTF) {
if (pin<JSH_PORTF_COUNT) return (Pin)(JSH_PORTF_OFFSET + pin);
#endif
#if JSH_PORTG_OFFSET!=-1
} else if (port == JSH_PORTG) {
if (pin<JSH_PORTG_COUNT) return (Pin)(JSH_PORTG_OFFSET + pin);
#endif
#if JSH_PORTH_OFFSET!=-1
} else if (port == JSH_PORTH) {
if (pin<JSH_PORTH_COUNT) return (Pin)(JSH_PORTH_OFFSET + pin);
#endif
#if JSH_PORTI_OFFSET!=-1
} else if (port == JSH_PORTI) {
if (pin<JSH_PORTI_COUNT) return (Pin)(JSH_PORTI_OFFSET + pin);
#endif
#if JSH_PORTV_OFFSET!=-1
} else if (port == JSH_PORTV) {
if (pin<JSH_PORTV_COUNT) return (Pin)(JSH_PORTV_OFFSET + pin);
#endif
}
#endif
}
}
return PIN_UNDEFINED;
}
/** Write the pin name to a string. String must have at least 10 characters (to be safe) */
void jshGetPinString(char *result, Pin pin) {
result[0] = 0; // just in case
#ifdef PIN_NAMES_DIRECT
if (jshIsPinValid(pin)) {
result[0] = (char)('A'+(pinInfo[pin].port&JSH_PORT_MASK)-JSH_PORTA);
itostr(pinInfo[pin].pin-JSH_PIN0,&result[1],10);
#else
if (false) {
#if JSH_PORTA_OFFSET!=-1
} else if(
#if JSH_PORTA_OFFSET!=0
pin>=JSH_PORTA_OFFSET &&
#endif
pin<JSH_PORTA_OFFSET+JSH_PORTA_COUNT) {
result[0]='A';
itostr(pin-JSH_PORTA_OFFSET,&result[1],10);
#endif
#if JSH_PORTB_OFFSET!=-1
} else if (pin>=JSH_PORTB_OFFSET && pin<JSH_PORTB_OFFSET+JSH_PORTB_COUNT) {
result[0]='B';
itostr(pin-JSH_PORTB_OFFSET,&result[1],10);
#endif
#if JSH_PORTC_OFFSET!=-1
} else if (pin>=JSH_PORTC_OFFSET && pin<JSH_PORTC_OFFSET+JSH_PORTC_COUNT) {
result[0]='C';
itostr(pin-JSH_PORTC_OFFSET,&result[1],10);
#endif
#if JSH_PORTD_OFFSET!=-1
} else if (
#if JSH_PORTD_OFFSET!=0
pin>=JSH_PORTD_OFFSET &&
#endif
pin<JSH_PORTD_OFFSET+JSH_PORTD_COUNT) {
result[0]='D';
itostr(pin-JSH_PORTD_OFFSET,&result[1],10);
#endif
#if JSH_PORTE_OFFSET!=-1
} else if (pin>=JSH_PORTE_OFFSET && pin<JSH_PORTE_OFFSET+JSH_PORTE_COUNT) {
result[0]='E';
itostr(pin-JSH_PORTE_OFFSET,&result[1],10);
#endif
#if JSH_PORTF_OFFSET!=-1
} else if (pin>=JSH_PORTF_OFFSET && pin<JSH_PORTF_OFFSET+JSH_PORTF_COUNT) {
result[0]='F';
itostr(pin-JSH_PORTF_OFFSET,&result[1],10);
#endif
#if JSH_PORTG_OFFSET!=-1
} else if (pin>=JSH_PORTG_OFFSET && pin<JSH_PORTG_OFFSET+JSH_PORTG_COUNT) {
result[0]='G';
itostr(pin-JSH_PORTG_OFFSET,&result[1],10);
#endif
#if JSH_PORTH_OFFSET!=-1
} else if (pin>=JSH_PORTH_OFFSET && pin<JSH_PORTH_OFFSET+JSH_PORTH_COUNT) {
result[0]='H';
itostr(pin-JSH_PORTH_OFFSET,&result[1],10);
#endif
#if JSH_PORTI_OFFSET!=-1
} else if (pin>=JSH_PORTI_OFFSET && pin<JSH_PORTI_OFFSET+JSH_PORTI_COUNT) {
result[0]='I';
itostr(pin-JSH_PORTI_OFFSET,&result[1],10);
#endif
#if JSH_PORTV_OFFSET!=-1
} else if (pin>=JSH_PORTV_OFFSET && pin<JSH_PORTV_OFFSET+JSH_PORTV_COUNT) {
result[0]='V';
itostr(pin-JSH_PORTV_OFFSET,&result[1],10);
#endif
#endif
} else {
strcpy(result, "undefined");
}
}
/**
* Given a var, convert it to a pin ID (or PIN_UNDEFINED if it doesn't exist). safe for undefined!
*/
Pin jshGetPinFromVar(
JsVar *pinv //!< The class instance representing a Pin.
) {
if (jsvIsString(pinv) && pinv->varData.str[5]==0/*should never be more than 4 chars!*/) {
return jshGetPinFromString(&pinv->varData.str[0]);
} else if (jsvIsInt(pinv) /* This also tests for the Pin datatype */) {
return (Pin)jsvGetInteger(pinv);
} else return PIN_UNDEFINED;
}
Pin jshGetPinFromVarAndUnLock(JsVar *pinv) {
Pin pin = jshGetPinFromVar(pinv);
jsvUnLock(pinv);
return pin;
}
// ----------------------------------------------------------------------------
bool jshGetPinStateIsManual(Pin pin) {
return BITFIELD_GET(jshPinStateIsManual, pin);
}
void jshSetPinStateIsManual(Pin pin, bool manual) {
BITFIELD_SET(jshPinStateIsManual, pin, manual);
}
// Reset our list of which pins are set manually - called from jshResetDevices
void jshResetPinStateIsManual() {
BITFIELD_CLEAR(jshPinStateIsManual);
}
// ----------------------------------------------------------------------------
/**
* Get the value of a pin.
* \return The value of the pin.
*/
bool jshPinInput(
Pin pin //!< The pin to have the value retrieved.
) {
bool value = false;
if (jshIsPinValid(pin)) {
if (!jshGetPinStateIsManual(pin))
jshPinSetState(pin, JSHPINSTATE_GPIO_IN);
value = jshPinGetValue(pin);
}
// Handle pin being invalid.
else jsExceptionHere(JSET_ERROR, "Invalid pin!");
return value;
}
/**
* Set the value of a pin.
*/
void jshPinOutput(
Pin pin, //!< The pin to set.
bool value //!< The new value to set on the pin.
) {
if (jshIsPinValid(pin)) {
jshPinSetValue(pin, value);
if (!jshGetPinStateIsManual(pin))
jshPinSetState(pin, JSHPINSTATE_GPIO_OUT);
}
// Handle pin being invalid.
else jsExceptionHere(JSET_ERROR, "Invalid pin!");
}
// ----------------------------------------------------------------------------
// Convert an event type flag into a jshPinFunction for an actual hardware device
JshPinFunction jshGetPinFunctionFromDevice(IOEventFlags device) {
if (DEVICE_IS_USART(device))
return JSH_USART1 + ((device - EV_SERIAL1)<<JSH_SHIFT_TYPE);
if (DEVICE_IS_SPI(device))
return JSH_SPI1 + ((device - EV_SPI1)<<JSH_SHIFT_TYPE);
if (DEVICE_IS_I2C(device))
return JSH_I2C1 + ((device - EV_I2C1)<<JSH_SHIFT_TYPE);
return 0;
}
// Convert a jshPinFunction to an event type flag
IOEventFlags jshGetFromDevicePinFunction(JshPinFunction func) {
if (JSH_PINFUNCTION_IS_USART(func))
return EV_SERIAL1 + ((func - JSH_USART1) >> JSH_SHIFT_TYPE);
if (JSH_PINFUNCTION_IS_SPI(func))
return EV_SPI1 + ((func - JSH_SPI1) >> JSH_SHIFT_TYPE);
if (JSH_PINFUNCTION_IS_I2C(func))
return EV_I2C1 + ((func - JSH_I2C1) >> JSH_SHIFT_TYPE);
return 0;
}
/** Try and find a specific type of function for the given pin. Can be given an invalid pin and will return 0. */
JshPinFunction NO_INLINE jshGetPinFunctionForPin(Pin pin, JshPinFunction functionType) {
if (!jshIsPinValid(pin)) return 0;
int i;
for (i=0;i<JSH_PININFO_FUNCTIONS;i++) {
if ((pinInfo[pin].functions[i]&JSH_MASK_TYPE) == functionType)
return pinInfo[pin].functions[i];
}
return 0;
}
/** Try and find the best pin suitable for the given function. Can return -1. */
Pin NO_INLINE jshFindPinForFunction(JshPinFunction functionType, JshPinFunction functionInfo) {
#ifdef OLIMEXINO_STM32
/** Hack, as you can't mix AFs on the STM32F1, and Olimexino reordered the pins
* such that D4(AF1) is before D11(AF0) - and there are no SCK/MISO for AF1! */
if (functionType == JSH_SPI1 && functionInfo==JSH_SPI_MOSI) return JSH_PORTD_OFFSET+11;
#endif
#ifdef PICO
/* On the Pico, A9 is used for sensing when USB power is applied. Is someone types in
* Serial1.setup(9600) it'll get chosen as it's the first pin, but setting it to an output
* totally messes up the STM32 as it's fed with 5V. This ensures that it won't get chosen
* UNLESS it is explicitly selected.
*
* TODO: better way of doing this? A JSH_DONT_DEFAULT flag for pin functions? */
if (functionType == JSH_USART1) {
if (functionInfo==JSH_USART_TX) return JSH_PORTB_OFFSET+6;
if (functionInfo==JSH_USART_RX) return JSH_PORTB_OFFSET+7;
}
#endif
Pin i;
int j;
// first, try and find the pin with an AF of 0 - this is usually the 'default'
for (i=0;i<JSH_PIN_COUNT;i++)
for (j=0;j<JSH_PININFO_FUNCTIONS;j++)
if ((pinInfo[i].functions[j]&JSH_MASK_AF) == JSH_AF0 &&
(pinInfo[i].functions[j]&JSH_MASK_TYPE) == functionType &&
(pinInfo[i].functions[j]&JSH_MASK_INFO) == functionInfo)
return i;
// otherwise just try and find anything
for (i=0;i<JSH_PIN_COUNT;i++)
for (j=0;j<JSH_PININFO_FUNCTIONS;j++)
if ((pinInfo[i].functions[j]&JSH_MASK_TYPE) == functionType &&
(pinInfo[i].functions[j]&JSH_MASK_INFO) == functionInfo)
return i;
return PIN_UNDEFINED;
}
/// Given a full pin function, return a string describing it depending of what's in the flags enum
void jshPinFunctionToString(JshPinFunction pinFunc, JshPinFunctionToStringFlags flags, char *buf, size_t bufSize) {
const char *devStr = "";
JshPinFunction info = JSH_MASK_INFO & pinFunc;
JshPinFunction firstDevice = 0;
const char *infoStr = 0;
char infoStrBuf[5];
buf[0]=0;
if (JSH_PINFUNCTION_IS_USART(pinFunc)) {
devStr=(flags&JSPFTS_JS_NAMES)?"Serial":"USART";
firstDevice=JSH_USART1;
if (info==JSH_USART_RX) infoStr="RX";
else if (info==JSH_USART_TX) infoStr="TX";
else if (info==JSH_USART_CK) infoStr="CK";
} else if (JSH_PINFUNCTION_IS_SPI(pinFunc)) {
devStr="SPI";
firstDevice=JSH_SPI1;
if (info==JSH_SPI_MISO) infoStr="MISO";
else if (info==JSH_SPI_MOSI) infoStr="MOSI";
else if (info==JSH_SPI_SCK) infoStr="SCK";
} else if (JSH_PINFUNCTION_IS_I2C(pinFunc)) {
devStr="I2C";
firstDevice=JSH_I2C1;
if (info==JSH_I2C_SCL) infoStr="SCL";
else if (info==JSH_I2C_SDA) infoStr="SDA";
} else if (JSH_PINFUNCTION_IS_DAC(pinFunc)) {
devStr="DAC";
firstDevice=JSH_DAC;
if (info==JSH_DAC_CH1) infoStr="CH1";
else if (info==JSH_DAC_CH2) infoStr="CH2";
} else if (JSH_PINFUNCTION_IS_TIMER(pinFunc)) {
devStr="TIM";
firstDevice=JSH_TIMER1;
infoStr = &infoStrBuf[0];
infoStrBuf[0] = 'C';
infoStrBuf[1] = 'H';
infoStrBuf[2] = (char)('1' + ((info&JSH_MASK_TIMER_CH)>>JSH_SHIFT_INFO));
if (info & JSH_TIMER_NEGATED) {
infoStrBuf[3]='N';
infoStrBuf[4] = 0;
} else {
infoStrBuf[3] = 0;
}
}
int devIdx = 1 + ((((pinFunc&JSH_MASK_TYPE) - firstDevice) >> JSH_SHIFT_TYPE));
if (!devStr) {
jsiConsolePrintf("Couldn't convert pin function %d\n", pinFunc);
return;
}
if (flags & JSPFTS_DEVICE) strncat(buf, devStr, bufSize-1);
if (flags & JSPFTS_DEVICE_NUMBER) itostr(devIdx, &buf[strlen(buf)], 10);
if (flags & JSPFTS_SPACE) strncat(buf, " ", bufSize-(strlen(buf)+1));
if (infoStr && (flags & JSPFTS_TYPE)) strncat(buf, infoStr, bufSize-(strlen(buf)+1));
}
/** Prints a list of capable pins, eg:
jshPrintCapablePins(..., "PWM", JSH_TIMER1, JSH_TIMERMAX, 0,0, false)
jshPrintCapablePins(..., "SPI", JSH_SPI1, JSH_SPIMAX, JSH_MASK_INFO,JSH_SPI_SCK, false)
jshPrintCapablePins(..., "Analog Input", 0,0,0,0, true) - for analogs */
void NO_INLINE jshPrintCapablePins(Pin existingPin, const char *functionName, JshPinFunction typeMin, JshPinFunction typeMax, JshPinFunction pMask, JshPinFunction pData, bool printAnalogs) {
if (functionName) {
jsError("Pin %p is not capable of %s\nSuitable pins are:", existingPin, functionName);
}
Pin pin;
int i,n=0;
for (pin=0;pin<JSH_PIN_COUNT;pin++) {
bool has = false;
#ifdef STM32F1
int af = 0;
#endif
if (printAnalogs) {
has = pinInfo[pin].analog!=JSH_ANALOG_NONE;
} else {
for (i=0;i<JSH_PININFO_FUNCTIONS;i++) {
JshPinFunction type = pinInfo[pin].functions[i] & JSH_MASK_TYPE;
if (type>=typeMin && type<=typeMax && ((pinInfo[pin].functions[i]&pMask)==pData)) {
has = true;
#ifdef STM32F1
af = pinInfo[pin].functions[i] & JSH_MASK_AF;
#endif
}
}
}
if (has) {
jsiConsolePrintf("%p",pin);
#ifdef STM32F1
if (af!=JSH_AF0) jsiConsolePrint("(AF)");
#endif
jsiConsolePrint(" ");
if (n++==8) { n=0; jsiConsolePrint("\n"); }
}
}
jsiConsolePrint("\n");
}
/** Find a device of the given type that works on the given pin. For instance:
* `jshGetDeviceFor(JSH_SPI1, JSH_SPIMAX, pin);
*/
JshPinFunction jshGetDeviceFor(JshPinFunction deviceMin, JshPinFunction deviceMax, Pin pin) {
if (!jshIsPinValid(pin)) return JSH_NOTHING;
int i;
for (i=0;i<JSH_PININFO_FUNCTIONS;i++) {
JshPinFunction f = pinInfo[pin].functions[i];
if ((f&JSH_MASK_TYPE) >= deviceMin &&
(f&JSH_MASK_TYPE) <= deviceMax)
return f;
}
return JSH_NOTHING;
}
/** Like jshGetDeviceFor, but returns an actual Object (eg. SPI) if one can be found. */
JsVar *jshGetDeviceObjectFor(JshPinFunction deviceMin, JshPinFunction deviceMax, Pin pin) {
JshPinFunction dev = jshGetDeviceFor(deviceMin, deviceMax, pin);
if (dev==JSH_NOTHING) return 0;
char devName[16];
jshPinFunctionToString(dev, JSPFTS_DEVICE|JSPFTS_DEVICE_NUMBER|JSPFTS_JS_NAMES, devName, sizeof(devName));
JsVar *devVar = jsvObjectGetChild(execInfo.root, devName, 0);
if (devVar) return devVar;
return jswFindBuiltInFunction(0, devName);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_160_2 |
crossvul-cpp_data_bad_374_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC4616 PLAIN authentication
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "vauth/vauth.h"
#include "curl_base64.h"
#include "curl_md5.h"
#include "warnless.h"
#include "strtok.h"
#include "sendf.h"
#include "curl_printf.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/*
* Curl_auth_create_plain_message()
*
* This is used to generate an already encoded PLAIN message ready
* for sending to the recipient.
*
* Parameters:
*
* data [in] - The session handle.
* userp [in] - The user name.
* passwdp [in] - The user's password.
* outptr [in/out] - The address where a pointer to newly allocated memory
* holding the result will be stored upon completion.
* outlen [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,
const char *userp,
const char *passwdp,
char **outptr, size_t *outlen)
{
CURLcode result;
char *plainauth;
size_t ulen;
size_t plen;
size_t plainlen;
*outlen = 0;
*outptr = NULL;
ulen = strlen(userp);
plen = strlen(passwdp);
/* Compute binary message length. Check for overflows. */
if((ulen > SIZE_T_MAX/2) || (plen > (SIZE_T_MAX/2 - 2)))
return CURLE_OUT_OF_MEMORY;
plainlen = 2 * ulen + plen + 2;
plainauth = malloc(plainlen);
if(!plainauth)
return CURLE_OUT_OF_MEMORY;
/* Calculate the reply */
memcpy(plainauth, userp, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, userp, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, passwdp, plen);
/* Base64 encode the reply */
result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);
free(plainauth);
return result;
}
/*
* Curl_auth_create_login_message()
*
* This is used to generate an already encoded LOGIN message containing the
* user name or password ready for sending to the recipient.
*
* Parameters:
*
* data [in] - The session handle.
* valuep [in] - The user name or user's password.
* outptr [in/out] - The address where a pointer to newly allocated memory
* holding the result will be stored upon completion.
* outlen [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_auth_create_login_message(struct Curl_easy *data,
const char *valuep, char **outptr,
size_t *outlen)
{
size_t vlen = strlen(valuep);
if(!vlen) {
/* Calculate an empty reply */
*outptr = strdup("=");
if(*outptr) {
*outlen = (size_t) 1;
return CURLE_OK;
}
*outlen = 0;
return CURLE_OUT_OF_MEMORY;
}
/* Base64 encode the value */
return Curl_base64_encode(data, valuep, vlen, outptr, outlen);
}
/*
* Curl_auth_create_external_message()
*
* This is used to generate an already encoded EXTERNAL message containing
* the user name ready for sending to the recipient.
*
* Parameters:
*
* data [in] - The session handle.
* user [in] - The user name.
* outptr [in/out] - The address where a pointer to newly allocated memory
* holding the result will be stored upon completion.
* outlen [out] - The length of the output message.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_auth_create_external_message(struct Curl_easy *data,
const char *user, char **outptr,
size_t *outlen)
{
/* This is the same formatting as the login message */
return Curl_auth_create_login_message(data, user, outptr, outlen);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_374_0 |
crossvul-cpp_data_bad_344_9 | /*
* Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com>
*
* This file is part of OpenSC.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "egk-tool-cmdline.h"
#include "libopensc/log.h"
#include "libopensc/opensc.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
#ifdef ENABLE_ZLIB
#include <zlib.h>
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
z_stream stream;
memset(&stream, 0, sizeof stream);
stream.total_in = compressed_len;
stream.avail_in = compressed_len;
stream.total_out = *uncompressed_len;
stream.avail_out = *uncompressed_len;
stream.next_in = (Bytef *) compressed;
stream.next_out = (Bytef *) uncompressed;
/* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */
if (Z_OK == inflateInit2(&stream, (15 + 32))
&& Z_STREAM_END == inflate(&stream, Z_FINISH)) {
*uncompressed_len = stream.total_out;
} else {
return SC_ERROR_INVALID_DATA;
}
inflateEnd(&stream);
return SC_SUCCESS;
}
#else
int uncompress_gzip(void* uncompressed, size_t *uncompressed_len,
const void* compressed, size_t compressed_len)
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif
#define PRINT(c) (isprint(c) ? c : '?')
void dump_binary(void *buf, size_t buf_len)
{
#ifdef _WIN32
_setmode(fileno(stdout), _O_BINARY);
#endif
fwrite(buf, 1, buf_len, stdout);
#ifdef _WIN32
_setmode(fileno(stdout), _O_TEXT);
#endif
}
const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02};
static int initialize(int reader_id, int verbose,
sc_context_t **ctx, sc_reader_t **reader)
{
unsigned int i, reader_count;
int r;
if (!ctx || !reader)
return SC_ERROR_INVALID_ARGUMENTS;
r = sc_establish_context(ctx, "");
if (r < 0 || !*ctx) {
fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r));
return r;
}
(*ctx)->debug = verbose;
(*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
reader_count = sc_ctx_get_reader_count(*ctx);
if (reader_count == 0) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n");
return SC_ERROR_NO_READERS_FOUND;
}
if (reader_id < 0) {
/* Automatically try to skip to a reader with a card if reader not specified */
for (i = 0; i < reader_count; i++) {
*reader = sc_ctx_get_reader(*ctx, i);
if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) {
reader_id = i;
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader"
" with a card: %s", (*reader)->name);
break;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader.");
reader_id = 0;
}
}
if ((unsigned int) reader_id >= reader_count) {
sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number "
"(%d), only %d available.\n", reader_id, reader_count);
return SC_ERROR_NO_READERS_FOUND;
}
*reader = sc_ctx_get_reader(*ctx, reader_id);
return SC_SUCCESS;
}
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)
{
struct sc_path path;
struct sc_file *file;
unsigned char *p;
int ok = 0;
int r;
size_t len;
sc_format_path(str_path, &path);
if (SC_SUCCESS != sc_select_file(card, &path, &file)) {
goto err;
}
len = file ? file->size : 4096;
p = realloc(*data, len);
if (!p) {
goto err;
}
*data = p;
*data_len = len;
r = sc_read_binary(card, 0, p, len, 0);
if (r < 0)
goto err;
*data_len = r;
ok = 1;
err:
sc_file_free(file);
return ok;
}
void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix)
{
*major = 0;
*minor = 0;
*fix = 0;
/* decode BCD to decimal */
if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) {
*major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4);
}
if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) {
*minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF);
}
if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10)
&& (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) {
*fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100
+ (bcd[4]>>4)*10 + (bcd[4]&0xF);
}
}
int
main (int argc, char **argv)
{
struct gengetopt_args_info cmdline;
struct sc_path path;
struct sc_context *ctx;
struct sc_reader *reader = NULL;
struct sc_card *card;
unsigned char *data = NULL;
size_t data_len = 0;
int r;
if (cmdline_parser(argc, argv, &cmdline) != 0)
exit(1);
r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader);
if (r < 0) {
fprintf(stderr, "Can't initialize reader\n");
exit(1);
}
if (sc_connect_card(reader, &card) < 0) {
fprintf(stderr, "Could not connect to card\n");
sc_release_context(ctx);
exit(1);
}
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0);
if (SC_SUCCESS != sc_select_file(card, &path, NULL))
goto err;
if (cmdline.pd_flag
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 2) {
size_t len_pd = (data[0] << 8) | data[1];
if (len_pd + 2 <= data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + 2, len_pd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + 2, len_pd);
}
}
}
if ((cmdline.vd_flag || cmdline.gvd_flag)
&& read_file(card, "D001", &data, &data_len)
&& data_len >= 8) {
size_t off_vd = (data[0] << 8) | data[1];
size_t end_vd = (data[2] << 8) | data[3];
size_t off_gvd = (data[4] << 8) | data[5];
size_t end_gvd = (data[6] << 8) | data[7];
size_t len_vd = end_vd - off_vd + 1;
size_t len_gvd = end_gvd - off_gvd + 1;
if (off_vd <= end_vd && end_vd < data_len
&& off_gvd <= end_gvd && end_gvd < data_len) {
unsigned char uncompressed[1024];
size_t uncompressed_len = sizeof uncompressed;
if (cmdline.vd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_vd, len_vd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_vd, len_vd);
}
}
if (cmdline.gvd_flag) {
if (uncompress_gzip(uncompressed, &uncompressed_len,
data + off_gvd, len_gvd) == SC_SUCCESS) {
dump_binary(uncompressed, uncompressed_len);
} else {
dump_binary(data + off_gvd, len_gvd);
}
}
}
}
if (cmdline.vsd_status_flag
&& read_file(card, "D00C", &data, &data_len)
&& data_len >= 25) {
char *status;
unsigned int major, minor, fix;
switch (data[0]) {
case '0':
status = "Transactions pending";
break;
case '1':
status = "No transactions pending";
break;
default:
status = "Unknown";
break;
}
decode_version(data+15, &major, &minor, &fix);
printf(
"Status %s\n"
"Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n"
"Version %u.%u.%u\n",
status,
PRINT(data[7]), PRINT(data[8]),
PRINT(data[5]), PRINT(data[6]),
PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]),
PRINT(data[9]), PRINT(data[10]),
PRINT(data[11]), PRINT(data[12]),
PRINT(data[13]), PRINT(data[14]),
major, minor, fix);
}
err:
sc_disconnect_card(card);
sc_release_context(ctx);
cmdline_parser_free (&cmdline);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_344_9 |
crossvul-cpp_data_bad_339_4 | /*
* PKCS15 emulation layer for EstEID card.
*
* Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net>
* Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it>
* Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it>
* Copyright (C) 2003, Olaf Kirch <okir@suse.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "opensc.h"
#include "pkcs15.h"
#include "esteid.h"
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *);
static void
set_string (char **strp, const char *value)
{
if (*strp)
free (*strp);
*strp = value ? strdup (value) : NULL;
}
int
select_esteid_df (sc_card_t * card)
{
int r;
sc_path_t tmppath;
sc_format_path ("3F00EEEE", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed");
return r;
}
static int
sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
unsigned char buff[128];
int r, i;
size_t field_length = 0, modulus_length = 0;
sc_path_t tmppath;
set_string (&p15card->tokeninfo->label, "ID-kaart");
set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus");
/* Select application directory */
sc_format_path ("3f00eeee5044", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed");
/* read the serial (document number) */
r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed");
buff[r] = '\0';
set_string (&p15card->tokeninfo->serial_number, (const char *) buff);
p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION
| SC_PKCS15_TOKEN_EID_COMPLIANT
| SC_PKCS15_TOKEN_READONLY;
/* add certificates */
for (i = 0; i < 2; i++) {
static const char *esteid_cert_names[2] = {
"Isikutuvastus",
"Allkirjastamine"};
static char const *esteid_cert_paths[2] = {
"3f00eeeeaace",
"3f00eeeeddce"};
static int esteid_cert_ids[2] = {1, 2};
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id.value[0] = esteid_cert_ids[i];
cert_info.id.len = 1;
sc_format_path(esteid_cert_paths[i], &cert_info.path);
strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if (r < 0)
return SC_ERROR_INTERNAL;
if (i == 0) {
sc_pkcs15_cert_t *cert = NULL;
r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert);
if (r < 0)
return SC_ERROR_INTERNAL;
if (cert->key->algorithm == SC_ALGORITHM_EC)
field_length = cert->key->u.ec.params.field_length;
else
modulus_length = cert->key->u.rsa.modulus.len * 8;
if (r == SC_SUCCESS) {
static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }};
u8 *cn_name = NULL;
size_t cn_len = 0;
sc_pkcs15_get_name_from_dn(card->ctx, cert->subject,
cert->subject_len, &cn_oid, &cn_name, &cn_len);
if (cn_len > 0) {
char *token_name = malloc(cn_len+1);
if (token_name) {
memcpy(token_name, cn_name, cn_len);
token_name[cn_len] = '\0';
set_string(&p15card->tokeninfo->label, (const char*)token_name);
free(token_name);
}
}
free(cn_name);
sc_pkcs15_free_certificate(cert);
}
}
}
/* the file with key pin info (tries left) */
sc_format_path ("3f000016", &tmppath);
r = sc_select_file (card, &tmppath, NULL);
if (r < 0)
return SC_ERROR_INTERNAL;
/* add pins */
for (i = 0; i < 3; i++) {
unsigned char tries_left;
static const char *esteid_pin_names[3] = {
"PIN1",
"PIN2",
"PUK" };
static const int esteid_pin_min[3] = {4, 5, 8};
static const int esteid_pin_ref[3] = {1, 2, 0};
static const int esteid_pin_authid[3] = {1, 2, 3};
static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN};
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
/* read the number of tries left for the PIN */
r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR);
if (r < 0)
return SC_ERROR_INTERNAL;
tries_left = buff[5];
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = esteid_pin_authid[i];
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = esteid_pin_ref[i];
pin_info.attrs.pin.flags = esteid_pin_flags[i];
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = esteid_pin_min[i];
pin_info.attrs.pin.stored_length = 12;
pin_info.attrs.pin.max_length = 12;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = (int)tries_left;
pin_info.max_tries = 3;
strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label));
pin_obj.flags = esteid_pin_flags[i];
/* Link normal PINs with PUK */
if (i < 2) {
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 3;
}
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
/* add private keys */
for (i = 0; i < 2; i++) {
static int prkey_pin[2] = {1, 2};
static const char *prkey_name[2] = {
"Isikutuvastus",
"Allkirjastamine"};
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
memset(&prkey_info, 0, sizeof(prkey_info));
memset(&prkey_obj, 0, sizeof(prkey_obj));
prkey_info.id.len = 1;
prkey_info.id.value[0] = prkey_pin[i];
prkey_info.native = 1;
prkey_info.key_reference = i + 1;
prkey_info.field_length = field_length;
prkey_info.modulus_length = modulus_length;
if (i == 1)
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
else if(field_length > 0) // ECC has sign and derive usage
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE;
else
prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT;
strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label));
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = prkey_pin[i];
prkey_obj.user_consent = 0;
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
if(field_length > 0)
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info);
else
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if (r < 0)
return SC_ERROR_INTERNAL;
}
return SC_SUCCESS;
}
static int esteid_detect_card(sc_pkcs15_card_t *p15card)
{
if (is_esteid_card(p15card->card))
return SC_SUCCESS;
else
return SC_ERROR_WRONG_CARD;
}
int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts)
{
if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)
return sc_pkcs15emu_esteid_init(p15card);
else {
int r = esteid_detect_card(p15card);
if (r)
return SC_ERROR_WRONG_CARD;
return sc_pkcs15emu_esteid_init(p15card);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_339_4 |
crossvul-cpp_data_bad_3305_0 | /*
* XDR support for nfsd/protocol version 3.
*
* Copyright (C) 1995, 1996, 1997 Olaf Kirch <okir@monad.swb.de>
*
* 2003-08-09 Jamie Lokier: Use htonl() for nanoseconds, not htons()!
*/
#include <linux/namei.h>
#include <linux/sunrpc/svc_xprt.h>
#include "xdr3.h"
#include "auth.h"
#include "netns.h"
#include "vfs.h"
#define NFSDDBG_FACILITY NFSDDBG_XDR
/*
* Mapping of S_IF* types to NFS file types
*/
static u32 nfs3_ftypes[] = {
NF3NON, NF3FIFO, NF3CHR, NF3BAD,
NF3DIR, NF3BAD, NF3BLK, NF3BAD,
NF3REG, NF3BAD, NF3LNK, NF3BAD,
NF3SOCK, NF3BAD, NF3LNK, NF3BAD,
};
/*
* XDR functions for basic NFS types
*/
static __be32 *
encode_time3(__be32 *p, struct timespec *time)
{
*p++ = htonl((u32) time->tv_sec); *p++ = htonl(time->tv_nsec);
return p;
}
static __be32 *
decode_time3(__be32 *p, struct timespec *time)
{
time->tv_sec = ntohl(*p++);
time->tv_nsec = ntohl(*p++);
return p;
}
static __be32 *
decode_fh(__be32 *p, struct svc_fh *fhp)
{
unsigned int size;
fh_init(fhp, NFS3_FHSIZE);
size = ntohl(*p++);
if (size > NFS3_FHSIZE)
return NULL;
memcpy(&fhp->fh_handle.fh_base, p, size);
fhp->fh_handle.fh_size = size;
return p + XDR_QUADLEN(size);
}
/* Helper function for NFSv3 ACL code */
__be32 *nfs3svc_decode_fh(__be32 *p, struct svc_fh *fhp)
{
return decode_fh(p, fhp);
}
static __be32 *
encode_fh(__be32 *p, struct svc_fh *fhp)
{
unsigned int size = fhp->fh_handle.fh_size;
*p++ = htonl(size);
if (size) p[XDR_QUADLEN(size)-1]=0;
memcpy(p, &fhp->fh_handle.fh_base, size);
return p + XDR_QUADLEN(size);
}
/*
* Decode a file name and make sure that the path contains
* no slashes or null bytes.
*/
static __be32 *
decode_filename(__be32 *p, char **namp, unsigned int *lenp)
{
char *name;
unsigned int i;
if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS3_MAXNAMLEN)) != NULL) {
for (i = 0, name = *namp; i < *lenp; i++, name++) {
if (*name == '\0' || *name == '/')
return NULL;
}
}
return p;
}
static __be32 *
decode_sattr3(__be32 *p, struct iattr *iap)
{
u32 tmp;
iap->ia_valid = 0;
if (*p++) {
iap->ia_valid |= ATTR_MODE;
iap->ia_mode = ntohl(*p++);
}
if (*p++) {
iap->ia_uid = make_kuid(&init_user_ns, ntohl(*p++));
if (uid_valid(iap->ia_uid))
iap->ia_valid |= ATTR_UID;
}
if (*p++) {
iap->ia_gid = make_kgid(&init_user_ns, ntohl(*p++));
if (gid_valid(iap->ia_gid))
iap->ia_valid |= ATTR_GID;
}
if (*p++) {
u64 newsize;
iap->ia_valid |= ATTR_SIZE;
p = xdr_decode_hyper(p, &newsize);
iap->ia_size = min_t(u64, newsize, NFS_OFFSET_MAX);
}
if ((tmp = ntohl(*p++)) == 1) { /* set to server time */
iap->ia_valid |= ATTR_ATIME;
} else if (tmp == 2) { /* set to client time */
iap->ia_valid |= ATTR_ATIME | ATTR_ATIME_SET;
iap->ia_atime.tv_sec = ntohl(*p++);
iap->ia_atime.tv_nsec = ntohl(*p++);
}
if ((tmp = ntohl(*p++)) == 1) { /* set to server time */
iap->ia_valid |= ATTR_MTIME;
} else if (tmp == 2) { /* set to client time */
iap->ia_valid |= ATTR_MTIME | ATTR_MTIME_SET;
iap->ia_mtime.tv_sec = ntohl(*p++);
iap->ia_mtime.tv_nsec = ntohl(*p++);
}
return p;
}
static __be32 *encode_fsid(__be32 *p, struct svc_fh *fhp)
{
u64 f;
switch(fsid_source(fhp)) {
default:
case FSIDSOURCE_DEV:
p = xdr_encode_hyper(p, (u64)huge_encode_dev
(fhp->fh_dentry->d_sb->s_dev));
break;
case FSIDSOURCE_FSID:
p = xdr_encode_hyper(p, (u64) fhp->fh_export->ex_fsid);
break;
case FSIDSOURCE_UUID:
f = ((u64*)fhp->fh_export->ex_uuid)[0];
f ^= ((u64*)fhp->fh_export->ex_uuid)[1];
p = xdr_encode_hyper(p, f);
break;
}
return p;
}
static __be32 *
encode_fattr3(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp,
struct kstat *stat)
{
*p++ = htonl(nfs3_ftypes[(stat->mode & S_IFMT) >> 12]);
*p++ = htonl((u32) (stat->mode & S_IALLUGO));
*p++ = htonl((u32) stat->nlink);
*p++ = htonl((u32) from_kuid(&init_user_ns, stat->uid));
*p++ = htonl((u32) from_kgid(&init_user_ns, stat->gid));
if (S_ISLNK(stat->mode) && stat->size > NFS3_MAXPATHLEN) {
p = xdr_encode_hyper(p, (u64) NFS3_MAXPATHLEN);
} else {
p = xdr_encode_hyper(p, (u64) stat->size);
}
p = xdr_encode_hyper(p, ((u64)stat->blocks) << 9);
*p++ = htonl((u32) MAJOR(stat->rdev));
*p++ = htonl((u32) MINOR(stat->rdev));
p = encode_fsid(p, fhp);
p = xdr_encode_hyper(p, stat->ino);
p = encode_time3(p, &stat->atime);
p = encode_time3(p, &stat->mtime);
p = encode_time3(p, &stat->ctime);
return p;
}
static __be32 *
encode_saved_post_attr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp)
{
/* Attributes to follow */
*p++ = xdr_one;
return encode_fattr3(rqstp, p, fhp, &fhp->fh_post_attr);
}
/*
* Encode post-operation attributes.
* The inode may be NULL if the call failed because of a stale file
* handle. In this case, no attributes are returned.
*/
static __be32 *
encode_post_op_attr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp)
{
struct dentry *dentry = fhp->fh_dentry;
if (dentry && d_really_is_positive(dentry)) {
__be32 err;
struct kstat stat;
err = fh_getattr(fhp, &stat);
if (!err) {
*p++ = xdr_one; /* attributes follow */
lease_get_mtime(d_inode(dentry), &stat.mtime);
return encode_fattr3(rqstp, p, fhp, &stat);
}
}
*p++ = xdr_zero;
return p;
}
/* Helper for NFSv3 ACLs */
__be32 *
nfs3svc_encode_post_op_attr(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp)
{
return encode_post_op_attr(rqstp, p, fhp);
}
/*
* Enocde weak cache consistency data
*/
static __be32 *
encode_wcc_data(struct svc_rqst *rqstp, __be32 *p, struct svc_fh *fhp)
{
struct dentry *dentry = fhp->fh_dentry;
if (dentry && d_really_is_positive(dentry) && fhp->fh_post_saved) {
if (fhp->fh_pre_saved) {
*p++ = xdr_one;
p = xdr_encode_hyper(p, (u64) fhp->fh_pre_size);
p = encode_time3(p, &fhp->fh_pre_mtime);
p = encode_time3(p, &fhp->fh_pre_ctime);
} else {
*p++ = xdr_zero;
}
return encode_saved_post_attr(rqstp, p, fhp);
}
/* no pre- or post-attrs */
*p++ = xdr_zero;
return encode_post_op_attr(rqstp, p, fhp);
}
/*
* Fill in the post_op attr for the wcc data
*/
void fill_post_wcc(struct svc_fh *fhp)
{
__be32 err;
if (fhp->fh_post_saved)
printk("nfsd: inode locked twice during operation.\n");
err = fh_getattr(fhp, &fhp->fh_post_attr);
fhp->fh_post_change = d_inode(fhp->fh_dentry)->i_version;
if (err) {
fhp->fh_post_saved = false;
/* Grab the ctime anyway - set_change_info might use it */
fhp->fh_post_attr.ctime = d_inode(fhp->fh_dentry)->i_ctime;
} else
fhp->fh_post_saved = true;
}
/*
* XDR decode functions
*/
int
nfs3svc_decode_fhandle(struct svc_rqst *rqstp, __be32 *p, struct nfsd_fhandle *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_sattrargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_sattrargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = decode_sattr3(p, &args->attrs);
if ((args->check_guard = ntohl(*p++)) != 0) {
struct timespec time;
p = decode_time3(p, &time);
args->guardtime = time.tv_sec;
}
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_diropargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_diropargs *args)
{
if (!(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_accessargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_accessargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->access = ntohl(*p++);
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readargs *args)
{
unsigned int len;
int v;
u32 max_blocksize = svc_max_payload(rqstp);
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->offset);
args->count = ntohl(*p++);
len = min(args->count, max_blocksize);
/* set up the kvec */
v=0;
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
rqstp->rq_vec[v].iov_base = page_address(p);
rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE);
len -= rqstp->rq_vec[v].iov_len;
v++;
}
args->vlen = v;
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_writeargs *args)
{
unsigned int len, v, hdr, dlen;
u32 max_blocksize = svc_max_payload(rqstp);
struct kvec *head = rqstp->rq_arg.head;
struct kvec *tail = rqstp->rq_arg.tail;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->offset);
args->count = ntohl(*p++);
args->stable = ntohl(*p++);
len = args->len = ntohl(*p++);
/*
* The count must equal the amount of data passed.
*/
if (args->count != args->len)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
dlen = head->iov_len + rqstp->rq_arg.page_len + tail->iov_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
if (args->count > max_blocksize) {
args->count = max_blocksize;
len = args->len = max_blocksize;
}
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
int
nfs3svc_decode_createargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_createargs *args)
{
if (!(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
switch (args->createmode = ntohl(*p++)) {
case NFS3_CREATE_UNCHECKED:
case NFS3_CREATE_GUARDED:
p = decode_sattr3(p, &args->attrs);
break;
case NFS3_CREATE_EXCLUSIVE:
args->verf = p;
p += 2;
break;
default:
return 0;
}
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_mkdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_createargs *args)
{
if (!(p = decode_fh(p, &args->fh)) ||
!(p = decode_filename(p, &args->name, &args->len)))
return 0;
p = decode_sattr3(p, &args->attrs);
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_symlinkargs *args)
{
unsigned int len, avail;
char *old, *new;
struct kvec *vec;
if (!(p = decode_fh(p, &args->ffh)) ||
!(p = decode_filename(p, &args->fname, &args->flen))
)
return 0;
p = decode_sattr3(p, &args->attrs);
/* now decode the pathname, which might be larger than the first page.
* As we have to check for nul's anyway, we copy it into a new page
* This page appears in the rq_res.pages list, but as pages_len is always
* 0, it won't get in the way
*/
len = ntohl(*p++);
if (len == 0 || len > NFS3_MAXPATHLEN || len >= PAGE_SIZE)
return 0;
args->tname = new = page_address(*(rqstp->rq_next_page++));
args->tlen = len;
/* first copy and check from the first page */
old = (char*)p;
vec = &rqstp->rq_arg.head[0];
avail = vec->iov_len - (old - (char*)vec->iov_base);
while (len && avail && *old) {
*new++ = *old++;
len--;
avail--;
}
/* now copy next page if there is one */
if (len && !avail && rqstp->rq_arg.page_len) {
avail = min_t(unsigned int, rqstp->rq_arg.page_len, PAGE_SIZE);
old = page_address(rqstp->rq_arg.pages[0]);
}
while (len && avail && *old) {
*new++ = *old++;
len--;
avail--;
}
*new = '\0';
if (len)
return 0;
return 1;
}
int
nfs3svc_decode_mknodargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_mknodargs *args)
{
if (!(p = decode_fh(p, &args->fh))
|| !(p = decode_filename(p, &args->name, &args->len)))
return 0;
args->ftype = ntohl(*p++);
if (args->ftype == NF3BLK || args->ftype == NF3CHR
|| args->ftype == NF3SOCK || args->ftype == NF3FIFO)
p = decode_sattr3(p, &args->attrs);
if (args->ftype == NF3BLK || args->ftype == NF3CHR) {
args->major = ntohl(*p++);
args->minor = ntohl(*p++);
}
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_renameargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_renameargs *args)
{
if (!(p = decode_fh(p, &args->ffh))
|| !(p = decode_filename(p, &args->fname, &args->flen))
|| !(p = decode_fh(p, &args->tfh))
|| !(p = decode_filename(p, &args->tname, &args->tlen)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readlinkargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_linkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_linkargs *args)
{
if (!(p = decode_fh(p, &args->ffh))
|| !(p = decode_fh(p, &args->tfh))
|| !(p = decode_filename(p, &args->tname, &args->tlen)))
return 0;
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ~0;
args->count = ntohl(*p++);
args->count = min_t(u32, args->count, PAGE_SIZE);
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_readdirplusargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
int len;
u32 max_blocksize = svc_max_payload(rqstp);
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ntohl(*p++);
args->count = ntohl(*p++);
len = args->count = min(args->count, max_blocksize);
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
if (!args->buffer)
args->buffer = page_address(p);
len -= PAGE_SIZE;
}
return xdr_argsize_check(rqstp, p);
}
int
nfs3svc_decode_commitargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_commitargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->offset);
args->count = ntohl(*p++);
return xdr_argsize_check(rqstp, p);
}
/*
* XDR encode functions
*/
/*
* There must be an encoding function for void results so svc_process
* will work properly.
*/
int
nfs3svc_encode_voidres(struct svc_rqst *rqstp, __be32 *p, void *dummy)
{
return xdr_ressize_check(rqstp, p);
}
/* GETATTR */
int
nfs3svc_encode_attrstat(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_attrstat *resp)
{
if (resp->status == 0) {
lease_get_mtime(d_inode(resp->fh.fh_dentry),
&resp->stat.mtime);
p = encode_fattr3(rqstp, p, &resp->fh, &resp->stat);
}
return xdr_ressize_check(rqstp, p);
}
/* SETATTR, REMOVE, RMDIR */
int
nfs3svc_encode_wccstat(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_attrstat *resp)
{
p = encode_wcc_data(rqstp, p, &resp->fh);
return xdr_ressize_check(rqstp, p);
}
/* LOOKUP */
int
nfs3svc_encode_diropres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_diropres *resp)
{
if (resp->status == 0) {
p = encode_fh(p, &resp->fh);
p = encode_post_op_attr(rqstp, p, &resp->fh);
}
p = encode_post_op_attr(rqstp, p, &resp->dirfh);
return xdr_ressize_check(rqstp, p);
}
/* ACCESS */
int
nfs3svc_encode_accessres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_accessres *resp)
{
p = encode_post_op_attr(rqstp, p, &resp->fh);
if (resp->status == 0)
*p++ = htonl(resp->access);
return xdr_ressize_check(rqstp, p);
}
/* READLINK */
int
nfs3svc_encode_readlinkres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readlinkres *resp)
{
p = encode_post_op_attr(rqstp, p, &resp->fh);
if (resp->status == 0) {
*p++ = htonl(resp->len);
xdr_ressize_check(rqstp, p);
rqstp->rq_res.page_len = resp->len;
if (resp->len & 3) {
/* need to pad the tail */
rqstp->rq_res.tail[0].iov_base = p;
*p = 0;
rqstp->rq_res.tail[0].iov_len = 4 - (resp->len&3);
}
return 1;
} else
return xdr_ressize_check(rqstp, p);
}
/* READ */
int
nfs3svc_encode_readres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readres *resp)
{
p = encode_post_op_attr(rqstp, p, &resp->fh);
if (resp->status == 0) {
*p++ = htonl(resp->count);
*p++ = htonl(resp->eof);
*p++ = htonl(resp->count); /* xdr opaque count */
xdr_ressize_check(rqstp, p);
/* now update rqstp->rq_res to reflect data as well */
rqstp->rq_res.page_len = resp->count;
if (resp->count & 3) {
/* need to pad the tail */
rqstp->rq_res.tail[0].iov_base = p;
*p = 0;
rqstp->rq_res.tail[0].iov_len = 4 - (resp->count & 3);
}
return 1;
} else
return xdr_ressize_check(rqstp, p);
}
/* WRITE */
int
nfs3svc_encode_writeres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_writeres *resp)
{
struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
p = encode_wcc_data(rqstp, p, &resp->fh);
if (resp->status == 0) {
*p++ = htonl(resp->count);
*p++ = htonl(resp->committed);
*p++ = htonl(nn->nfssvc_boot.tv_sec);
*p++ = htonl(nn->nfssvc_boot.tv_usec);
}
return xdr_ressize_check(rqstp, p);
}
/* CREATE, MKDIR, SYMLINK, MKNOD */
int
nfs3svc_encode_createres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_diropres *resp)
{
if (resp->status == 0) {
*p++ = xdr_one;
p = encode_fh(p, &resp->fh);
p = encode_post_op_attr(rqstp, p, &resp->fh);
}
p = encode_wcc_data(rqstp, p, &resp->dirfh);
return xdr_ressize_check(rqstp, p);
}
/* RENAME */
int
nfs3svc_encode_renameres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_renameres *resp)
{
p = encode_wcc_data(rqstp, p, &resp->ffh);
p = encode_wcc_data(rqstp, p, &resp->tfh);
return xdr_ressize_check(rqstp, p);
}
/* LINK */
int
nfs3svc_encode_linkres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_linkres *resp)
{
p = encode_post_op_attr(rqstp, p, &resp->fh);
p = encode_wcc_data(rqstp, p, &resp->tfh);
return xdr_ressize_check(rqstp, p);
}
/* READDIR */
int
nfs3svc_encode_readdirres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirres *resp)
{
p = encode_post_op_attr(rqstp, p, &resp->fh);
if (resp->status == 0) {
/* stupid readdir cookie */
memcpy(p, resp->verf, 8); p += 2;
xdr_ressize_check(rqstp, p);
if (rqstp->rq_res.head[0].iov_len + (2<<2) > PAGE_SIZE)
return 1; /*No room for trailer */
rqstp->rq_res.page_len = (resp->count) << 2;
/* add the 'tail' to the end of the 'head' page - page 0. */
rqstp->rq_res.tail[0].iov_base = p;
*p++ = 0; /* no more entries */
*p++ = htonl(resp->common.err == nfserr_eof);
rqstp->rq_res.tail[0].iov_len = 2<<2;
return 1;
} else
return xdr_ressize_check(rqstp, p);
}
static __be32 *
encode_entry_baggage(struct nfsd3_readdirres *cd, __be32 *p, const char *name,
int namlen, u64 ino)
{
*p++ = xdr_one; /* mark entry present */
p = xdr_encode_hyper(p, ino); /* file id */
p = xdr_encode_array(p, name, namlen);/* name length & name */
cd->offset = p; /* remember pointer */
p = xdr_encode_hyper(p, NFS_OFFSET_MAX);/* offset of next entry */
return p;
}
static __be32
compose_entry_fh(struct nfsd3_readdirres *cd, struct svc_fh *fhp,
const char *name, int namlen, u64 ino)
{
struct svc_export *exp;
struct dentry *dparent, *dchild;
__be32 rv = nfserr_noent;
dparent = cd->fh.fh_dentry;
exp = cd->fh.fh_export;
if (isdotent(name, namlen)) {
if (namlen == 2) {
dchild = dget_parent(dparent);
/* filesystem root - cannot return filehandle for ".." */
if (dchild == dparent)
goto out;
} else
dchild = dget(dparent);
} else
dchild = lookup_one_len_unlocked(name, dparent, namlen);
if (IS_ERR(dchild))
return rv;
if (d_mountpoint(dchild))
goto out;
if (d_really_is_negative(dchild))
goto out;
if (dchild->d_inode->i_ino != ino)
goto out;
rv = fh_compose(fhp, exp, dchild, &cd->fh);
out:
dput(dchild);
return rv;
}
static __be32 *encode_entryplus_baggage(struct nfsd3_readdirres *cd, __be32 *p, const char *name, int namlen, u64 ino)
{
struct svc_fh *fh = &cd->scratch;
__be32 err;
fh_init(fh, NFS3_FHSIZE);
err = compose_entry_fh(cd, fh, name, namlen, ino);
if (err) {
*p++ = 0;
*p++ = 0;
goto out;
}
p = encode_post_op_attr(cd->rqstp, p, fh);
*p++ = xdr_one; /* yes, a file handle follows */
p = encode_fh(p, fh);
out:
fh_put(fh);
return p;
}
/*
* Encode a directory entry. This one works for both normal readdir
* and readdirplus.
* The normal readdir reply requires 2 (fileid) + 1 (stringlen)
* + string + 2 (cookie) + 1 (next) words, i.e. 6 + strlen.
*
* The readdirplus baggage is 1+21 words for post_op_attr, plus the
* file handle.
*/
#define NFS3_ENTRY_BAGGAGE (2 + 1 + 2 + 1)
#define NFS3_ENTRYPLUS_BAGGAGE (1 + 21 + 1 + (NFS3_FHSIZE >> 2))
static int
encode_entry(struct readdir_cd *ccd, const char *name, int namlen,
loff_t offset, u64 ino, unsigned int d_type, int plus)
{
struct nfsd3_readdirres *cd = container_of(ccd, struct nfsd3_readdirres,
common);
__be32 *p = cd->buffer;
caddr_t curr_page_addr = NULL;
struct page ** page;
int slen; /* string (name) length */
int elen; /* estimated entry length in words */
int num_entry_words = 0; /* actual number of words */
if (cd->offset) {
u64 offset64 = offset;
if (unlikely(cd->offset1)) {
/* we ended up with offset on a page boundary */
*cd->offset = htonl(offset64 >> 32);
*cd->offset1 = htonl(offset64 & 0xffffffff);
cd->offset1 = NULL;
} else {
xdr_encode_hyper(cd->offset, offset64);
}
}
/*
dprintk("encode_entry(%.*s @%ld%s)\n",
namlen, name, (long) offset, plus? " plus" : "");
*/
/* truncate filename if too long */
namlen = min(namlen, NFS3_MAXNAMLEN);
slen = XDR_QUADLEN(namlen);
elen = slen + NFS3_ENTRY_BAGGAGE
+ (plus? NFS3_ENTRYPLUS_BAGGAGE : 0);
if (cd->buflen < elen) {
cd->common.err = nfserr_toosmall;
return -EINVAL;
}
/* determine which page in rq_respages[] we are currently filling */
for (page = cd->rqstp->rq_respages + 1;
page < cd->rqstp->rq_next_page; page++) {
curr_page_addr = page_address(*page);
if (((caddr_t)cd->buffer >= curr_page_addr) &&
((caddr_t)cd->buffer < curr_page_addr + PAGE_SIZE))
break;
}
if ((caddr_t)(cd->buffer + elen) < (curr_page_addr + PAGE_SIZE)) {
/* encode entry in current page */
p = encode_entry_baggage(cd, p, name, namlen, ino);
if (plus)
p = encode_entryplus_baggage(cd, p, name, namlen, ino);
num_entry_words = p - cd->buffer;
} else if (*(page+1) != NULL) {
/* temporarily encode entry into next page, then move back to
* current and next page in rq_respages[] */
__be32 *p1, *tmp;
int len1, len2;
/* grab next page for temporary storage of entry */
p1 = tmp = page_address(*(page+1));
p1 = encode_entry_baggage(cd, p1, name, namlen, ino);
if (plus)
p1 = encode_entryplus_baggage(cd, p1, name, namlen, ino);
/* determine entry word length and lengths to go in pages */
num_entry_words = p1 - tmp;
len1 = curr_page_addr + PAGE_SIZE - (caddr_t)cd->buffer;
if ((num_entry_words << 2) < len1) {
/* the actual number of words in the entry is less
* than elen and can still fit in the current page
*/
memmove(p, tmp, num_entry_words << 2);
p += num_entry_words;
/* update offset */
cd->offset = cd->buffer + (cd->offset - tmp);
} else {
unsigned int offset_r = (cd->offset - tmp) << 2;
/* update pointer to offset location.
* This is a 64bit quantity, so we need to
* deal with 3 cases:
* - entirely in first page
* - entirely in second page
* - 4 bytes in each page
*/
if (offset_r + 8 <= len1) {
cd->offset = p + (cd->offset - tmp);
} else if (offset_r >= len1) {
cd->offset -= len1 >> 2;
} else {
/* sitting on the fence */
BUG_ON(offset_r != len1 - 4);
cd->offset = p + (cd->offset - tmp);
cd->offset1 = tmp;
}
len2 = (num_entry_words << 2) - len1;
/* move from temp page to current and next pages */
memmove(p, tmp, len1);
memmove(tmp, (caddr_t)tmp+len1, len2);
p = tmp + (len2 >> 2);
}
}
else {
cd->common.err = nfserr_toosmall;
return -EINVAL;
}
cd->buflen -= num_entry_words;
cd->buffer = p;
cd->common.err = nfs_ok;
return 0;
}
int
nfs3svc_encode_entry(void *cd, const char *name,
int namlen, loff_t offset, u64 ino, unsigned int d_type)
{
return encode_entry(cd, name, namlen, offset, ino, d_type, 0);
}
int
nfs3svc_encode_entry_plus(void *cd, const char *name,
int namlen, loff_t offset, u64 ino,
unsigned int d_type)
{
return encode_entry(cd, name, namlen, offset, ino, d_type, 1);
}
/* FSSTAT */
int
nfs3svc_encode_fsstatres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_fsstatres *resp)
{
struct kstatfs *s = &resp->stats;
u64 bs = s->f_bsize;
*p++ = xdr_zero; /* no post_op_attr */
if (resp->status == 0) {
p = xdr_encode_hyper(p, bs * s->f_blocks); /* total bytes */
p = xdr_encode_hyper(p, bs * s->f_bfree); /* free bytes */
p = xdr_encode_hyper(p, bs * s->f_bavail); /* user available bytes */
p = xdr_encode_hyper(p, s->f_files); /* total inodes */
p = xdr_encode_hyper(p, s->f_ffree); /* free inodes */
p = xdr_encode_hyper(p, s->f_ffree); /* user available inodes */
*p++ = htonl(resp->invarsec); /* mean unchanged time */
}
return xdr_ressize_check(rqstp, p);
}
/* FSINFO */
int
nfs3svc_encode_fsinfores(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_fsinfores *resp)
{
*p++ = xdr_zero; /* no post_op_attr */
if (resp->status == 0) {
*p++ = htonl(resp->f_rtmax);
*p++ = htonl(resp->f_rtpref);
*p++ = htonl(resp->f_rtmult);
*p++ = htonl(resp->f_wtmax);
*p++ = htonl(resp->f_wtpref);
*p++ = htonl(resp->f_wtmult);
*p++ = htonl(resp->f_dtpref);
p = xdr_encode_hyper(p, resp->f_maxfilesize);
*p++ = xdr_one;
*p++ = xdr_zero;
*p++ = htonl(resp->f_properties);
}
return xdr_ressize_check(rqstp, p);
}
/* PATHCONF */
int
nfs3svc_encode_pathconfres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_pathconfres *resp)
{
*p++ = xdr_zero; /* no post_op_attr */
if (resp->status == 0) {
*p++ = htonl(resp->p_link_max);
*p++ = htonl(resp->p_name_max);
*p++ = htonl(resp->p_no_trunc);
*p++ = htonl(resp->p_chown_restricted);
*p++ = htonl(resp->p_case_insensitive);
*p++ = htonl(resp->p_case_preserving);
}
return xdr_ressize_check(rqstp, p);
}
/* COMMIT */
int
nfs3svc_encode_commitres(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_commitres *resp)
{
struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
p = encode_wcc_data(rqstp, p, &resp->fh);
/* Write verifier */
if (resp->status == 0) {
*p++ = htonl(nn->nfssvc_boot.tv_sec);
*p++ = htonl(nn->nfssvc_boot.tv_usec);
}
return xdr_ressize_check(rqstp, p);
}
/*
* XDR release functions
*/
int
nfs3svc_release_fhandle(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_attrstat *resp)
{
fh_put(&resp->fh);
return 1;
}
int
nfs3svc_release_fhandle2(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_fhandle_pair *resp)
{
fh_put(&resp->fh1);
fh_put(&resp->fh2);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_3305_0 |
crossvul-cpp_data_good_4787_5 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% BBBB M M PPPP %
% B B MM MM P P %
% BBBB M M M PPPP %
% B B M M P %
% BBBB M M P %
% %
% %
% Read/Write Microsoft Windows Bitmap Image Format %
% %
% Software Design %
% Cristy %
% Glenn Randers-Pehrson %
% December 2001 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colormap-private.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Macro definitions (from Windows wingdi.h).
*/
#undef BI_JPEG
#define BI_JPEG 4
#undef BI_PNG
#define BI_PNG 5
#if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__) || defined(__MINGW64__)
#undef BI_RGB
#define BI_RGB 0
#undef BI_RLE8
#define BI_RLE8 1
#undef BI_RLE4
#define BI_RLE4 2
#undef BI_BITFIELDS
#define BI_BITFIELDS 3
#undef LCS_CALIBRATED_RBG
#define LCS_CALIBRATED_RBG 0
#undef LCS_sRGB
#define LCS_sRGB 1
#undef LCS_WINDOWS_COLOR_SPACE
#define LCS_WINDOWS_COLOR_SPACE 2
#undef PROFILE_LINKED
#define PROFILE_LINKED 3
#undef PROFILE_EMBEDDED
#define PROFILE_EMBEDDED 4
#undef LCS_GM_BUSINESS
#define LCS_GM_BUSINESS 1 /* Saturation */
#undef LCS_GM_GRAPHICS
#define LCS_GM_GRAPHICS 2 /* Relative */
#undef LCS_GM_IMAGES
#define LCS_GM_IMAGES 4 /* Perceptual */
#undef LCS_GM_ABS_COLORIMETRIC
#define LCS_GM_ABS_COLORIMETRIC 8 /* Absolute */
#endif
/*
Typedef declarations.
*/
typedef struct _BMPInfo
{
unsigned int
file_size,
ba_offset,
offset_bits,
size;
ssize_t
width,
height;
unsigned short
planes,
bits_per_pixel;
unsigned int
compression,
image_size,
x_pixels,
y_pixels,
number_colors,
red_mask,
green_mask,
blue_mask,
alpha_mask,
colors_important;
int
colorspace;
PrimaryInfo
red_primary,
green_primary,
blue_primary,
gamma_scale;
} BMPInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteBMPImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecodeImage unpacks the packed image pixels into runlength-encoded
% pixel packets.
%
% The format of the DecodeImage method is:
%
% MagickBooleanType DecodeImage(Image *image,
% const size_t compression,unsigned char *pixels)
%
% A description of each parameter follows:
%
% o image: the address of a structure of type Image.
%
% o compression: Zero means uncompressed. A value of 1 means the
% compressed pixels are runlength encoded for a 256-color bitmap.
% A value of 2 means a 16-color bitmap. A value of 3 means bitfields
% encoding.
%
% o pixels: The address of a byte (8 bits) array of pixel data created by
% the decoding process.
%
*/
static inline ssize_t MagickAbsoluteValue(const ssize_t x)
{
if (x < 0)
return(-x);
return(x);
}
static inline size_t MagickMax(const size_t x,const size_t y)
{
if (x > y)
return(x);
return(y);
}
static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
{
if (x < y)
return(x);
return(y);
}
static MagickBooleanType DecodeImage(Image *image,const size_t compression,
unsigned char *pixels)
{
int
count;
register ssize_t
i,
x;
register unsigned char
*p,
*q;
ssize_t
y;
unsigned char
byte;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
(void) ResetMagickMemory(pixels,0,(size_t) image->columns*image->rows*
sizeof(*pixels));
byte=0;
x=0;
p=pixels;
q=pixels+(size_t) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; )
{
if ((p < pixels) || (p >= q))
break;
count=ReadBlobByte(image);
if (count == EOF)
break;
if (count != 0)
{
/*
Encoded mode.
*/
count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p));
byte=(unsigned char) ReadBlobByte(image);
if (compression == BI_RLE8)
{
for (i=0; i < (ssize_t) count; i++)
*p++=(unsigned char) byte;
}
else
{
for (i=0; i < (ssize_t) count; i++)
*p++=(unsigned char)
((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
}
x+=count;
}
else
{
/*
Escape mode.
*/
count=ReadBlobByte(image);
if (count == 0x01)
return(MagickTrue);
switch (count)
{
case 0x00:
{
/*
End of line.
*/
x=0;
y++;
p=pixels+y*image->columns;
break;
}
case 0x02:
{
/*
Delta mode.
*/
x+=ReadBlobByte(image);
y+=ReadBlobByte(image);
p=pixels+y*image->columns+x;
break;
}
default:
{
/*
Absolute mode.
*/
count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p));
if (compression == BI_RLE8)
for (i=0; i < (ssize_t) count; i++)
*p++=(unsigned char) ReadBlobByte(image);
else
for (i=0; i < (ssize_t) count; i++)
{
if ((i & 0x01) == 0)
byte=(unsigned char) ReadBlobByte(image);
*p++=(unsigned char)
((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
}
x+=count;
/*
Read pad byte.
*/
if (compression == BI_RLE8)
{
if ((count & 0x01) != 0)
(void) ReadBlobByte(image);
}
else
if (((count & 0x03) == 1) || ((count & 0x03) == 2))
(void) ReadBlobByte(image);
break;
}
}
}
if (SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows) == MagickFalse)
break;
}
(void) ReadBlobByte(image); /* end of line */
(void) ReadBlobByte(image);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E n c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EncodeImage compresses pixels using a runlength encoded format.
%
% The format of the EncodeImage method is:
%
% static MagickBooleanType EncodeImage(Image *image,
% const size_t bytes_per_line,const unsigned char *pixels,
% unsigned char *compressed_pixels)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o bytes_per_line: the number of bytes in a scanline of compressed pixels
%
% o pixels: The address of a byte (8 bits) array of pixel data created by
% the compression process.
%
% o compressed_pixels: The address of a byte (8 bits) array of compressed
% pixel data.
%
*/
static size_t EncodeImage(Image *image,const size_t bytes_per_line,
const unsigned char *pixels,unsigned char *compressed_pixels)
{
MagickBooleanType
status;
register const unsigned char
*p;
register ssize_t
i,
x;
register unsigned char
*q;
ssize_t
y;
/*
Runlength encode pixels.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (const unsigned char *) NULL);
assert(compressed_pixels != (unsigned char *) NULL);
p=pixels;
q=compressed_pixels;
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
for (x=0; x < (ssize_t) bytes_per_line; x+=i)
{
/*
Determine runlength.
*/
for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++)
if ((i == 255) || (*(p+i) != *p))
break;
*q++=(unsigned char) i;
*q++=(*p);
p+=i;
}
/*
End of line.
*/
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
End of bitmap.
*/
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x01;
return((size_t) (q-compressed_pixels));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s B M P %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsBMP() returns MagickTrue if the image format type, identified by the
% magick string, is BMP.
%
% The format of the IsBMP method is:
%
% MagickBooleanType IsBMP(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsBMP(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if ((LocaleNCompare((char *) magick,"BA",2) == 0) ||
(LocaleNCompare((char *) magick,"BM",2) == 0) ||
(LocaleNCompare((char *) magick,"IC",2) == 0) ||
(LocaleNCompare((char *) magick,"PI",2) == 0) ||
(LocaleNCompare((char *) magick,"CI",2) == 0) ||
(LocaleNCompare((char *) magick,"CP",2) == 0))
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d B M P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadBMPImage() reads a Microsoft Windows bitmap image file, Version
% 2, 3 (for Windows or NT), or 4, and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the ReadBMPImage method is:
%
% image=ReadBMPImage(image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
BMPInfo
bmp_info;
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
MagickOffsetType
offset,
start_position;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
blue,
bytes_per_line,
green,
length,
red;
ssize_t
count,
y;
unsigned char
magick[12],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a BMP file.
*/
(void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
bmp_info.ba_offset=0;
start_position=0;
count=ReadBlob(image,2,magick);
do
{
LongPixelPacket
shift;
PixelPacket
quantum_bits;
size_t
profile_data,
profile_size;
/*
Verify BMP identifier.
*/
if (bmp_info.ba_offset == 0)
start_position=TellBlob(image)-2;
bmp_info.ba_offset=0;
while (LocaleNCompare((char *) magick,"BA",2) == 0)
{
bmp_info.file_size=ReadBlobLSBLong(image);
bmp_info.ba_offset=ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
count=ReadBlob(image,2,magick);
if (count != 2)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c",
magick[0],magick[1]);
if ((count == 0) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"CI",2) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bmp_info.file_size=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" File_size in header: %u bytes",bmp_info.file_size);
bmp_info.offset_bits=ReadBlobLSBLong(image);
bmp_info.size=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u",
bmp_info.size);
if (bmp_info.size == 12)
{
/*
OS/2 BMP image file.
*/
(void) CopyMagickString(image->magick,"BMP2",MaxTextExtent);
bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.x_pixels=0;
bmp_info.y_pixels=0;
bmp_info.number_colors=0;
bmp_info.compression=BI_RGB;
bmp_info.image_size=0;
bmp_info.alpha_mask=0;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: OS/2 Bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
}
}
else
{
/*
Microsoft Windows BMP image file.
*/
if (bmp_info.size < 40)
ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError");
bmp_info.width=(ssize_t) ((int) ReadBlobLSBLong(image));
bmp_info.height=(ssize_t) ((int) ReadBlobLSBLong(image));
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.compression=ReadBlobLSBLong(image);
bmp_info.image_size=ReadBlobLSBLong(image);
bmp_info.x_pixels=ReadBlobLSBLong(image);
bmp_info.y_pixels=ReadBlobLSBLong(image);
bmp_info.number_colors=ReadBlobLSBLong(image);
bmp_info.colors_important=ReadBlobLSBLong(image);
profile_data=0;
profile_size=0;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: MS Windows bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel);
switch ((int) bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RGB");
break;
}
case BI_RLE4:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE4");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_BITFIELDS");
break;
}
case BI_PNG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_PNG");
break;
}
case BI_JPEG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_JPEG");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: UNKNOWN (%u)",bmp_info.compression);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %u",bmp_info.number_colors);
}
bmp_info.red_mask=ReadBlobLSBLong(image);
bmp_info.green_mask=ReadBlobLSBLong(image);
bmp_info.blue_mask=ReadBlobLSBLong(image);
if (bmp_info.size > 40)
{
double
sum;
/*
Read color management information.
*/
bmp_info.alpha_mask=ReadBlobLSBLong(image);
bmp_info.colorspace=(int) ReadBlobLSBLong(image);
/*
Decode 2^30 fixed point formatted CIE primaries.
*/
# define BMP_DENOM ((double) 0x40000000)
bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
sum=bmp_info.red_primary.x+bmp_info.red_primary.y+
bmp_info.red_primary.z;
bmp_info.red_primary.x/=sum;
bmp_info.red_primary.y/=sum;
image->chromaticity.red_primary.x=bmp_info.red_primary.x;
image->chromaticity.red_primary.y=bmp_info.red_primary.y;
sum=bmp_info.green_primary.x+bmp_info.green_primary.y+
bmp_info.green_primary.z;
bmp_info.green_primary.x/=sum;
bmp_info.green_primary.y/=sum;
image->chromaticity.green_primary.x=bmp_info.green_primary.x;
image->chromaticity.green_primary.y=bmp_info.green_primary.y;
sum=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
bmp_info.blue_primary.z;
bmp_info.blue_primary.x/=sum;
bmp_info.blue_primary.y/=sum;
image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;
image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;
/*
Decode 16^16 fixed point formatted gamma_scales.
*/
bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;
/*
Compute a single gamma from the BMP 3-channel gamma.
*/
image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+
bmp_info.gamma_scale.z)/3.0;
}
else
(void) CopyMagickString(image->magick,"BMP3",MaxTextExtent);
if (bmp_info.size > 108)
{
size_t
intent;
/*
Read BMP Version 5 color management information.
*/
intent=ReadBlobLSBLong(image);
switch ((int) intent)
{
case LCS_GM_BUSINESS:
{
image->rendering_intent=SaturationIntent;
break;
}
case LCS_GM_GRAPHICS:
{
image->rendering_intent=RelativeIntent;
break;
}
case LCS_GM_IMAGES:
{
image->rendering_intent=PerceptualIntent;
break;
}
case LCS_GM_ABS_COLORIMETRIC:
{
image->rendering_intent=AbsoluteIntent;
break;
}
}
profile_data=ReadBlobLSBLong(image);
profile_size=ReadBlobLSBLong(image);
(void) profile_data;
(void) profile_size;
(void) ReadBlobLSBLong(image); /* Reserved byte */
}
}
if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"LengthAndFilesizeDoNotMatch","`%s'",image->filename);
else
if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'",
image->filename);
if (bmp_info.width <= 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.height == 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.planes != 1)
ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&
(bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&
(bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
if (bmp_info.bits_per_pixel < 16 &&
bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))
{
ThrowReaderException(CorruptImageError,
"UnrecognizedNumberOfColors");
}
if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
switch (bmp_info.compression)
{
case BI_RGB:
case BI_RLE8:
case BI_RLE4:
case BI_BITFIELDS:
break;
case BI_JPEG:
ThrowReaderException(CoderError,"JPEGCompressNotSupported");
case BI_PNG:
ThrowReaderException(CoderError,"PNGCompressNotSupported");
default:
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);
image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);
image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;
image->matte=((bmp_info.alpha_mask != 0) &&
(bmp_info.compression == BI_BITFIELDS)) ||
(bmp_info.bits_per_pixel == 32) ? MagickTrue : MagickFalse;
if (bmp_info.bits_per_pixel < 16)
{
size_t
one;
image->storage_class=PseudoClass;
image->colors=bmp_info.number_colors;
one=1;
if (image->colors == 0)
image->colors=one << bmp_info.bits_per_pixel;
}
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
size_t
packet_size;
/*
Read BMP raster colormap.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading colormap of %.20g colors",(double) image->colors);
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
image->colors,4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((bmp_info.size == 12) || (bmp_info.size == 64))
packet_size=3;
else
packet_size=4;
offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
if (count != (ssize_t) (packet_size*image->colors))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
p=bmp_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].red=ScaleCharToQuantum(*p++);
if (packet_size == 4)
p++;
}
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
image->x_resolution=(double) bmp_info.x_pixels/100.0;
image->y_resolution=(double) bmp_info.y_pixels/100.0;
image->units=PixelsPerCentimeterResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read image data.
*/
offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (bmp_info.compression == BI_RLE4)
bmp_info.bits_per_pixel<<=1;
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
length=(size_t) bytes_per_line*image->rows;
pixel_info=AcquireVirtualMemory((size_t) image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading pixels (%.20g bytes)",(double) length);
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
}
else
{
/*
Convert run-length encoded raster pixels.
*/
status=DecodeImage(image,bmp_info.compression,pixels);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnableToRunlengthDecodeImage");
}
}
/*
Convert BMP raster image to pixel packets.
*/
if (bmp_info.compression == BI_RGB)
{
bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U;
bmp_info.red_mask=0x00ff0000U;
bmp_info.green_mask=0x0000ff00U;
bmp_info.blue_mask=0x000000ffU;
if (bmp_info.bits_per_pixel == 16)
{
/*
RGB555.
*/
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
}
}
if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
{
register size_t
sample;
/*
Get shift and quantum bits info from bitfield masks.
*/
(void) ResetMagickMemory(&shift,0,sizeof(shift));
(void) ResetMagickMemory(&quantum_bits,0,sizeof(quantum_bits));
if (bmp_info.red_mask != 0)
while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
shift.red++;
if (bmp_info.green_mask != 0)
while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
shift.green++;
if (bmp_info.blue_mask != 0)
while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
shift.blue++;
if (bmp_info.alpha_mask != 0)
while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0)
shift.opacity++;
sample=shift.red;
while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
sample++;
quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red);
sample=shift.green;
while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
sample++;
quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green);
sample=shift.blue;
while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
sample++;
quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue);
sample=shift.opacity;
while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
sample++;
quantum_bits.opacity=ClampToQuantum((MagickRealType) sample-
shift.opacity);
}
switch (bmp_info.bits_per_pixel)
{
case 1:
{
/*
Convert bitmap scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
q++;
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
break;
}
case 4:
{
/*
Convert PseudoColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,*p & 0x0f);
SetPixelIndex(indexes+x+1,index);
p++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0xf);
SetPixelIndex(indexes+x,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
break;
}
case 8:
{
/*
Convert PseudoColor scanline.
*/
if ((bmp_info.compression == BI_RLE8) ||
(bmp_info.compression == BI_RLE4))
bytes_per_line=image->columns;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=(ssize_t) image->columns; x != 0; --x)
{
index=ConstrainColormapIndex(image,*p);
SetPixelIndex(indexes,index);
indexes++;
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
break;
}
case 16:
{
size_t
alpha,
pixel;
/*
Convert bitfield encoded 16-bit PseudoColor scanline.
*/
if (bmp_info.compression != BI_RGB &&
bmp_info.compression != BI_BITFIELDS)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=2*(image->columns+image->columns % 2);
image->storage_class=DirectClass;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(size_t) (*p++);
pixel|=(*p++) << 8;
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 5)
red|=((red & 0xe000) >> 5);
if (quantum_bits.red <= 8)
red|=((red & 0xff00) >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 5)
green|=((green & 0xe000) >> 5);
if (quantum_bits.green == 6)
green|=((green & 0xc000) >> 6);
if (quantum_bits.green <= 8)
green|=((green & 0xff00) >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 5)
blue|=((blue & 0xe000) >> 5);
if (quantum_bits.blue <= 8)
blue|=((blue & 0xff00) >> 8);
alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;
if (quantum_bits.opacity <= 8)
alpha|=((alpha & 0xff00) >> 8);
SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectColor scanline.
*/
bytes_per_line=4*((image->columns*24+31)/32);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelOpacity(q,OpaqueOpacity);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert bitfield encoded DirectColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
size_t
alpha,
pixel;
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(size_t) (*p++);
pixel|=((size_t) *p++ << 8);
pixel|=((size_t) *p++ << 16);
pixel|=((size_t) *p++ << 24);
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 8)
red|=(red >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 8)
green|=(green >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 8)
blue|=(blue >> 8);
alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16;
if (quantum_bits.opacity == 8)
alpha|=(alpha >> 8);
SetPixelRed(q,ScaleShortToQuantum((unsigned short) red));
SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green));
SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue));
SetPixelAlpha(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
default:
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if (bmp_info.height < 0)
{
Image
*flipped_image;
/*
Correct image orientation.
*/
flipped_image=FlipImage(image,exception);
if (flipped_image != (Image *) NULL)
{
DuplicateBlob(flipped_image,image);
image=DestroyImage(image);
image=flipped_image;
}
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
*magick='\0';
if (bmp_info.ba_offset != 0)
{
offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,2,magick);
if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
{
/*
Acquire next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (IsBMP(magick,2) != MagickFalse);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r B M P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterBMPImage() adds attributes for the BMP image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterBMPImage method is:
%
% size_t RegisterBMPImage(void)
%
*/
ModuleExport size_t RegisterBMPImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("BMP");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->description=ConstantString("Microsoft Windows bitmap image");
entry->module=ConstantString("BMP");
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("BMP2");
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->description=ConstantString("Microsoft Windows bitmap image (V2)");
entry->module=ConstantString("BMP");
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("BMP3");
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->description=ConstantString("Microsoft Windows bitmap image (V3)");
entry->module=ConstantString("BMP");
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r B M P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterBMPImage() removes format registrations made by the
% BMP module from the list of supported formats.
%
% The format of the UnregisterBMPImage method is:
%
% UnregisterBMPImage(void)
%
*/
ModuleExport void UnregisterBMPImage(void)
{
(void) UnregisterMagickInfo("BMP");
(void) UnregisterMagickInfo("BMP2");
(void) UnregisterMagickInfo("BMP3");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e B M P I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteBMPImage() writes an image in Microsoft Windows bitmap encoded
% image format, version 3 for Windows or (if the image has a matte channel)
% version 4.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image)
{
BMPInfo
bmp_info;
const char
*value;
const StringInfo
*profile;
MagickBooleanType
have_color_info,
status;
MemoryInfo
*pixel_info;
MagickOffsetType
scene;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
bytes_per_line,
type;
ssize_t
y;
unsigned char
*bmp_data,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
type=4;
if (LocaleCompare(image_info->magick,"BMP2") == 0)
type=2;
else
if (LocaleCompare(image_info->magick,"BMP3") == 0)
type=3;
value=GetImageOption(image_info,"bmp:format");
if (value != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",value);
if (LocaleCompare(value,"bmp2") == 0)
type=2;
if (LocaleCompare(value,"bmp3") == 0)
type=3;
if (LocaleCompare(value,"bmp4") == 0)
type=4;
}
scene=0;
do
{
/*
Initialize BMP raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
(void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info));
bmp_info.file_size=14+12;
if (type > 2)
bmp_info.file_size+=28;
bmp_info.offset_bits=bmp_info.file_size;
bmp_info.compression=BI_RGB;
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass);
if (image->storage_class != DirectClass)
{
/*
Colormapped BMP raster.
*/
bmp_info.bits_per_pixel=8;
if (image->colors <= 2)
bmp_info.bits_per_pixel=1;
else
if (image->colors <= 16)
bmp_info.bits_per_pixel=4;
else
if (image->colors <= 256)
bmp_info.bits_per_pixel=8;
if (image_info->compression == RLECompression)
bmp_info.bits_per_pixel=8;
bmp_info.number_colors=1U << bmp_info.bits_per_pixel;
if (image->matte != MagickFalse)
(void) SetImageStorageClass(image,DirectClass);
else
if ((size_t) bmp_info.number_colors < image->colors)
(void) SetImageStorageClass(image,DirectClass);
else
{
bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel);
bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel);
if (type > 2)
{
bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel);
bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel);
}
}
}
if (image->storage_class == DirectClass)
{
/*
Full color BMP raster.
*/
bmp_info.number_colors=0;
bmp_info.bits_per_pixel=(unsigned short)
((type > 3) && (image->matte != MagickFalse) ? 32 : 24);
bmp_info.compression=(unsigned int) ((type > 3) &&
(image->matte != MagickFalse) ? BI_BITFIELDS : BI_RGB);
}
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
bmp_info.ba_offset=0;
profile=GetImageProfile(image,"icc");
have_color_info=(image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue :
MagickFalse;
if (type == 2)
bmp_info.size=12;
else
if ((type == 3) || ((image->matte == MagickFalse) &&
(have_color_info == MagickFalse)))
{
type=3;
bmp_info.size=40;
}
else
{
int
extra_size;
bmp_info.size=108;
extra_size=68;
if ((image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL))
{
bmp_info.size=124;
extra_size+=16;
}
bmp_info.file_size+=extra_size;
bmp_info.offset_bits+=extra_size;
}
bmp_info.width=(ssize_t) image->columns;
bmp_info.height=(ssize_t) image->rows;
bmp_info.planes=1;
bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows);
bmp_info.file_size+=bmp_info.image_size;
bmp_info.x_pixels=75*39;
bmp_info.y_pixels=75*39;
switch (image->units)
{
case UndefinedResolution:
case PixelsPerInchResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution/2.54);
bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution/2.54);
break;
}
case PixelsPerCentimeterResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->x_resolution);
bmp_info.y_pixels=(unsigned int) (100.0*image->y_resolution);
break;
}
}
bmp_info.colors_important=bmp_info.number_colors;
/*
Convert MIFF to BMP raster pixels.
*/
pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size,
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size);
switch (bmp_info.bits_per_pixel)
{
case 1:
{
size_t
bit,
byte;
/*
Convert PseudoClass image to a BMP monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels+(image->rows-y-1)*bytes_per_line;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00;
bit++;
if (bit == 8)
{
*q++=(unsigned char) byte;
bit=0;
byte=0;
}
}
if (bit != 0)
{
*q++=(unsigned char) (byte << (8-bit));
x++;
}
for (x=(ssize_t) (image->columns+7)/8; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 4:
{
size_t
nibble,
byte;
/*
Convert PseudoClass image to a BMP monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels+(image->rows-y-1)*bytes_per_line;
nibble=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=4;
byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f);
nibble++;
if (nibble == 2)
{
*q++=(unsigned char) byte;
nibble=0;
byte=0;
}
}
if (nibble != 0)
{
*q++=(unsigned char) (byte << 4);
x++;
}
for (x=(ssize_t) (image->columns+1)/2; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 8:
{
/*
Convert PseudoClass packet to BMP pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
*q++=(unsigned char) GetPixelIndex(indexes+x);
for ( ; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelRed(p));
p++;
}
for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++)
*q++=0x00;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert DirectClass packet to ARGB8888 pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelAlpha(p));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
if ((type > 2) && (bmp_info.bits_per_pixel == 8))
if (image_info->compression != NoCompression)
{
MemoryInfo
*rle_info;
/*
Convert run-length encoded raster pixels.
*/
rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2),
(image->rows+2)*sizeof(*pixels));
if (rle_info == (MemoryInfo *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info);
bmp_info.file_size-=bmp_info.image_size;
bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line,
pixels,bmp_data);
bmp_info.file_size+=bmp_info.image_size;
pixel_info=RelinquishVirtualMemory(pixel_info);
pixel_info=rle_info;
pixels=bmp_data;
bmp_info.compression=BI_RLE8;
}
/*
Write BMP for Windows, all versions, 14-byte header.
*/
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing BMP version %.20g datastream",(double) type);
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class=DirectClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Storage class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image depth=%.20g",(double) image->depth);
if (image->matte != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte=True");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Matte=MagickFalse");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel);
switch ((int) bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_RGB");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=BI_BITFIELDS");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression=UNKNOWN (%u)",bmp_info.compression);
break;
}
}
if (bmp_info.number_colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number_colors=unspecified");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number_colors=%u",bmp_info.number_colors);
}
(void) WriteBlob(image,2,(unsigned char *) "BM");
(void) WriteBlobLSBLong(image,bmp_info.file_size);
(void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */
(void) WriteBlobLSBLong(image,bmp_info.offset_bits);
if (type == 2)
{
/*
Write 12-byte version 2 bitmap header.
*/
(void) WriteBlobLSBLong(image,bmp_info.size);
(void) WriteBlobLSBShort(image,(unsigned short) bmp_info.width);
(void) WriteBlobLSBShort(image,(unsigned short) bmp_info.height);
(void) WriteBlobLSBShort(image,bmp_info.planes);
(void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
}
else
{
/*
Write 40-byte version 3+ bitmap header.
*/
(void) WriteBlobLSBLong(image,bmp_info.size);
(void) WriteBlobLSBLong(image,(unsigned int) bmp_info.width);
(void) WriteBlobLSBLong(image,(unsigned int) bmp_info.height);
(void) WriteBlobLSBShort(image,bmp_info.planes);
(void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel);
(void) WriteBlobLSBLong(image,bmp_info.compression);
(void) WriteBlobLSBLong(image,bmp_info.image_size);
(void) WriteBlobLSBLong(image,bmp_info.x_pixels);
(void) WriteBlobLSBLong(image,bmp_info.y_pixels);
(void) WriteBlobLSBLong(image,bmp_info.number_colors);
(void) WriteBlobLSBLong(image,bmp_info.colors_important);
}
if ((type > 3) && ((image->matte != MagickFalse) ||
(have_color_info != MagickFalse)))
{
/*
Write the rest of the 108-byte BMP Version 4 header.
*/
(void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */
(void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */
(void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */
(void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */
(void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.red_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.red_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.red_primary.x+
image->chromaticity.red_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.green_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.green_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.green_primary.x+
image->chromaticity.green_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.blue_primary.x*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(image->chromaticity.blue_primary.y*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
((1.000f-(image->chromaticity.blue_primary.x+
image->chromaticity.blue_primary.y))*0x40000000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.x*0x10000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.y*0x10000));
(void) WriteBlobLSBLong(image,(unsigned int)
(bmp_info.gamma_scale.z*0x10000));
if ((image->rendering_intent != UndefinedIntent) ||
(profile != (StringInfo *) NULL))
{
ssize_t
intent;
switch ((int) image->rendering_intent)
{
case SaturationIntent:
{
intent=LCS_GM_BUSINESS;
break;
}
case RelativeIntent:
{
intent=LCS_GM_GRAPHICS;
break;
}
case PerceptualIntent:
{
intent=LCS_GM_IMAGES;
break;
}
case AbsoluteIntent:
{
intent=LCS_GM_ABS_COLORIMETRIC;
break;
}
default:
{
intent=0;
break;
}
}
(void) WriteBlobLSBLong(image,(unsigned int) intent);
(void) WriteBlobLSBLong(image,0x00); /* dummy profile data */
(void) WriteBlobLSBLong(image,0x00); /* dummy profile length */
(void) WriteBlobLSBLong(image,0x00); /* reserved */
}
}
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
/*
Dump colormap to file.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Colormap: %.20g entries",(double) image->colors);
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL <<
bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
q=bmp_colormap;
for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++)
{
*q++=ScaleQuantumToChar(image->colormap[i].blue);
*q++=ScaleQuantumToChar(image->colormap[i].green);
*q++=ScaleQuantumToChar(image->colormap[i].red);
if (type > 2)
*q++=(unsigned char) 0x0;
}
for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++)
{
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
*q++=(unsigned char) 0x00;
if (type > 2)
*q++=(unsigned char) 0x00;
}
if (type <= 2)
(void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)),
bmp_colormap);
else
(void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)),
bmp_colormap);
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Pixels: %u bytes",bmp_info.image_size);
(void) WriteBlob(image,(size_t) bmp_info.image_size,pixels);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" File_size: %u bytes",bmp_info.file_size);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4787_5 |
crossvul-cpp_data_bad_622_4 | /*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*====================================================================*/
/*!
* \file sel1.c
* <pre>
*
* Basic ops on Sels and Selas
*
* Create/destroy/copy:
* SELA *selaCreate()
* void selaDestroy()
* SEL *selCreate()
* void selDestroy()
* SEL *selCopy()
* SEL *selCreateBrick()
* SEL *selCreateComb()
*
* Helper proc:
* l_int32 **create2dIntArray()
*
* Extension of sela:
* SELA *selaAddSel()
* static l_int32 selaExtendArray()
*
* Accessors:
* l_int32 selaGetCount()
* SEL *selaGetSel()
* char *selGetName()
* l_int32 selSetName()
* l_int32 selaFindSelByName()
* l_int32 selGetElement()
* l_int32 selSetElement()
* l_int32 selGetParameters()
* l_int32 selSetOrigin()
* l_int32 selGetTypeAtOrigin()
* char *selaGetBrickName()
* char *selaGetCombName()
* static char *selaComputeCompositeParameters()
* l_int32 getCompositeParameters()
* SARRAY *selaGetSelnames()
*
* Max translations for erosion and hmt
* l_int32 selFindMaxTranslations()
*
* Rotation by multiples of 90 degrees
* SEL *selRotateOrth()
*
* Sela and Sel serialized I/O
* SELA *selaRead()
* SELA *selaReadStream()
* SEL *selRead()
* SEL *selReadStream()
* l_int32 selaWrite()
* l_int32 selaWriteStream()
* l_int32 selWrite()
* l_int32 selWriteStream()
*
* Building custom hit-miss sels from compiled strings
* SEL *selCreateFromString()
* char *selPrintToString() [for debugging]
*
* Building custom hit-miss sels from a simple file format
* SELA *selaCreateFromFile()
* static SEL *selCreateFromSArray()
*
* Making hit-only sels from Pta and Pix
* SEL *selCreateFromPta()
* SEL *selCreateFromPix()
*
* Making hit-miss sels from Pix and image files
* SEL *selReadFromColorImage()
* SEL *selCreateFromColorPix()
*
* Printable display of sel
* PIX *selDisplayInPix()
* PIX *selaDisplayInPix()
*
* Usage notes:
* In this file we have seven functions that make sels:
* (1) selCreate(), with input (h, w, [name])
* The generic function. Roll your own, using selSetElement().
* (2) selCreateBrick(), with input (h, w, cy, cx, val)
* The most popular function. Makes a rectangular sel of
* all hits, misses or don't-cares. We have many morphology
* operations that create a sel of all hits, use it, and
* destroy it.
* (3) selCreateFromString() with input (text, h, w, [name])
* Adam Langley's clever function, allows you to make a hit-miss
* sel from a string in code that is geometrically laid out
* just like the actual sel.
* (4) selaCreateFromFile() with input (filename)
* This parses a simple file format to create an array of
* hit-miss sels. The sel data uses the same encoding
* as in (3), with geometrical layout enforced.
* (5) selCreateFromPta() with input (pta, cy, cx, [name])
* Another way to make a sel with only hits.
* (6) selCreateFromPix() with input (pix, cy, cx, [name])
* Yet another way to make a sel from hits.
* (7) selCreateFromColorPix() with input (pix, name).
* Another way to make a general hit-miss sel, starting with
* an image editor.
* In addition, there are three functions in selgen.c that
* automatically generate a hit-miss sel from a pix and
* a number of parameters. This is useful for problems like
* "find all patterns that look like this one."
*
* Consistency, being the hobgoblin of small minds,
* is adhered to here in the dimensioning and accessing of sels.
* Everything is done in standard matrix (row, column) order.
* When we set specific elements in a sel, we likewise use
* (row, col) ordering:
* selSetElement(), with input (row, col, type)
* </pre>
*/
#include <string.h>
#include "allheaders.h"
static const l_int32 L_BUF_SIZE = 256;
static const l_int32 INITIAL_PTR_ARRAYSIZE = 50; /* n'import quoi */
static const l_int32 MANY_SELS = 1000;
/* Static functions */
static l_int32 selaExtendArray(SELA *sela);
static SEL *selCreateFromSArray(SARRAY *sa, l_int32 first, l_int32 last);
struct CompParameterMap
{
l_int32 size;
l_int32 size1;
l_int32 size2;
char selnameh1[20];
char selnameh2[20];
char selnamev1[20];
char selnamev2[20];
};
static const struct CompParameterMap comp_parameter_map[] =
{ { 2, 2, 1, "sel_2h", "", "sel_2v", "" },
{ 3, 3, 1, "sel_3h", "", "sel_3v", "" },
{ 4, 2, 2, "sel_2h", "sel_comb_4h", "sel_2v", "sel_comb_4v" },
{ 5, 5, 1, "sel_5h", "", "sel_5v", "" },
{ 6, 3, 2, "sel_3h", "sel_comb_6h", "sel_3v", "sel_comb_6v" },
{ 7, 7, 1, "sel_7h", "", "sel_7v", "" },
{ 8, 4, 2, "sel_4h", "sel_comb_8h", "sel_4v", "sel_comb_8v" },
{ 9, 3, 3, "sel_3h", "sel_comb_9h", "sel_3v", "sel_comb_9v" },
{ 10, 5, 2, "sel_5h", "sel_comb_10h", "sel_5v", "sel_comb_10v" },
{ 11, 4, 3, "sel_4h", "sel_comb_12h", "sel_4v", "sel_comb_12v" },
{ 12, 4, 3, "sel_4h", "sel_comb_12h", "sel_4v", "sel_comb_12v" },
{ 13, 4, 3, "sel_4h", "sel_comb_12h", "sel_4v", "sel_comb_12v" },
{ 14, 7, 2, "sel_7h", "sel_comb_14h", "sel_7v", "sel_comb_14v" },
{ 15, 5, 3, "sel_5h", "sel_comb_15h", "sel_5v", "sel_comb_15v" },
{ 16, 4, 4, "sel_4h", "sel_comb_16h", "sel_4v", "sel_comb_16v" },
{ 17, 4, 4, "sel_4h", "sel_comb_16h", "sel_4v", "sel_comb_16v" },
{ 18, 6, 3, "sel_6h", "sel_comb_18h", "sel_6v", "sel_comb_18v" },
{ 19, 5, 4, "sel_5h", "sel_comb_20h", "sel_5v", "sel_comb_20v" },
{ 20, 5, 4, "sel_5h", "sel_comb_20h", "sel_5v", "sel_comb_20v" },
{ 21, 7, 3, "sel_7h", "sel_comb_21h", "sel_7v", "sel_comb_21v" },
{ 22, 11, 2, "sel_11h", "sel_comb_22h", "sel_11v", "sel_comb_22v" },
{ 23, 6, 4, "sel_6h", "sel_comb_24h", "sel_6v", "sel_comb_24v" },
{ 24, 6, 4, "sel_6h", "sel_comb_24h", "sel_6v", "sel_comb_24v" },
{ 25, 5, 5, "sel_5h", "sel_comb_25h", "sel_5v", "sel_comb_25v" },
{ 26, 5, 5, "sel_5h", "sel_comb_25h", "sel_5v", "sel_comb_25v" },
{ 27, 9, 3, "sel_9h", "sel_comb_27h", "sel_9v", "sel_comb_27v" },
{ 28, 7, 4, "sel_7h", "sel_comb_28h", "sel_7v", "sel_comb_28v" },
{ 29, 6, 5, "sel_6h", "sel_comb_30h", "sel_6v", "sel_comb_30v" },
{ 30, 6, 5, "sel_6h", "sel_comb_30h", "sel_6v", "sel_comb_30v" },
{ 31, 6, 5, "sel_6h", "sel_comb_30h", "sel_6v", "sel_comb_30v" },
{ 32, 8, 4, "sel_8h", "sel_comb_32h", "sel_8v", "sel_comb_32v" },
{ 33, 11, 3, "sel_11h", "sel_comb_33h", "sel_11v", "sel_comb_33v" },
{ 34, 7, 5, "sel_7h", "sel_comb_35h", "sel_7v", "sel_comb_35v" },
{ 35, 7, 5, "sel_7h", "sel_comb_35h", "sel_7v", "sel_comb_35v" },
{ 36, 6, 6, "sel_6h", "sel_comb_36h", "sel_6v", "sel_comb_36v" },
{ 37, 6, 6, "sel_6h", "sel_comb_36h", "sel_6v", "sel_comb_36v" },
{ 38, 6, 6, "sel_6h", "sel_comb_36h", "sel_6v", "sel_comb_36v" },
{ 39, 13, 3, "sel_13h", "sel_comb_39h", "sel_13v", "sel_comb_39v" },
{ 40, 8, 5, "sel_8h", "sel_comb_40h", "sel_8v", "sel_comb_40v" },
{ 41, 7, 6, "sel_7h", "sel_comb_42h", "sel_7v", "sel_comb_42v" },
{ 42, 7, 6, "sel_7h", "sel_comb_42h", "sel_7v", "sel_comb_42v" },
{ 43, 7, 6, "sel_7h", "sel_comb_42h", "sel_7v", "sel_comb_42v" },
{ 44, 11, 4, "sel_11h", "sel_comb_44h", "sel_11v", "sel_comb_44v" },
{ 45, 9, 5, "sel_9h", "sel_comb_45h", "sel_9v", "sel_comb_45v" },
{ 46, 9, 5, "sel_9h", "sel_comb_45h", "sel_9v", "sel_comb_45v" },
{ 47, 8, 6, "sel_8h", "sel_comb_48h", "sel_8v", "sel_comb_48v" },
{ 48, 8, 6, "sel_8h", "sel_comb_48h", "sel_8v", "sel_comb_48v" },
{ 49, 7, 7, "sel_7h", "sel_comb_49h", "sel_7v", "sel_comb_49v" },
{ 50, 10, 5, "sel_10h", "sel_comb_50h", "sel_10v", "sel_comb_50v" },
{ 51, 10, 5, "sel_10h", "sel_comb_50h", "sel_10v", "sel_comb_50v" },
{ 52, 13, 4, "sel_13h", "sel_comb_52h", "sel_13v", "sel_comb_52v" },
{ 53, 9, 6, "sel_9h", "sel_comb_54h", "sel_9v", "sel_comb_54v" },
{ 54, 9, 6, "sel_9h", "sel_comb_54h", "sel_9v", "sel_comb_54v" },
{ 55, 11, 5, "sel_11h", "sel_comb_55h", "sel_11v", "sel_comb_55v" },
{ 56, 8, 7, "sel_8h", "sel_comb_56h", "sel_8v", "sel_comb_56v" },
{ 57, 8, 7, "sel_8h", "sel_comb_56h", "sel_8v", "sel_comb_56v" },
{ 58, 8, 7, "sel_8h", "sel_comb_56h", "sel_8v", "sel_comb_56v" },
{ 59, 10, 6, "sel_10h", "sel_comb_60h", "sel_10v", "sel_comb_60v" },
{ 60, 10, 6, "sel_10h", "sel_comb_60h", "sel_10v", "sel_comb_60v" },
{ 61, 10, 6, "sel_10h", "sel_comb_60h", "sel_10v", "sel_comb_60v" },
{ 62, 9, 7, "sel_9h", "sel_comb_63h", "sel_9v", "sel_comb_63v" },
{ 63, 9, 7, "sel_9h", "sel_comb_63h", "sel_9v", "sel_comb_63v" } };
/*------------------------------------------------------------------------*
* Create / Destroy / Copy *
*------------------------------------------------------------------------*/
/*!
* \brief selaCreate()
*
* \param[in] n initial number of sel ptrs; use 0 for default
* \return sela, or NULL on error
*/
SELA *
selaCreate(l_int32 n)
{
SELA *sela;
PROCNAME("selaCreate");
if (n <= 0)
n = INITIAL_PTR_ARRAYSIZE;
if (n > MANY_SELS)
L_WARNING("%d sels\n", procName, n);
if ((sela = (SELA *)LEPT_CALLOC(1, sizeof(SELA))) == NULL)
return (SELA *)ERROR_PTR("sela not made", procName, NULL);
sela->nalloc = n;
sela->n = 0;
/* make array of se ptrs */
if ((sela->sel = (SEL **)LEPT_CALLOC(n, sizeof(SEL *))) == NULL) {
LEPT_FREE(sela);
return (SELA *)ERROR_PTR("sel ptrs not made", procName, NULL);
}
return sela;
}
/*!
* \brief selaDestroy()
*
* \param[in,out] psela to be nulled
* \return void
*/
void
selaDestroy(SELA **psela)
{
SELA *sela;
l_int32 i;
if (!psela) return;
if ((sela = *psela) == NULL)
return;
for (i = 0; i < sela->n; i++)
selDestroy(&sela->sel[i]);
LEPT_FREE(sela->sel);
LEPT_FREE(sela);
*psela = NULL;
return;
}
/*!
* \brief selCreate()
*
* \param[in] height, width
* \param[in] name [optional] sel name; can be null
* \return sel, or NULL on error
*
* <pre>
* Notes:
* (1) selCreate() initializes all values to 0.
* (2) After this call, (cy,cx) and nonzero data values must be
* assigned. If a text name is not assigned here, it will
* be needed later when the sel is put into a sela.
* </pre>
*/
SEL *
selCreate(l_int32 height,
l_int32 width,
const char *name)
{
SEL *sel;
PROCNAME("selCreate");
if ((sel = (SEL *)LEPT_CALLOC(1, sizeof(SEL))) == NULL)
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
if (name)
sel->name = stringNew(name);
sel->sy = height;
sel->sx = width;
if ((sel->data = create2dIntArray(height, width)) == NULL) {
LEPT_FREE(sel->name);
LEPT_FREE(sel);
return (SEL *)ERROR_PTR("data not allocated", procName, NULL);
}
return sel;
}
/*!
* \brief selDestroy()
*
* \param[in,out] psel to be nulled
* \return void
*/
void
selDestroy(SEL **psel)
{
l_int32 i;
SEL *sel;
PROCNAME("selDestroy");
if (psel == NULL) {
L_WARNING("ptr address is NULL!\n", procName);
return;
}
if ((sel = *psel) == NULL)
return;
for (i = 0; i < sel->sy; i++)
LEPT_FREE(sel->data[i]);
LEPT_FREE(sel->data);
if (sel->name)
LEPT_FREE(sel->name);
LEPT_FREE(sel);
*psel = NULL;
return;
}
/*!
* \brief selCopy()
*
* \param[in] sel
* \return a copy of the sel, or NULL on error
*/
SEL *
selCopy(SEL *sel)
{
l_int32 sx, sy, cx, cy, i, j;
SEL *csel;
PROCNAME("selCopy");
if (!sel)
return (SEL *)ERROR_PTR("sel not defined", procName, NULL);
if ((csel = (SEL *)LEPT_CALLOC(1, sizeof(SEL))) == NULL)
return (SEL *)ERROR_PTR("csel not made", procName, NULL);
selGetParameters(sel, &sy, &sx, &cy, &cx);
csel->sy = sy;
csel->sx = sx;
csel->cy = cy;
csel->cx = cx;
if ((csel->data = create2dIntArray(sy, sx)) == NULL) {
LEPT_FREE(csel);
return (SEL *)ERROR_PTR("sel data not made", procName, NULL);
}
for (i = 0; i < sy; i++)
for (j = 0; j < sx; j++)
csel->data[i][j] = sel->data[i][j];
if (sel->name)
csel->name = stringNew(sel->name);
return csel;
}
/*!
* \brief selCreateBrick()
*
* \param[in] h, w height, width
* \param[in] cy, cx origin, relative to UL corner at 0,0
* \param[in] type SEL_HIT, SEL_MISS, or SEL_DONT_CARE
* \return sel, or NULL on error
*
* <pre>
* Notes:
* (1) This is a rectangular sel of all hits, misses or don't cares.
* </pre>
*/
SEL *
selCreateBrick(l_int32 h,
l_int32 w,
l_int32 cy,
l_int32 cx,
l_int32 type)
{
l_int32 i, j;
SEL *sel;
PROCNAME("selCreateBrick");
if (h <= 0 || w <= 0)
return (SEL *)ERROR_PTR("h and w must both be > 0", procName, NULL);
if (type != SEL_HIT && type != SEL_MISS && type != SEL_DONT_CARE)
return (SEL *)ERROR_PTR("invalid sel element type", procName, NULL);
if ((sel = selCreate(h, w, NULL)) == NULL)
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
selSetOrigin(sel, cy, cx);
for (i = 0; i < h; i++)
for (j = 0; j < w; j++)
sel->data[i][j] = type;
return sel;
}
/*!
* \brief selCreateComb()
*
* \param[in] factor1 contiguous space between comb tines
* \param[in] factor2 number of comb tines
* \param[in] direction L_HORIZ, L_VERT
* \return sel, or NULL on error
*
* <pre>
* Notes:
* (1) This generates a comb Sel of hits with the origin as
* near the center as possible.
* (2) In use, this is complemented by a brick sel of size %factor1,
* Both brick and comb sels are made by selectComposableSels().
* </pre>
*/
SEL *
selCreateComb(l_int32 factor1,
l_int32 factor2,
l_int32 direction)
{
l_int32 i, size, z;
SEL *sel;
PROCNAME("selCreateComb");
if (factor1 < 1 || factor2 < 1)
return (SEL *)ERROR_PTR("factors must be >= 1", procName, NULL);
if (direction != L_HORIZ && direction != L_VERT)
return (SEL *)ERROR_PTR("invalid direction", procName, NULL);
size = factor1 * factor2;
if (direction == L_HORIZ) {
sel = selCreate(1, size, NULL);
selSetOrigin(sel, 0, size / 2);
} else {
sel = selCreate(size, 1, NULL);
selSetOrigin(sel, size / 2, 0);
}
/* Lay down the elements of the comb */
for (i = 0; i < factor2; i++) {
z = factor1 / 2 + i * factor1;
/* fprintf(stderr, "i = %d, factor1 = %d, factor2 = %d, z = %d\n",
i, factor1, factor2, z); */
if (direction == L_HORIZ)
selSetElement(sel, 0, z, SEL_HIT);
else
selSetElement(sel, z, 0, SEL_HIT);
}
return sel;
}
/*!
* \brief create2dIntArray()
*
* \param[in] sy rows == height
* \param[in] sx columns == width
* \return doubly indexed array i.e., an array of sy row pointers,
* each of which points to an array of sx ints
*
* <pre>
* Notes:
* (1) The array[sy][sx] is indexed in standard "matrix notation",
* with the row index first.
* </pre>
*/
l_int32 **
create2dIntArray(l_int32 sy,
l_int32 sx)
{
l_int32 i, j, success;
l_int32 **array;
PROCNAME("create2dIntArray");
if ((array = (l_int32 **)LEPT_CALLOC(sy, sizeof(l_int32 *))) == NULL)
return (l_int32 **)ERROR_PTR("ptr array not made", procName, NULL);
success = TRUE;
for (i = 0; i < sy; i++) {
if ((array[i] = (l_int32 *)LEPT_CALLOC(sx, sizeof(l_int32))) == NULL) {
success = FALSE;
break;
}
}
if (success) return array;
/* Cleanup after error */
for (j = 0; j < i; j++)
LEPT_FREE(array[j]);
LEPT_FREE(array);
return (l_int32 **)ERROR_PTR("array not made", procName, NULL);
}
/*------------------------------------------------------------------------*
* Extension of sela *
*------------------------------------------------------------------------*/
/*!
* \brief selaAddSel()
*
* \param[in] sela
* \param[in] sel to be added
* \param[in] selname ignored if already defined in sel;
* req'd in sel when added to a sela
* \param[in] copyflag L_INSERT or L_COPY
* \return 0 if OK; 1 on error
*
* <pre>
* Notes:
* (1) This adds a sel, either inserting or making a copy.
* (2) Because every sel in a sela must have a name, it copies
* the input name if necessary. You can input NULL for
* selname if the sel already has a name.
* </pre>
*/
l_int32
selaAddSel(SELA *sela,
SEL *sel,
const char *selname,
l_int32 copyflag)
{
l_int32 n;
SEL *csel;
PROCNAME("selaAddSel");
if (!sela)
return ERROR_INT("sela not defined", procName, 1);
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
if (!sel->name && !selname)
return ERROR_INT("added sel must have name", procName, 1);
if (copyflag != L_INSERT && copyflag != L_COPY)
return ERROR_INT("invalid copyflag", procName, 1);
if (copyflag == L_COPY) {
if ((csel = selCopy(sel)) == NULL)
return ERROR_INT("csel not made", procName, 1);
} else { /* copyflag == L_INSERT */
csel = sel;
}
if (!csel->name)
csel->name = stringNew(selname);
n = selaGetCount(sela);
if (n >= sela->nalloc)
selaExtendArray(sela);
sela->sel[n] = csel;
sela->n++;
return 0;
}
/*!
* \brief selaExtendArray()
*
* \param[in] sela
* \return 0 if OK; 1 on error
*/
static l_int32
selaExtendArray(SELA *sela)
{
PROCNAME("selaExtendArray");
if (!sela)
return ERROR_INT("sela not defined", procName, 1);
if ((sela->sel = (SEL **)reallocNew((void **)&sela->sel,
sizeof(SEL *) * sela->nalloc,
2 * sizeof(SEL *) * sela->nalloc)) == NULL)
return ERROR_INT("new ptr array not returned", procName, 1);
sela->nalloc = 2 * sela->nalloc;
return 0;
}
/*----------------------------------------------------------------------*
* Accessors *
*----------------------------------------------------------------------*/
/*!
* \brief selaGetCount()
*
* \param[in] sela
* \return count, or 0 on error
*/
l_int32
selaGetCount(SELA *sela)
{
PROCNAME("selaGetCount");
if (!sela)
return ERROR_INT("sela not defined", procName, 0);
return sela->n;
}
/*!
* \brief selaGetSel()
*
* \param[in] sela
* \param[in] i index of sel to be retrieved not copied
* \return sel, or NULL on error
*
* <pre>
* Notes:
* (1) This returns a ptr to the sel, not a copy, so the caller
* must not destroy it!
* </pre>
*/
SEL *
selaGetSel(SELA *sela,
l_int32 i)
{
PROCNAME("selaGetSel");
if (!sela)
return (SEL *)ERROR_PTR("sela not defined", procName, NULL);
if (i < 0 || i >= sela->n)
return (SEL *)ERROR_PTR("invalid index", procName, NULL);
return sela->sel[i];
}
/*!
* \brief selGetName()
*
* \param[in] sel
* \return sel name not copied, or NULL if no name or on error
*/
char *
selGetName(SEL *sel)
{
PROCNAME("selGetName");
if (!sel)
return (char *)ERROR_PTR("sel not defined", procName, NULL);
return sel->name;
}
/*!
* \brief selSetName()
*
* \param[in] sel
* \param[in] name [optional]; can be null
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) Always frees the existing sel name, if defined.
* (2) If name is not defined, just clears any existing sel name.
* </pre>
*/
l_int32
selSetName(SEL *sel,
const char *name)
{
PROCNAME("selSetName");
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
return stringReplace(&sel->name, name);
}
/*!
* \brief selaFindSelByName()
*
* \param[in] sela
* \param[in] name sel name
* \param[out] pindex [optional]
* \param[in] psel [optional] sel (not a copy)
* \return 0 if OK; 1 on error
*/
l_int32
selaFindSelByName(SELA *sela,
const char *name,
l_int32 *pindex,
SEL **psel)
{
l_int32 i, n;
char *sname;
SEL *sel;
PROCNAME("selaFindSelByName");
if (pindex) *pindex = -1;
if (psel) *psel = NULL;
if (!sela)
return ERROR_INT("sela not defined", procName, 1);
n = selaGetCount(sela);
for (i = 0; i < n; i++)
{
if ((sel = selaGetSel(sela, i)) == NULL) {
L_WARNING("missing sel\n", procName);
continue;
}
sname = selGetName(sel);
if (sname && (!strcmp(name, sname))) {
if (pindex)
*pindex = i;
if (psel)
*psel = sel;
return 0;
}
}
return 1;
}
/*!
* \brief selGetElement()
*
* \param[in] sel
* \param[in] row
* \param[in] col
* \param[out] ptype SEL_HIT, SEL_MISS, SEL_DONT_CARE
* \return 0 if OK; 1 on error
*/
l_int32
selGetElement(SEL *sel,
l_int32 row,
l_int32 col,
l_int32 *ptype)
{
PROCNAME("selGetElement");
if (!ptype)
return ERROR_INT("&type not defined", procName, 1);
*ptype = SEL_DONT_CARE;
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
if (row < 0 || row >= sel->sy)
return ERROR_INT("sel row out of bounds", procName, 1);
if (col < 0 || col >= sel->sx)
return ERROR_INT("sel col out of bounds", procName, 1);
*ptype = sel->data[row][col];
return 0;
}
/*!
* \brief selSetElement()
*
* \param[in] sel
* \param[in] row
* \param[in] col
* \param[in] type SEL_HIT, SEL_MISS, SEL_DONT_CARE
* \return 0 if OK; 1 on error
*
* <pre>
* Notes:
* (1) Because we use row and column to index into an array,
* they are always non-negative. The location of the origin
* (and the type of operation) determine the actual
* direction of the rasterop.
* </pre>
*/
l_int32
selSetElement(SEL *sel,
l_int32 row,
l_int32 col,
l_int32 type)
{
PROCNAME("selSetElement");
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
if (type != SEL_HIT && type != SEL_MISS && type != SEL_DONT_CARE)
return ERROR_INT("invalid sel element type", procName, 1);
if (row < 0 || row >= sel->sy)
return ERROR_INT("sel row out of bounds", procName, 1);
if (col < 0 || col >= sel->sx)
return ERROR_INT("sel col out of bounds", procName, 1);
sel->data[row][col] = type;
return 0;
}
/*!
* \brief selGetParameters()
*
* \param[in] sel
* \param[out] psy, psx, pcy, pcx [optional] each can be null
* \return 0 if OK, 1 on error
*/
l_int32
selGetParameters(SEL *sel,
l_int32 *psy,
l_int32 *psx,
l_int32 *pcy,
l_int32 *pcx)
{
PROCNAME("selGetParameters");
if (psy) *psy = 0;
if (psx) *psx = 0;
if (pcy) *pcy = 0;
if (pcx) *pcx = 0;
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
if (psy) *psy = sel->sy;
if (psx) *psx = sel->sx;
if (pcy) *pcy = sel->cy;
if (pcx) *pcx = sel->cx;
return 0;
}
/*!
* \brief selSetOrigin()
*
* \param[in] sel
* \param[in] cy, cx
* \return 0 if OK; 1 on error
*/
l_int32
selSetOrigin(SEL *sel,
l_int32 cy,
l_int32 cx)
{
PROCNAME("selSetOrigin");
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
sel->cy = cy;
sel->cx = cx;
return 0;
}
/*!
* \brief selGetTypeAtOrigin()
*
* \param[in] sel
* \param[out] ptype SEL_HIT, SEL_MISS, SEL_DONT_CARE
* \return 0 if OK; 1 on error or if origin is not found
*/
l_int32
selGetTypeAtOrigin(SEL *sel,
l_int32 *ptype)
{
l_int32 sx, sy, cx, cy, i, j;
PROCNAME("selGetTypeAtOrigin");
if (!ptype)
return ERROR_INT("&type not defined", procName, 1);
*ptype = SEL_DONT_CARE; /* init */
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
selGetParameters(sel, &sy, &sx, &cy, &cx);
for (i = 0; i < sy; i++) {
for (j = 0; j < sx; j++) {
if (i == cy && j == cx) {
selGetElement(sel, i, j, ptype);
return 0;
}
}
}
return ERROR_INT("sel origin not found", procName, 1);
}
/*!
* \brief selaGetBrickName()
*
* \param[in] sela
* \param[in] hsize, vsize of brick sel
* \return sel name new string, or NULL if no name or on error
*/
char *
selaGetBrickName(SELA *sela,
l_int32 hsize,
l_int32 vsize)
{
l_int32 i, nsels, sx, sy;
SEL *sel;
PROCNAME("selaGetBrickName");
if (!sela)
return (char *)ERROR_PTR("sela not defined", procName, NULL);
nsels = selaGetCount(sela);
for (i = 0; i < nsels; i++) {
sel = selaGetSel(sela, i);
selGetParameters(sel, &sy, &sx, NULL, NULL);
if (hsize == sx && vsize == sy)
return stringNew(selGetName(sel));
}
return (char *)ERROR_PTR("sel not found", procName, NULL);
}
/*!
* \brief selaGetCombName()
*
* \param[in] sela
* \param[in] size the product of sizes of the brick and comb parts
* \param[in] direction L_HORIZ, L_VERT
* \return sel name new string, or NULL if name not found or on error
*
* <pre>
* Notes:
* (1) Combs are by definition 1-dimensional, either horiz or vert.
* (2) Use this with comb Sels; e.g., from selaAddDwaCombs().
* </pre>
*/
char *
selaGetCombName(SELA *sela,
l_int32 size,
l_int32 direction)
{
char *selname;
char combname[L_BUF_SIZE];
l_int32 i, nsels, sx, sy, found;
SEL *sel;
PROCNAME("selaGetCombName");
if (!sela)
return (char *)ERROR_PTR("sela not defined", procName, NULL);
if (direction != L_HORIZ && direction != L_VERT)
return (char *)ERROR_PTR("invalid direction", procName, NULL);
/* Derive the comb name we're looking for */
if (direction == L_HORIZ)
snprintf(combname, L_BUF_SIZE, "sel_comb_%dh", size);
else /* direction == L_VERT */
snprintf(combname, L_BUF_SIZE, "sel_comb_%dv", size);
found = FALSE;
nsels = selaGetCount(sela);
for (i = 0; i < nsels; i++) {
sel = selaGetSel(sela, i);
selGetParameters(sel, &sy, &sx, NULL, NULL);
if (sy != 1 && sx != 1) /* 2-D; not a comb */
continue;
selname = selGetName(sel);
if (!strcmp(selname, combname)) {
found = TRUE;
break;
}
}
if (found)
return stringNew(selname);
else
return (char *)ERROR_PTR("sel not found", procName, NULL);
}
/* --------- Function used to generate code in this file ---------- */
#if 0
static void selaComputeCompositeParameters(const char *fileout);
/*!
* \brief selaComputeCompParameters()
*
* \param[in] output filename
* \return void
*
* <pre>
* Notes:
* (1) This static function was used to construct the comp_parameter_map[]
* array at the top of this file. It is static because it does
* not need to be called again. It remains here to show how
* the composite parameter map was computed.
* (2) The output file was pasted directly into comp_parameter_map[].
* The composite parameter map is used to quickly determine
* the linear decomposition parameters and sel names.
* </pre>
*/
static void
selaComputeCompositeParameters(const char *fileout)
{
char *str, *nameh1, *nameh2, *namev1, *namev2;
char buf[L_BUF_SIZE];
l_int32 size, size1, size2, len;
SARRAY *sa;
SELA *selabasic, *selacomb;
selabasic = selaAddBasic(NULL);
selacomb = selaAddDwaCombs(NULL);
sa = sarrayCreate(64);
for (size = 2; size < 64; size++) {
selectComposableSizes(size, &size1, &size2);
nameh1 = selaGetBrickName(selabasic, size1, 1);
namev1 = selaGetBrickName(selabasic, 1, size1);
if (size2 > 1) {
nameh2 = selaGetCombName(selacomb, size1 * size2, L_HORIZ);
namev2 = selaGetCombName(selacomb, size1 * size2, L_VERT);
} else {
nameh2 = stringNew("");
namev2 = stringNew("");
}
snprintf(buf, L_BUF_SIZE,
" { %d, %d, %d, \"%s\", \"%s\", \"%s\", \"%s\" },",
size, size1, size2, nameh1, nameh2, namev1, namev2);
sarrayAddString(sa, buf, L_COPY);
LEPT_FREE(nameh1);
LEPT_FREE(nameh2);
LEPT_FREE(namev1);
LEPT_FREE(namev2);
}
str = sarrayToString(sa, 1);
len = strlen(str);
l_binaryWrite(fileout, "w", str, len + 1);
LEPT_FREE(str);
sarrayDestroy(&sa);
selaDestroy(&selabasic);
selaDestroy(&selacomb);
return;
}
#endif
/* -------------------------------------------------------------------- */
/*!
* \brief getCompositeParameters()
*
* \param[in] size
* \param[out] psize1 [optional] brick factor size
* \param[out] psize2 [optional] comb factor size
* \param[out] pnameh1 [optional] name of horiz brick
* \param[out] pnameh2 [optional] name of horiz comb
* \param[out] pnamev1 [optional] name of vert brick
* \param[out] pnamev2 [optional] name of vert comb
* \return 0 if OK, 1 on error
*
* <pre>
* Notes:
* (1) This uses the big lookup table at the top of this file.
* (2) All returned strings are copies that must be freed.
* </pre>
*/
l_int32
getCompositeParameters(l_int32 size,
l_int32 *psize1,
l_int32 *psize2,
char **pnameh1,
char **pnameh2,
char **pnamev1,
char **pnamev2)
{
l_int32 index;
PROCNAME("selaGetSelnames");
if (psize1) *psize1 = 0;
if (psize2) *psize2 = 0;
if (pnameh1) *pnameh1 = NULL;
if (pnameh2) *pnameh2 = NULL;
if (pnamev1) *pnamev1 = NULL;
if (pnamev2) *pnamev2 = NULL;
if (size < 2 || size > 63)
return ERROR_INT("valid size range is {2 ... 63}", procName, 1);
index = size - 2;
if (psize1)
*psize1 = comp_parameter_map[index].size1;
if (psize2)
*psize2 = comp_parameter_map[index].size2;
if (pnameh1)
*pnameh1 = stringNew(comp_parameter_map[index].selnameh1);
if (pnameh2)
*pnameh2 = stringNew(comp_parameter_map[index].selnameh2);
if (pnamev1)
*pnamev1 = stringNew(comp_parameter_map[index].selnamev1);
if (pnamev2)
*pnamev2 = stringNew(comp_parameter_map[index].selnamev2);
return 0;
}
/*!
* \brief selaGetSelnames()
*
* \param[in] sela
* \return sa of all sel names, or NULL on error
*/
SARRAY *
selaGetSelnames(SELA *sela)
{
char *selname;
l_int32 i, n;
SEL *sel;
SARRAY *sa;
PROCNAME("selaGetSelnames");
if (!sela)
return (SARRAY *)ERROR_PTR("sela not defined", procName, NULL);
if ((n = selaGetCount(sela)) == 0)
return (SARRAY *)ERROR_PTR("no sels in sela", procName, NULL);
if ((sa = sarrayCreate(n)) == NULL)
return (SARRAY *)ERROR_PTR("sa not made", procName, NULL);
for (i = 0; i < n; i++) {
sel = selaGetSel(sela, i);
selname = selGetName(sel);
sarrayAddString(sa, selname, L_COPY);
}
return sa;
}
/*----------------------------------------------------------------------*
* Max translations for erosion and hmt *
*----------------------------------------------------------------------*/
/*!
* \brief selFindMaxTranslations()
*
* \param[in] sel
* \param[out] pxp, pyp, pxn, pyn max shifts
* \return 0 if OK; 1 on error
*
* <pre>
* Notes:
These are the maximum shifts for the erosion operation.
* For example, when j < cx, the shift of the image
* is +x to the cx. This is a positive xp shift.
* </pre>
*/
l_int32
selFindMaxTranslations(SEL *sel,
l_int32 *pxp,
l_int32 *pyp,
l_int32 *pxn,
l_int32 *pyn)
{
l_int32 sx, sy, cx, cy, i, j;
l_int32 maxxp, maxyp, maxxn, maxyn;
PROCNAME("selaFindMaxTranslations");
if (!pxp || !pyp || !pxn || !pyn)
return ERROR_INT("&xp (etc) defined", procName, 1);
*pxp = *pyp = *pxn = *pyn = 0;
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
selGetParameters(sel, &sy, &sx, &cy, &cx);
maxxp = maxyp = maxxn = maxyn = 0;
for (i = 0; i < sy; i++) {
for (j = 0; j < sx; j++) {
if (sel->data[i][j] == 1) {
maxxp = L_MAX(maxxp, cx - j);
maxyp = L_MAX(maxyp, cy - i);
maxxn = L_MAX(maxxn, j - cx);
maxyn = L_MAX(maxyn, i - cy);
}
}
}
*pxp = maxxp;
*pyp = maxyp;
*pxn = maxxn;
*pyn = maxyn;
return 0;
}
/*----------------------------------------------------------------------*
* Rotation by multiples of 90 degrees *
*----------------------------------------------------------------------*/
/*!
* \brief selRotateOrth()
*
* \param[in] sel
* \param[in] quads 0 - 4; number of 90 degree cw rotations
* \return seld, or NULL on error
*/
SEL *
selRotateOrth(SEL *sel,
l_int32 quads)
{
l_int32 i, j, ni, nj, sx, sy, cx, cy, nsx, nsy, ncx, ncy, type;
SEL *seld;
PROCNAME("selRotateOrth");
if (!sel)
return (SEL *)ERROR_PTR("sel not defined", procName, NULL);
if (quads < 0 || quads > 4)
return (SEL *)ERROR_PTR("quads not in {0,1,2,3,4}", procName, NULL);
if (quads == 0 || quads == 4)
return selCopy(sel);
selGetParameters(sel, &sy, &sx, &cy, &cx);
if (quads == 1) { /* 90 degrees cw */
nsx = sy;
nsy = sx;
ncx = sy - cy - 1;
ncy = cx;
} else if (quads == 2) { /* 180 degrees cw */
nsx = sx;
nsy = sy;
ncx = sx - cx - 1;
ncy = sy - cy - 1;
} else { /* 270 degrees cw */
nsx = sy;
nsy = sx;
ncx = cy;
ncy = sx - cx - 1;
}
seld = selCreateBrick(nsy, nsx, ncy, ncx, SEL_DONT_CARE);
if (sel->name)
seld->name = stringNew(sel->name);
for (i = 0; i < sy; i++) {
for (j = 0; j < sx; j++) {
selGetElement(sel, i, j, &type);
if (quads == 1) {
ni = j;
nj = sy - i - 1;
} else if (quads == 2) {
ni = sy - i - 1;
nj = sx - j - 1;
} else { /* quads == 3 */
ni = sx - j - 1;
nj = i;
}
selSetElement(seld, ni, nj, type);
}
}
return seld;
}
/*----------------------------------------------------------------------*
* Sela and Sel serialized I/O *
*----------------------------------------------------------------------*/
/*!
* \brief selaRead()
*
* \param[in] fname filename
* \return sela, or NULL on error
*/
SELA *
selaRead(const char *fname)
{
FILE *fp;
SELA *sela;
PROCNAME("selaRead");
if (!fname)
return (SELA *)ERROR_PTR("fname not defined", procName, NULL);
if ((fp = fopenReadStream(fname)) == NULL)
return (SELA *)ERROR_PTR("stream not opened", procName, NULL);
if ((sela = selaReadStream(fp)) == NULL) {
fclose(fp);
return (SELA *)ERROR_PTR("sela not returned", procName, NULL);
}
fclose(fp);
return sela;
}
/*!
* \brief selaReadStream()
*
* \param[in] fp file stream
* \return sela, or NULL on error
*/
SELA *
selaReadStream(FILE *fp)
{
l_int32 i, n, version;
SEL *sel;
SELA *sela;
PROCNAME("selaReadStream");
if (!fp)
return (SELA *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, "\nSela Version %d\n", &version) != 1)
return (SELA *)ERROR_PTR("not a sela file", procName, NULL);
if (version != SEL_VERSION_NUMBER)
return (SELA *)ERROR_PTR("invalid sel version", procName, NULL);
if (fscanf(fp, "Number of Sels = %d\n\n", &n) != 1)
return (SELA *)ERROR_PTR("not a sela file", procName, NULL);
if ((sela = selaCreate(n)) == NULL)
return (SELA *)ERROR_PTR("sela not made", procName, NULL);
sela->nalloc = n;
for (i = 0; i < n; i++) {
if ((sel = selReadStream(fp)) == NULL) {
selaDestroy(&sela);
return (SELA *)ERROR_PTR("sel not read", procName, NULL);
}
selaAddSel(sela, sel, NULL, 0);
}
return sela;
}
/*!
* \brief selRead()
*
* \param[in] fname filename
* \return sel, or NULL on error
*/
SEL *
selRead(const char *fname)
{
FILE *fp;
SEL *sel;
PROCNAME("selRead");
if (!fname)
return (SEL *)ERROR_PTR("fname not defined", procName, NULL);
if ((fp = fopenReadStream(fname)) == NULL)
return (SEL *)ERROR_PTR("stream not opened", procName, NULL);
if ((sel = selReadStream(fp)) == NULL) {
fclose(fp);
return (SEL *)ERROR_PTR("sela not returned", procName, NULL);
}
fclose(fp);
return sel;
}
/*!
* \brief selReadStream()
*
* \param[in] fp file stream
* \return sel, or NULL on error
*/
SEL *
selReadStream(FILE *fp)
{
char *selname;
char linebuf[L_BUF_SIZE];
l_int32 sy, sx, cy, cx, i, j, version, ignore;
SEL *sel;
PROCNAME("selReadStream");
if (!fp)
return (SEL *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, " Sel Version %d\n", &version) != 1)
return (SEL *)ERROR_PTR("not a sel file", procName, NULL);
if (version != SEL_VERSION_NUMBER)
return (SEL *)ERROR_PTR("invalid sel version", procName, NULL);
if (fgets(linebuf, L_BUF_SIZE, fp) == NULL)
return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL);
selname = stringNew(linebuf);
sscanf(linebuf, " ------ %s ------", selname);
if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n",
&sy, &sx, &cy, &cx) != 4) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("dimensions not read", procName, NULL);
}
if ((sel = selCreate(sy, sx, selname)) == NULL) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
}
selSetOrigin(sel, cy, cx);
for (i = 0; i < sy; i++) {
ignore = fscanf(fp, " ");
for (j = 0; j < sx; j++)
ignore = fscanf(fp, "%1d", &sel->data[i][j]);
ignore = fscanf(fp, "\n");
}
ignore = fscanf(fp, "\n");
LEPT_FREE(selname);
return sel;
}
/*!
* \brief selaWrite()
*
* \param[in] fname filename
* \param[in] sela
* \return 0 if OK, 1 on error
*/
l_int32
selaWrite(const char *fname,
SELA *sela)
{
FILE *fp;
PROCNAME("selaWrite");
if (!fname)
return ERROR_INT("fname not defined", procName, 1);
if (!sela)
return ERROR_INT("sela not defined", procName, 1);
if ((fp = fopenWriteStream(fname, "wb")) == NULL)
return ERROR_INT("stream not opened", procName, 1);
selaWriteStream(fp, sela);
fclose(fp);
return 0;
}
/*!
* \brief selaWriteStream()
*
* \param[in] fp file stream
* \param[in] sela
* \return 0 if OK, 1 on error
*/
l_int32
selaWriteStream(FILE *fp,
SELA *sela)
{
l_int32 i, n;
SEL *sel;
PROCNAME("selaWriteStream");
if (!fp)
return ERROR_INT("stream not defined", procName, 1);
if (!sela)
return ERROR_INT("sela not defined", procName, 1);
n = selaGetCount(sela);
fprintf(fp, "\nSela Version %d\n", SEL_VERSION_NUMBER);
fprintf(fp, "Number of Sels = %d\n\n", n);
for (i = 0; i < n; i++) {
if ((sel = selaGetSel(sela, i)) == NULL)
continue;
selWriteStream(fp, sel);
}
return 0;
}
/*!
* \brief selWrite()
*
* \param[in] fname filename
* \param[in] sel
* \return 0 if OK, 1 on error
*/
l_int32
selWrite(const char *fname,
SEL *sel)
{
FILE *fp;
PROCNAME("selWrite");
if (!fname)
return ERROR_INT("fname not defined", procName, 1);
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
if ((fp = fopenWriteStream(fname, "wb")) == NULL)
return ERROR_INT("stream not opened", procName, 1);
selWriteStream(fp, sel);
fclose(fp);
return 0;
}
/*!
* \brief selWriteStream()
*
* \param[in] fp file stream
* \param[in] sel
* \return 0 if OK, 1 on error
*/
l_int32
selWriteStream(FILE *fp,
SEL *sel)
{
l_int32 sx, sy, cx, cy, i, j;
PROCNAME("selWriteStream");
if (!fp)
return ERROR_INT("stream not defined", procName, 1);
if (!sel)
return ERROR_INT("sel not defined", procName, 1);
selGetParameters(sel, &sy, &sx, &cy, &cx);
fprintf(fp, " Sel Version %d\n", SEL_VERSION_NUMBER);
fprintf(fp, " ------ %s ------\n", selGetName(sel));
fprintf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n", sy, sx, cy, cx);
for (i = 0; i < sy; i++) {
fprintf(fp, " ");
for (j = 0; j < sx; j++)
fprintf(fp, "%d", sel->data[i][j]);
fprintf(fp, "\n");
}
fprintf(fp, "\n");
return 0;
}
/*----------------------------------------------------------------------*
* Building custom hit-miss sels from compiled strings *
*----------------------------------------------------------------------*/
/*!
* \brief selCreateFromString()
*
* \param[in] text
* \param[in] h, w height, width
* \param[in] name [optional] sel name; can be null
* \return sel of the given size, or NULL on error
*
* <pre>
* Notes:
* (1) The text is an array of chars (in row-major order) where
* each char can be one of the following:
* 'x': hit
* 'o': miss
* ' ': don't-care
* (2) When the origin falls on a hit or miss, use an upper case
* char (e.g., 'X' or 'O') to indicate it. When the origin
* falls on a don't-care, indicate this with a 'C'.
* The string must have exactly one origin specified.
* (3) The advantage of this method is that the text can be input
* in a format that shows the 2D layout of the Sel; e.g.,
* \code
* static const char *seltext = "x "
* "x Oo "
* "x "
* "xxxxx";
* \endcode
* </pre>
*/
SEL *
selCreateFromString(const char *text,
l_int32 h,
l_int32 w,
const char *name)
{
SEL *sel;
l_int32 y, x, norig;
char ch;
PROCNAME("selCreateFromString");
if (h < 1)
return (SEL *)ERROR_PTR("height must be > 0", procName, NULL);
if (w < 1)
return (SEL *)ERROR_PTR("width must be > 0", procName, NULL);
sel = selCreate(h, w, name);
norig = 0;
for (y = 0; y < h; ++y) {
for (x = 0; x < w; ++x) {
ch = *(text++);
switch (ch)
{
case 'X':
norig++;
selSetOrigin(sel, y, x);
case 'x':
selSetElement(sel, y, x, SEL_HIT);
break;
case 'O':
norig++;
selSetOrigin(sel, y, x);
case 'o':
selSetElement(sel, y, x, SEL_MISS);
break;
case 'C':
norig++;
selSetOrigin(sel, y, x);
case ' ':
selSetElement(sel, y, x, SEL_DONT_CARE);
break;
case '\n':
/* ignored */
continue;
default:
selDestroy(&sel);
return (SEL *)ERROR_PTR("unknown char", procName, NULL);
}
}
}
if (norig != 1) {
L_ERROR("Exactly one origin must be specified; this string has %d\n",
procName, norig);
selDestroy(&sel);
}
return sel;
}
/*!
* \brief selPrintToString()
*
* \param[in] sel
* \return str string; caller must free
*
* <pre>
* Notes:
* (1) This is an inverse function of selCreateFromString.
* It prints a textual representation of the SEL to a malloc'd
* string. The format is the same as selCreateFromString
* except that newlines are inserted into the output
* between rows.
* (2) This is useful for debugging. However, if you want to
* save some Sels in a file, put them in a Sela and write
* them out with selaWrite(). They can then be read in
* with selaRead().
* </pre>
*/
char *
selPrintToString(SEL *sel)
{
char is_center;
char *str, *strptr;
l_int32 type;
l_int32 sx, sy, cx, cy, x, y;
PROCNAME("selPrintToString");
if (!sel)
return (char *)ERROR_PTR("sel not defined", procName, NULL);
selGetParameters(sel, &sy, &sx, &cy, &cx);
if ((str = (char *)LEPT_CALLOC(1, sy * (sx + 1) + 1)) == NULL)
return (char *)ERROR_PTR("calloc fail for str", procName, NULL);
strptr = str;
for (y = 0; y < sy; ++y) {
for (x = 0; x < sx; ++x) {
selGetElement(sel, y, x, &type);
is_center = (x == cx && y == cy);
switch (type) {
case SEL_HIT:
*(strptr++) = is_center ? 'X' : 'x';
break;
case SEL_MISS:
*(strptr++) = is_center ? 'O' : 'o';
break;
case SEL_DONT_CARE:
*(strptr++) = is_center ? 'C' : ' ';
break;
}
}
*(strptr++) = '\n';
}
return str;
}
/*----------------------------------------------------------------------*
* Building custom hit-miss sels from a simple file format *
*----------------------------------------------------------------------*/
/*!
* \brief selaCreateFromFile()
*
* \param[in] filename
* \return sela, or NULL on error
*
* <pre>
* Notes:
* (1) The file contains a sequence of Sel descriptions.
* (2) Each Sel is formatted as follows:
* ~ Any number of comment lines starting with '#' are ignored
* ~ The next line contains the selname
* ~ The next lines contain the Sel data. They must be
* formatted similarly to the string format in
* selCreateFromString(), with each line beginning and
* ending with a double-quote, and showing the 2D layout.
* ~ Each Sel ends when a blank line, a comment line, or
* the end of file is reached.
* (3) See selCreateFromString() for a description of the string
* format for the Sel data. As an example, here are the lines
* of is a valid file for a single Sel. In the file, all lines
* are left-justified:
* # diagonal sel
* sel_5diag
* "x "
* " x "
* " X "
* " x "
* " x"
* </pre>
*/
SELA *
selaCreateFromFile(const char *filename)
{
char *filestr, *line;
l_int32 i, n, first, last, nsel, insel;
size_t nbytes;
NUMA *nafirst, *nalast;
SARRAY *sa;
SEL *sel;
SELA *sela;
PROCNAME("selaCreateFromFile");
if (!filename)
return (SELA *)ERROR_PTR("filename not defined", procName, NULL);
filestr = (char *)l_binaryRead(filename, &nbytes);
sa = sarrayCreateLinesFromString(filestr, 1);
LEPT_FREE(filestr);
n = sarrayGetCount(sa);
sela = selaCreate(0);
/* Find the start and end lines for each Sel.
* We allow the "blank" lines to be null strings or
* to have standard whitespace (' ','\t',\'n') or be '#'. */
nafirst = numaCreate(0);
nalast = numaCreate(0);
insel = FALSE;
for (i = 0; i < n; i++) {
line = sarrayGetString(sa, i, L_NOCOPY);
if (!insel &&
(line[0] != '\0' && line[0] != ' ' &&
line[0] != '\t' && line[0] != '\n' && line[0] != '#')) {
numaAddNumber(nafirst, i);
insel = TRUE;
continue;
}
if (insel &&
(line[0] == '\0' || line[0] == ' ' ||
line[0] == '\t' || line[0] == '\n' || line[0] == '#')) {
numaAddNumber(nalast, i - 1);
insel = FALSE;
continue;
}
}
if (insel) /* fell off the end of the file */
numaAddNumber(nalast, n - 1);
/* Extract sels */
nsel = numaGetCount(nafirst);
for (i = 0; i < nsel; i++) {
numaGetIValue(nafirst, i, &first);
numaGetIValue(nalast, i, &last);
if ((sel = selCreateFromSArray(sa, first, last)) == NULL) {
fprintf(stderr, "Error reading sel from %d to %d\n", first, last);
selaDestroy(&sela);
sarrayDestroy(&sa);
numaDestroy(&nafirst);
numaDestroy(&nalast);
return (SELA *)ERROR_PTR("bad sela file", procName, NULL);
}
selaAddSel(sela, sel, NULL, 0);
}
numaDestroy(&nafirst);
numaDestroy(&nalast);
sarrayDestroy(&sa);
return sela;
}
/*!
* \brief selCreateFromSArray()
*
* \param[in] sa
* \param[in] first line of sarray where Sel begins
* \param[in] last line of sarray where Sel ends
* \return sela, or NULL on error
*
* <pre>
* Notes:
* (1) The Sel contains the following lines:
* ~ The first line is the selname
* ~ The remaining lines contain the Sel data. They must
* be formatted similarly to the string format in
* selCreateFromString(), with each line beginning and
* ending with a double-quote, and showing the 2D layout.
* ~ 'last' gives the last line in the Sel data.
* (2) See selCreateFromString() for a description of the string
* format for the Sel data. As an example, here are the lines
* of is a valid file for a single Sel. In the file, all lines
* are left-justified:
* # diagonal sel
* sel_5diag
* "x "
* " x "
* " X "
* " x "
* " x"
* </pre>
*/
static SEL *
selCreateFromSArray(SARRAY *sa,
l_int32 first,
l_int32 last)
{
char ch;
char *name, *line;
l_int32 n, len, i, w, h, y, x;
SEL *sel;
PROCNAME("selCreateFromSArray");
if (!sa)
return (SEL *)ERROR_PTR("sa not defined", procName, NULL);
n = sarrayGetCount(sa);
if (first < 0 || first >= n || last <= first || last >= n)
return (SEL *)ERROR_PTR("invalid range", procName, NULL);
name = sarrayGetString(sa, first, L_NOCOPY);
h = last - first;
line = sarrayGetString(sa, first + 1, L_NOCOPY);
len = strlen(line);
if (line[0] != '"' || line[len - 1] != '"')
return (SEL *)ERROR_PTR("invalid format", procName, NULL);
w = len - 2;
if ((sel = selCreate(h, w, name)) == NULL)
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
for (i = first + 1; i <= last; i++) {
line = sarrayGetString(sa, i, L_NOCOPY);
y = i - first - 1;
for (x = 0; x < w; ++x) {
ch = line[x + 1]; /* skip the leading double-quote */
switch (ch)
{
case 'X':
selSetOrigin(sel, y, x); /* set origin and hit */
case 'x':
selSetElement(sel, y, x, SEL_HIT);
break;
case 'O':
selSetOrigin(sel, y, x); /* set origin and miss */
case 'o':
selSetElement(sel, y, x, SEL_MISS);
break;
case 'C':
selSetOrigin(sel, y, x); /* set origin and don't-care */
case ' ':
selSetElement(sel, y, x, SEL_DONT_CARE);
break;
default:
selDestroy(&sel);
return (SEL *)ERROR_PTR("unknown char", procName, NULL);
}
}
}
return sel;
}
/*----------------------------------------------------------------------*
* Making hit-only SELs from Pta and Pix *
*----------------------------------------------------------------------*/
/*!
* \brief selCreateFromPta()
*
* \param[in] pta
* \param[in] cy, cx origin of sel
* \param[in] name [optional] sel name; can be null
* \return sel of minimum required size, or NULL on error
*
* <pre>
* Notes:
* (1) The origin and all points in the pta must be positive.
* </pre>
*/
SEL *
selCreateFromPta(PTA *pta,
l_int32 cy,
l_int32 cx,
const char *name)
{
l_int32 i, n, x, y, w, h;
BOX *box;
SEL *sel;
PROCNAME("selCreateFromPta");
if (!pta)
return (SEL *)ERROR_PTR("pta not defined", procName, NULL);
if (cy < 0 || cx < 0)
return (SEL *)ERROR_PTR("(cy, cx) not both >= 0", procName, NULL);
n = ptaGetCount(pta);
if (n == 0)
return (SEL *)ERROR_PTR("no pts in pta", procName, NULL);
box = ptaGetBoundingRegion(pta);
boxGetGeometry(box, &x, &y, &w, &h);
boxDestroy(&box);
if (x < 0 || y < 0)
return (SEL *)ERROR_PTR("not all x and y >= 0", procName, NULL);
sel = selCreate(y + h, x + w, name);
selSetOrigin(sel, cy, cx);
for (i = 0; i < n; i++) {
ptaGetIPt(pta, i, &x, &y);
selSetElement(sel, y, x, SEL_HIT);
}
return sel;
}
/*!
* \brief selCreateFromPix()
*
* \param[in] pix
* \param[in] cy, cx origin of sel
* \param[in] name [optional] sel name; can be null
* \return sel, or NULL on error
*
* <pre>
* Notes:
* (1) The origin must be positive.
* </pre>
*/
SEL *
selCreateFromPix(PIX *pix,
l_int32 cy,
l_int32 cx,
const char *name)
{
SEL *sel;
l_int32 i, j, w, h, d;
l_uint32 val;
PROCNAME("selCreateFromPix");
if (!pix)
return (SEL *)ERROR_PTR("pix not defined", procName, NULL);
if (cy < 0 || cx < 0)
return (SEL *)ERROR_PTR("(cy, cx) not both >= 0", procName, NULL);
pixGetDimensions(pix, &w, &h, &d);
if (d != 1)
return (SEL *)ERROR_PTR("pix not 1 bpp", procName, NULL);
sel = selCreate(h, w, name);
selSetOrigin(sel, cy, cx);
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
pixGetPixel(pix, j, i, &val);
if (val)
selSetElement(sel, i, j, SEL_HIT);
}
}
return sel;
}
/*----------------------------------------------------------------------*
* Making hit-miss sels from color Pix and image files *
*----------------------------------------------------------------------*/
/*!
*
* selReadFromColorImage()
*
* \param[in] pathname
* \return sel if OK; NULL on error
*
* <pre>
* Notes:
* (1) Loads an image from a file and creates a (hit-miss) sel.
* (2) The sel name is taken from the pathname without the directory
* and extension.
* </pre>
*/
SEL *
selReadFromColorImage(const char *pathname)
{
PIX *pix;
SEL *sel;
char *basename, *selname;
PROCNAME("selReadFromColorImage");
splitPathAtExtension (pathname, &basename, NULL);
splitPathAtDirectory (basename, NULL, &selname);
LEPT_FREE(basename);
if ((pix = pixRead(pathname)) == NULL) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("pix not returned", procName, NULL);
}
if ((sel = selCreateFromColorPix(pix, selname)) == NULL)
L_ERROR("sel not made\n", procName);
LEPT_FREE(selname);
pixDestroy(&pix);
return sel;
}
/*!
*
* selCreateFromColorPix()
*
* \param[in] pixs cmapped or rgb
* \param[in] selname [optional] sel name; can be null
* \return sel if OK, NULL on error
*
* <pre>
* Notes:
* (1) The sel size is given by the size of pixs.
* (2) In pixs, hits are represented by green pixels, misses by red
* pixels, and don't-cares by white pixels.
* (3) In pixs, there may be no misses, but there must be at least 1 hit.
* (4) At most there can be only one origin pixel, which is optionally
* specified by using a lower-intensity pixel:
* if a hit: dark green
* if a miss: dark red
* if a don't care: gray
* If there is no such pixel, the origin defaults to the approximate
* center of the sel.
* </pre>
*/
SEL *
selCreateFromColorPix(PIX *pixs,
char *selname)
{
PIXCMAP *cmap;
SEL *sel;
l_int32 hascolor, hasorigin, nohits;
l_int32 w, h, d, i, j, red, green, blue;
l_uint32 pixval;
PROCNAME("selCreateFromColorPix");
if (!pixs)
return (SEL *)ERROR_PTR("pixs not defined", procName, NULL);
hascolor = FALSE;
cmap = pixGetColormap(pixs);
if (cmap)
pixcmapHasColor(cmap, &hascolor);
pixGetDimensions(pixs, &w, &h, &d);
if (hascolor == FALSE && d != 32)
return (SEL *)ERROR_PTR("pixs has no color", procName, NULL);
if ((sel = selCreate (h, w, NULL)) == NULL)
return (SEL *)ERROR_PTR ("sel not made", procName, NULL);
selSetOrigin (sel, h / 2, w / 2);
selSetName(sel, selname);
hasorigin = FALSE;
nohits = TRUE;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
pixGetPixel (pixs, j, i, &pixval);
if (cmap) {
pixcmapGetColor (cmap, pixval, &red, &green, &blue);
} else {
red = GET_DATA_BYTE (&pixval, COLOR_RED);
green = GET_DATA_BYTE (&pixval, COLOR_GREEN);
blue = GET_DATA_BYTE (&pixval, COLOR_BLUE);
}
if (red < 255 && green < 255 && blue < 255) {
if (hasorigin)
L_WARNING("multiple origins in sel image\n", procName);
selSetOrigin (sel, i, j);
hasorigin = TRUE;
}
if (!red && green && !blue) {
nohits = FALSE;
selSetElement (sel, i, j, SEL_HIT);
} else if (red && !green && !blue) {
selSetElement (sel, i, j, SEL_MISS);
} else if (red && green && blue) {
selSetElement (sel, i, j, SEL_DONT_CARE);
} else {
selDestroy(&sel);
return (SEL *)ERROR_PTR("invalid color", procName, NULL);
}
}
}
if (nohits) {
selDestroy(&sel);
return (SEL *)ERROR_PTR("no hits in sel", procName, NULL);
}
return sel;
}
/*----------------------------------------------------------------------*
* Printable display of sel *
*----------------------------------------------------------------------*/
/*!
* \brief selDisplayInPix()
*
* \param[in] sel
* \param[in] size of grid interiors; odd; minimum size of 13 is enforced
* \param[in] gthick grid thickness; minimum size of 2 is enforced
* \return pix display of sel, or NULL on error
*
* <pre>
* Notes:
* (1) This gives a visual representation of a general (hit-miss) sel.
* (2) The empty sel is represented by a grid of intersecting lines.
* (3) Three different patterns are generated for the sel elements:
* ~ hit (solid black circle)
* ~ miss (black ring; inner radius is radius2)
* ~ origin (cross, XORed with whatever is there)
* </pre>
*/
PIX *
selDisplayInPix(SEL *sel,
l_int32 size,
l_int32 gthick)
{
l_int32 i, j, w, h, sx, sy, cx, cy, type, width;
l_int32 radius1, radius2, shift1, shift2, x0, y0;
PIX *pixd, *pix2, *pixh, *pixm, *pixorig;
PTA *pta1, *pta2, *pta1t, *pta2t;
PROCNAME("selDisplayInPix");
if (!sel)
return (PIX *)ERROR_PTR("sel not defined", procName, NULL);
if (size < 13) {
L_WARNING("size < 13; setting to 13\n", procName);
size = 13;
}
if (size % 2 == 0)
size++;
if (gthick < 2) {
L_WARNING("grid thickness < 2; setting to 2\n", procName);
gthick = 2;
}
selGetParameters(sel, &sy, &sx, &cy, &cx);
w = size * sx + gthick * (sx + 1);
h = size * sy + gthick * (sy + 1);
pixd = pixCreate(w, h, 1);
/* Generate grid lines */
for (i = 0; i <= sy; i++)
pixRenderLine(pixd, 0, gthick / 2 + i * (size + gthick),
w - 1, gthick / 2 + i * (size + gthick),
gthick, L_SET_PIXELS);
for (j = 0; j <= sx; j++)
pixRenderLine(pixd, gthick / 2 + j * (size + gthick), 0,
gthick / 2 + j * (size + gthick), h - 1,
gthick, L_SET_PIXELS);
/* Generate hit and miss patterns */
radius1 = (l_int32)(0.85 * ((size - 1) / 2.0) + 0.5); /* of hit */
radius2 = (l_int32)(0.65 * ((size - 1) / 2.0) + 0.5); /* of inner miss */
pta1 = generatePtaFilledCircle(radius1);
pta2 = generatePtaFilledCircle(radius2);
shift1 = (size - 1) / 2 - radius1; /* center circle in square */
shift2 = (size - 1) / 2 - radius2;
pta1t = ptaTransform(pta1, shift1, shift1, 1.0, 1.0);
pta2t = ptaTransform(pta2, shift2, shift2, 1.0, 1.0);
pixh = pixGenerateFromPta(pta1t, size, size); /* hits */
pix2 = pixGenerateFromPta(pta2t, size, size);
pixm = pixSubtract(NULL, pixh, pix2);
/* Generate crossed lines for origin pattern */
pixorig = pixCreate(size, size, 1);
width = size / 8;
pixRenderLine(pixorig, size / 2, (l_int32)(0.12 * size),
size / 2, (l_int32)(0.88 * size),
width, L_SET_PIXELS);
pixRenderLine(pixorig, (l_int32)(0.15 * size), size / 2,
(l_int32)(0.85 * size), size / 2,
width, L_FLIP_PIXELS);
pixRasterop(pixorig, size / 2 - width, size / 2 - width,
2 * width, 2 * width, PIX_NOT(PIX_DST), NULL, 0, 0);
/* Specialize origin pattern for this sel */
selGetTypeAtOrigin(sel, &type);
if (type == SEL_HIT)
pixXor(pixorig, pixorig, pixh);
else if (type == SEL_MISS)
pixXor(pixorig, pixorig, pixm);
/* Paste the patterns in */
y0 = gthick;
for (i = 0; i < sy; i++) {
x0 = gthick;
for (j = 0; j < sx; j++) {
selGetElement(sel, i, j, &type);
if (i == cy && j == cx) /* origin */
pixRasterop(pixd, x0, y0, size, size, PIX_SRC, pixorig, 0, 0);
else if (type == SEL_HIT)
pixRasterop(pixd, x0, y0, size, size, PIX_SRC, pixh, 0, 0);
else if (type == SEL_MISS)
pixRasterop(pixd, x0, y0, size, size, PIX_SRC, pixm, 0, 0);
x0 += size + gthick;
}
y0 += size + gthick;
}
pixDestroy(&pix2);
pixDestroy(&pixh);
pixDestroy(&pixm);
pixDestroy(&pixorig);
ptaDestroy(&pta1);
ptaDestroy(&pta1t);
ptaDestroy(&pta2);
ptaDestroy(&pta2t);
return pixd;
}
/*!
* \brief selaDisplayInPix()
*
* \param[in] sela
* \param[in] size of grid interiors; odd; minimum size of 13 is enforced
* \param[in] gthick grid thickness; minimum size of 2 is enforced
* \param[in] spacing between sels, both horizontally and vertically
* \param[in] ncols number of sels per "line"
* \return pix display of all sels in sela, or NULL on error
*
* <pre>
* Notes:
* (1) This gives a visual representation of all the sels in a sela.
* (2) See notes in selDisplayInPix() for display params of each sel.
* (3) This gives the nicest results when all sels in the sela
* are the same size.
* </pre>
*/
PIX *
selaDisplayInPix(SELA *sela,
l_int32 size,
l_int32 gthick,
l_int32 spacing,
l_int32 ncols)
{
l_int32 nsels, i, w, width;
PIX *pixt, *pixd;
PIXA *pixa;
SEL *sel;
PROCNAME("selaDisplayInPix");
if (!sela)
return (PIX *)ERROR_PTR("sela not defined", procName, NULL);
if (size < 13) {
L_WARNING("size < 13; setting to 13\n", procName);
size = 13;
}
if (size % 2 == 0)
size++;
if (gthick < 2) {
L_WARNING("grid thickness < 2; setting to 2\n", procName);
gthick = 2;
}
if (spacing < 5) {
L_WARNING("spacing < 5; setting to 5\n", procName);
spacing = 5;
}
/* Accumulate the pix of each sel */
nsels = selaGetCount(sela);
pixa = pixaCreate(nsels);
for (i = 0; i < nsels; i++) {
sel = selaGetSel(sela, i);
pixt = selDisplayInPix(sel, size, gthick);
pixaAddPix(pixa, pixt, L_INSERT);
}
/* Find the tiled output width, using just the first
* ncols pix in the pixa. If all pix have the same width,
* they will align properly in columns. */
width = 0;
ncols = L_MIN(nsels, ncols);
for (i = 0; i < ncols; i++) {
pixt = pixaGetPix(pixa, i, L_CLONE);
pixGetDimensions(pixt, &w, NULL, NULL);
width += w;
pixDestroy(&pixt);
}
width += (ncols + 1) * spacing; /* add spacing all around as well */
pixd = pixaDisplayTiledInRows(pixa, 1, width, 1.0, 0, spacing, 0);
pixaDestroy(&pixa);
return pixd;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_622_4 |
crossvul-cpp_data_good_2019_1 | /* src/interfaces/ecpg/pgtypeslib/datetime.c */
#include "postgres_fe.h"
#include <time.h>
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include "extern.h"
#include "dt.h"
#include "pgtypes_error.h"
#include "pgtypes_date.h"
date *
PGTYPESdate_new(void)
{
date *result;
result = (date *) pgtypes_alloc(sizeof(date));
/* result can be NULL if we run out of memory */
return result;
}
void
PGTYPESdate_free(date * d)
{
free(d);
}
date
PGTYPESdate_from_timestamp(timestamp dt)
{
date dDate;
dDate = 0; /* suppress compiler warning */
if (!TIMESTAMP_NOT_FINITE(dt))
{
#ifdef HAVE_INT64_TIMESTAMP
/* Microseconds to days */
dDate = (dt / USECS_PER_DAY);
#else
/* Seconds to days */
dDate = (dt / (double) SECS_PER_DAY);
#endif
}
return dDate;
}
date
PGTYPESdate_from_asc(char *str, char **endptr)
{
date dDate;
fsec_t fsec;
struct tm tt,
*tm = &tt;
int dtype;
int nf;
char *field[MAXDATEFIELDS];
int ftype[MAXDATEFIELDS];
char lowstr[MAXDATELEN + MAXDATEFIELDS];
char *realptr;
char **ptr = (endptr != NULL) ? endptr : &realptr;
bool EuroDates = FALSE;
errno = 0;
if (strlen(str) > MAXDATELEN)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
if (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 ||
DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, EuroDates) != 0)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
switch (dtype)
{
case DTK_DATE:
break;
case DTK_EPOCH:
if (GetEpochTime(tm) < 0)
{
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
break;
default:
errno = PGTYPES_DATE_BAD_DATE;
return INT_MIN;
}
dDate = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1));
return dDate;
}
char *
PGTYPESdate_to_asc(date dDate)
{
struct tm tt,
*tm = &tt;
char buf[MAXDATELEN + 1];
int DateStyle = 1;
bool EuroDates = FALSE;
j2date(dDate + date2j(2000, 1, 1), &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
EncodeDateOnly(tm, DateStyle, buf, EuroDates);
return pgtypes_strdup(buf);
}
void
PGTYPESdate_julmdy(date jd, int *mdy)
{
int y,
m,
d;
j2date((int) (jd + date2j(2000, 1, 1)), &y, &m, &d);
mdy[0] = m;
mdy[1] = d;
mdy[2] = y;
}
void
PGTYPESdate_mdyjul(int *mdy, date * jdate)
{
/* month is mdy[0] */
/* day is mdy[1] */
/* year is mdy[2] */
*jdate = (date) (date2j(mdy[2], mdy[0], mdy[1]) - date2j(2000, 1, 1));
}
int
PGTYPESdate_dayofweek(date dDate)
{
/*
* Sunday: 0 Monday: 1 Tuesday: 2 Wednesday: 3 Thursday: 4
* Friday: 5 Saturday: 6
*/
return (int) (dDate + date2j(2000, 1, 1) + 1) % 7;
}
void
PGTYPESdate_today(date * d)
{
struct tm ts;
GetCurrentDateTime(&ts);
if (errno == 0)
*d = date2j(ts.tm_year, ts.tm_mon, ts.tm_mday) - date2j(2000, 1, 1);
return;
}
#define PGTYPES_DATE_NUM_MAX_DIGITS 20 /* should suffice for most
* years... */
#define PGTYPES_FMTDATE_DAY_DIGITS_LZ 1 /* LZ means "leading zeroes" */
#define PGTYPES_FMTDATE_DOW_LITERAL_SHORT 2
#define PGTYPES_FMTDATE_MONTH_DIGITS_LZ 3
#define PGTYPES_FMTDATE_MONTH_LITERAL_SHORT 4
#define PGTYPES_FMTDATE_YEAR_DIGITS_SHORT 5
#define PGTYPES_FMTDATE_YEAR_DIGITS_LONG 6
int
PGTYPESdate_fmt_asc(date dDate, const char *fmtstring, char *outbuf)
{
static struct
{
char *format;
int component;
} mapping[] =
{
/*
* format items have to be sorted according to their length, since the
* first pattern that matches gets replaced by its value
*/
{
"ddd", PGTYPES_FMTDATE_DOW_LITERAL_SHORT
},
{
"dd", PGTYPES_FMTDATE_DAY_DIGITS_LZ
},
{
"mmm", PGTYPES_FMTDATE_MONTH_LITERAL_SHORT
},
{
"mm", PGTYPES_FMTDATE_MONTH_DIGITS_LZ
},
{
"yyyy", PGTYPES_FMTDATE_YEAR_DIGITS_LONG
},
{
"yy", PGTYPES_FMTDATE_YEAR_DIGITS_SHORT
},
{
NULL, 0
}
};
union un_fmt_comb replace_val;
int replace_type;
int i;
int dow;
char *start_pattern;
struct tm tm;
/* copy the string over */
strcpy(outbuf, fmtstring);
/* get the date */
j2date(dDate + date2j(2000, 1, 1), &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
dow = PGTYPESdate_dayofweek(dDate);
for (i = 0; mapping[i].format != NULL; i++)
{
while ((start_pattern = strstr(outbuf, mapping[i].format)) != NULL)
{
switch (mapping[i].component)
{
case PGTYPES_FMTDATE_DOW_LITERAL_SHORT:
replace_val.str_val = pgtypes_date_weekdays_short[dow];
replace_type = PGTYPES_TYPE_STRING_CONSTANT;
break;
case PGTYPES_FMTDATE_DAY_DIGITS_LZ:
replace_val.uint_val = tm.tm_mday;
replace_type = PGTYPES_TYPE_UINT_2_LZ;
break;
case PGTYPES_FMTDATE_MONTH_LITERAL_SHORT:
replace_val.str_val = months[tm.tm_mon - 1];
replace_type = PGTYPES_TYPE_STRING_CONSTANT;
break;
case PGTYPES_FMTDATE_MONTH_DIGITS_LZ:
replace_val.uint_val = tm.tm_mon;
replace_type = PGTYPES_TYPE_UINT_2_LZ;
break;
case PGTYPES_FMTDATE_YEAR_DIGITS_LONG:
replace_val.uint_val = tm.tm_year;
replace_type = PGTYPES_TYPE_UINT_4_LZ;
break;
case PGTYPES_FMTDATE_YEAR_DIGITS_SHORT:
replace_val.uint_val = tm.tm_year % 100;
replace_type = PGTYPES_TYPE_UINT_2_LZ;
break;
default:
/*
* should not happen, set something anyway
*/
replace_val.str_val = " ";
replace_type = PGTYPES_TYPE_STRING_CONSTANT;
}
switch (replace_type)
{
case PGTYPES_TYPE_STRING_MALLOCED:
case PGTYPES_TYPE_STRING_CONSTANT:
strncpy(start_pattern, replace_val.str_val,
strlen(replace_val.str_val));
if (replace_type == PGTYPES_TYPE_STRING_MALLOCED)
free(replace_val.str_val);
break;
case PGTYPES_TYPE_UINT:
{
char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS);
if (!t)
return -1;
snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS,
"%u", replace_val.uint_val);
strncpy(start_pattern, t, strlen(t));
free(t);
}
break;
case PGTYPES_TYPE_UINT_2_LZ:
{
char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS);
if (!t)
return -1;
snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS,
"%02u", replace_val.uint_val);
strncpy(start_pattern, t, strlen(t));
free(t);
}
break;
case PGTYPES_TYPE_UINT_4_LZ:
{
char *t = pgtypes_alloc(PGTYPES_DATE_NUM_MAX_DIGITS);
if (!t)
return -1;
snprintf(t, PGTYPES_DATE_NUM_MAX_DIGITS,
"%04u", replace_val.uint_val);
strncpy(start_pattern, t, strlen(t));
free(t);
}
break;
default:
/*
* doesn't happen (we set replace_type to
* PGTYPES_TYPE_STRING_CONSTANT in case of an error above)
*/
break;
}
}
}
return 0;
}
/*
* PGTYPESdate_defmt_asc
*
* function works as follows:
* - first we analyze the paramters
* - if this is a special case with no delimiters, add delimters
* - find the tokens. First we look for numerical values. If we have found
* less than 3 tokens, we check for the months' names and thereafter for
* the abbreviations of the months' names.
* - then we see which parameter should be the date, the month and the
* year and from these values we calculate the date
*/
#define PGTYPES_DATE_MONTH_MAXLENGTH 20 /* probably even less :-) */
int
PGTYPESdate_defmt_asc(date * d, const char *fmt, char *str)
{
/*
* token[2] = { 4,6 } means that token 2 starts at position 4 and ends at
* (including) position 6
*/
int token[3][2];
int token_values[3] = {-1, -1, -1};
char *fmt_token_order;
char *fmt_ystart,
*fmt_mstart,
*fmt_dstart;
unsigned int i;
int reading_digit;
int token_count;
char *str_copy;
struct tm tm;
tm.tm_year = tm.tm_mon = tm.tm_mday = 0; /* keep compiler quiet */
if (!d || !str || !fmt)
{
errno = PGTYPES_DATE_ERR_EARGS;
return -1;
}
/* analyze the fmt string */
fmt_ystart = strstr(fmt, "yy");
fmt_mstart = strstr(fmt, "mm");
fmt_dstart = strstr(fmt, "dd");
if (!fmt_ystart || !fmt_mstart || !fmt_dstart)
{
errno = PGTYPES_DATE_ERR_EARGS;
return -1;
}
if (fmt_ystart < fmt_mstart)
{
/* y m */
if (fmt_dstart < fmt_ystart)
{
/* d y m */
fmt_token_order = "dym";
}
else if (fmt_dstart > fmt_mstart)
{
/* y m d */
fmt_token_order = "ymd";
}
else
{
/* y d m */
fmt_token_order = "ydm";
}
}
else
{
/* fmt_ystart > fmt_mstart */
/* m y */
if (fmt_dstart < fmt_mstart)
{
/* d m y */
fmt_token_order = "dmy";
}
else if (fmt_dstart > fmt_ystart)
{
/* m y d */
fmt_token_order = "myd";
}
else
{
/* m d y */
fmt_token_order = "mdy";
}
}
/*
* handle the special cases where there is no delimiter between the
* digits. If we see this:
*
* only digits, 6 or 8 bytes then it might be ddmmyy and ddmmyyyy (or
* similar)
*
* we reduce it to a string with delimiters and continue processing
*/
/* check if we have only digits */
reading_digit = 1;
for (i = 0; str[i]; i++)
{
if (!isdigit((unsigned char) str[i]))
{
reading_digit = 0;
break;
}
}
if (reading_digit)
{
int frag_length[3];
int target_pos;
i = strlen(str);
if (i != 8 && i != 6)
{
errno = PGTYPES_DATE_ERR_ENOSHORTDATE;
return -1;
}
/* okay, this really is the special case */
/*
* as long as the string, one additional byte for the terminator and 2
* for the delimiters between the 3 fiedls
*/
str_copy = pgtypes_alloc(strlen(str) + 1 + 2);
if (!str_copy)
return -1;
/* determine length of the fragments */
if (i == 6)
{
frag_length[0] = 2;
frag_length[1] = 2;
frag_length[2] = 2;
}
else
{
if (fmt_token_order[0] == 'y')
{
frag_length[0] = 4;
frag_length[1] = 2;
frag_length[2] = 2;
}
else if (fmt_token_order[1] == 'y')
{
frag_length[0] = 2;
frag_length[1] = 4;
frag_length[2] = 2;
}
else
{
frag_length[0] = 2;
frag_length[1] = 2;
frag_length[2] = 4;
}
}
target_pos = 0;
/*
* XXX: Here we could calculate the positions of the tokens and save
* the for loop down there where we again check with isdigit() for
* digits.
*/
for (i = 0; i < 3; i++)
{
int start_pos = 0;
if (i >= 1)
start_pos += frag_length[0];
if (i == 2)
start_pos += frag_length[1];
strncpy(str_copy + target_pos, str + start_pos,
frag_length[i]);
target_pos += frag_length[i];
if (i != 2)
{
str_copy[target_pos] = ' ';
target_pos++;
}
}
str_copy[target_pos] = '\0';
}
else
{
str_copy = pgtypes_strdup(str);
if (!str_copy)
return -1;
/* convert the whole string to lower case */
for (i = 0; str_copy[i]; i++)
str_copy[i] = (char) pg_tolower((unsigned char) str_copy[i]);
}
/* look for numerical tokens */
reading_digit = 0;
token_count = 0;
for (i = 0; i < strlen(str_copy); i++)
{
if (!isdigit((unsigned char) str_copy[i]) && reading_digit)
{
/* the token is finished */
token[token_count][1] = i - 1;
reading_digit = 0;
token_count++;
}
else if (isdigit((unsigned char) str_copy[i]) && !reading_digit)
{
/* we have found a token */
token[token_count][0] = i;
reading_digit = 1;
}
}
/*
* we're at the end of the input string, but maybe we are still reading a
* number...
*/
if (reading_digit)
{
token[token_count][1] = i - 1;
token_count++;
}
if (token_count < 2)
{
/*
* not all tokens found, no way to find 2 missing tokens with string
* matches
*/
free(str_copy);
errno = PGTYPES_DATE_ERR_ENOSHORTDATE;
return -1;
}
if (token_count != 3)
{
/*
* not all tokens found but we may find another one with string
* matches by testing for the months names and months abbreviations
*/
char *month_lower_tmp = pgtypes_alloc(PGTYPES_DATE_MONTH_MAXLENGTH);
char *start_pos;
int j;
int offset;
int found = 0;
char **list;
if (!month_lower_tmp)
{
/* free variables we alloc'ed before */
free(str_copy);
return -1;
}
list = pgtypes_date_months;
for (i = 0; list[i]; i++)
{
for (j = 0; j < PGTYPES_DATE_MONTH_MAXLENGTH; j++)
{
month_lower_tmp[j] = (char) pg_tolower((unsigned char) list[i][j]);
if (!month_lower_tmp[j])
{
/* properly terminated */
break;
}
}
if ((start_pos = strstr(str_copy, month_lower_tmp)))
{
offset = start_pos - str_copy;
/*
* sort the new token into the numeric tokens, shift them if
* necessary
*/
if (offset < token[0][0])
{
token[2][0] = token[1][0];
token[2][1] = token[1][1];
token[1][0] = token[0][0];
token[1][1] = token[0][1];
token_count = 0;
}
else if (offset < token[1][0])
{
token[2][0] = token[1][0];
token[2][1] = token[1][1];
token_count = 1;
}
else
token_count = 2;
token[token_count][0] = offset;
token[token_count][1] = offset + strlen(month_lower_tmp) - 1;
/*
* the value is the index of the month in the array of months
* + 1 (January is month 0)
*/
token_values[token_count] = i + 1;
found = 1;
break;
}
/*
* evil[tm] hack: if we read the pgtypes_date_months and haven't
* found a match, reset list to point to pgtypes_date_months_short
* and reset the counter variable i
*/
if (list == pgtypes_date_months)
{
if (list[i + 1] == NULL)
{
list = months;
i = -1;
}
}
}
if (!found)
{
free(month_lower_tmp);
free(str_copy);
errno = PGTYPES_DATE_ERR_ENOTDMY;
return -1;
}
/*
* here we found a month. token[token_count] and
* token_values[token_count] reflect the month's details.
*
* only the month can be specified with a literal. Here we can do a
* quick check if the month is at the right position according to the
* format string because we can check if the token that we expect to
* be the month is at the position of the only token that already has
* a value. If we wouldn't check here we could say "December 4 1990"
* with a fmt string of "dd mm yy" for 12 April 1990.
*/
if (fmt_token_order[token_count] != 'm')
{
/* deal with the error later on */
token_values[token_count] = -1;
}
free(month_lower_tmp);
}
/* terminate the tokens with ASCII-0 and get their values */
for (i = 0; i < 3; i++)
{
*(str_copy + token[i][1] + 1) = '\0';
/* A month already has a value set, check for token_value == -1 */
if (token_values[i] == -1)
{
errno = 0;
token_values[i] = strtol(str_copy + token[i][0], (char **) NULL, 10);
/* strtol sets errno in case of an error */
if (errno)
token_values[i] = -1;
}
if (fmt_token_order[i] == 'd')
tm.tm_mday = token_values[i];
else if (fmt_token_order[i] == 'm')
tm.tm_mon = token_values[i];
else if (fmt_token_order[i] == 'y')
tm.tm_year = token_values[i];
}
free(str_copy);
if (tm.tm_mday < 1 || tm.tm_mday > 31)
{
errno = PGTYPES_DATE_BAD_DAY;
return -1;
}
if (tm.tm_mon < 1 || tm.tm_mon > MONTHS_PER_YEAR)
{
errno = PGTYPES_DATE_BAD_MONTH;
return -1;
}
if (tm.tm_mday == 31 && (tm.tm_mon == 4 || tm.tm_mon == 6 || tm.tm_mon == 9 || tm.tm_mon == 11))
{
errno = PGTYPES_DATE_BAD_DAY;
return -1;
}
if (tm.tm_mon == 2 && tm.tm_mday > 29)
{
errno = PGTYPES_DATE_BAD_DAY;
return -1;
}
*d = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - date2j(2000, 1, 1);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2019_1 |
crossvul-cpp_data_good_740_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M EEEEE TTTTT AAA %
% MM MM E T A A %
% M M M EEE T AAAAA %
% M M E T A A %
% M M EEEEE T A A %
% %
% %
% Read/Write Embedded Image Profiles. %
% %
% Software Design %
% William Radcliffe %
% July 2001 %
% %
% %
% Copyright 1999-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/channel.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/profile.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMETAImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M E T A %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMETA() returns MagickTrue if the image format type, identified by the
% magick string, is META.
%
% The format of the IsMETA method is:
%
% MagickBooleanType IsMETA(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
#ifdef IMPLEMENT_IS_FUNCTION
static MagickBooleanType IsMETA(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"8BIM",4) == 0)
return(MagickTrue);
if (LocaleNCompare((char *) magick,"APP1",4) == 0)
return(MagickTrue);
if (LocaleNCompare((char *) magick,"\034\002",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMETAImage() reads a META image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMETAImage method is:
%
% Image *ReadMETAImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% Decompression code contributed by Kyle Shorter.
%
% A description of each parameter follows:
%
% o image: Method ReadMETAImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or
% if the image cannot be read.
%
% o image_info: Specifies a pointer to an ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _html_code
{
const short int
len;
const char
*code,
val;
} html_code;
static const html_code html_codes[] = {
#ifdef HANDLE_GT_LT
{ 4,"<",'<' },
{ 4,">",'>' },
#endif
{ 5,"&",'&' },
{ 6,""",'"' },
{ 6,"'",'\''}
};
static int stringnicmp(const char *p,const char *q,size_t n)
{
register ssize_t
i,
j;
if (p == q)
return(0);
if (p == (char *) NULL)
return(-1);
if (q == (char *) NULL)
return(1);
while ((*p != '\0') && (*q != '\0'))
{
if ((*p == '\0') || (*q == '\0'))
break;
i=(*p);
if (islower(i))
i=toupper(i);
j=(*q);
if (islower(j))
j=toupper(j);
if (i != j)
break;
n--;
if (n == 0)
break;
p++;
q++;
}
return(toupper((int) *p)-toupper((int) *q));
}
static size_t convertHTMLcodes(char *s, const size_t len)
{
int
value;
if ((len == 0) || (s == (char*) NULL) || (*s=='\0'))
return(0);
if ((len > 3) && (s[1] == '#') && (strchr(s,';') != (char *) NULL) &&
(sscanf(s,"&#%d;",&value) == 1))
{
size_t o = 3;
while (s[o] != ';')
{
o++;
if (o > 5)
break;
}
if (o < 6)
(void) memmove(s+1,s+1+o,strlen(s+1+o)+1);
*s=value;
return(o);
}
else
{
int
i,
codes;
codes=sizeof(html_codes)/sizeof(html_code);
for (i=0; i < codes; i++)
{
if (html_codes[i].len <= (ssize_t) len)
if (stringnicmp(s, html_codes[i].code,(size_t) (html_codes[i].len)) == 0)
{
(void) memmove(s+1,s+html_codes[i].len,
strlen(s+html_codes[i].len)+1);
*s=html_codes[i].val;
return(html_codes[i].len-1);
}
}
}
return(0);
}
static char *super_fgets(char **b, int *blen, Image *file)
{
int
c,
len;
unsigned char
*p,
*q;
len=*blen;
p=(unsigned char *) (*b);
for (q=p; ; q++)
{
c=ReadBlobByte(file);
if (c == EOF || c == '\n')
break;
if ((q-p+1) >= (int) len)
{
int
tlen;
tlen=q-p;
len<<=1;
p=(unsigned char *) ResizeQuantumMemory(p,(size_t) len+2UL,sizeof(*p));
*b=(char *) p;
if (p == (unsigned char *) NULL)
break;
q=p+tlen;
}
*q=(unsigned char) c;
}
*blen=0;
if (p != (unsigned char *) NULL)
{
int
tlen;
tlen=q-p;
if (tlen == 0)
return (char *) NULL;
p[tlen] = '\0';
*blen=++tlen;
}
return((char *) p);
}
#define IPTC_ID 1028
#define THUMBNAIL_ID 1033
static ssize_t parse8BIM(Image *ifile, Image *ofile)
{
char
brkused,
quoted,
*line,
*token,
*newstr,
*name;
int
state,
next;
unsigned char
dataset;
unsigned int
recnum;
int
inputlen = MagickPathExtent;
MagickOffsetType
savedpos,
currentpos;
ssize_t
savedolen = 0L,
outputlen = 0L;
TokenInfo
*token_info;
dataset = 0;
recnum = 0;
line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line));
if (line == (char *) NULL)
return(-1);
newstr = name = token = (char *) NULL;
savedpos = 0;
token_info=AcquireTokenInfo();
while (super_fgets(&line,&inputlen,ifile)!=NULL)
{
state=0;
next=0;
token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token));
if (token == (char *) NULL)
break;
newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr));
if (newstr == (char *) NULL)
break;
while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0,
&brkused,&next,"ed)==0)
{
if (state == 0)
{
int
state,
next;
char
brkused,
quoted;
state=0;
next=0;
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#",
"", 0,&brkused,&next,"ed)==0)
{
switch (state)
{
case 0:
if (strcmp(newstr,"8BIM")==0)
dataset = 255;
else
dataset = (unsigned char) StringToLong(newstr);
break;
case 1:
recnum = (unsigned int) StringToUnsignedLong(newstr);
break;
case 2:
name=(char *) AcquireQuantumMemory(strlen(newstr)+MagickPathExtent,
sizeof(*name));
if (name)
(void) strcpy(name,newstr);
break;
}
state++;
}
}
else
if (state == 1)
{
int
next;
ssize_t
len;
char
brkused,
quoted;
next=0;
len = (ssize_t) strlen(token);
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&",
"",0,&brkused,&next,"ed)==0)
{
if (brkused && next > 0)
{
size_t
codes_length;
char
*s = &token[next-1];
codes_length=convertHTMLcodes(s, strlen(s));
if ((ssize_t) codes_length > len)
len=0;
else
len-=codes_length;
}
}
if (dataset == 255)
{
unsigned char
nlen = 0;
int
i;
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
(void) WriteBlobString(ofile,"8BIM");
(void) WriteBlobMSBShort(ofile,(unsigned short) recnum);
outputlen += 6;
if (name)
nlen = (unsigned char) strlen(name);
(void) WriteBlobByte(ofile,nlen);
outputlen++;
for (i=0; i<nlen; i++)
(void) WriteBlobByte(ofile,(unsigned char) name[i]);
outputlen += nlen;
if ((nlen & 0x01) == 0)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
if (recnum != IPTC_ID)
{
(void) WriteBlobMSBLong(ofile, (unsigned int) len);
outputlen += 4;
next=0;
outputlen += len;
while (len-- > 0)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
}
else
{
/* patch in a fake length for now and fix it later */
savedpos = TellBlob(ofile);
if (savedpos < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,0xFFFFFFFFU);
outputlen += 4;
savedolen = outputlen;
}
}
else
{
if (len <= 0x7FFF)
{
(void) WriteBlobByte(ofile,0x1c);
(void) WriteBlobByte(ofile,(unsigned char) dataset);
(void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff));
(void) WriteBlobMSBShort(ofile,(unsigned short) len);
outputlen += 5;
next=0;
outputlen += len;
while (len-- > 0)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
}
}
}
state++;
}
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
}
token_info=DestroyTokenInfo(token_info);
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
line=DestroyString(line);
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
return outputlen;
}
static char *super_fgets_w(char **b, int *blen, Image *file)
{
int
c,
len;
unsigned char
*p,
*q;
len=*blen;
p=(unsigned char *) (*b);
for (q=p; ; q++)
{
c=ReadBlobLSBSignedShort(file);
if ((c == -1) || (c == '\n'))
break;
if (EOFBlob(file))
break;
if ((q-p+1) >= (int) len)
{
int
tlen;
tlen=q-p;
len<<=1;
p=(unsigned char *) ResizeQuantumMemory(p,(size_t) (len+2),sizeof(*p));
*b=(char *) p;
if (p == (unsigned char *) NULL)
break;
q=p+tlen;
}
*q=(unsigned char) c;
}
*blen=0;
if ((*b) != (char *) NULL)
{
int
tlen;
tlen=q-p;
if (tlen == 0)
return (char *) NULL;
p[tlen] = '\0';
*blen=++tlen;
}
return((char *) p);
}
static ssize_t parse8BIMW(Image *ifile, Image *ofile)
{
char
brkused,
quoted,
*line,
*token,
*newstr,
*name;
int
state,
next;
unsigned char
dataset;
unsigned int
recnum;
int
inputlen = MagickPathExtent;
ssize_t
savedolen = 0L,
outputlen = 0L;
MagickOffsetType
savedpos,
currentpos;
TokenInfo
*token_info;
dataset = 0;
recnum = 0;
line=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line));
if (line == (char *) NULL)
return(-1);
newstr = name = token = (char *) NULL;
savedpos = 0;
token_info=AcquireTokenInfo();
while (super_fgets_w(&line,&inputlen,ifile) != NULL)
{
state=0;
next=0;
token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token));
if (token == (char *) NULL)
break;
newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr));
if (newstr == (char *) NULL)
break;
while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"","=","\"",0,
&brkused,&next,"ed)==0)
{
if (state == 0)
{
int
state,
next;
char
brkused,
quoted;
state=0;
next=0;
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","#",
"",0,&brkused,&next,"ed)==0)
{
switch (state)
{
case 0:
if (strcmp(newstr,"8BIM")==0)
dataset = 255;
else
dataset = (unsigned char) StringToLong(newstr);
break;
case 1:
recnum=(unsigned int) StringToUnsignedLong(newstr);
break;
case 2:
name=(char *) AcquireQuantumMemory(strlen(newstr)+MagickPathExtent,
sizeof(*name));
if (name)
(void) CopyMagickString(name,newstr,strlen(newstr)+MagickPathExtent);
break;
}
state++;
}
}
else
if (state == 1)
{
int
next;
ssize_t
len;
char
brkused,
quoted;
next=0;
len = (ssize_t) strlen(token);
while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"","&",
"",0,&brkused,&next,"ed)==0)
{
if (brkused && next > 0)
{
size_t
codes_length;
char
*s = &token[next-1];
codes_length=convertHTMLcodes(s, strlen(s));
if ((ssize_t) codes_length > len)
len=0;
else
len-=codes_length;
}
}
if (dataset == 255)
{
unsigned char
nlen = 0;
int
i;
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
(void) WriteBlobString(ofile,"8BIM");
(void) WriteBlobMSBShort(ofile,(unsigned short) recnum);
outputlen += 6;
if (name)
nlen = (unsigned char) strlen(name);
(void) WriteBlobByte(ofile,(unsigned char) nlen);
outputlen++;
for (i=0; i<nlen; i++)
(void) WriteBlobByte(ofile,(unsigned char) name[i]);
outputlen += nlen;
if ((nlen & 0x01) == 0)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
if (recnum != IPTC_ID)
{
(void) WriteBlobMSBLong(ofile,(unsigned int) len);
outputlen += 4;
next=0;
outputlen += len;
while (len--)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
if (outputlen & 1)
{
(void) WriteBlobByte(ofile,0x00);
outputlen++;
}
}
else
{
/* patch in a fake length for now and fix it later */
savedpos = TellBlob(ofile);
if (savedpos < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,0xFFFFFFFFU);
outputlen += 4;
savedolen = outputlen;
}
}
else
{
if (len <= 0x7FFF)
{
(void) WriteBlobByte(ofile,0x1c);
(void) WriteBlobByte(ofile,dataset);
(void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff));
(void) WriteBlobMSBShort(ofile,(unsigned short) len);
outputlen += 5;
next=0;
outputlen += len;
while (len--)
(void) WriteBlobByte(ofile,(unsigned char) token[next++]);
}
}
}
state++;
}
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
}
token_info=DestroyTokenInfo(token_info);
if (token != (char *) NULL)
token=DestroyString(token);
if (newstr != (char *) NULL)
newstr=DestroyString(newstr);
if (name != (char *) NULL)
name=DestroyString(name);
line=DestroyString(line);
if (savedolen > 0)
{
MagickOffsetType
offset;
ssize_t diff = outputlen - savedolen;
currentpos = TellBlob(ofile);
if (currentpos < 0)
return(-1);
offset=SeekBlob(ofile,savedpos,SEEK_SET);
if (offset < 0)
return(-1);
(void) WriteBlobMSBLong(ofile,(unsigned int) diff);
offset=SeekBlob(ofile,currentpos,SEEK_SET);
if (offset < 0)
return(-1);
savedolen = 0L;
}
return(outputlen);
}
/* some defines for the different JPEG block types */
#define M_SOF0 0xC0 /* Start Of Frame N */
#define M_SOF1 0xC1 /* N indicates which compression process */
#define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */
#define M_SOF3 0xC3
#define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */
#define M_SOF6 0xC6
#define M_SOF7 0xC7
#define M_SOF9 0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI 0xD8
#define M_EOI 0xD9 /* End Of Image (end of datastream) */
#define M_SOS 0xDA /* Start Of Scan (begins compressed data) */
#define M_APP0 0xe0
#define M_APP1 0xe1
#define M_APP2 0xe2
#define M_APP3 0xe3
#define M_APP4 0xe4
#define M_APP5 0xe5
#define M_APP6 0xe6
#define M_APP7 0xe7
#define M_APP8 0xe8
#define M_APP9 0xe9
#define M_APP10 0xea
#define M_APP11 0xeb
#define M_APP12 0xec
#define M_APP13 0xed
#define M_APP14 0xee
#define M_APP15 0xef
static int jpeg_transfer_1(Image *ifile, Image *ofile)
{
int c;
c = ReadBlobByte(ifile);
if (c == EOF)
return EOF;
(void) WriteBlobByte(ofile,(unsigned char) c);
return c;
}
#if defined(future)
static int jpeg_skip_1(Image *ifile)
{
int c;
c = ReadBlobByte(ifile);
if (c == EOF)
return EOF;
return c;
}
#endif
static int jpeg_read_remaining(Image *ifile, Image *ofile)
{
int c;
while ((c = jpeg_transfer_1(ifile, ofile)) != EOF)
continue;
return M_EOI;
}
static int jpeg_skip_variable(Image *ifile, Image *ofile)
{
unsigned int length;
int c1,c2;
if ((c1 = jpeg_transfer_1(ifile, ofile)) == EOF)
return M_EOI;
if ((c2 = jpeg_transfer_1(ifile, ofile)) == EOF)
return M_EOI;
length = (((unsigned char) c1) << 8) + ((unsigned char) c2);
length -= 2;
while (length--)
if (jpeg_transfer_1(ifile, ofile) == EOF)
return M_EOI;
return 0;
}
static int jpeg_skip_variable2(Image *ifile, Image *ofile)
{
unsigned int length;
int c1,c2;
(void) ofile;
if ((c1 = ReadBlobByte(ifile)) == EOF) return M_EOI;
if ((c2 = ReadBlobByte(ifile)) == EOF) return M_EOI;
length = (((unsigned char) c1) << 8) + ((unsigned char) c2);
length -= 2;
while (length--)
if (ReadBlobByte(ifile) == EOF)
return M_EOI;
return 0;
}
static int jpeg_nextmarker(Image *ifile, Image *ofile)
{
int c;
/* transfer anything until we hit 0xff */
do
{
c = ReadBlobByte(ifile);
if (c == EOF)
return M_EOI; /* we hit EOF */
else
if (c != 0xff)
(void) WriteBlobByte(ofile,(unsigned char) c);
} while (c != 0xff);
/* get marker byte, swallowing possible padding */
do
{
c = ReadBlobByte(ifile);
if (c == EOF)
return M_EOI; /* we hit EOF */
} while (c == 0xff);
return c;
}
#if defined(future)
static int jpeg_skip_till_marker(Image *ifile, int marker)
{
int c, i;
do
{
/* skip anything until we hit 0xff */
i = 0;
do
{
c = ReadBlobByte(ifile);
i++;
if (c == EOF)
return M_EOI; /* we hit EOF */
} while (c != 0xff);
/* get marker byte, swallowing possible padding */
do
{
c = ReadBlobByte(ifile);
if (c == EOF)
return M_EOI; /* we hit EOF */
} while (c == 0xff);
} while (c != marker);
return c;
}
#endif
/* Embed binary IPTC data into a JPEG image. */
static int jpeg_embed(Image *ifile, Image *ofile, Image *iptc)
{
unsigned int marker;
unsigned int done = 0;
unsigned int len;
int inx;
if (jpeg_transfer_1(ifile, ofile) != 0xFF)
return 0;
if (jpeg_transfer_1(ifile, ofile) != M_SOI)
return 0;
while (done == MagickFalse)
{
marker=(unsigned int) jpeg_nextmarker(ifile, ofile);
if (marker == M_EOI)
{ /* EOF */
break;
}
else
{
if (marker != M_APP13)
{
(void) WriteBlobByte(ofile,0xff);
(void) WriteBlobByte(ofile,(unsigned char) marker);
}
}
switch (marker)
{
case M_APP13:
/* we are going to write a new APP13 marker, so don't output the old one */
jpeg_skip_variable2(ifile, ofile);
break;
case M_APP0:
/* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */
jpeg_skip_variable(ifile, ofile);
if (iptc != (Image *) NULL)
{
char
psheader[] = "\xFF\xED\0\0Photoshop 3.0\0" "8BIM\x04\x04\0\0\0\0";
len=(unsigned int) GetBlobSize(iptc);
if (len & 1)
len++; /* make the length even */
psheader[2]=(char) ((len+16)>>8);
psheader[3]=(char) ((len+16)&0xff);
for (inx = 0; inx < 18; inx++)
(void) WriteBlobByte(ofile,(unsigned char) psheader[inx]);
jpeg_read_remaining(iptc, ofile);
len=(unsigned int) GetBlobSize(iptc);
if (len & 1)
(void) WriteBlobByte(ofile,0);
}
break;
case M_SOS:
/* we hit data, no more marker-inserting can be done! */
jpeg_read_remaining(ifile, ofile);
done = 1;
break;
default:
jpeg_skip_variable(ifile, ofile);
break;
}
}
return 1;
}
/* handle stripping the APP13 data out of a JPEG */
#if defined(future)
static void jpeg_strip(Image *ifile, Image *ofile)
{
unsigned int marker;
marker = jpeg_skip_till_marker(ifile, M_SOI);
if (marker == M_SOI)
{
(void) WriteBlobByte(ofile,0xff);
(void) WriteBlobByte(ofile,M_SOI);
jpeg_read_remaining(ifile, ofile);
}
}
/* Extract any APP13 binary data into a file. */
static int jpeg_extract(Image *ifile, Image *ofile)
{
unsigned int marker;
unsigned int done = 0;
if (jpeg_skip_1(ifile) != 0xff)
return 0;
if (jpeg_skip_1(ifile) != M_SOI)
return 0;
while (done == MagickFalse)
{
marker = jpeg_skip_till_marker(ifile, M_APP13);
if (marker == M_APP13)
{
marker = jpeg_nextmarker(ifile, ofile);
break;
}
}
return 1;
}
#endif
static inline void CopyBlob(Image *source,Image *destination)
{
ssize_t
i;
unsigned char
*buffer;
ssize_t
count,
length;
buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,
sizeof(*buffer));
if (buffer != (unsigned char *) NULL)
{
i=0;
while ((length=ReadBlob(source,MagickMaxBufferExtent,buffer)) != 0)
{
count=0;
for (i=0; i < (ssize_t) length; i+=count)
{
count=WriteBlob(destination,(size_t) (length-i),buffer+i);
if (count <= 0)
break;
}
if (i < (ssize_t) length)
break;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
}
}
static Image *ReadMETAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*buff,
*image;
MagickBooleanType
status;
StringInfo
*profile;
size_t
length;
void
*blob;
/*
Open file containing binary metadata
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == 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);
}
image->columns=1;
image->rows=1;
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
length=1;
if (LocaleNCompare(image_info->magick,"8BIM",4) == 0)
{
/*
Read 8BIM binary metadata.
*/
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0)
{
length=(size_t) parse8BIM(image, buff);
if (length & 1)
(void) WriteBlobByte(buff,0x0);
}
else if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0)
{
length=(size_t) parse8BIMW(image, buff);
if (length & 1)
(void) WriteBlobByte(buff,0x0);
}
else
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (LocaleNCompare(image_info->magick,"APP1",4) == 0)
{
char
name[MagickPathExtent];
(void) FormatLocaleString(name,MagickPathExtent,"APP%d",1);
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
if (LocaleCompare(image_info->magick,"APP1JPEG") == 0)
{
Image
*iptc;
int
result;
if (image_info->profile == (void *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(CoderError,"NoIPTCProfileAvailable");
}
profile=CloneStringInfo((StringInfo *) image_info->profile);
iptc=AcquireImage((ImageInfo *) NULL,exception);
if (iptc == (Image *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(iptc->blob,GetStringInfoDatum(profile),
GetStringInfoLength(profile));
result=jpeg_embed(image,buff,iptc);
blob=DetachBlob(iptc->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
iptc=DestroyImage(iptc);
if (result == 0)
{
buff=DestroyImage(buff);
ThrowReaderException(CoderError,"JPEGEmbeddingFailed");
}
}
else
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
status=SetImageProfile(image,name,profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if ((LocaleCompare(image_info->magick,"ICC") == 0) ||
(LocaleCompare(image_info->magick,"ICM") == 0))
{
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
if (LocaleCompare(image_info->magick,"IPTC") == 0)
{
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
if (LocaleCompare(image_info->magick,"XMP") == 0)
{
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
blob=(unsigned char *) AcquireQuantumMemory(length,sizeof(unsigned char));
if (blob == (unsigned char *) NULL)
{
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
AttachBlob(buff->blob,blob,length);
CopyBlob(image,buff);
profile=BlobToStringInfo(GetBlobStreamData(buff),(size_t)
GetBlobSize(buff));
if (profile == (StringInfo *) NULL)
{
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) SetImageProfile(image,"xmp",profile,exception);
profile=DestroyStringInfo(profile);
blob=DetachBlob(buff->blob);
blob=(unsigned char *) RelinquishMagickMemory(blob);
buff=DestroyImage(buff);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMETAImage() adds attributes for the META image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMETAImage method is:
%
% size_t RegisterMETAImage(void)
%
*/
ModuleExport size_t RegisterMETAImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("META","8BIM","Photoshop resource format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","8BIMTEXT","Photoshop resource text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","8BIMWTEXT",
"Photoshop resource wide text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","APP1","Raw application information");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","APP1JPEG","Raw JPEG binary data");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","EXIF","Exif digital camera binary data");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","XMP","Adobe XML metadata");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","ICM","ICC Color Profile");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","ICC","ICC Color Profile");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","IPTC","IPTC Newsphoto");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","IPTCTEXT","IPTC Newsphoto text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("META","IPTCWTEXT","IPTC Newsphoto text format");
entry->decoder=(DecodeImageHandler *) ReadMETAImage;
entry->encoder=(EncodeImageHandler *) WriteMETAImage;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderStealthFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMETAImage() removes format registrations made by the
% META module from the list of supported formats.
%
% The format of the UnregisterMETAImage method is:
%
% UnregisterMETAImage(void)
%
*/
ModuleExport void UnregisterMETAImage(void)
{
(void) UnregisterMagickInfo("8BIM");
(void) UnregisterMagickInfo("8BIMTEXT");
(void) UnregisterMagickInfo("8BIMWTEXT");
(void) UnregisterMagickInfo("EXIF");
(void) UnregisterMagickInfo("APP1");
(void) UnregisterMagickInfo("APP1JPEG");
(void) UnregisterMagickInfo("ICCTEXT");
(void) UnregisterMagickInfo("ICM");
(void) UnregisterMagickInfo("ICC");
(void) UnregisterMagickInfo("IPTC");
(void) UnregisterMagickInfo("IPTCTEXT");
(void) UnregisterMagickInfo("IPTCWTEXT");
(void) UnregisterMagickInfo("XMP");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M E T A I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMETAImage() writes a META image to a file.
%
% The format of the WriteMETAImage method is:
%
% MagickBooleanType WriteMETAImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% Compression code contributed by Kyle Shorter.
%
% A description of each parameter follows:
%
% o image_info: Specifies a pointer to an ImageInfo structure.
%
% o image: A pointer to a Image structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t GetIPTCStream(unsigned char **info,size_t length)
{
int
c;
register ssize_t
i;
register unsigned char
*p;
size_t
extent,
info_length;
unsigned int
marker;
size_t
tag_length;
p=(*info);
extent=length;
if ((*p == 0x1c) && (*(p+1) == 0x02))
return(length);
/*
Extract IPTC from 8BIM resource block.
*/
while (extent >= 12)
{
if (strncmp((const char *) p,"8BIM",4))
break;
p+=4;
extent-=4;
marker=(unsigned int) (*p) << 8 | *(p+1);
p+=2;
extent-=2;
c=*p++;
extent--;
c|=0x01;
if ((size_t) c >= extent)
break;
p+=c;
extent-=c;
if (extent < 4)
break;
tag_length=(((size_t) *p) << 24) | (((size_t) *(p+1)) << 16) |
(((size_t) *(p+2)) << 8) | ((size_t) *(p+3));
p+=4;
extent-=4;
if (tag_length > extent)
break;
if (marker == IPTC_ID)
{
*info=p;
return(tag_length);
}
if ((tag_length & 0x01) != 0)
tag_length++;
p+=tag_length;
extent-=tag_length;
}
/*
Find the beginning of the IPTC info.
*/
p=(*info);
tag_length=0;
iptc_find:
info_length=0;
marker=MagickFalse;
while (length != 0)
{
c=(*p++);
length--;
if (length == 0)
break;
if (c == 0x1c)
{
p--;
*info=p; /* let the caller know were it is */
break;
}
}
/*
Determine the length of the IPTC info.
*/
while (length != 0)
{
c=(*p++);
length--;
if (length == 0)
break;
if (c == 0x1c)
marker=MagickTrue;
else
if (marker)
break;
else
continue;
info_length++;
/*
Found the 0x1c tag; skip the dataset and record number tags.
*/
c=(*p++); /* should be 2 */
length--;
if (length == 0)
break;
if ((info_length == 1) && (c != 2))
goto iptc_find;
info_length++;
c=(*p++); /* should be 0 */
length--;
if (length == 0)
break;
if ((info_length == 2) && (c != 0))
goto iptc_find;
info_length++;
/*
Decode the length of the block that follows - ssize_t or short format.
*/
c=(*p++);
length--;
if (length == 0)
break;
info_length++;
if ((c & 0x80) != 0)
{
/*
Long format.
*/
tag_length=0;
for (i=0; i < 4; i++)
{
tag_length<<=8;
tag_length|=(*p++);
length--;
if (length == 0)
break;
info_length++;
}
}
else
{
/*
Short format.
*/
tag_length=((long) c) << 8;
c=(*p++);
length--;
if (length == 0)
break;
info_length++;
tag_length|=(long) c;
}
if (tag_length > (length+1))
break;
p+=tag_length;
length-=tag_length;
if (length == 0)
break;
info_length+=tag_length;
}
return(info_length);
}
static void formatString(Image *ofile, const char *s, int len)
{
char
temp[MagickPathExtent];
(void) WriteBlobByte(ofile,'"');
for (; len > 0; len--, s++) {
int c = (*s) & 255;
switch (c) {
case '&':
(void) WriteBlobString(ofile,"&");
break;
#ifdef HANDLE_GT_LT
case '<':
(void) WriteBlobString(ofile,"<");
break;
case '>':
(void) WriteBlobString(ofile,">");
break;
#endif
case '"':
(void) WriteBlobString(ofile,""");
break;
default:
if (isprint(c))
(void) WriteBlobByte(ofile,(unsigned char) *s);
else
{
(void) FormatLocaleString(temp,MagickPathExtent,"&#%d;", c & 255);
(void) WriteBlobString(ofile,temp);
}
break;
}
}
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
(void) WriteBlobString(ofile,"\"\r\n");
#else
#if defined(macintosh)
(void) WriteBlobString(ofile,"\"\r");
#else
(void) WriteBlobString(ofile,"\"\n");
#endif
#endif
}
typedef struct _tag_spec
{
const short
id;
const char
*name;
} tag_spec;
static const tag_spec tags[] = {
{ 5, "Image Name" },
{ 7, "Edit Status" },
{ 10, "Priority" },
{ 15, "Category" },
{ 20, "Supplemental Category" },
{ 22, "Fixture Identifier" },
{ 25, "Keyword" },
{ 30, "Release Date" },
{ 35, "Release Time" },
{ 40, "Special Instructions" },
{ 45, "Reference Service" },
{ 47, "Reference Date" },
{ 50, "Reference Number" },
{ 55, "Created Date" },
{ 60, "Created Time" },
{ 65, "Originating Program" },
{ 70, "Program Version" },
{ 75, "Object Cycle" },
{ 80, "Byline" },
{ 85, "Byline Title" },
{ 90, "City" },
{ 92, "Sub-Location" },
{ 95, "Province State" },
{ 100, "Country Code" },
{ 101, "Country" },
{ 103, "Original Transmission Reference" },
{ 105, "Headline" },
{ 110, "Credit" },
{ 115, "Source" },
{ 116, "Copyright String" },
{ 120, "Caption" },
{ 121, "Image Orientation" },
{ 122, "Caption Writer" },
{ 131, "Local Caption" },
{ 200, "Custom Field 1" },
{ 201, "Custom Field 2" },
{ 202, "Custom Field 3" },
{ 203, "Custom Field 4" },
{ 204, "Custom Field 5" },
{ 205, "Custom Field 6" },
{ 206, "Custom Field 7" },
{ 207, "Custom Field 8" },
{ 208, "Custom Field 9" },
{ 209, "Custom Field 10" },
{ 210, "Custom Field 11" },
{ 211, "Custom Field 12" },
{ 212, "Custom Field 13" },
{ 213, "Custom Field 14" },
{ 214, "Custom Field 15" },
{ 215, "Custom Field 16" },
{ 216, "Custom Field 17" },
{ 217, "Custom Field 18" },
{ 218, "Custom Field 19" },
{ 219, "Custom Field 20" }
};
static int formatIPTC(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
c = ReadBlobByte(ifile);
while (c != EOF)
{
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return(-1);
else
{
c=0;
continue;
}
}
/* we found the 0x1c tag and now grab the dataset and record number tags */
c = ReadBlobByte(ifile);
if (c == EOF)
return(-1);
dataset = (unsigned char) c;
c = ReadBlobByte(ifile);
if (c == EOF)
return(-1);
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
{
if (tags[i].id == (short) recnum)
break;
}
if (i < tagcount)
readable = (unsigned char *) tags[i].name;
else
readable = (unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
int
c0;
c0=ReadBlobByte(ifile);
if (c0 == EOF)
return(-1);
taglen = (c << 8) | c0;
}
if (taglen < 0)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent),
sizeof(*str));
if (str == (unsigned char *) NULL)
return(0);
for (tagindx=0; tagindx<taglen; tagindx++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
return(-1);
}
str[tagindx] = (unsigned char) c;
}
str[taglen] = 0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset, (unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
c=ReadBlobByte(ifile);
}
return((int) tagsfound);
}
static int readWordFromBuffer(char **s, ssize_t *len)
{
unsigned char
buffer[2];
int
i,
c;
for (i=0; i<2; i++)
{
c = *(*s)++; (*len)--;
if (*len < 0) return -1;
buffer[i] = (unsigned char) c;
}
return (((int) buffer[ 0 ]) << 8) |
(((int) buffer[ 1 ]));
}
static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
while (len > 0)
{
c = *s++; len--;
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return -1;
else
continue;
}
/*
We found the 0x1c tag and now grab the dataset and record number tags.
*/
c = *s++; len--;
if (len < 0) return -1;
dataset = (unsigned char) c;
c = *s++; len--;
if (len < 0) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
if (tags[i].id == (short) recnum)
break;
if (i < tagcount)
readable=(unsigned char *) tags[i].name;
else
readable=(unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=(*s++);
len--;
if (len < 0)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
s--;
len++;
taglen=readWordFromBuffer(&s, &len);
}
if (taglen < 0)
return(-1);
if (taglen > 65535)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MagickPathExtent),
sizeof(*str));
if (str == (unsigned char *) NULL)
printf("MemoryAllocationFailed");
for (tagindx=0; tagindx<taglen; tagindx++)
{
c = *s++; len--;
if (len < 0)
return(-1);
str[tagindx]=(unsigned char) c;
}
str[taglen]=0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset,(unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
}
return ((int) tagsfound);
}
static int format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=ReadBlobMSBSignedShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
return 0;
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
}
}
count=(ssize_t) ReadBlobMSBSignedLong(ifile);
if ((count < 0) || (count > GetBlobSize(ifile)))
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
/* make a buffer to hold the data and snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count+1,sizeof(*str));
if (str == (unsigned char *) NULL)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
static MagickBooleanType WriteMETAImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const StringInfo
*profile;
MagickBooleanType
status;
size_t
length;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=0;
if (LocaleCompare(image_info->magick,"8BIM") == 0)
{
/*
Write 8BIM image.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"iptc") == 0)
{
size_t
length;
unsigned char
*info;
profile=GetImageProfile(image,"iptc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
info=GetStringInfoDatum(profile);
length=GetStringInfoLength(profile);
length=GetIPTCStream(&info,length);
if (length == 0)
ThrowWriterException(CoderError,"NoIPTCProfileAvailable");
(void) WriteBlob(image,length,info);
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"8BIMTEXT") == 0)
{
Image
*buff;
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
AttachBlob(buff->blob,GetStringInfoDatum(profile),
GetStringInfoLength(profile));
format8BIM(buff,image);
(void) DetachBlob(buff->blob);
buff=DestroyImage(buff);
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"8BIMWTEXT") == 0)
return(MagickFalse);
if (LocaleCompare(image_info->magick,"IPTCTEXT") == 0)
{
Image
*buff;
unsigned char
*info;
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"No8BIMDataIsAvailable");
info=GetStringInfoDatum(profile);
length=GetStringInfoLength(profile);
length=GetIPTCStream(&info,length);
if (length == 0)
ThrowWriterException(CoderError,"NoIPTCProfileAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
buff=AcquireImage((ImageInfo *) NULL,exception);
if (buff == (Image *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
AttachBlob(buff->blob,info,length);
formatIPTC(buff,image);
(void) DetachBlob(buff->blob);
buff=DestroyImage(buff);
(void) CloseBlob(image);
return(MagickTrue);
}
if (LocaleCompare(image_info->magick,"IPTCWTEXT") == 0)
return(MagickFalse);
if ((LocaleCompare(image_info->magick,"APP1") == 0) ||
(LocaleCompare(image_info->magick,"EXIF") == 0) ||
(LocaleCompare(image_info->magick,"XMP") == 0))
{
/*
(void) Write APP1 image.
*/
profile=GetImageProfile(image,image_info->magick);
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"NoAPP1DataIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) CloseBlob(image);
return(MagickTrue);
}
if ((LocaleCompare(image_info->magick,"ICC") == 0) ||
(LocaleCompare(image_info->magick,"ICM") == 0))
{
/*
Write ICM image.
*/
profile=GetImageProfile(image,"icc");
if (profile == (StringInfo *) NULL)
ThrowWriterException(CoderError,"NoColorProfileIsAvailable");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) CloseBlob(image);
return(MagickTrue);
}
return(MagickFalse);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_740_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.