project
stringclasses 633
values | commit_id
stringlengths 7
81
| target
int64 0
1
| func
stringlengths 5
484k
| cwe
stringclasses 131
values | big_vul_idx
float64 0
189k
⌀ | idx
int64 0
522k
| hash
stringlengths 34
39
| size
float64 1
24k
⌀ | message
stringlengths 0
11.5k
⌀ | dataset
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
savannah
|
df14e6c0b9592cbb24d5381dfc6106b14f915e75
| 1 |
parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
|
CWE-399
| 178,009 | 177 |
272856134003844809072499589562648977382
| null | null | null |
haproxy
|
17514045e5d934dede62116216c1b016fe23dd06
| 1 |
void check_request_for_cacheability(struct stream *s, struct channel *chn)
{
struct http_txn *txn = s->txn;
char *p1, *p2;
char *cur_ptr, *cur_end, *cur_next;
int pragma_found;
int cc_found;
int cur_idx;
if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE)
return; /* nothing more to do here */
cur_idx = 0;
pragma_found = cc_found = 0;
cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx);
while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) {
struct hdr_idx_elem *cur_hdr;
int val;
cur_hdr = &txn->hdr_idx.v[cur_idx];
cur_ptr = cur_next;
cur_end = cur_ptr + cur_hdr->len;
cur_next = cur_end + cur_hdr->cr + 1;
/* We have one full header between cur_ptr and cur_end, and the
* next header starts at cur_next.
*/
val = http_header_match2(cur_ptr, cur_end, "Pragma", 6);
if (val) {
if ((cur_end - (cur_ptr + val) >= 8) &&
strncasecmp(cur_ptr + val, "no-cache", 8) == 0) {
pragma_found = 1;
continue;
}
}
val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13);
if (!val)
continue;
p2 = p1;
while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2))
p2++;
/* we have a complete value between p1 and p2. We don't check the
* values after max-age, max-stale nor min-fresh, we simply don't
* use the cache when they're specified.
*/
if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) ||
((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) ||
((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) {
txn->flags |= TX_CACHE_IGNORE;
continue;
}
if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) {
txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK;
continue;
}
}
/* RFC7234#5.4:
* When the Cache-Control header field is also present and
* understood in a request, Pragma is ignored.
* When the Cache-Control header field is not present in a
* request, caches MUST consider the no-cache request
* pragma-directive as having the same effect as if
* "Cache-Control: no-cache" were present.
*/
if (!cc_found && pragma_found)
txn->flags |= TX_CACHE_IGNORE;
}
|
CWE-200
| 178,013 | 178 |
324327278202769570327385397929081223567
| null | null | null |
savannah
|
18a8f0d9943369449bc4de92d411c78fb08d616c
| 1 |
parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
|
CWE-119
| 178,014 | 179 |
233045259701863811358636688341910118112
| null | null | null |
savannah
|
0e2f5d518c60e2978f26400d110eff178fa7e3c3
| 1 |
pcf_read_TOC( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
PCF_Toc toc = &face->toc;
PCF_Table tables;
FT_Memory memory = FT_FACE( face )->memory;
FT_UInt n;
if ( FT_STREAM_SEEK ( 0 ) ||
FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) )
return FT_THROW( Cannot_Open_Resource );
if ( toc->version != PCF_FILE_VERSION ||
toc->count > FT_ARRAY_MAX( face->toc.tables ) ||
toc->count == 0 )
return FT_THROW( Invalid_File_Format );
if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) )
return FT_THROW( Out_Of_Memory );
tables = face->toc.tables;
for ( n = 0; n < toc->count; n++ )
{
if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) )
goto Exit;
tables++;
}
/* Sort tables and check for overlaps. Because they are almost */
/* always ordered already, an in-place bubble sort with simultaneous */
/* boundary checking seems appropriate. */
tables = face->toc.tables;
for ( n = 0; n < toc->count - 1; n++ )
{
FT_UInt i, have_change;
have_change = 0;
for ( i = 0; i < toc->count - 1 - n; i++ )
{
PCF_TableRec tmp;
if ( tables[i].offset > tables[i + 1].offset )
{
tmp = tables[i];
tables[i] = tables[i + 1];
tables[i + 1] = tmp;
have_change = 1;
}
if ( ( tables[i].size > tables[i + 1].offset ) ||
( tables[i].offset > tables[i + 1].offset - tables[i].size ) )
{
error = FT_THROW( Invalid_Offset );
goto Exit;
}
}
if ( !have_change )
break;
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_TRACE4(( " %d: type=%s, format=0x%X, "
"size=%ld (0x%lX), offset=%ld (0x%lX)\n",
i, name,
tables[i].format,
tables[i].size, tables[i].size,
tables[i].offset, tables[i].offset ));
}
}
| 178,015 | 180 |
99642060190973035507344569907798525276
| null | null | null |
|
savannah
|
ef1eba75187adfac750f326b563fe543dd5ff4e6
| 1 |
pcf_get_encodings( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
FT_Memory memory = FT_FACE( face )->memory;
FT_ULong format, size;
int firstCol, lastCol;
int firstRow, lastRow;
int nencoding, encodingOffset;
int i, j, k;
PCF_Encoding encoding = NULL;
error = pcf_seek_to_table_type( stream,
face->toc.tables,
face->toc.count,
PCF_BDF_ENCODINGS,
&format,
&size );
if ( error )
return error;
error = FT_Stream_EnterFrame( stream, 14 );
if ( error )
return error;
format = FT_GET_ULONG_LE();
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
{
firstCol = FT_GET_SHORT();
lastCol = FT_GET_SHORT();
firstRow = FT_GET_SHORT();
lastRow = FT_GET_SHORT();
face->defaultChar = FT_GET_SHORT();
}
else
{
firstCol = FT_GET_SHORT_LE();
lastCol = FT_GET_SHORT_LE();
firstRow = FT_GET_SHORT_LE();
lastRow = FT_GET_SHORT_LE();
face->defaultChar = FT_GET_SHORT_LE();
}
FT_Stream_ExitFrame( stream );
if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) )
return FT_THROW( Invalid_File_Format );
FT_TRACE4(( "pdf_get_encodings:\n" ));
FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n",
goto Bail;
k = 0;
for ( i = firstRow; i <= lastRow; i++ )
{
for ( j = firstCol; j <= lastCol; j++ )
{
if ( PCF_BYTE_ORDER( format ) == MSBFirst )
encodingOffset = FT_GET_SHORT();
else
encodingOffset = FT_GET_SHORT_LE();
if ( encodingOffset != -1 )
{
encoding[k].enc = i * 256 + j;
encoding[k].glyph = (FT_Short)encodingOffset;
FT_TRACE5(( " code %d (0x%04X): idx %d\n",
encoding[k].enc, encoding[k].enc, encoding[k].glyph ));
k++;
}
}
}
FT_Stream_ExitFrame( stream );
if ( FT_RENEW_ARRAY( encoding, nencoding, k ) )
goto Bail;
face->nencodings = k;
face->encodings = encoding;
return error;
Bail:
FT_FREE( encoding );
return error;
}
|
CWE-189
| 178,016 | 181 |
176043909406430594682157391299639166951
| null | null | null |
savannah
|
602040b1112c9f94d68e200be59ea7ac3d104565
| 1 |
tt_cmap8_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_Byte* is32;
FT_UInt32 length;
FT_UInt32 num_groups;
if ( table + 16 + 8192 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 )
FT_INVALID_TOO_SHORT;
is32 = table + 12;
p = is32 + 8192; /* skip `is32' array */
num_groups = TT_NEXT_ULONG( p );
if ( p + num_groups * 12 > valid->limit )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
FT_UInt32 n, start, end, start_id, count, last = 0;
for ( n = 0; n < num_groups; n++ )
{
FT_UInt hi, lo;
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
count = (FT_UInt32)( end - start + 1 );
{
hi = (FT_UInt)( start >> 16 );
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 )
FT_INVALID_DATA;
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 )
FT_INVALID_DATA;
}
}
else
{
/* start_hi == 0; check that is32[i] is 0 for each i in */
/* the range [start..end] */
/* end_hi cannot be != 0! */
if ( end & ~0xFFFFU )
FT_INVALID_DATA;
for ( ; count > 0; count--, start++ )
{
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 )
FT_INVALID_DATA;
}
}
}
last = end;
}
|
CWE-125
| 178,017 | 182 |
66140172033877381862359087550042336117
| null | null | null |
savannah
|
257c270bd25e15890190a28a1456e7623bba4439
| 1 |
tt_sbit_decoder_init( TT_SBitDecoder decoder,
TT_Face face,
FT_ULong strike_index,
TT_SBit_MetricsRec* metrics )
{
FT_Error error;
FT_Stream stream = face->root.stream;
FT_ULong ebdt_size;
error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size );
if ( error )
error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size );
if ( error )
error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size );
if ( error )
goto Exit;
decoder->face = face;
decoder->stream = stream;
decoder->bitmap = &face->root.glyph->bitmap;
decoder->metrics = metrics;
decoder->metrics_loaded = 0;
decoder->bitmap_allocated = 0;
decoder->ebdt_start = FT_STREAM_POS();
decoder->ebdt_size = ebdt_size;
decoder->eblc_base = face->sbit_table;
decoder->eblc_limit = face->sbit_table + face->sbit_table_size;
/* now find the strike corresponding to the index */
{
FT_Byte* p;
if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
p = decoder->eblc_base + 8 + 48 * strike_index;
decoder->strike_index_array = FT_NEXT_ULONG( p );
p += 4;
decoder->strike_index_count = FT_NEXT_ULONG( p );
p += 34;
decoder->bit_depth = *p;
if ( decoder->strike_index_array > face->sbit_table_size ||
decoder->strike_index_array + 8 * decoder->strike_index_count >
face->sbit_table_size )
error = FT_THROW( Invalid_File_Format );
}
}
|
CWE-189
| 178,018 | 183 |
275985852182915999395742860178488690228
| null | null | null |
savannah
|
42fcd6693ec7bd6ffc65ddc63e74287a65dda669
| 1 |
T42_Face_Init( FT_Stream stream,
FT_Face t42face, /* T42_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
T42_Face face = (T42_Face)t42face;
FT_Error error;
FT_Service_PsCMaps psnames;
PSAux_Service psaux;
FT_Face root = (FT_Face)&face->root;
T1_Font type1 = &face->type1;
PS_FontInfo info = &type1->font_info;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_UNUSED( stream );
face->ttf_face = NULL;
face->root.num_faces = 1;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
face->psnames = psnames;
face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"psaux" );
psaux = (PSAux_Service)face->psaux;
if ( !psaux )
{
FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
FT_TRACE2(( "Type 42 driver\n" ));
/* open the tokenizer, this will also check the font format */
error = T42_Open_Face( face );
if ( error )
goto Exit;
/* if we just wanted to check the format, leave successfully now */
if ( face_index < 0 )
goto Exit;
/* check the face index */
if ( face_index > 0 )
{
FT_ERROR(( "T42_Face_Init: invalid face index\n" ));
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* Now load the font program into the face object */
/* Init the face object fields */
/* Now set up root face fields */
root->num_glyphs = type1->num_glyphs;
root->num_charmaps = 0;
root->face_index = 0;
root->face_flags |= FT_FACE_FLAG_SCALABLE |
FT_FACE_FLAG_HORIZONTAL |
FT_FACE_FLAG_GLYPH_NAMES;
if ( info->is_fixed_pitch )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
/* We only set this flag if we have the patented bytecode interpreter. */
/* There are no known `tricky' Type42 fonts that could be loaded with */
/* the unpatented interpreter. */
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
root->face_flags |= FT_FACE_FLAG_HINTER;
#endif
/* XXX: TODO -- add kerning with .afm support */
/* get style name -- be careful, some broken fonts only */
/* have a `/FontName' dictionary entry! */
root->family_name = info->family_name;
/* assume "Regular" style if we don't know better */
root->style_name = (char *)"Regular";
if ( root->family_name )
{
char* full = info->full_name;
char* family = root->family_name;
if ( full )
{
while ( *full )
{
if ( *full == *family )
{
family++;
full++;
}
else
{
if ( *full == ' ' || *full == '-' )
full++;
else if ( *family == ' ' || *family == '-' )
family++;
else
{
if ( !*family )
root->style_name = full;
break;
}
}
}
}
}
else
{
/* do we have a `/FontName'? */
if ( type1->font_name )
root->family_name = type1->font_name;
}
/* no embedded bitmap support */
root->num_fixed_sizes = 0;
root->available_sizes = 0;
/* Load the TTF font embedded in the T42 font */
{
FT_Open_Args args;
args.flags = FT_OPEN_MEMORY;
args.memory_base = face->ttf_data;
args.memory_size = face->ttf_size;
args.flags |= FT_OPEN_PARAMS;
args.num_params = num_params;
args.params = params;
}
error = FT_Open_Face( FT_FACE_LIBRARY( face ),
&args, 0, &face->ttf_face );
}
| 178,032 | 194 |
284802888516693989399704178152042676324
| null | null | null |
|
savannah
|
f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
| 1 |
tt_face_load_kern( TT_Face face,
FT_Stream stream )
{
FT_Error error;
FT_ULong table_size;
FT_Byte* p;
FT_Byte* p_limit;
FT_UInt nn, num_tables;
FT_UInt32 avail = 0, ordered = 0;
/* the kern table is optional; exit silently if it is missing */
error = face->goto_table( face, TTAG_kern, stream, &table_size );
if ( error )
goto Exit;
if ( table_size < 4 ) /* the case of a malformed table */
{
FT_ERROR(( "tt_face_load_kern:"
" kerning table is too small - ignored\n" ));
error = FT_THROW( Table_Missing );
goto Exit;
}
if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) )
{
FT_ERROR(( "tt_face_load_kern:"
" could not extract kerning table\n" ));
goto Exit;
}
face->kern_table_size = table_size;
p = face->kern_table;
p_limit = p + table_size;
p += 2; /* skip version */
num_tables = FT_NEXT_USHORT( p );
if ( num_tables > 32 ) /* we only support up to 32 sub-tables */
num_tables = 32;
for ( nn = 0; nn < num_tables; nn++ )
{
FT_UInt num_pairs, length, coverage;
FT_Byte* p_next;
FT_UInt32 mask = (FT_UInt32)1UL << nn;
if ( p + 6 > p_limit )
break;
p_next = p;
p += 2; /* skip version */
length = FT_NEXT_USHORT( p );
coverage = FT_NEXT_USHORT( p );
if ( length <= 6 )
break;
p_next += length;
if ( p_next > p_limit ) /* handle broken table */
p_next = p_limit;
/* only use horizontal kerning tables */
if ( ( coverage & ~8 ) != 0x0001 ||
p + 8 > p_limit )
goto NextTable;
num_pairs = FT_NEXT_USHORT( p );
p += 6;
if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */
num_pairs = (FT_UInt)( ( p_next - p ) / 6 );
avail |= mask;
/*
* Now check whether the pairs in this table are ordered.
* We then can use binary search.
*/
if ( num_pairs > 0 )
{
FT_ULong count;
FT_ULong old_pair;
old_pair = FT_NEXT_ULONG( p );
p += 2;
for ( count = num_pairs - 1; count > 0; count-- )
{
FT_UInt32 cur_pair;
cur_pair = FT_NEXT_ULONG( p );
if ( cur_pair <= old_pair )
break;
p += 2;
old_pair = cur_pair;
}
if ( count == 0 )
ordered |= mask;
}
NextTable:
p = p_next;
}
face->num_kern_tables = nn;
face->kern_avail_bits = avail;
face->kern_order_bits = ordered;
Exit:
return error;
}
|
CWE-125
| 178,037 | 199 |
223904594839516096150742880543791775725
| null | null | null |
savannah
|
f0292bb9920aa1dbfed5f53861e7c7a89b35833a
| 1 |
tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
|
CWE-119
| 178,038 | 200 |
28994602925432626900683012190657933065
| null | null | null |
savannah
|
3774fc08b502c3e685afca098b6e8a195aded6a0
| 1 |
ps_parser_to_token( PS_Parser parser,
T1_Token token )
{
FT_Byte* cur;
FT_Byte* limit;
FT_Int embed;
token->type = T1_TOKEN_TYPE_NONE;
token->start = NULL;
token->limit = NULL;
/* first of all, skip leading whitespace */
ps_parser_skip_spaces( parser );
cur = parser->cursor;
limit = parser->limit;
if ( cur >= limit )
return;
switch ( *cur )
{
/************* check for literal string *****************/
case '(':
token->type = T1_TOKEN_TYPE_STRING;
token->start = cur;
if ( skip_literal_string( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for programs/array *****************/
case '{':
token->type = T1_TOKEN_TYPE_ARRAY;
token->start = cur;
if ( skip_procedure( &cur, limit ) == FT_Err_Ok )
token->limit = cur;
break;
/************* check for table/array ********************/
/* XXX: in theory we should also look for "<<" */
/* since this is semantically equivalent to "["; */
/* in practice it doesn't matter (?) */
case '[':
token->type = T1_TOKEN_TYPE_ARRAY;
embed = 1;
token->start = cur++;
/* we need this to catch `[ ]' */
parser->cursor = cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
while ( cur < limit && !parser->error )
{
/* XXX: this is wrong because it does not */
/* skip comments, procedures, and strings */
if ( *cur == '[' )
embed++;
else if ( *cur == ']' )
{
embed--;
if ( embed <= 0 )
{
token->limit = ++cur;
break;
}
}
parser->cursor = cur;
ps_parser_skip_PS_token( parser );
/* we need this to catch `[XXX ]' */
ps_parser_skip_spaces ( parser );
cur = parser->cursor;
}
break;
/* ************ otherwise, it is any token **************/
default:
token->start = cur;
token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY;
ps_parser_skip_PS_token( parser );
cur = parser->cursor;
if ( !parser->error )
token->limit = cur;
}
if ( !token->limit )
{
token->start = NULL;
token->type = T1_TOKEN_TYPE_NONE;
}
parser->cursor = cur;
}
/* NB: `tokens' can be NULL if we only want to count */
/* the number of array elements */
FT_LOCAL_DEF( void )
ps_parser_to_token_array( PS_Parser parser,
T1_Token tokens,
FT_UInt max_tokens,
FT_Int* pnum_tokens )
{
T1_TokenRec master;
*pnum_tokens = -1;
/* this also handles leading whitespace */
ps_parser_to_token( parser, &master );
if ( master.type == T1_TOKEN_TYPE_ARRAY )
{
FT_Byte* old_cursor = parser->cursor;
FT_Byte* old_limit = parser->limit;
T1_Token cur = tokens;
T1_Token limit = cur + max_tokens;
/* don't include outermost delimiters */
parser->cursor = master.start + 1;
parser->limit = master.limit - 1;
while ( parser->cursor < parser->limit )
{
T1_TokenRec token;
ps_parser_to_token( parser, &token );
if ( !token.type )
break;
if ( tokens && cur < limit )
*cur = token;
cur++;
}
*pnum_tokens = (FT_Int)( cur - tokens );
parser->cursor = old_cursor;
parser->limit = old_limit;
}
}
/* first character must be a delimiter or a part of a number */
/* NB: `coords' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_coords' */
static FT_Int
ps_tocoordarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_coords,
FT_Short* coords )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* check for the beginning of an array; otherwise, only one number */
/* will be read */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the coordinates */
while ( cur < limit )
{
FT_Short dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( coords && count >= max_coords )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( coords ? &coords[count] : &dummy ) =
(FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
/* first character must be a delimiter or a part of a number */
/* NB: `values' can be NULL if we just want to skip the */
/* array; in this case we ignore `max_values' */
/* */
/* return number of successfully parsed values */
static FT_Int
ps_tofixedarray( FT_Byte* *acur,
FT_Byte* limit,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
FT_Byte* cur = *acur;
FT_Int count = 0;
FT_Byte c, ender;
if ( cur >= limit )
goto Exit;
/* Check for the beginning of an array. Otherwise, only one number */
/* will be read. */
c = *cur;
ender = 0;
if ( c == '[' )
ender = ']';
else if ( c == '{' )
ender = '}';
if ( ender )
cur++;
/* now, read the values */
while ( cur < limit )
{
FT_Fixed dummy;
FT_Byte* old_cur;
/* skip whitespace in front of data */
skip_spaces( &cur, limit );
if ( cur >= limit )
goto Exit;
if ( *cur == ender )
{
cur++;
break;
}
old_cur = cur;
if ( values && count >= max_values )
break;
/* call PS_Conv_ToFixed() even if coords == NULL */
/* to properly parse number at `cur' */
*( values ? &values[count] : &dummy ) =
PS_Conv_ToFixed( &cur, limit, power_ten );
if ( old_cur == cur )
{
count = -1;
goto Exit;
}
else
count++;
if ( !ender )
break;
}
Exit:
*acur = cur;
return count;
}
#if 0
static FT_String*
ps_tostring( FT_Byte** cursor,
FT_Byte* limit,
FT_Memory memory )
{
FT_Byte* cur = *cursor;
FT_UInt len = 0;
FT_Int count;
FT_String* result;
FT_Error error;
/* XXX: some stupid fonts have a `Notice' or `Copyright' string */
/* that simply doesn't begin with an opening parenthesis, even */
/* though they have a closing one! E.g. "amuncial.pfb" */
/* */
/* We must deal with these ill-fated cases there. Note that */
/* these fonts didn't work with the old Type 1 driver as the */
/* notice/copyright was not recognized as a valid string token */
/* and made the old token parser commit errors. */
while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) )
cur++;
if ( cur + 1 >= limit )
return 0;
if ( *cur == '(' )
cur++; /* skip the opening parenthesis, if there is one */
*cursor = cur;
count = 0;
/* then, count its length */
for ( ; cur < limit; cur++ )
{
if ( *cur == '(' )
count++;
else if ( *cur == ')' )
{
count--;
if ( count < 0 )
break;
}
}
len = (FT_UInt)( cur - *cursor );
if ( cur >= limit || FT_ALLOC( result, len + 1 ) )
return 0;
/* now copy the string */
FT_MEM_COPY( result, *cursor, len );
result[len] = '\0';
*cursor = cur;
return result;
}
#endif /* 0 */
static int
ps_tobool( FT_Byte* *acur,
FT_Byte* limit )
{
FT_Byte* cur = *acur;
FT_Bool result = 0;
/* return 1 if we find `true', 0 otherwise */
if ( cur + 3 < limit &&
cur[0] == 't' &&
cur[1] == 'r' &&
cur[2] == 'u' &&
cur[3] == 'e' )
{
result = 1;
cur += 5;
}
else if ( cur + 4 < limit &&
cur[0] == 'f' &&
cur[1] == 'a' &&
cur[2] == 'l' &&
cur[3] == 's' &&
cur[4] == 'e' )
{
result = 0;
cur += 6;
}
*acur = cur;
return result;
}
/* load a simple field (i.e. non-table) into the current list of objects */
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec token;
FT_Byte* cur;
FT_Byte* limit;
FT_UInt count;
FT_UInt idx;
FT_Error error;
T1_FieldType type;
/* this also skips leading whitespace */
ps_parser_to_token( parser, &token );
if ( !token.type )
goto Fail;
count = 1;
idx = 0;
cur = token.start;
limit = token.limit;
type = field->type;
/* we must detect arrays in /FontBBox */
if ( type == T1_FIELD_TYPE_BBOX )
{
T1_TokenRec token2;
FT_Byte* old_cur = parser->cursor;
FT_Byte* old_limit = parser->limit;
/* don't include delimiters */
parser->cursor = token.start + 1;
parser->limit = token.limit - 1;
ps_parser_to_token( parser, &token2 );
parser->cursor = old_cur;
parser->limit = old_limit;
if ( token2.type == T1_TOKEN_TYPE_ARRAY )
{
type = T1_FIELD_TYPE_MM_BBOX;
goto FieldArray;
}
}
else if ( token.type == T1_TOKEN_TYPE_ARRAY )
{
count = max_objects;
FieldArray:
/* if this is an array and we have no blend, an error occurs */
if ( max_objects == 0 )
goto Fail;
idx = 1;
/* don't include delimiters */
cur++;
limit--;
}
for ( ; count > 0; count--, idx++ )
{
FT_Byte* q = (FT_Byte*)objects[idx] + field->offset;
FT_Long val;
FT_String* string = NULL;
skip_spaces( &cur, limit );
switch ( type )
{
case T1_FIELD_TYPE_BOOL:
val = ps_tobool( &cur, limit );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED:
val = PS_Conv_ToFixed( &cur, limit, 0 );
goto Store_Integer;
case T1_FIELD_TYPE_FIXED_1000:
val = PS_Conv_ToFixed( &cur, limit, 3 );
goto Store_Integer;
case T1_FIELD_TYPE_INTEGER:
val = PS_Conv_ToInt( &cur, limit );
/* fall through */
Store_Integer:
switch ( field->size )
{
case (8 / FT_CHAR_BIT):
*(FT_Byte*)q = (FT_Byte)val;
break;
case (16 / FT_CHAR_BIT):
*(FT_UShort*)q = (FT_UShort)val;
break;
case (32 / FT_CHAR_BIT):
*(FT_UInt32*)q = (FT_UInt32)val;
break;
default: /* for 64-bit systems */
*(FT_Long*)q = val;
}
break;
case T1_FIELD_TYPE_STRING:
case T1_FIELD_TYPE_KEY:
{
FT_Memory memory = parser->memory;
FT_UInt len = (FT_UInt)( limit - cur );
if ( cur >= limit )
break;
/* we allow both a string or a name */
/* for cases like /FontName (foo) def */
if ( token.type == T1_TOKEN_TYPE_KEY )
{
/* don't include leading `/' */
len--;
cur++;
}
else if ( token.type == T1_TOKEN_TYPE_STRING )
{
/* don't include delimiting parentheses */
/* XXX we don't handle <<...>> here */
/* XXX should we convert octal escapes? */
/* if so, what encoding should we use? */
cur++;
len -= 2;
}
else
{
FT_ERROR(( "ps_parser_load_field:"
" expected a name or string\n"
" "
" but found token of type %d instead\n",
token.type ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* for this to work (FT_String**)q must have been */
/* initialized to NULL */
if ( *(FT_String**)q )
{
FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n",
field->ident ));
FT_FREE( *(FT_String**)q );
*(FT_String**)q = NULL;
}
if ( FT_ALLOC( string, len + 1 ) )
goto Exit;
FT_MEM_COPY( string, cur, len );
string[len] = 0;
*(FT_String**)q = string;
}
break;
case T1_FIELD_TYPE_BBOX:
{
FT_Fixed temp[4];
FT_BBox* bbox = (FT_BBox*)q;
FT_Int result;
result = ps_tofixedarray( &cur, limit, 4, temp, 0 );
if ( result < 4 )
{
FT_ERROR(( "ps_parser_load_field:"
" expected four integers in bounding box\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
bbox->xMin = FT_RoundFix( temp[0] );
bbox->yMin = FT_RoundFix( temp[1] );
bbox->xMax = FT_RoundFix( temp[2] );
bbox->yMax = FT_RoundFix( temp[3] );
}
break;
case T1_FIELD_TYPE_MM_BBOX:
{
FT_Memory memory = parser->memory;
FT_Fixed* temp = NULL;
FT_Int result;
FT_UInt i;
if ( FT_NEW_ARRAY( temp, max_objects * 4 ) )
goto Exit;
for ( i = 0; i < 4; i++ )
{
result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects,
temp + i * max_objects, 0 );
if ( result < 0 || (FT_UInt)result < max_objects )
{
FT_ERROR(( "ps_parser_load_field:"
" expected %d integer%s in the %s subarray\n"
" "
" of /FontBBox in the /Blend dictionary\n",
max_objects, max_objects > 1 ? "s" : "",
i == 0 ? "first"
: ( i == 1 ? "second"
: ( i == 2 ? "third"
: "fourth" ) ) ));
error = FT_THROW( Invalid_File_Format );
FT_FREE( temp );
goto Exit;
}
skip_spaces( &cur, limit );
}
for ( i = 0; i < max_objects; i++ )
{
FT_BBox* bbox = (FT_BBox*)objects[i];
bbox->xMin = FT_RoundFix( temp[i ] );
bbox->yMin = FT_RoundFix( temp[i + max_objects] );
bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] );
bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] );
}
FT_FREE( temp );
}
break;
default:
/* an error occurred */
goto Fail;
}
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
error = FT_Err_Ok;
Exit:
return error;
Fail:
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
#define T1_MAX_TABLE_ELEMENTS 32
FT_LOCAL_DEF( FT_Error )
ps_parser_load_field_table( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags )
{
T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS];
T1_Token token;
FT_Int num_elements;
FT_Error error = FT_Err_Ok;
FT_Byte* old_cursor;
FT_Byte* old_limit;
T1_FieldRec fieldrec = *(T1_Field)field;
fieldrec.type = T1_FIELD_TYPE_INTEGER;
if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY ||
field->type == T1_FIELD_TYPE_BBOX )
fieldrec.type = T1_FIELD_TYPE_FIXED;
ps_parser_to_token_array( parser, elements,
T1_MAX_TABLE_ELEMENTS, &num_elements );
if ( num_elements < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( (FT_UInt)num_elements > field->array_max )
num_elements = (FT_Int)field->array_max;
old_cursor = parser->cursor;
old_limit = parser->limit;
/* we store the elements count if necessary; */
/* we further assume that `count_offset' can't be zero */
if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 )
*(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) =
(FT_Byte)num_elements;
/* we now load each element, adjusting the field.offset on each one */
token = elements;
for ( ; num_elements > 0; num_elements--, token++ )
{
parser->cursor = token->start;
parser->limit = token->limit;
error = ps_parser_load_field( parser,
&fieldrec,
objects,
max_objects,
0 );
if ( error )
break;
fieldrec.offset += fieldrec.size;
}
#if 0 /* obsolete -- keep for reference */
if ( pflags )
*pflags |= 1L << field->flag_bit;
#else
FT_UNUSED( pflags );
#endif
parser->cursor = old_cursor;
parser->limit = old_limit;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Long )
ps_parser_to_int( PS_Parser parser )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToInt( &parser->cursor, parser->limit );
}
/* first character must be `<' if `delimiters' is non-zero */
FT_LOCAL_DEF( FT_Error )
ps_parser_to_bytes( PS_Parser parser,
FT_Byte* bytes,
FT_Offset max_bytes,
FT_ULong* pnum_bytes,
FT_Bool delimiters )
{
FT_Error error = FT_Err_Ok;
FT_Byte* cur;
ps_parser_skip_spaces( parser );
cur = parser->cursor;
if ( cur >= parser->limit )
goto Exit;
if ( delimiters )
{
if ( *cur != '<' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
*pnum_bytes = PS_Conv_ASCIIHexDecode( &cur,
parser->limit,
bytes,
max_bytes );
if ( delimiters )
{
if ( cur < parser->limit && *cur != '>' )
{
FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
cur++;
}
parser->cursor = cur;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Fixed )
ps_parser_to_fixed( PS_Parser parser,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_coord_array( PS_Parser parser,
FT_Int max_coords,
FT_Short* coords )
{
ps_parser_skip_spaces( parser );
return ps_tocoordarray( &parser->cursor, parser->limit,
max_coords, coords );
}
FT_LOCAL_DEF( FT_Int )
ps_parser_to_fixed_array( PS_Parser parser,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten )
{
ps_parser_skip_spaces( parser );
return ps_tofixedarray( &parser->cursor, parser->limit,
max_values, values, power_ten );
}
#if 0
FT_LOCAL_DEF( FT_String* )
T1_ToString( PS_Parser parser )
{
return ps_tostring( &parser->cursor, parser->limit, parser->memory );
}
FT_LOCAL_DEF( FT_Bool )
T1_ToBool( PS_Parser parser )
{
return ps_tobool( &parser->cursor, parser->limit );
}
#endif /* 0 */
FT_LOCAL_DEF( void )
ps_parser_init( PS_Parser parser,
FT_Byte* base,
FT_Byte* limit,
FT_Memory memory )
{
parser->error = FT_Err_Ok;
parser->base = base;
parser->limit = limit;
parser->cursor = base;
parser->memory = memory;
parser->funcs = ps_parser_funcs;
}
FT_LOCAL_DEF( void )
ps_parser_done( PS_Parser parser )
{
FT_UNUSED( parser );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* t1_builder_init */
/* */
/* <Description> */
/* Initializes a given glyph builder. */
/* */
/* <InOut> */
/* builder :: A pointer to the glyph builder to initialize. */
/* */
/* <Input> */
/* face :: The current face object. */
/* */
/* size :: The current size object. */
/* */
/* glyph :: The current glyph object. */
/* */
/* hinting :: Whether hinting should be applied. */
/* */
FT_LOCAL_DEF( void )
t1_builder_init( T1_Builder builder,
FT_Face face,
FT_Size size,
FT_GlyphSlot glyph,
FT_Bool hinting )
{
builder->parse_state = T1_Parse_Start;
builder->load_points = 1;
builder->face = face;
builder->glyph = glyph;
builder->memory = face->memory;
if ( glyph )
{
FT_GlyphLoader loader = glyph->internal->loader;
builder->loader = loader;
builder->base = &loader->base.outline;
builder->current = &loader->current.outline;
FT_GlyphLoader_Rewind( loader );
builder->hints_globals = size->internal;
builder->hints_funcs = NULL;
if ( hinting )
builder->hints_funcs = glyph->internal->glyph_hints;
}
builder->pos_x = 0;
builder->pos_y = 0;
builder->left_bearing.x = 0;
builder->left_bearing.y = 0;
builder->advance.x = 0;
builder->advance.y = 0;
builder->funcs = t1_builder_funcs;
}
/*************************************************************************/
/* */
/* <Function> */
/* t1_builder_done */
/* */
/* <Description> */
/* Finalizes a given glyph builder. Its contents can still be used */
/* after the call, but the function saves important information */
/* within the corresponding glyph slot. */
/* */
/* <Input> */
/* builder :: A pointer to the glyph builder to finalize. */
/* */
FT_LOCAL_DEF( void )
t1_builder_done( T1_Builder builder )
{
FT_GlyphSlot glyph = builder->glyph;
if ( glyph )
glyph->outline = *builder->base;
}
/* check that there is enough space for `count' more points */
FT_LOCAL_DEF( FT_Error )
t1_builder_check_points( T1_Builder builder,
FT_Int count )
{
return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 );
}
/* add a new point, do not check space */
FT_LOCAL_DEF( void )
t1_builder_add_point( T1_Builder builder,
FT_Pos x,
FT_Pos y,
FT_Byte flag )
{
FT_Outline* outline = builder->current;
if ( builder->load_points )
{
FT_Vector* point = outline->points + outline->n_points;
FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points;
point->x = FIXED_TO_INT( x );
point->y = FIXED_TO_INT( y );
*control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC );
}
outline->n_points++;
}
/* check space for a new on-curve point, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_point1( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error;
error = t1_builder_check_points( builder, 1 );
if ( !error )
t1_builder_add_point( builder, x, y, 1 );
return error;
}
/* check space for a new contour, then add it */
FT_LOCAL_DEF( FT_Error )
t1_builder_add_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Error error;
/* this might happen in invalid fonts */
if ( !outline )
{
FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" ));
return FT_THROW( Invalid_File_Format );
}
if ( !builder->load_points )
{
outline->n_contours++;
return FT_Err_Ok;
}
error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 );
if ( !error )
{
if ( outline->n_contours > 0 )
outline->contours[outline->n_contours - 1] =
(short)( outline->n_points - 1 );
outline->n_contours++;
}
return error;
}
/* if a path was begun, add its first on-curve point */
FT_LOCAL_DEF( FT_Error )
t1_builder_start_point( T1_Builder builder,
FT_Pos x,
FT_Pos y )
{
FT_Error error = FT_ERR( Invalid_File_Format );
/* test whether we are building a new contour */
if ( builder->parse_state == T1_Parse_Have_Path )
error = FT_Err_Ok;
else
{
builder->parse_state = T1_Parse_Have_Path;
error = t1_builder_add_contour( builder );
if ( !error )
error = t1_builder_add_point1( builder, x, y );
}
return error;
}
/* close the current contour */
FT_LOCAL_DEF( void )
t1_builder_close_contour( T1_Builder builder )
{
FT_Outline* outline = builder->current;
FT_Int first;
if ( !outline )
return;
first = outline->n_contours <= 1
? 0 : outline->contours[outline->n_contours - 2] + 1;
/* We must not include the last point in the path if it */
/* is located on the first point. */
if ( outline->n_points > 1 )
if ( p1->x == p2->x && p1->y == p2->y )
if ( *control == FT_CURVE_TAG_ON )
outline->n_points--;
}
if ( outline->n_contours > 0 )
{
/* Don't add contours only consisting of one point, i.e., */
/* check whether the first and the last point is the same. */
if ( first == outline->n_points - 1 )
{
outline->n_contours--;
outline->n_points--;
}
else
outline->contours[outline->n_contours - 1] =
(short)( outline->n_points - 1 );
}
}
|
CWE-119
| 178,047 | 204 |
328688916561979850895211877372718866822
| null | null | null |
savannah
|
f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
| 1 |
t1_decoder_parse_charstrings( T1_Decoder decoder,
FT_Byte* charstring_base,
FT_UInt charstring_len )
{
FT_Error error;
T1_Decoder_Zone zone;
FT_Byte* ip;
FT_Byte* limit;
T1_Builder builder = &decoder->builder;
FT_Pos x, y, orig_x, orig_y;
FT_Int known_othersubr_result_cnt = 0;
FT_Int unknown_othersubr_result_cnt = 0;
FT_Bool large_int;
FT_Fixed seed;
T1_Hints_Funcs hinter;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_Bool bol = TRUE;
#endif
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^
(FT_Offset)(char*)&decoder ^
(FT_Offset)(char*)&charstring_base ) &
FT_ULONG_MAX );
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* First of all, initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
builder->parse_state = T1_Parse_Start;
hinter = (T1_Hints_Funcs)builder->hints_funcs;
/* a font that reads BuildCharArray without setting */
/* its values first is buggy, but ... */
FT_ASSERT( ( decoder->len_buildchar == 0 ) ==
( decoder->buildchar == NULL ) );
if ( decoder->buildchar && decoder->len_buildchar > 0 )
FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar );
FT_TRACE4(( "\n"
"Start charstring\n" ));
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = FT_Err_Ok;
x = orig_x = builder->pos_x;
y = orig_y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
large_int = FALSE;
/* now, execute loop */
while ( ip < limit )
{
FT_Long* top = decoder->top;
T1_Operator op = op_none;
FT_Int32 value = 0;
FT_ASSERT( known_othersubr_result_cnt == 0 ||
unknown_othersubr_result_cnt == 0 );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( bol )
{
FT_TRACE5(( " (%d)", decoder->top - decoder->stack ));
bol = FALSE;
}
#endif
/*********************************************************************/
/* */
/* Decode operator or operand */
/* */
/* */
/* first of all, decompress operator or value */
switch ( *ip++ )
{
case 1:
op = op_hstem;
break;
case 3:
op = op_vstem;
break;
case 4:
op = op_vmoveto;
break;
case 5:
op = op_rlineto;
break;
case 6:
op = op_hlineto;
break;
case 7:
op = op_vlineto;
break;
case 8:
op = op_rrcurveto;
break;
case 9:
op = op_closepath;
break;
case 10:
op = op_callsubr;
break;
case 11:
op = op_return;
break;
case 13:
op = op_hsbw;
break;
case 14:
op = op_endchar;
break;
case 15: /* undocumented, obsolete operator */
op = op_unknown15;
break;
case 21:
op = op_rmoveto;
break;
case 22:
op = op_hmoveto;
break;
case 30:
op = op_vhcurveto;
break;
case 31:
op = op_hvcurveto;
break;
case 12:
if ( ip >= limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+EOF)\n" ));
goto Syntax_Error;
}
switch ( *ip++ )
{
case 0:
op = op_dotsection;
break;
case 1:
op = op_vstem3;
break;
case 2:
op = op_hstem3;
break;
case 6:
op = op_seac;
break;
case 7:
op = op_sbw;
break;
case 12:
op = op_div;
break;
case 16:
op = op_callothersubr;
break;
case 17:
op = op_pop;
break;
case 33:
op = op_setcurrentpoint;
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid escape (12+%d)\n",
ip[-1] ));
goto Syntax_Error;
}
break;
case 255: /* four bytes integer */
if ( ip + 4 > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) |
( (FT_UInt32)ip[1] << 16 ) |
( (FT_UInt32)ip[2] << 8 ) |
(FT_UInt32)ip[3] );
ip += 4;
/* According to the specification, values > 32000 or < -32000 must */
/* be followed by a `div' operator to make the result be in the */
/* range [-32000;32000]. We expect that the second argument of */
/* `div' is not a large number. Additionally, we don't handle */
/* stuff like `<large1> <large2> <num> div <num> div' or */
/* <large1> <large2> <num> div div'. This is probably not allowed */
/* anyway. */
if ( value > 32000 || value < -32000 )
{
if ( large_int )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
}
else
large_int = TRUE;
}
else
{
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
break;
default:
if ( ip[-1] >= 32 )
{
if ( ip[-1] < 247 )
value = (FT_Int32)ip[-1] - 139;
else
{
if ( ++ip > limit )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected EOF in integer\n" ));
goto Syntax_Error;
}
if ( ip[-2] < 251 )
value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108;
else
value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 );
}
if ( !large_int )
value = (FT_Int32)( (FT_UInt32)value << 16 );
}
else
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid byte (%d)\n", ip[-1] ));
goto Syntax_Error;
}
}
if ( unknown_othersubr_result_cnt > 0 )
{
switch ( op )
{
case op_callsubr:
case op_return:
case op_none:
case op_pop:
break;
default:
/* all operands have been transferred by previous pops */
unknown_othersubr_result_cnt = 0;
break;
}
}
if ( large_int && !( op == op_none || op == op_div ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no `div' after large integer\n" ));
large_int = FALSE;
}
/*********************************************************************/
/* */
/* Push value on stack, or process operator */
/* */
/* */
if ( op == op_none )
{
if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS )
{
FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" ));
goto Syntax_Error;
}
#ifdef FT_DEBUG_LEVEL_TRACE
if ( large_int )
FT_TRACE4(( " %d", value ));
else
FT_TRACE4(( " %d", value / 65536 ));
#endif
*top++ = value;
decoder->top = top;
}
else if ( op == op_callothersubr ) /* callothersubr */
{
FT_Int subr_no;
FT_Int arg_cnt;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( " callothersubr\n" ));
bol = TRUE;
#endif
if ( top - decoder->stack < 2 )
goto Stack_Underflow;
top -= 2;
subr_no = Fix2Int( top[1] );
arg_cnt = Fix2Int( top[0] );
/***********************************************************/
/* */
/* remove all operands to callothersubr from the stack */
/* */
/* for handled othersubrs, where we know the number of */
/* arguments, we increase the stack by the value of */
/* known_othersubr_result_cnt */
/* */
/* for unhandled othersubrs the following pops adjust the */
/* stack pointer as necessary */
if ( arg_cnt > top - decoder->stack )
goto Stack_Underflow;
top -= arg_cnt;
known_othersubr_result_cnt = 0;
unknown_othersubr_result_cnt = 0;
/* XXX TODO: The checks to `arg_count == <whatever>' */
/* might not be correct; an othersubr expects a certain */
/* number of operands on the PostScript stack (as opposed */
/* to the T1 stack) but it doesn't have to put them there */
/* by itself; previous othersubrs might have left the */
/* operands there if they were not followed by an */
/* appropriate number of pops */
/* */
/* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */
/* accept a font that contains charstrings like */
/* */
/* 100 200 2 20 callothersubr */
/* 300 1 20 callothersubr pop */
/* */
/* Perhaps this is the reason why BuildCharArray exists. */
switch ( subr_no )
{
case 0: /* end flex feature */
if ( arg_cnt != 3 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state ||
decoder->num_flex_vectors != 7 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected flex end\n" ));
goto Syntax_Error;
}
/* the two `results' are popped by the following setcurrentpoint */
top[0] = x;
top[1] = y;
known_othersubr_result_cnt = 2;
break;
case 1: /* start flex feature */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) )
goto Fail;
decoder->flex_state = 1;
decoder->num_flex_vectors = 0;
break;
case 2: /* add flex vectors */
{
FT_Int idx;
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
if ( !decoder->flex_state )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" missing flex start\n" ));
goto Syntax_Error;
}
/* note that we should not add a point for index 0; */
/* this will move our current position to the flex */
/* point without adding any point to the outline */
idx = decoder->num_flex_vectors++;
if ( idx > 0 && idx < 7 )
t1_builder_add_point( builder,
x,
y,
(FT_Byte)( idx == 3 || idx == 6 ) );
}
break;
break;
case 12:
case 13:
/* counter control hints, clear stack */
top = decoder->stack;
break;
case 14:
case 15:
case 16:
case 17:
case 18: /* multiple masters */
{
PS_Blend blend = decoder->blend;
FT_UInt num_points, nn, mm;
FT_Long* delta;
FT_Long* values;
if ( !blend )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected multiple masters operator\n" ));
goto Syntax_Error;
}
num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 );
if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" incorrect number of multiple masters arguments\n" ));
goto Syntax_Error;
}
/* We want to compute */
/* */
/* a0*w0 + a1*w1 + ... + ak*wk */
/* */
/* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */
/* */
/* However, given that w0 + w1 + ... + wk == 1, we can */
/* rewrite it easily as */
/* */
/* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */
/* */
/* where k == num_designs-1. */
/* */
/* I guess that's why it's written in this `compact' */
/* form. */
/* */
delta = top + num_points;
values = top;
for ( nn = 0; nn < num_points; nn++ )
{
FT_Long tmp = values[0];
for ( mm = 1; mm < blend->num_designs; mm++ )
tmp += FT_MulFix( *delta++, blend->weight_vector[mm] );
*values++ = tmp;
}
known_othersubr_result_cnt = (FT_Int)num_points;
break;
}
case 19:
/* <idx> 1 19 callothersubr */
/* => replace elements starting from index cvi( <idx> ) */
/* of BuildCharArray with WeightVector */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 ||
(FT_UInt)idx + blend->num_designs > decoder->len_buildchar )
goto Unexpected_OtherSubr;
ft_memcpy( &decoder->buildchar[idx],
blend->weight_vector,
blend->num_designs *
sizeof ( blend->weight_vector[0] ) );
}
break;
case 20:
/* <arg1> <arg2> 2 20 callothersubr pop */
/* ==> push <arg1> + <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] += top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 21:
/* <arg1> <arg2> 2 21 callothersubr pop */
/* ==> push <arg1> - <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] -= top[1]; /* XXX (over|under)flow */
known_othersubr_result_cnt = 1;
break;
case 22:
/* <arg1> <arg2> 2 22 callothersubr pop */
/* ==> push <arg1> * <arg2> onto T1 stack */
if ( arg_cnt != 2 )
goto Unexpected_OtherSubr;
top[0] = FT_MulFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 23:
/* <arg1> <arg2> 2 23 callothersubr pop */
/* ==> push <arg1> / <arg2> onto T1 stack */
if ( arg_cnt != 2 || top[1] == 0 )
goto Unexpected_OtherSubr;
top[0] = FT_DivFix( top[0], top[1] );
known_othersubr_result_cnt = 1;
break;
case 24:
/* <val> <idx> 2 24 callothersubr */
/* ==> set BuildCharArray[cvi( <idx> )] = <val> */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 2 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[1] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
decoder->buildchar[idx] = top[0];
}
break;
case 25:
/* <idx> 1 25 callothersubr pop */
/* ==> push BuildCharArray[cvi( idx )] */
/* onto T1 stack */
{
FT_Int idx;
PS_Blend blend = decoder->blend;
if ( arg_cnt != 1 || !blend )
goto Unexpected_OtherSubr;
idx = Fix2Int( top[0] );
if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar )
goto Unexpected_OtherSubr;
top[0] = decoder->buildchar[idx];
}
known_othersubr_result_cnt = 1;
break;
#if 0
case 26:
/* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */
/* leave mark on T1 stack */
/* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */
XXX which routine has left its mark on the (PostScript) stack?;
break;
#endif
case 27:
/* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */
/* ==> push <res1> onto T1 stack if <val1> <= <val2>, */
/* otherwise push <res2> */
if ( arg_cnt != 4 )
goto Unexpected_OtherSubr;
if ( top[2] > top[3] )
top[0] = top[1];
known_othersubr_result_cnt = 1;
break;
case 28:
/* 0 28 callothersubr pop */
/* => push random value from interval [0, 1) onto stack */
if ( arg_cnt != 0 )
goto Unexpected_OtherSubr;
{
FT_Fixed Rand;
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
top[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
}
known_othersubr_result_cnt = 1;
break;
default:
if ( arg_cnt >= 0 && subr_no >= 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unknown othersubr [%d %d], wish me luck\n",
arg_cnt, subr_no ));
unknown_othersubr_result_cnt = arg_cnt;
break;
}
/* fall through */
Unexpected_OtherSubr:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid othersubr [%d %d]\n", arg_cnt, subr_no ));
goto Syntax_Error;
}
top += known_othersubr_result_cnt;
decoder->top = top;
}
else /* general operator */
{
FT_Int num_args = t1_args_count[op];
FT_ASSERT( num_args >= 0 );
if ( top - decoder->stack < num_args )
goto Stack_Underflow;
/* XXX Operators usually take their operands from the */
/* bottom of the stack, i.e., the operands are */
/* decoder->stack[0], ..., decoder->stack[num_args - 1]; */
/* only div, callsubr, and callothersubr are different. */
/* In practice it doesn't matter (?). */
#ifdef FT_DEBUG_LEVEL_TRACE
switch ( op )
{
case op_callsubr:
case op_div:
case op_callothersubr:
case op_pop:
case op_return:
break;
default:
if ( top - decoder->stack != num_args )
FT_TRACE0(( "t1_decoder_parse_charstrings:"
" too much operands on the stack"
" (seen %d, expected %d)\n",
top - decoder->stack, num_args ));
break;
}
#endif /* FT_DEBUG_LEVEL_TRACE */
top -= num_args;
switch ( op )
{
case op_endchar:
FT_TRACE4(( " endchar\n" ));
t1_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints,
(FT_UInt)builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
error = hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
if ( error )
goto Fail;
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* the compiler should optimize away this empty loop but ... */
#ifdef FT_DEBUG_LEVEL_TRACE
if ( decoder->len_buildchar > 0 )
{
FT_UInt i;
FT_TRACE4(( "BuildCharArray = [ " ));
for ( i = 0; i < decoder->len_buildchar; i++ )
FT_TRACE4(( "%d ", decoder->buildchar[i] ));
FT_TRACE4(( "]\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
FT_TRACE4(( "\n" ));
/* return now! */
return FT_Err_Ok;
case op_hsbw:
FT_TRACE4(( " hsbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->advance.x = top[1];
builder->advance.y = 0;
orig_x = x = builder->pos_x + top[0];
orig_y = y = builder->pos_y;
FT_UNUSED( orig_y );
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_seac:
return t1operator_seac( decoder,
top[0],
top[1],
top[2],
Fix2Int( top[3] ),
Fix2Int( top[4] ) );
case op_sbw:
FT_TRACE4(( " sbw" ));
builder->parse_state = T1_Parse_Have_Width;
builder->left_bearing.x += top[0];
builder->left_bearing.y += top[1];
builder->advance.x = top[2];
builder->advance.y = top[3];
x = builder->pos_x + top[0];
y = builder->pos_y + top[1];
/* the `metrics_only' indicates that we only want to compute */
/* the glyph's metrics (lsb + advance width), not load the */
/* rest of it; so exit immediately */
if ( builder->metrics_only )
return FT_Err_Ok;
break;
case op_closepath:
FT_TRACE4(( " closepath" ));
/* if there is no path, `closepath' is a no-op */
if ( builder->parse_state == T1_Parse_Have_Path ||
builder->parse_state == T1_Parse_Have_Moveto )
t1_builder_close_contour( builder );
builder->parse_state = T1_Parse_Have_Width;
break;
case op_hlineto:
FT_TRACE4(( " hlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
goto Add_Line;
case op_hmoveto:
FT_TRACE4(( " hmoveto" ));
x += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_hvcurveto:
FT_TRACE4(( " hvcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
y += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_rlineto:
FT_TRACE4(( " rlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
x += top[0];
y += top[1];
Add_Line:
if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) )
goto Fail;
break;
case op_rmoveto:
FT_TRACE4(( " rmoveto" ));
x += top[0];
y += top[1];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_rrcurveto:
FT_TRACE4(( " rrcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
x += top[0];
y += top[1];
t1_builder_add_point( builder, x, y, 0 );
x += top[2];
y += top[3];
t1_builder_add_point( builder, x, y, 0 );
x += top[4];
y += top[5];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vhcurveto:
FT_TRACE4(( " vhcurveto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ||
FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) )
goto Fail;
y += top[0];
t1_builder_add_point( builder, x, y, 0 );
x += top[1];
y += top[2];
t1_builder_add_point( builder, x, y, 0 );
x += top[3];
t1_builder_add_point( builder, x, y, 1 );
break;
case op_vlineto:
FT_TRACE4(( " vlineto" ));
if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) )
goto Fail;
y += top[0];
goto Add_Line;
case op_vmoveto:
FT_TRACE4(( " vmoveto" ));
y += top[0];
if ( !decoder->flex_state )
{
if ( builder->parse_state == T1_Parse_Start )
goto Syntax_Error;
builder->parse_state = T1_Parse_Have_Moveto;
}
break;
case op_div:
FT_TRACE4(( " div" ));
/* if `large_int' is set, we divide unscaled numbers; */
/* otherwise, we divide numbers in 16.16 format -- */
/* in both cases, it is the same operation */
*top = FT_DivFix( top[0], top[1] );
top++;
large_int = FALSE;
break;
case op_callsubr:
{
FT_Int idx;
FT_TRACE4(( " callsubr" ));
idx = Fix2Int( top[0] );
if ( decoder->subrs_hash )
{
size_t* val = ft_hash_num_lookup( idx,
decoder->subrs_hash );
if ( val )
idx = *val;
else
idx = -1;
}
if ( idx < 0 || idx >= decoder->num_subrs )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invalid subrs index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
/* The Type 1 driver stores subroutines without the seed bytes. */
/* The CID driver stores subroutines with seed bytes. This */
/* case is taken care of when decoder->subrs_len == 0. */
zone->base = decoder->subrs[idx];
if ( decoder->subrs_len )
zone->limit = zone->base + decoder->subrs_len[idx];
else
{
/* We are using subroutines from a CID font. We must adjust */
/* for the seed bytes. */
zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 );
zone->limit = decoder->subrs[idx + 1];
}
zone->cursor = zone->base;
if ( !zone->base )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
break;
}
case op_pop:
FT_TRACE4(( " pop" ));
if ( known_othersubr_result_cnt > 0 )
{
known_othersubr_result_cnt--;
/* ignore, we pushed the operands ourselves */
break;
}
if ( unknown_othersubr_result_cnt == 0 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" no more operands for othersubr\n" ));
goto Syntax_Error;
}
unknown_othersubr_result_cnt--;
top++; /* `push' the operand to callothersubr onto the stack */
break;
case op_return:
FT_TRACE4(( " return" ));
if ( zone <= decoder->zones )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
zone--;
ip = zone->cursor;
limit = zone->limit;
decoder->zone = zone;
break;
case op_dotsection:
FT_TRACE4(( " dotsection" ));
break;
case op_hstem:
FT_TRACE4(( " hstem" ));
/* record horizontal hint */
if ( hinter )
{
/* top[0] += builder->left_bearing.y; */
hinter->stem( hinter->hints, 1, top );
}
break;
case op_hstem3:
FT_TRACE4(( " hstem3" ));
/* record horizontal counter-controlled hints */
if ( hinter )
hinter->stem3( hinter->hints, 1, top );
break;
case op_vstem:
FT_TRACE4(( " vstem" ));
/* record vertical hint */
if ( hinter )
{
top[0] += orig_x;
hinter->stem( hinter->hints, 0, top );
}
break;
case op_vstem3:
FT_TRACE4(( " vstem3" ));
/* record vertical counter-controlled hints */
if ( hinter )
{
FT_Pos dx = orig_x;
top[0] += dx;
top[2] += dx;
top[4] += dx;
hinter->stem3( hinter->hints, 0, top );
}
break;
case op_setcurrentpoint:
FT_TRACE4(( " setcurrentpoint" ));
/* From the T1 specification, section 6.4: */
/* */
/* The setcurrentpoint command is used only in */
/* conjunction with results from OtherSubrs procedures. */
/* known_othersubr_result_cnt != 0 is already handled */
/* above. */
/* Note, however, that both Ghostscript and Adobe */
/* Distiller handle this situation by silently ignoring */
/* the inappropriate `setcurrentpoint' instruction. So */
/* we do the same. */
#if 0
if ( decoder->flex_state != 1 )
{
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unexpected `setcurrentpoint'\n" ));
goto Syntax_Error;
}
else
...
#endif
x = top[0];
y = top[1];
decoder->flex_state = 0;
break;
case op_unknown15:
FT_TRACE4(( " opcode_15" ));
/* nothing to do except to pop the two arguments */
break;
default:
FT_ERROR(( "t1_decoder_parse_charstrings:"
" unhandled opcode %d\n", op ));
goto Syntax_Error;
}
/* XXX Operators usually clear the operand stack; */
/* only div, callsubr, callothersubr, pop, and */
/* return are different. */
/* In practice it doesn't matter (?). */
decoder->top = top;
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE4(( "\n" ));
bol = TRUE;
#endif
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
return FT_THROW( Syntax_Error );
Stack_Underflow:
return FT_THROW( Stack_Underflow );
}
|
CWE-787
| 178,056 | 211 |
173319081189597155474138387684978602892
| null | null | null |
dbus
|
7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
| 1 |
validate_body_helper (DBusTypeReader *reader,
int byte_order,
dbus_bool_t walk_reader_to_end,
const unsigned char *p,
const unsigned char *end,
const unsigned char **new_p)
{
int current_type;
while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID)
{
const unsigned char *a;
case DBUS_TYPE_BYTE:
++p;
break;
case DBUS_TYPE_BOOLEAN:
case DBUS_TYPE_INT16:
case DBUS_TYPE_UINT16:
case DBUS_TYPE_INT32:
case DBUS_TYPE_UINT32:
case DBUS_TYPE_UNIX_FD:
case DBUS_TYPE_INT64:
case DBUS_TYPE_UINT64:
case DBUS_TYPE_DOUBLE:
alignment = _dbus_type_get_alignment (current_type);
a = _DBUS_ALIGN_ADDRESS (p, alignment);
if (a >= end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
if (current_type == DBUS_TYPE_BOOLEAN)
{
dbus_uint32_t v = _dbus_unpack_uint32 (byte_order,
p);
if (!(v == 0 || v == 1))
return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
}
p += alignment;
break;
case DBUS_TYPE_ARRAY:
case DBUS_TYPE_STRING:
case DBUS_TYPE_OBJECT_PATH:
{
dbus_uint32_t claimed_len;
a = _DBUS_ALIGN_ADDRESS (p, 4);
if (a + 4 > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
claimed_len = _dbus_unpack_uint32 (byte_order, p);
p += 4;
/* p may now be == end */
_dbus_assert (p <= end);
if (current_type == DBUS_TYPE_ARRAY)
{
int array_elem_type = _dbus_type_reader_get_element_type (reader);
if (!_dbus_type_is_valid (array_elem_type))
{
return DBUS_INVALID_UNKNOWN_TYPECODE;
}
alignment = _dbus_type_get_alignment (array_elem_type);
a = _DBUS_ALIGN_ADDRESS (p, alignment);
/* a may now be == end */
if (a > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
}
if (claimed_len > (unsigned long) (end - p))
return DBUS_INVALID_LENGTH_OUT_OF_BOUNDS;
if (current_type == DBUS_TYPE_OBJECT_PATH)
{
DBusString str;
_dbus_string_init_const_len (&str, p, claimed_len);
if (!_dbus_validate_path (&str, 0,
_dbus_string_get_length (&str)))
return DBUS_INVALID_BAD_PATH;
p += claimed_len;
}
else if (current_type == DBUS_TYPE_STRING)
{
DBusString str;
_dbus_string_init_const_len (&str, p, claimed_len);
if (!_dbus_string_validate_utf8 (&str, 0,
_dbus_string_get_length (&str)))
return DBUS_INVALID_BAD_UTF8_IN_STRING;
p += claimed_len;
}
else if (current_type == DBUS_TYPE_ARRAY && claimed_len > 0)
{
DBusTypeReader sub;
DBusValidity validity;
const unsigned char *array_end;
int array_elem_type;
if (claimed_len > DBUS_MAXIMUM_ARRAY_LENGTH)
return DBUS_INVALID_ARRAY_LENGTH_EXCEEDS_MAXIMUM;
/* Remember that the reader is types only, so we can't
* use it to iterate over elements. It stays the same
* for all elements.
*/
_dbus_type_reader_recurse (reader, &sub);
array_end = p + claimed_len;
array_elem_type = _dbus_type_reader_get_element_type (reader);
/* avoid recursive call to validate_body_helper if this is an array
* of fixed-size elements
*/
if (dbus_type_is_fixed (array_elem_type))
{
/* bools need to be handled differently, because they can
* have an invalid value
*/
if (array_elem_type == DBUS_TYPE_BOOLEAN)
{
dbus_uint32_t v;
alignment = _dbus_type_get_alignment (array_elem_type);
while (p < array_end)
{
v = _dbus_unpack_uint32 (byte_order, p);
if (!(v == 0 || v == 1))
return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE;
p += alignment;
}
}
else
{
p = array_end;
}
}
else
{
while (p < array_end)
{
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
}
if (p != array_end)
return DBUS_INVALID_ARRAY_LENGTH_INCORRECT;
}
/* check nul termination */
{
while (p < array_end)
{
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
}
break;
case DBUS_TYPE_SIGNATURE:
{
dbus_uint32_t claimed_len;
DBusString str;
DBusValidity validity;
claimed_len = *p;
++p;
/* 1 is for nul termination */
if (claimed_len + 1 > (unsigned long) (end - p))
return DBUS_INVALID_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
_dbus_string_init_const_len (&str, p, claimed_len);
validity =
_dbus_validate_signature_with_reason (&str, 0,
_dbus_string_get_length (&str));
if (validity != DBUS_VALID)
return validity;
p += claimed_len;
_dbus_assert (p < end);
if (*p != DBUS_TYPE_INVALID)
return DBUS_INVALID_SIGNATURE_MISSING_NUL;
++p;
_dbus_verbose ("p = %p end = %p claimed_len %u\n", p, end, claimed_len);
}
break;
case DBUS_TYPE_VARIANT:
{
/* 1 byte sig len, sig typecodes, align to
* contained-type-boundary, values.
*/
/* In addition to normal signature validation, we need to be sure
* the signature contains only a single (possibly container) type.
*/
dbus_uint32_t claimed_len;
DBusString sig;
DBusTypeReader sub;
DBusValidity validity;
int contained_alignment;
int contained_type;
DBusValidity reason;
claimed_len = *p;
++p;
/* + 1 for nul */
if (claimed_len + 1 > (unsigned long) (end - p))
return DBUS_INVALID_VARIANT_SIGNATURE_LENGTH_OUT_OF_BOUNDS;
_dbus_string_init_const_len (&sig, p, claimed_len);
reason = _dbus_validate_signature_with_reason (&sig, 0,
_dbus_string_get_length (&sig));
if (!(reason == DBUS_VALID))
{
if (reason == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
return reason;
else
return DBUS_INVALID_VARIANT_SIGNATURE_BAD;
}
p += claimed_len;
if (*p != DBUS_TYPE_INVALID)
return DBUS_INVALID_VARIANT_SIGNATURE_MISSING_NUL;
++p;
contained_type = _dbus_first_type_in_signature (&sig, 0);
if (contained_type == DBUS_TYPE_INVALID)
return DBUS_INVALID_VARIANT_SIGNATURE_EMPTY;
contained_alignment = _dbus_type_get_alignment (contained_type);
a = _DBUS_ALIGN_ADDRESS (p, contained_alignment);
if (a > end)
return DBUS_INVALID_NOT_ENOUGH_DATA;
while (p != a)
{
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
_dbus_type_reader_init_types_only (&sub, &sig, 0);
_dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
if (_dbus_type_reader_next (&sub))
return DBUS_INVALID_VARIANT_SIGNATURE_SPECIFIES_MULTIPLE_VALUES;
_dbus_assert (_dbus_type_reader_get_current_type (&sub) == DBUS_TYPE_INVALID);
}
break;
case DBUS_TYPE_DICT_ENTRY:
case DBUS_TYPE_STRUCT:
_dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID);
validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
if (*p != '\0')
return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL;
++p;
}
_dbus_type_reader_recurse (reader, &sub);
validity = validate_body_helper (&sub, byte_order, TRUE, p, end, &p);
if (validity != DBUS_VALID)
return validity;
}
break;
default:
_dbus_assert_not_reached ("invalid typecode in supposedly-validated signature");
break;
}
|
CWE-399
| 178,058 | 212 |
293803507783746447357509233379751643676
| null | null | null |
savannah
|
e6699596af5c5d6f0ae0ea06e19df87dce088df8
| 1 |
tt_size_reset( TT_Size size,
FT_Bool only_height )
{
TT_Face face;
FT_Size_Metrics* metrics;
size->ttmetrics.valid = FALSE;
face = (TT_Face)size->root.face;
metrics = &size->metrics;
/* copy the result from base layer */
/* This bit flag, if set, indicates that the ppems must be */
/* rounded to integers. Nearly all TrueType fonts have this bit */
/* set, as hinting won't work really well otherwise. */
/* */
if ( face->header.Flags & 8 )
{
metrics->ascender =
FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) );
metrics->descender =
FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) );
metrics->height =
FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) );
}
size->ttmetrics.valid = TRUE;
if ( only_height )
return FT_Err_Ok;
if ( face->header.Flags & 8 )
{
metrics->x_scale = FT_DivFix( metrics->x_ppem << 6,
face->root.units_per_EM );
metrics->y_scale = FT_DivFix( metrics->y_ppem << 6,
face->root.units_per_EM );
metrics->max_advance =
FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width,
metrics->x_scale ) );
}
/* compute new transformation */
if ( metrics->x_ppem >= metrics->y_ppem )
{
size->ttmetrics.scale = metrics->x_scale;
size->ttmetrics.ppem = metrics->x_ppem;
size->ttmetrics.x_ratio = 0x10000L;
size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem,
metrics->x_ppem );
}
else
{
size->ttmetrics.scale = metrics->y_scale;
size->ttmetrics.ppem = metrics->y_ppem;
size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem,
metrics->y_ppem );
size->ttmetrics.y_ratio = 0x10000L;
}
#ifdef TT_USE_BYTECODE_INTERPRETER
size->cvt_ready = -1;
#endif /* TT_USE_BYTECODE_INTERPRETER */
return FT_Err_Ok;
}
|
CWE-787
| 178,059 | 213 |
328349556850502930530519513006179954778
| null | null | null |
savannah
|
7bbb91fbf47fc0775cc9705673caf0c47a81f94b
| 1 |
sfnt_init_face( FT_Stream stream,
TT_Face face,
FT_Int face_instance_index,
FT_Int num_params,
FT_Parameter* params )
{
FT_Error error;
FT_Memory memory = face->root.memory;
FT_Library library = face->root.driver->root.library;
SFNT_Service sfnt;
FT_Int face_index;
/* for now, parameters are unused */
FT_UNUSED( num_params );
FT_UNUSED( params );
sfnt = (SFNT_Service)face->sfnt;
if ( !sfnt )
{
sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" );
if ( !sfnt )
{
FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" ));
return FT_THROW( Missing_Module );
}
face->sfnt = sfnt;
face->goto_table = sfnt->goto_table;
}
FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS );
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
if ( !face->mm )
{
/* we want the MM interface from the `truetype' module only */
FT_Module tt_module = FT_Get_Module( library, "truetype" );
face->mm = ft_module_get_service( tt_module,
FT_SERVICE_ID_MULTI_MASTERS,
0 );
}
if ( !face->var )
{
/* we want the metrics variations interface */
/* from the `truetype' module only */
FT_Module tt_module = FT_Get_Module( library, "truetype" );
face->var = ft_module_get_service( tt_module,
FT_SERVICE_ID_METRICS_VARIATIONS,
0 );
}
#endif
FT_TRACE2(( "SFNT driver\n" ));
error = sfnt_open_font( stream, face );
if ( error )
return error;
/* Stream may have changed in sfnt_open_font. */
stream = face->root.stream;
FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index ));
face_index = FT_ABS( face_instance_index ) & 0xFFFF;
/* value -(N+1) requests information on index N */
if ( face_instance_index < 0 )
face_index--;
if ( face_index >= face->ttc_header.count )
{
if ( face_instance_index >= 0 )
return FT_THROW( Invalid_Argument );
else
face_index = 0;
}
if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) )
return error;
/* check whether we have a valid TrueType file */
error = sfnt->load_font_dir( face, stream );
if ( error )
return error;
#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT
{
FT_ULong fvar_len;
FT_ULong version;
FT_ULong offset;
FT_UShort num_axes;
FT_UShort axis_size;
FT_UShort num_instances;
FT_UShort instance_size;
FT_Int instance_index;
FT_Byte* default_values = NULL;
FT_Byte* instance_values = NULL;
face->is_default_instance = 1;
instance_index = FT_ABS( face_instance_index ) >> 16;
/* test whether current face is a GX font with named instances */
if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) ||
fvar_len < 20 ||
FT_READ_ULONG( version ) ||
FT_READ_USHORT( offset ) ||
FT_STREAM_SKIP( 2 ) /* reserved */ ||
FT_READ_USHORT( num_axes ) ||
FT_READ_USHORT( axis_size ) ||
FT_READ_USHORT( num_instances ) ||
FT_READ_USHORT( instance_size ) )
{
version = 0;
offset = 0;
num_axes = 0;
axis_size = 0;
num_instances = 0;
instance_size = 0;
}
/* check that the data is bound by the table length */
if ( version != 0x00010000UL ||
axis_size != 20 ||
num_axes == 0 ||
/* `num_axes' limit implied by 16-bit `instance_size' */
num_axes > 0x3FFE ||
!( instance_size == 4 + 4 * num_axes ||
instance_size == 6 + 4 * num_axes ) ||
/* `num_instances' limit implied by limited range of name IDs */
num_instances > 0x7EFF ||
offset +
axis_size * num_axes +
instance_size * num_instances > fvar_len )
num_instances = 0;
else
face->variation_support |= TT_FACE_FLAG_VAR_FVAR;
/*
* As documented in the OpenType specification, an entry for the
* default instance may be omitted in the named instance table. In
* particular this means that even if there is no named instance
* table in the font we actually do have a named instance, namely the
* default instance.
*
* For consistency, we always want the default instance in our list
* of named instances. If it is missing, we try to synthesize it
* later on. Here, we have to adjust `num_instances' accordingly.
*/
if ( !( FT_ALLOC( default_values, num_axes * 2 ) ||
FT_ALLOC( instance_values, num_axes * 2 ) ) )
{
/* the current stream position is 16 bytes after the table start */
FT_ULong array_start = FT_STREAM_POS() - 16 + offset;
FT_ULong default_value_offset, instance_offset;
FT_Byte* p;
FT_UInt i;
default_value_offset = array_start + 8;
p = default_values;
for ( i = 0; i < num_axes; i++ )
{
(void)FT_STREAM_READ_AT( default_value_offset, p, 2 );
default_value_offset += axis_size;
p += 2;
}
instance_offset = array_start + axis_size * num_axes + 4;
for ( i = 0; i < num_instances; i++ )
{
(void)FT_STREAM_READ_AT( instance_offset,
instance_values,
num_axes * 2 );
if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) )
break;
instance_offset += instance_size;
}
if ( i == num_instances )
{
/* no default instance in named instance table; */
/* we thus have to synthesize it */
num_instances++;
}
}
FT_FREE( default_values );
FT_FREE( instance_values );
/* we don't support Multiple Master CFFs yet */
if ( face->goto_table( face, TTAG_glyf, stream, 0 ) &&
!face->goto_table( face, TTAG_CFF, stream, 0 ) )
num_instances = 0;
if ( instance_index > num_instances )
{
if ( face_instance_index >= 0 )
return FT_THROW( Invalid_Argument );
else
num_instances = 0;
}
face->root.style_flags = (FT_Long)num_instances << 16;
}
#endif
face->root.num_faces = face->ttc_header.count;
face->root.face_index = face_instance_index;
return error;
}
|
CWE-787
| 178,060 | 214 |
119798325318146814691558712066205414712
| null | null | null |
poppler
|
5c9b08a875b07853be6c44e43ff5f7f059df666a
| 1 |
int main (int argc, char *argv[])
{
int objectsCount = 0;
Guint numOffset = 0;
std::vector<Object> pages;
std::vector<Guint> offsets;
XRef *yRef, *countRef;
FILE *f;
OutStream *outStr;
int i;
int j, rootNum;
std::vector<PDFDoc *>docs;
int majorVersion = 0;
int minorVersion = 0;
char *fileName = argv[argc - 1];
int exitCode;
exitCode = 99;
const GBool ok = parseArgs (argDesc, &argc, argv);
if (!ok || argc < 3 || printVersion || printHelp) {
fprintf(stderr, "pdfunite version %s\n", PACKAGE_VERSION);
fprintf(stderr, "%s\n", popplerCopyright);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdfunite", "<PDF-sourcefile-1>..<PDF-sourcefile-n> <PDF-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
return exitCode;
}
exitCode = 0;
globalParams = new GlobalParams();
for (i = 1; i < argc - 1; i++) {
GooString *gfileName = new GooString(argv[i]);
PDFDoc *doc = new PDFDoc(gfileName, NULL, NULL, NULL);
if (doc->isOk() && !doc->isEncrypted()) {
docs.push_back(doc);
if (doc->getPDFMajorVersion() > majorVersion) {
majorVersion = doc->getPDFMajorVersion();
minorVersion = doc->getPDFMinorVersion();
} else if (doc->getPDFMajorVersion() == majorVersion) {
if (doc->getPDFMinorVersion() > minorVersion) {
minorVersion = doc->getPDFMinorVersion();
}
}
} else if (doc->isOk()) {
error(errUnimplemented, -1, "Could not merge encrypted files ('{0:s}')", argv[i]);
return -1;
} else {
error(errSyntaxError, -1, "Could not merge damaged documents ('{0:s}')", argv[i]);
return -1;
}
}
if (!(f = fopen(fileName, "wb"))) {
error(errIO, -1, "Could not open file '{0:s}'", fileName);
return -1;
}
outStr = new FileOutStream(f, 0);
yRef = new XRef();
countRef = new XRef();
yRef->add(0, 65535, 0, gFalse);
PDFDoc::writeHeader(outStr, majorVersion, minorVersion);
Object intents;
Object afObj;
Object ocObj;
Object names;
if (docs.size() >= 1) {
Object catObj;
docs[0]->getXRef()->getCatalog(&catObj);
Dict *catDict = catObj.getDict();
catDict->lookup("OutputIntents", &intents);
catDict->lookupNF("AcroForm", &afObj);
Ref *refPage = docs[0]->getCatalog()->getPageRef(1);
if (!afObj.isNull()) {
docs[0]->markAcroForm(&afObj, yRef, countRef, 0, refPage->num, refPage->num);
}
catDict->lookupNF("OCProperties", &ocObj);
if (!ocObj.isNull() && ocObj.isDict()) {
docs[0]->markPageObjects(ocObj.getDict(), yRef, countRef, 0, refPage->num, refPage->num);
}
catDict->lookup("Names", &names);
if (!names.isNull() && names.isDict()) {
docs[0]->markPageObjects(names.getDict(), yRef, countRef, 0, refPage->num, refPage->num);
}
if (intents.isArray() && intents.arrayGetLength() > 0) {
for (i = 1; i < (int) docs.size(); i++) {
Object pagecatObj, pageintents;
docs[i]->getXRef()->getCatalog(&pagecatObj);
Dict *pagecatDict = pagecatObj.getDict();
pagecatDict->lookup("OutputIntents", &pageintents);
if (pageintents.isArray() && pageintents.arrayGetLength() > 0) {
for (j = intents.arrayGetLength() - 1; j >= 0; j--) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
Object idf;
intent.dictLookup("OutputConditionIdentifier", &idf);
if (idf.isString()) {
GooString *gidf = idf.getString();
GBool removeIntent = gTrue;
for (int k = 0; k < pageintents.arrayGetLength(); k++) {
Object pgintent;
pageintents.arrayGet(k, &pgintent, 0);
if (pgintent.isDict()) {
Object pgidf;
pgintent.dictLookup("OutputConditionIdentifier", &pgidf);
if (pgidf.isString()) {
GooString *gpgidf = pgidf.getString();
if (gpgidf->cmp(gidf) == 0) {
pgidf.free();
removeIntent = gFalse;
break;
}
}
pgidf.free();
}
}
if (removeIntent) {
intents.arrayRemove(j);
error(errSyntaxWarning, -1, "Output intent {0:s} missing in pdf {1:s}, removed",
gidf->getCString(), docs[i]->getFileName()->getCString());
}
} else {
intents.arrayRemove(j);
error(errSyntaxWarning, -1, "Invalid output intent dict, missing required OutputConditionIdentifier");
}
idf.free();
} else {
intents.arrayRemove(j);
}
intent.free();
}
} else {
error(errSyntaxWarning, -1, "Output intents differs, remove them all");
intents.free();
break;
}
pagecatObj.free();
pageintents.free();
}
}
if (intents.isArray() && intents.arrayGetLength() > 0) {
for (j = intents.arrayGetLength() - 1; j >= 0; j--) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
docs[0]->markPageObjects(intent.getDict(), yRef, countRef, numOffset, 0, 0);
} else {
intents.arrayRemove(j);
}
intent.free();
}
}
catObj.free();
}
for (i = 0; i < (int) docs.size(); i++) {
for (j = 1; j <= docs[i]->getNumPages(); j++) {
PDFRectangle *cropBox = NULL;
if (docs[i]->getCatalog()->getPage(j)->isCropped())
cropBox = docs[i]->getCatalog()->getPage(j)->getCropBox();
Object page;
docs[i]->getXRef()->fetch(refPage->num, refPage->gen, &page);
Dict *pageDict = page.getDict();
Dict *resDict = docs[i]->getCatalog()->getPage(j)->getResourceDict();
if (resDict) {
Object *newResource = new Object();
newResource->initDict(resDict);
pageDict->set("Resources", newResource);
delete newResource;
}
pages.push_back(page);
offsets.push_back(numOffset);
docs[i]->markPageObjects(pageDict, yRef, countRef, numOffset, refPage->num, refPage->num);
Object annotsObj;
pageDict->lookupNF("Annots", &annotsObj);
if (!annotsObj.isNull()) {
docs[i]->markAnnotations(&annotsObj, yRef, countRef, numOffset, refPage->num, refPage->num);
annotsObj.free();
}
}
Object pageCatObj, pageNames, pageForm;
docs[i]->getXRef()->getCatalog(&pageCatObj);
Dict *pageCatDict = pageCatObj.getDict();
pageCatDict->lookup("Names", &pageNames);
if (!pageNames.isNull() && pageNames.isDict()) {
if (!names.isDict()) {
names.free();
names.initDict(yRef);
}
doMergeNameDict(docs[i], yRef, countRef, 0, 0, names.getDict(), pageNames.getDict(), numOffset);
}
pageCatDict->lookup("AcroForm", &pageForm);
if (i > 0 && !pageForm.isNull() && pageForm.isDict()) {
if (afObj.isNull()) {
pageCatDict->lookupNF("AcroForm", &afObj);
} else if (afObj.isDict()) {
doMergeFormDict(afObj.getDict(), pageForm.getDict(), numOffset);
}
}
pageForm.free();
pageNames.free();
pageCatObj.free();
objectsCount += docs[i]->writePageObjects(outStr, yRef, numOffset, gTrue);
numOffset = yRef->getNumObjects() + 1;
}
rootNum = yRef->getNumObjects() + 1;
yRef->add(rootNum, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum);
outStr->printf("<< /Type /Catalog /Pages %d 0 R", rootNum + 1);
if (intents.isArray() && intents.arrayGetLength() > 0) {
outStr->printf(" /OutputIntents [");
for (j = 0; j < intents.arrayGetLength(); j++) {
Object intent;
intents.arrayGet(j, &intent, 0);
if (intent.isDict()) {
PDFDoc::writeObject(&intent, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
}
intent.free();
}
outStr->printf("]");
}
intents.free();
if (!afObj.isNull()) {
outStr->printf(" /AcroForm ");
PDFDoc::writeObject(&afObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
afObj.free();
}
if (!ocObj.isNull() && ocObj.isDict()) {
outStr->printf(" /OCProperties ");
PDFDoc::writeObject(&ocObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
ocObj.free();
}
if (!names.isNull() && names.isDict()) {
outStr->printf(" /Names ");
PDFDoc::writeObject(&names, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0);
names.free();
}
outStr->printf(">>\nendobj\n");
objectsCount++;
yRef->add(rootNum + 1, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum + 1);
outStr->printf("<< /Type /Pages /Kids [");
for (j = 0; j < (int) pages.size(); j++)
outStr->printf(" %d 0 R", rootNum + j + 2);
outStr->printf(" ] /Count %zd >>\nendobj\n", pages.size());
objectsCount++;
for (i = 0; i < (int) pages.size(); i++) {
yRef->add(rootNum + i + 2, 0, outStr->getPos(), gTrue);
outStr->printf("%d 0 obj\n", rootNum + i + 2);
outStr->printf("<< ");
Dict *pageDict = pages[i].getDict();
for (j = 0; j < pageDict->getLength(); j++) {
if (j > 0)
outStr->printf(" ");
const char *key = pageDict->getKey(j);
Object value;
pageDict->getValNF(j, &value);
if (strcmp(key, "Parent") == 0) {
outStr->printf("/Parent %d 0 R", rootNum + 1);
} else {
outStr->printf("/%s ", key);
PDFDoc::writeObject(&value, outStr, yRef, offsets[i], NULL, cryptRC4, 0, 0, 0);
}
value.free();
}
outStr->printf(" >>\nendobj\n");
objectsCount++;
}
Goffset uxrefOffset = outStr->getPos();
Ref ref;
ref.num = rootNum;
ref.gen = 0;
Dict *trailerDict = PDFDoc::createTrailerDict(objectsCount, gFalse, 0, &ref, yRef,
fileName, outStr->getPos());
PDFDoc::writeXRefTableTrailer(trailerDict, yRef, gTrue, // write all entries according to ISO 32000-1, 7.5.4 Cross-Reference Table: "For a file that has never been incrementally updated, the cross-reference section shall contain only one subsection, whose object numbering begins at 0."
uxrefOffset, outStr, yRef);
delete trailerDict;
outStr->close();
delete outStr;
fclose(f);
delete yRef;
delete countRef;
for (j = 0; j < (int) pages.size (); j++) pages[j].free();
for (i = 0; i < (int) docs.size (); i++) delete docs[i];
delete globalParams;
return exitCode;
}
|
CWE-476
| 178,062 | 215 |
180050936886598415271458736244884709418
| null | null | null |
savannah
|
94e01571507835ff59dd8ce2a0b56a4b566965a4
| 1 |
main (int argc _GL_UNUSED, char **argv)
{
struct timespec result;
struct timespec result2;
struct timespec expected;
struct timespec now;
const char *p;
int i;
long gmtoff;
time_t ref_time = 1304250918;
/* Set the time zone to US Eastern time with the 2012 rules. This
should disable any leap second support. Otherwise, there will be
a problem with glibc on sites that default to leap seconds; see
<http://bugs.gnu.org/12206>. */
setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1);
gmtoff = gmt_offset (ref_time);
/* ISO 8601 extended date and time of day representation,
'T' separator, local time zone */
p = "2011-05-01T11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, local time zone */
p = "2011-05-01 11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
'T' separator, UTC */
p = "2011-05-01T11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
' ' separator, UTC */
p = "2011-05-01 11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/UTC offset */
p = "2011-05-01T11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/UTC offset */
p = "2011-05-01 11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/hour only UTC offset */
p = "2011-05-01T11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/hour only UTC offset */
p = "2011-05-01 11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "4 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
/* test if timezone is not being ignored for day offset */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 +24 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* test if several time zones formats are handled same way */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC-1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+0:15";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+0015";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-1:30";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-130";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* TZ out of range should cause parse_datetime failure */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+25:00";
ASSERT (!parse_datetime (&result, p, &now));
/* Check for several invalid countable dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+4:00 +40 yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 next yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow hence";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 40 now ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 last tomorrow";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 -4 today";
ASSERT (!parse_datetime (&result, p, &now));
/* And check correct usage of dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+400 1 day hence";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 1 day ago";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* Check that some "next Monday", "last Wednesday", etc. are correct. */
setenv ("TZ", "UTC0", 1);
for (i = 0; day_table[i]; i++)
{
unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */
char tmp[32];
sprintf (tmp, "NEXT %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600);
sprintf (tmp, "LAST %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600);
}
p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == now.tv_sec
&& result.tv_nsec == now.tv_nsec);
p = "FRIDAY UTC+00";
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == 24 * 3600
&& result.tv_nsec == now.tv_nsec);
/* Exercise a sign-extension bug. Before July 2012, an input
starting with a high-bit-set byte would be treated like "0". */
ASSERT ( ! parse_datetime (&result, "\xb0", &now));
/* Exercise TZ="" parsing code. */
/* These two would infloop or segfault before Feb 2014. */
ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now));
/* Exercise invalid patterns. */
ASSERT ( ! parse_datetime (&result, "TZ=\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now));
/* Exercise valid patterns. */
ASSERT ( parse_datetime (&result, "TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now));
ASSERT ( parse_datetime (&result, " TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now));
return 0;
}
|
CWE-119
| 178,063 | 216 |
85463602567582995767126053202641542542
| null | null | null |
savannah
|
59eb9f8cfe7d1df379a2318316d1f04f80fba54a
| 1 |
ft_var_readpackedpoints( FT_Stream stream,
FT_UInt *point_cnt )
{
FT_UShort *points;
FT_Int n;
FT_Int runcnt;
FT_Int i;
FT_Int j;
FT_Int first;
FT_Memory memory = stream->memory;
FT_Error error = TT_Err_Ok;
FT_UNUSED( error );
*point_cnt = n = FT_GET_BYTE();
if ( n == 0 )
return ALL_POINTS;
if ( n & GX_PT_POINTS_ARE_WORDS )
n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 );
if ( FT_NEW_ARRAY( points, n ) )
return NULL;
i = 0;
while ( i < n )
{
runcnt = FT_GET_BYTE();
if ( runcnt & GX_PT_POINTS_ARE_WORDS )
{
runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK;
first = points[i++] = FT_GET_USHORT();
if ( runcnt < 1 )
goto Exit;
/* first point not included in runcount */
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_USHORT() );
}
else
{
first = points[i++] = FT_GET_BYTE();
if ( runcnt < 1 )
goto Exit;
for ( j = 0; j < runcnt; ++j )
points[i++] = (FT_UShort)( first += FT_GET_BYTE() );
}
}
Exit:
return points;
}
|
CWE-119
| 178,069 | 217 |
176444419672545527315649492039587951909
| null | null | null |
ghostscript
|
39b1e54b2968620723bf32e96764c88797714879
| 1 |
set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat)
{
int code = gs_distance_transform_inverse(dx, dy, pmat, pdist);
double rounded;
if (code == gs_error_undefinedresult) {
/* The CTM is degenerate.
Can't know the distance in user space.
} else if (code < 0)
return code;
/* If the distance is very close to integers, round it. */
if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005)
pdist->x = rounded;
if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005)
pdist->y = rounded;
return 0;
}
|
CWE-119
| 178,070 | 218 |
334604983653907615489271299004330168271
| null | null | null |
haproxy
|
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
| 1 |
static void h2_process_demux(struct h2c *h2c)
{
struct h2s *h2s;
if (h2c->st0 >= H2_CS_ERROR)
return;
if (unlikely(h2c->st0 < H2_CS_FRAME_H)) {
if (h2c->st0 == H2_CS_PREFACE) {
if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR)
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
h2c->max_id = 0;
h2c->st0 = H2_CS_SETTINGS1;
}
if (h2c->st0 == H2_CS_SETTINGS1) {
struct h2_fh hdr;
/* ensure that what is pending is a valid SETTINGS frame
* without an ACK.
*/
if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR)
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
h2c->st0 = H2_CS_ERROR2;
goto fail;
}
/* that's OK, switch to FRAME_P to process it */
h2c->dfl = hdr.len;
h2c->dsi = hdr.sid;
h2c->dft = hdr.ft;
h2c->dff = hdr.ff;
h2c->dpl = 0;
h2c->st0 = H2_CS_FRAME_P;
}
}
/* process as many incoming frames as possible below */
while (h2c->dbuf->i) {
int ret = 0;
if (h2c->st0 >= H2_CS_ERROR)
break;
if (h2c->st0 == H2_CS_FRAME_H) {
struct h2_fh hdr;
if (!h2_peek_frame_hdr(h2c->dbuf, &hdr))
break;
if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) {
h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR);
h2c->st0 = H2_CS_ERROR;
break;
}
h2c->dfl = hdr.len;
h2c->dsi = hdr.sid;
h2c->dft = hdr.ft;
h2c->dff = hdr.ff;
h2c->dpl = 0;
h2c->st0 = H2_CS_FRAME_P;
h2_skip_frame_hdr(h2c->dbuf);
}
/* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */
h2s = h2c_st_by_id(h2c, h2c->dsi);
if (h2c->st0 == H2_CS_FRAME_E)
goto strm_err;
if (h2s->st == H2_SS_IDLE &&
h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than HEADERS or PRIORITY in
* this state MUST be treated as a connection error
*/
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_ERROR;
break;
}
if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE &&
h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than WU/PRIO/RST in
* this state MUST be treated as a stream error
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto strm_err;
}
/* Below the management of frames received in closed state is a
* bit hackish because the spec makes strong differences between
* streams closed by receiving RST, sending RST, and seeing ES
* in both directions. In addition to this, the creation of a
* new stream reusing the identifier of a closed one will be
* detected here. Given that we cannot keep track of all closed
* streams forever, we consider that unknown closed streams were
* closed on RST received, which allows us to respond with an
* RST without breaking the connection (eg: to abort a transfer).
* Some frames have to be silently ignored as well.
*/
if (h2s->st == H2_SS_CLOSED && h2c->dsi) {
if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) {
/* #5.1.1: The identifier of a newly
* established stream MUST be numerically
* greater than all streams that the initiating
* endpoint has opened or reserved. This
* governs streams that are opened using a
* HEADERS frame and streams that are reserved
* using PUSH_PROMISE. An endpoint that
* receives an unexpected stream identifier
* MUST respond with a connection error.
*/
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
goto strm_err;
}
if (h2s->flags & H2_SF_RST_RCVD) {
/* RFC7540#5.1:closed: an endpoint that
* receives any frame other than PRIORITY after
* receiving a RST_STREAM MUST treat that as a
* stream error of type STREAM_CLOSED.
*
* Note that old streams fall into this category
* and will lead to an RST being sent.
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto strm_err;
}
/* RFC7540#5.1:closed: if this state is reached as a
* result of sending a RST_STREAM frame, the peer that
* receives the RST_STREAM might have already sent
* frames on the stream that cannot be withdrawn. An
* endpoint MUST ignore frames that it receives on
* closed streams after it has sent a RST_STREAM
* frame. An endpoint MAY choose to limit the period
* over which it ignores frames and treat frames that
* arrive after this time as being in error.
*/
if (!(h2s->flags & H2_SF_RST_SENT)) {
/* RFC7540#5.1:closed: any frame other than
* PRIO/WU/RST in this state MUST be treated as
* a connection error
*/
if (h2c->dft != H2_FT_RST_STREAM &&
h2c->dft != H2_FT_PRIORITY &&
h2c->dft != H2_FT_WINDOW_UPDATE) {
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
goto strm_err;
}
}
}
#if 0
/* graceful shutdown, ignore streams whose ID is higher than
* the one advertised in GOAWAY. RFC7540#6.8.
*/
if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) {
ret = MIN(h2c->dbuf->i, h2c->dfl);
bi_del(h2c->dbuf, ret);
h2c->dfl -= ret;
ret = h2c->dfl == 0;
goto strm_err;
}
#endif
switch (h2c->dft) {
case H2_FT_SETTINGS:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_settings(h2c);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_ack_settings(h2c);
break;
case H2_FT_PING:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_ping(h2c);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_ack_ping(h2c);
break;
case H2_FT_WINDOW_UPDATE:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_window_update(h2c, h2s);
break;
case H2_FT_CONTINUATION:
/* we currently don't support CONTINUATION frames since
* we have nowhere to store the partial HEADERS frame.
* Let's abort the stream on an INTERNAL_ERROR here.
*/
if (h2c->st0 == H2_CS_FRAME_P) {
h2s_error(h2s, H2_ERR_INTERNAL_ERROR);
h2c->st0 = H2_CS_FRAME_E;
}
break;
case H2_FT_HEADERS:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_frt_handle_headers(h2c, h2s);
break;
case H2_FT_DATA:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_frt_handle_data(h2c, h2s);
if (h2c->st0 == H2_CS_FRAME_A)
ret = h2c_send_strm_wu(h2c);
break;
case H2_FT_PRIORITY:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_priority(h2c);
break;
case H2_FT_RST_STREAM:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_rst_stream(h2c, h2s);
break;
case H2_FT_GOAWAY:
if (h2c->st0 == H2_CS_FRAME_P)
ret = h2c_handle_goaway(h2c);
break;
case H2_FT_PUSH_PROMISE:
/* not permitted here, RFC7540#5.1 */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
break;
/* implement all extra frame types here */
default:
/* drop frames that we ignore. They may be larger than
* the buffer so we drain all of their contents until
* we reach the end.
*/
ret = MIN(h2c->dbuf->i, h2c->dfl);
bi_del(h2c->dbuf, ret);
h2c->dfl -= ret;
ret = h2c->dfl == 0;
}
strm_err:
/* We may have to send an RST if not done yet */
if (h2s->st == H2_SS_ERROR)
h2c->st0 = H2_CS_FRAME_E;
if (h2c->st0 == H2_CS_FRAME_E)
ret = h2c_send_rst_stream(h2c, h2s);
/* error or missing data condition met above ? */
if (ret <= 0)
break;
if (h2c->st0 != H2_CS_FRAME_H) {
bi_del(h2c->dbuf, h2c->dfl);
h2c->st0 = H2_CS_FRAME_H;
}
}
if (h2c->rcvd_c > 0 &&
!(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM)))
h2c_send_conn_wu(h2c);
fail:
/* we can go here on missing data, blocked response or error */
return;
}
|
CWE-119
| 178,071 | 219 |
197791135802871490452896068201538076195
| null | null | null |
ghostscript
|
5008105780c0b0182ea6eda83ad5598f225be3ee
| 1 |
static void cstm(JF, js_Ast *stm)
{
js_Ast *target;
int loop, cont, then, end;
emitline(J, F, stm);
switch (stm->type) {
case AST_FUNDEC:
break;
case STM_BLOCK:
cstmlist(J, F, stm->a);
break;
case STM_EMPTY:
if (F->script) {
emit(J, F, OP_POP);
emit(J, F, OP_UNDEF);
}
break;
case STM_VAR:
cvarinit(J, F, stm->a);
break;
case STM_IF:
if (stm->c) {
cexp(J, F, stm->a);
then = emitjump(J, F, OP_JTRUE);
cstm(J, F, stm->c);
end = emitjump(J, F, OP_JUMP);
label(J, F, then);
cstm(J, F, stm->b);
label(J, F, end);
} else {
cexp(J, F, stm->a);
end = emitjump(J, F, OP_JFALSE);
cstm(J, F, stm->b);
label(J, F, end);
}
break;
case STM_DO:
loop = here(J, F);
cstm(J, F, stm->a);
cont = here(J, F);
cexp(J, F, stm->b);
emitjumpto(J, F, OP_JTRUE, loop);
labeljumps(J, F, stm->jumps, here(J,F), cont);
break;
case STM_WHILE:
loop = here(J, F);
cexp(J, F, stm->a);
end = emitjump(J, F, OP_JFALSE);
cstm(J, F, stm->b);
emitjumpto(J, F, OP_JUMP, loop);
label(J, F, end);
labeljumps(J, F, stm->jumps, here(J,F), loop);
break;
case STM_FOR:
case STM_FOR_VAR:
if (stm->type == STM_FOR_VAR) {
cvarinit(J, F, stm->a);
} else {
if (stm->a) {
cexp(J, F, stm->a);
emit(J, F, OP_POP);
}
}
loop = here(J, F);
if (stm->b) {
cexp(J, F, stm->b);
end = emitjump(J, F, OP_JFALSE);
} else {
end = 0;
}
cstm(J, F, stm->d);
cont = here(J, F);
if (stm->c) {
cexp(J, F, stm->c);
emit(J, F, OP_POP);
}
emitjumpto(J, F, OP_JUMP, loop);
if (end)
label(J, F, end);
labeljumps(J, F, stm->jumps, here(J,F), cont);
break;
case STM_FOR_IN:
case STM_FOR_IN_VAR:
cexp(J, F, stm->b);
emit(J, F, OP_ITERATOR);
loop = here(J, F);
{
emit(J, F, OP_NEXTITER);
end = emitjump(J, F, OP_JFALSE);
cassignforin(J, F, stm);
if (F->script) {
emit(J, F, OP_ROT2);
cstm(J, F, stm->c);
emit(J, F, OP_ROT2);
} else {
cstm(J, F, stm->c);
}
emitjumpto(J, F, OP_JUMP, loop);
}
label(J, F, end);
labeljumps(J, F, stm->jumps, here(J,F), loop);
break;
case STM_SWITCH:
cswitch(J, F, stm->a, stm->b);
labeljumps(J, F, stm->jumps, here(J,F), 0);
break;
case STM_LABEL:
cstm(J, F, stm->b);
/* skip consecutive labels */
while (stm->type == STM_LABEL)
stm = stm->b;
/* loops and switches have already been labelled */
if (!isloop(stm->type) && stm->type != STM_SWITCH)
labeljumps(J, F, stm->jumps, here(J,F), 0);
break;
case STM_BREAK:
if (stm->a) {
target = breaktarget(J, F, stm, stm->a->string);
if (!target)
jsC_error(J, stm, "break label '%s' not found", stm->a->string);
} else {
target = breaktarget(J, F, stm, NULL);
if (!target)
jsC_error(J, stm, "unlabelled break must be inside loop or switch");
}
cexit(J, F, STM_BREAK, stm, target);
addjump(J, F, STM_BREAK, target, emitjump(J, F, OP_JUMP));
break;
case STM_CONTINUE:
if (stm->a) {
target = continuetarget(J, F, stm, stm->a->string);
if (!target)
jsC_error(J, stm, "continue label '%s' not found", stm->a->string);
} else {
target = continuetarget(J, F, stm, NULL);
if (!target)
jsC_error(J, stm, "continue must be inside loop");
}
cexit(J, F, STM_CONTINUE, stm, target);
addjump(J, F, STM_CONTINUE, target, emitjump(J, F, OP_JUMP));
break;
case STM_RETURN:
if (stm->a)
cexp(J, F, stm->a);
else
emit(J, F, OP_UNDEF);
target = returntarget(J, F, stm);
if (!target)
jsC_error(J, stm, "return not in function");
cexit(J, F, STM_RETURN, stm, target);
emit(J, F, OP_RETURN);
break;
case STM_THROW:
cexp(J, F, stm->a);
emit(J, F, OP_THROW);
break;
case STM_WITH:
cexp(J, F, stm->a);
emit(J, F, OP_WITH);
cstm(J, F, stm->b);
emit(J, F, OP_ENDWITH);
break;
case STM_TRY:
if (stm->b && stm->c) {
if (stm->d)
ctrycatchfinally(J, F, stm->a, stm->b, stm->c, stm->d);
else
ctrycatch(J, F, stm->a, stm->b, stm->c);
} else {
ctryfinally(J, F, stm->a, stm->d);
}
break;
case STM_DEBUGGER:
emit(J, F, OP_DEBUGGER);
break;
default:
if (F->script) {
emit(J, F, OP_POP);
cexp(J, F, stm);
} else {
cexp(J, F, stm);
emit(J, F, OP_POP);
}
break;
}
}
|
CWE-476
| 178,073 | 220 |
119034873631662377239453193687499055805
| null | null | null |
libXvMC
|
2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
| 1 |
Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
|
CWE-119
| 178,085 | 223 |
225773238597816987128397211875317401076
| null | null | null |
libXfixes
|
61c1039ee23a2d1de712843bed3480654d7ef42e
| 1 |
XFixesFetchRegionAndBounds (Display *dpy,
XserverRegion region,
int *nrectanglesRet,
XRectangle *bounds)
{
XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy);
xXFixesFetchRegionReq *req;
xXFixesFetchRegionReply rep;
XRectangle *rects;
int nrects;
long nbytes;
long nread;
XFixesCheckExtension (dpy, info, NULL);
LockDisplay (dpy);
GetReq (XFixesFetchRegion, req);
req->reqType = info->codes->major_opcode;
req->xfixesReqType = X_XFixesFetchRegion;
req->region = region;
*nrectanglesRet = 0;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
bounds->x = rep.x;
bounds->y = rep.y;
bounds->y = rep.y;
bounds->width = rep.width;
bounds->height = rep.height;
nbytes = (long) rep.length << 2;
nrects = rep.length >> 1;
rects = Xmalloc (nrects * sizeof (XRectangle));
if (!rects)
{
_XEatDataWords(dpy, rep.length);
_XEatData (dpy, (unsigned long) (nbytes - nread));
}
UnlockDisplay (dpy);
SyncHandle();
*nrectanglesRet = nrects;
return rects;
}
|
CWE-190
| 178,094 | 231 |
306933036253550523681529656378317307640
| null | null | null |
libav
|
136f55207521f0b03194ef5b55ba70f1635d6aee
| 1 |
static inline int hpel_motion(MpegEncContext *s,
uint8_t *dest, uint8_t *src,
int src_x, int src_y,
op_pixels_func *pix_op,
int motion_x, int motion_y)
{
int dxy = 0;
int emu = 0;
src_x += motion_x >> 1;
src_y += motion_y >> 1;
/* WARNING: do no forget half pels */
src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu?
if (src_x != s->width)
dxy |= motion_x & 1;
src_y = av_clip(src_y, -16, s->height);
if (src_y != s->height)
dxy |= (motion_y & 1) << 1;
src += src_y * s->linesize + src_x;
if (s->unrestricted_mv) {
if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||
(unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {
s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,
s->linesize, s->linesize,
9, 9,
src_x, src_y, s->h_edge_pos,
s->v_edge_pos);
src = s->sc.edge_emu_buffer;
emu = 1;
}
}
pix_op[dxy](dest, src, s->linesize, 8);
return emu;
}
|
CWE-476
| 178,099 | 232 |
111292629842222758487961407224615725800
| null | null | null |
tartarus
|
4ff22863d895cb7ebfced4cf923a012a614adaa8
| 1 |
static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
{
int i;
struct ssh_channel *c;
if (enable == ssh->throttled_all)
return;
ssh->throttled_all = enable;
ssh->overall_bufsize = bufsize;
if (!ssh->channels)
return;
for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
switch (c->type) {
case CHAN_MAINSESSION:
/*
* This is treated separately, outside the switch.
*/
break;
x11_override_throttle(c->u.x11.xconn, enable);
break;
case CHAN_AGENT:
/* Agent channels require no buffer management. */
break;
case CHAN_SOCKDATA:
pfd_override_throttle(c->u.pfd.pf, enable);
static void ssh_agent_callback(void *sshv, void *reply, int replylen)
{
Ssh ssh = (Ssh) sshv;
ssh->auth_agent_query = NULL;
ssh->agent_response = reply;
ssh->agent_response_len = replylen;
if (ssh->version == 1)
do_ssh1_login(ssh, NULL, -1, NULL);
else
do_ssh2_authconn(ssh, NULL, -1, NULL);
}
static void ssh_dialog_callback(void *sshv, int ret)
{
Ssh ssh = (Ssh) sshv;
ssh->user_response = ret;
if (ssh->version == 1)
do_ssh1_login(ssh, NULL, -1, NULL);
else
do_ssh2_transport(ssh, NULL, -1, NULL);
/*
* This may have unfrozen the SSH connection, so do a
* queued-data run.
*/
ssh_process_queued_incoming_data(ssh);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen)
ssh_process_queued_incoming_data(ssh);
}
static void ssh_agentf_callback(void *cv, void *reply, int replylen)
{
struct ssh_channel *c = (struct ssh_channel *)cv;
const void *sentreply = reply;
c->u.a.pending = NULL;
c->u.a.outstanding_requests--;
if (!sentreply) {
/* Fake SSH_AGENT_FAILURE. */
sentreply = "\0\0\0\1\5";
replylen = 5;
}
ssh_send_channel_data(c, sentreply, replylen);
if (reply)
sfree(reply);
/*
* If we've already seen an incoming EOF but haven't sent an
* outgoing one, this may be the moment to send it.
*/
if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
sshfwd_write_eof(c);
}
/*
* Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
* non-NULL, otherwise just close the connection. `client_reason' == NULL
struct Packet *pktin)
{
int i, j, ret;
unsigned char cookie[8], *ptr;
struct MD5Context md5c;
struct do_ssh1_login_state {
int crLine;
int len;
unsigned char *rsabuf;
const unsigned char *keystr1, *keystr2;
unsigned long supported_ciphers_mask, supported_auths_mask;
int tried_publickey, tried_agent;
int tis_auth_refused, ccard_auth_refused;
unsigned char session_id[16];
int cipher_type;
void *publickey_blob;
int publickey_bloblen;
char *publickey_comment;
int privatekey_available, privatekey_encrypted;
prompts_t *cur_prompt;
char c;
int pwpkt_type;
unsigned char request[5], *response, *p;
int responselen;
int keyi, nkeys;
int authed;
struct RSAKey key;
Bignum challenge;
char *commentp;
int commentlen;
int dlgret;
Filename *keyfile;
struct RSAKey servkey, hostkey;
};
crState(do_ssh1_login_state);
crBeginState;
if (!pktin)
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
bombout(("Public key packet not received"));
crStop(0);
}
logevent("Received public keys");
ptr = ssh_pkt_getdata(pktin, 8);
if (!ptr) {
bombout(("SSH-1 public key packet stopped before random cookie"));
crStop(0);
}
memcpy(cookie, ptr, 8);
if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
!ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
bombout(("Failed to read SSH-1 public keys from public key packet"));
crStop(0);
}
/*
* Log the host key fingerprint.
*/
{
char logmsg[80];
logevent("Host key fingerprint is:");
strcpy(logmsg, " ");
s->hostkey.comment = NULL;
rsa_fingerprint(logmsg + strlen(logmsg),
sizeof(logmsg) - strlen(logmsg), &s->hostkey);
logevent(logmsg);
}
ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
s->supported_auths_mask = ssh_pkt_getuint32(pktin);
if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
ssh->v1_local_protoflags =
ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
MD5Init(&md5c);
MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
MD5Update(&md5c, s->keystr1, s->servkey.bytes);
MD5Update(&md5c, cookie, 8);
MD5Final(s->session_id, &md5c);
for (i = 0; i < 32; i++)
ssh->session_key[i] = random_byte();
/*
* Verify that the `bits' and `bytes' parameters match.
*/
if (s->hostkey.bits > s->hostkey.bytes * 8 ||
s->servkey.bits > s->servkey.bytes * 8) {
bombout(("SSH-1 public keys were badly formatted"));
crStop(0);
}
s->len = (s->hostkey.bytes > s->servkey.bytes ?
s->hostkey.bytes : s->servkey.bytes);
s->rsabuf = snewn(s->len, unsigned char);
/*
* Verify the host key.
*/
{
/*
* First format the key into a string.
*/
int len = rsastr_len(&s->hostkey);
char fingerprint[100];
char *keystr = snewn(len, char);
rsastr_fmt(keystr, &s->hostkey);
rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
/* First check against manually configured host keys. */
s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
if (s->dlgret == 0) { /* did not match */
bombout(("Host key did not appear in manually configured list"));
sfree(keystr);
crStop(0);
} else if (s->dlgret < 0) { /* none configured; use standard handling */
ssh_set_frozen(ssh, 1);
s->dlgret = verify_ssh_host_key(ssh->frontend,
ssh->savedhost, ssh->savedport,
"rsa", keystr, fingerprint,
ssh_dialog_callback, ssh);
sfree(keystr);
#ifdef FUZZING
s->dlgret = 1;
#endif
if (s->dlgret < 0) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for user host key response"));
crStop(0);
}
} while (pktin || inlen > 0);
s->dlgret = ssh->user_response;
}
ssh_set_frozen(ssh, 0);
if (s->dlgret == 0) {
ssh_disconnect(ssh, "User aborted at host key verification",
NULL, 0, TRUE);
crStop(0);
}
} else {
sfree(keystr);
}
}
for (i = 0; i < 32; i++) {
s->rsabuf[i] = ssh->session_key[i];
if (i < 16)
s->rsabuf[i] ^= s->session_id[i];
}
if (s->hostkey.bytes > s->servkey.bytes) {
ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
if (ret)
ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
} else {
ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
if (ret)
ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
}
if (!ret) {
bombout(("SSH-1 public key encryptions failed due to bad formatting"));
crStop(0);
}
logevent("Encrypted session key");
{
int cipher_chosen = 0, warn = 0;
const char *cipher_string = NULL;
int i;
for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
int next_cipher = conf_get_int_int(ssh->conf,
CONF_ssh_cipherlist, i);
if (next_cipher == CIPHER_WARN) {
/* If/when we choose a cipher, warn about it */
warn = 1;
} else if (next_cipher == CIPHER_AES) {
/* XXX Probably don't need to mention this. */
logevent("AES not supported in SSH-1, skipping");
} else {
switch (next_cipher) {
case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
cipher_string = "3DES"; break;
case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
cipher_string = "Blowfish"; break;
case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
cipher_string = "single-DES"; break;
}
if (s->supported_ciphers_mask & (1 << s->cipher_type))
cipher_chosen = 1;
}
}
if (!cipher_chosen) {
if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
bombout(("Server violates SSH-1 protocol by not "
"supporting 3DES encryption"));
else
/* shouldn't happen */
bombout(("No supported ciphers found"));
crStop(0);
}
/* Warn about chosen cipher if necessary. */
if (warn) {
ssh_set_frozen(ssh, 1);
s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
ssh_dialog_callback, ssh);
if (s->dlgret < 0) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for user response"));
crStop(0);
}
} while (pktin || inlen > 0);
s->dlgret = ssh->user_response;
}
ssh_set_frozen(ssh, 0);
if (s->dlgret == 0) {
ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
0, TRUE);
crStop(0);
}
}
}
switch (s->cipher_type) {
case SSH_CIPHER_3DES:
logevent("Using 3DES encryption");
break;
case SSH_CIPHER_DES:
logevent("Using single-DES encryption");
break;
case SSH_CIPHER_BLOWFISH:
logevent("Using Blowfish encryption");
break;
}
send_packet(ssh, SSH1_CMSG_SESSION_KEY,
PKT_CHAR, s->cipher_type,
PKT_DATA, cookie, 8,
PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
PKT_DATA, s->rsabuf, s->len,
PKT_INT, ssh->v1_local_protoflags, PKT_END);
logevent("Trying to enable encryption...");
sfree(s->rsabuf);
ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
&ssh_3des);
ssh->v1_cipher_ctx = ssh->cipher->make_context();
ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
ssh->crcda_ctx = crcda_make_context();
logevent("Installing CRC compensation attack detector");
if (s->servkey.modulus) {
sfree(s->servkey.modulus);
s->servkey.modulus = NULL;
}
if (s->servkey.exponent) {
sfree(s->servkey.exponent);
s->servkey.exponent = NULL;
}
if (s->hostkey.modulus) {
sfree(s->hostkey.modulus);
s->hostkey.modulus = NULL;
}
if (s->hostkey.exponent) {
sfree(s->hostkey.exponent);
s->hostkey.exponent = NULL;
}
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Encryption not successfully enabled"));
crStop(0);
}
logevent("Successfully started encryption");
fflush(stdout); /* FIXME eh? */
{
if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
int ret; /* need not be kept over crReturn */
s->cur_prompt = new_prompts(ssh->frontend);
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH login name");
add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/*
* Failed to get a username. Terminate.
*/
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
crStop(0);
}
ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
free_prompts(s->cur_prompt);
}
send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
{
char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
logevent(userlog);
if (flags & FLAG_INTERACTIVE &&
(!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
c_write_str(ssh, userlog);
c_write_str(ssh, "\r\n");
}
sfree(userlog);
}
}
crWaitUntil(pktin);
if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
/* We must not attempt PK auth. Pretend we've already tried it. */
s->tried_publickey = s->tried_agent = 1;
} else {
s->tried_publickey = s->tried_agent = 0;
}
s->tis_auth_refused = s->ccard_auth_refused = 0;
/*
* Load the public half of any configured keyfile for later use.
*/
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
if (!filename_is_null(s->keyfile)) {
int keytype;
logeventf(ssh, "Reading key file \"%.150s\"",
filename_to_str(s->keyfile));
keytype = key_type(s->keyfile);
if (keytype == SSH_KEYTYPE_SSH1 ||
keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
const char *error;
if (rsakey_pubblob(s->keyfile,
&s->publickey_blob, &s->publickey_bloblen,
&s->publickey_comment, &error)) {
s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
if (!s->privatekey_available)
logeventf(ssh, "Key file contains public key only");
s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
NULL);
} else {
char *msgbuf;
logeventf(ssh, "Unable to load key (%s)", error);
msgbuf = dupprintf("Unable to load key file "
"\"%.150s\" (%s)\r\n",
filename_to_str(s->keyfile),
error);
c_write_str(ssh, msgbuf);
sfree(msgbuf);
s->publickey_blob = NULL;
}
} else {
char *msgbuf;
logeventf(ssh, "Unable to use this key file (%s)",
key_type_to_str(keytype));
msgbuf = dupprintf("Unable to use key file \"%.150s\""
" (%s)\r\n",
filename_to_str(s->keyfile),
key_type_to_str(keytype));
c_write_str(ssh, msgbuf);
sfree(msgbuf);
s->publickey_blob = NULL;
}
} else
s->publickey_blob = NULL;
while (pktin->type == SSH1_SMSG_FAILURE) {
s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
/*
* Attempt RSA authentication using Pageant.
*/
void *r;
s->authed = FALSE;
s->tried_agent = 1;
logevent("Pageant is running. Requesting keys.");
/* Request the keys held by the agent. */
PUT_32BIT(s->request, 1);
s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
ssh->auth_agent_query = agent_query(
s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
if (ssh->auth_agent_query) {
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server while waiting"
" for agent response"));
crStop(0);
}
} while (pktin || inlen > 0);
r = ssh->agent_response;
s->responselen = ssh->agent_response_len;
}
s->response = (unsigned char *) r;
if (s->response && s->responselen >= 5 &&
s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
s->p = s->response + 5;
s->nkeys = toint(GET_32BIT(s->p));
if (s->nkeys < 0) {
logeventf(ssh, "Pageant reported negative key count %d",
s->nkeys);
s->nkeys = 0;
}
s->p += 4;
logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
unsigned char *pkblob = s->p;
s->p += 4;
{
int n, ok = FALSE;
do { /* do while (0) to make breaking easy */
n = ssh1_read_bignum
(s->p, toint(s->responselen-(s->p-s->response)),
&s->key.exponent);
if (n < 0)
break;
s->p += n;
n = ssh1_read_bignum
(s->p, toint(s->responselen-(s->p-s->response)),
&s->key.modulus);
if (n < 0)
break;
s->p += n;
if (s->responselen - (s->p-s->response) < 4)
break;
s->commentlen = toint(GET_32BIT(s->p));
s->p += 4;
if (s->commentlen < 0 ||
toint(s->responselen - (s->p-s->response)) <
s->commentlen)
break;
s->commentp = (char *)s->p;
s->p += s->commentlen;
ok = TRUE;
} while (0);
if (!ok) {
logevent("Pageant key list packet was truncated");
break;
}
}
if (s->publickey_blob) {
if (!memcmp(pkblob, s->publickey_blob,
s->publickey_bloblen)) {
logeventf(ssh, "Pageant key #%d matches "
"configured key file", s->keyi);
s->tried_publickey = 1;
} else
/* Skip non-configured key */
continue;
}
logeventf(ssh, "Trying Pageant key #%d", s->keyi);
send_packet(ssh, SSH1_CMSG_AUTH_RSA,
PKT_BIGNUM, s->key.modulus, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
logevent("Key refused");
continue;
}
logevent("Received RSA challenge");
if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
bombout(("Server's RSA challenge was badly formatted"));
crStop(0);
}
{
char *agentreq, *q, *ret;
void *vret;
int len, retlen;
len = 1 + 4; /* message type, bit count */
len += ssh1_bignum_length(s->key.exponent);
len += ssh1_bignum_length(s->key.modulus);
len += ssh1_bignum_length(s->challenge);
len += 16; /* session id */
len += 4; /* response format */
agentreq = snewn(4 + len, char);
PUT_32BIT(agentreq, len);
q = agentreq + 4;
*q++ = SSH1_AGENTC_RSA_CHALLENGE;
PUT_32BIT(q, bignum_bitcount(s->key.modulus));
q += 4;
q += ssh1_write_bignum(q, s->key.exponent);
q += ssh1_write_bignum(q, s->key.modulus);
q += ssh1_write_bignum(q, s->challenge);
memcpy(q, s->session_id, 16);
q += 16;
PUT_32BIT(q, 1); /* response format */
ssh->auth_agent_query = agent_query(
agentreq, len + 4, &vret, &retlen,
ssh_agent_callback, ssh);
if (ssh->auth_agent_query) {
sfree(agentreq);
do {
crReturn(0);
if (pktin) {
bombout(("Unexpected data from server"
" while waiting for agent"
" response"));
crStop(0);
}
} while (pktin || inlen > 0);
vret = ssh->agent_response;
retlen = ssh->agent_response_len;
} else
sfree(agentreq);
ret = vret;
if (ret) {
if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
logevent("Sending Pageant's response");
send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
PKT_DATA, ret + 5, 16,
PKT_END);
sfree(ret);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_SUCCESS) {
logevent
("Pageant's response accepted");
if (flags & FLAG_VERBOSE) {
c_write_str(ssh, "Authenticated using"
" RSA key \"");
c_write(ssh, s->commentp,
s->commentlen);
c_write_str(ssh, "\" from agent\r\n");
}
s->authed = TRUE;
} else
logevent
("Pageant's response not accepted");
} else {
logevent
("Pageant failed to answer challenge");
sfree(ret);
}
} else {
logevent("No reply received from Pageant");
}
}
freebn(s->key.exponent);
freebn(s->key.modulus);
freebn(s->challenge);
if (s->authed)
break;
}
sfree(s->response);
if (s->publickey_blob && !s->tried_publickey)
logevent("Configured key file not in Pageant");
} else {
logevent("Failed to get reply from Pageant");
}
if (s->authed)
break;
}
if (s->publickey_blob && s->privatekey_available &&
!s->tried_publickey) {
/*
* Try public key authentication with the specified
* key file.
*/
int got_passphrase; /* need not be kept over crReturn */
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Trying public key authentication.\r\n");
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
logeventf(ssh, "Trying public key \"%s\"",
filename_to_str(s->keyfile));
s->tried_publickey = 1;
got_passphrase = FALSE;
while (!got_passphrase) {
/*
* Get a passphrase, if necessary.
*/
char *passphrase = NULL; /* only written after crReturn */
const char *error;
if (!s->privatekey_encrypted) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "No passphrase required.\r\n");
passphrase = NULL;
} else {
int ret; /* need not be kept over crReturn */
s->cur_prompt = new_prompts(ssh->frontend);
s->cur_prompt->to_server = FALSE;
s->cur_prompt->name = dupstr("SSH key passphrase");
add_prompt(s->cur_prompt,
dupprintf("Passphrase for key \"%.100s\": ",
s->publickey_comment), FALSE);
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/* Failed to get a passphrase. Terminate. */
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, NULL, "Unable to authenticate",
0, TRUE);
crStop(0);
}
passphrase = dupstr(s->cur_prompt->prompts[0]->result);
free_prompts(s->cur_prompt);
}
/*
* Try decrypting key with passphrase.
*/
s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
ret = loadrsakey(s->keyfile, &s->key, passphrase,
&error);
if (passphrase) {
smemclr(passphrase, strlen(passphrase));
sfree(passphrase);
}
if (ret == 1) {
/* Correct passphrase. */
got_passphrase = TRUE;
} else if (ret == 0) {
c_write_str(ssh, "Couldn't load private key from ");
c_write_str(ssh, filename_to_str(s->keyfile));
c_write_str(ssh, " (");
c_write_str(ssh, error);
c_write_str(ssh, ").\r\n");
got_passphrase = FALSE;
break; /* go and try something else */
} else if (ret == -1) {
c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
got_passphrase = FALSE;
/* and try again */
} else {
assert(0 && "unexpected return from loadrsakey()");
got_passphrase = FALSE; /* placate optimisers */
}
}
if (got_passphrase) {
/*
* Send a public key attempt.
*/
send_packet(ssh, SSH1_CMSG_AUTH_RSA,
PKT_BIGNUM, s->key.modulus, PKT_END);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
c_write_str(ssh, "Server refused our public key.\r\n");
continue; /* go and try something else */
}
if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
bombout(("Bizarre response to offer of public key"));
crStop(0);
}
{
int i;
unsigned char buffer[32];
Bignum challenge, response;
if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
bombout(("Server's RSA challenge was badly formatted"));
crStop(0);
}
response = rsadecrypt(challenge, &s->key);
freebn(s->key.private_exponent);/* burn the evidence */
for (i = 0; i < 32; i++) {
buffer[i] = bignum_byte(response, 31 - i);
}
MD5Init(&md5c);
MD5Update(&md5c, buffer, 32);
MD5Update(&md5c, s->session_id, 16);
MD5Final(buffer, &md5c);
send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
PKT_DATA, buffer, 16, PKT_END);
freebn(challenge);
freebn(response);
}
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Failed to authenticate with"
" our public key.\r\n");
continue; /* go and try something else */
} else if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Bizarre response to RSA authentication response"));
crStop(0);
}
break; /* we're through! */
}
}
/*
* Otherwise, try various forms of password-like authentication.
*/
s->cur_prompt = new_prompts(ssh->frontend);
if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
(s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
!s->tis_auth_refused) {
s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
logevent("Requested TIS authentication");
send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
logevent("TIS authentication declined");
if (flags & FLAG_INTERACTIVE)
c_write_str(ssh, "TIS authentication refused.\r\n");
s->tis_auth_refused = 1;
continue;
} else {
char *challenge;
int challengelen;
char *instr_suf, *prompt;
ssh_pkt_getstring(pktin, &challenge, &challengelen);
if (!challenge) {
bombout(("TIS challenge packet was badly formed"));
crStop(0);
}
logevent("Received TIS challenge");
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH TIS authentication");
/* Prompt heuristic comes from OpenSSH */
if (memchr(challenge, '\n', challengelen)) {
instr_suf = dupstr("");
prompt = dupprintf("%.*s", challengelen, challenge);
} else {
instr_suf = dupprintf("%.*s", challengelen, challenge);
prompt = dupstr("Response: ");
}
s->cur_prompt->instruction =
dupprintf("Using TIS authentication.%s%s",
(*instr_suf) ? "\n" : "",
instr_suf);
s->cur_prompt->instr_reqd = TRUE;
add_prompt(s->cur_prompt, prompt, FALSE);
sfree(instr_suf);
}
}
if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
(s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
!s->ccard_auth_refused) {
s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
logevent("Requested CryptoCard authentication");
send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
crWaitUntil(pktin);
if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
logevent("CryptoCard authentication declined");
c_write_str(ssh, "CryptoCard authentication refused.\r\n");
s->ccard_auth_refused = 1;
continue;
} else {
char *challenge;
int challengelen;
char *instr_suf, *prompt;
ssh_pkt_getstring(pktin, &challenge, &challengelen);
if (!challenge) {
bombout(("CryptoCard challenge packet was badly formed"));
crStop(0);
}
logevent("Received CryptoCard challenge");
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
s->cur_prompt->name_reqd = FALSE;
/* Prompt heuristic comes from OpenSSH */
if (memchr(challenge, '\n', challengelen)) {
instr_suf = dupstr("");
prompt = dupprintf("%.*s", challengelen, challenge);
} else {
instr_suf = dupprintf("%.*s", challengelen, challenge);
prompt = dupstr("Response: ");
}
s->cur_prompt->instruction =
dupprintf("Using CryptoCard authentication.%s%s",
(*instr_suf) ? "\n" : "",
instr_suf);
s->cur_prompt->instr_reqd = TRUE;
add_prompt(s->cur_prompt, prompt, FALSE);
sfree(instr_suf);
}
}
if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
bombout(("No supported authentication methods available"));
crStop(0);
}
s->cur_prompt->to_server = TRUE;
s->cur_prompt->name = dupstr("SSH password");
add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
ssh->username, ssh->savedhost),
FALSE);
}
/*
* Show password prompt, having first obtained it via a TIS
* or CryptoCard exchange if we're doing TIS or CryptoCard
* authentication.
*/
{
int ret; /* need not be kept over crReturn */
ret = get_userpass_input(s->cur_prompt, NULL, 0);
while (ret < 0) {
ssh->send_ok = 1;
crWaitUntil(!pktin);
ret = get_userpass_input(s->cur_prompt, in, inlen);
ssh->send_ok = 0;
}
if (!ret) {
/*
* Failed to get a password (for example
* because one was supplied on the command line
* which has already failed to work). Terminate.
*/
free_prompts(s->cur_prompt);
ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
crStop(0);
}
}
if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
/*
* Defence against traffic analysis: we send a
* whole bunch of packets containing strings of
* different lengths. One of these strings is the
* password, in a SSH1_CMSG_AUTH_PASSWORD packet.
* The others are all random data in
* SSH1_MSG_IGNORE packets. This way a passive
* listener can't tell which is the password, and
* hence can't deduce the password length.
*
* Anybody with a password length greater than 16
* bytes is going to have enough entropy in their
* password that a listener won't find it _that_
* much help to know how long it is. So what we'll
* do is:
*
* - if password length < 16, we send 15 packets
* containing string lengths 1 through 15
*
* - otherwise, we let N be the nearest multiple
* of 8 below the password length, and send 8
* packets containing string lengths N through
* N+7. This won't obscure the order of
* magnitude of the password length, but it will
* introduce a bit of extra uncertainty.
*
* A few servers can't deal with SSH1_MSG_IGNORE, at
* least in this context. For these servers, we need
* an alternative defence. We make use of the fact
* that the password is interpreted as a C string:
* so we can append a NUL, then some random data.
*
* A few servers can deal with neither SSH1_MSG_IGNORE
* here _nor_ a padded password string.
* For these servers we are left with no defences
* against password length sniffing.
*/
if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
/*
* The server can deal with SSH1_MSG_IGNORE, so
* we can use the primary defence.
*/
int bottom, top, pwlen, i;
char *randomstr;
pwlen = strlen(s->cur_prompt->prompts[0]->result);
if (pwlen < 16) {
bottom = 0; /* zero length passwords are OK! :-) */
top = 15;
} else {
bottom = pwlen & ~7;
top = bottom + 7;
}
assert(pwlen >= bottom && pwlen <= top);
randomstr = snewn(top + 1, char);
for (i = bottom; i <= top; i++) {
if (i == pwlen) {
defer_packet(ssh, s->pwpkt_type,
PKT_STR,s->cur_prompt->prompts[0]->result,
PKT_END);
} else {
for (j = 0; j < i; j++) {
do {
randomstr[j] = random_byte();
} while (randomstr[j] == '\0');
}
randomstr[i] = '\0';
defer_packet(ssh, SSH1_MSG_IGNORE,
PKT_STR, randomstr, PKT_END);
}
}
logevent("Sending password with camouflage packets");
ssh_pkt_defersend(ssh);
sfree(randomstr);
}
else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
/*
* The server can't deal with SSH1_MSG_IGNORE
* but can deal with padded passwords, so we
* can use the secondary defence.
*/
char string[64];
char *ss;
int len;
len = strlen(s->cur_prompt->prompts[0]->result);
if (len < sizeof(string)) {
ss = string;
strcpy(string, s->cur_prompt->prompts[0]->result);
len++; /* cover the zero byte */
while (len < sizeof(string)) {
string[len++] = (char) random_byte();
}
} else {
ss = s->cur_prompt->prompts[0]->result;
}
logevent("Sending length-padded password");
send_packet(ssh, s->pwpkt_type,
PKT_INT, len, PKT_DATA, ss, len,
PKT_END);
} else {
/*
* The server is believed unable to cope with
* any of our password camouflage methods.
*/
int len;
len = strlen(s->cur_prompt->prompts[0]->result);
logevent("Sending unpadded password");
send_packet(ssh, s->pwpkt_type,
PKT_INT, len,
PKT_DATA, s->cur_prompt->prompts[0]->result, len,
PKT_END);
}
} else {
send_packet(ssh, s->pwpkt_type,
PKT_STR, s->cur_prompt->prompts[0]->result,
PKT_END);
}
logevent("Sent password");
free_prompts(s->cur_prompt);
crWaitUntil(pktin);
if (pktin->type == SSH1_SMSG_FAILURE) {
if (flags & FLAG_VERBOSE)
c_write_str(ssh, "Access denied\r\n");
logevent("Authentication refused");
} else if (pktin->type != SSH1_SMSG_SUCCESS) {
bombout(("Strange packet received, type %d", pktin->type));
crStop(0);
}
}
/* Clear up */
if (s->publickey_blob) {
sfree(s->publickey_blob);
sfree(s->publickey_comment);
}
logevent("Authentication successful");
crFinish(1);
}
static void ssh_channel_try_eof(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
assert(c->pending_eof); /* precondition for calling us */
if (c->halfopen)
return; /* can't close: not even opened yet */
if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
return; /* can't send EOF: pending outgoing data */
c->pending_eof = FALSE; /* we're about to send it */
if (ssh->version == 1) {
send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
PKT_END);
c->closes |= CLOSES_SENT_EOF;
} else {
struct Packet *pktout;
pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
ssh2_pkt_adduint32(pktout, c->remoteid);
ssh2_pkt_send(ssh, pktout);
c->closes |= CLOSES_SENT_EOF;
ssh2_channel_check_close(c);
}
}
Conf *sshfwd_get_conf(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
return ssh->conf;
}
void sshfwd_write_eof(struct ssh_channel *c)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return;
if (c->closes & CLOSES_SENT_EOF)
return;
c->pending_eof = TRUE;
ssh_channel_try_eof(c);
}
void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
{
Ssh ssh = c->ssh;
char *reason;
if (ssh->state == SSH_STATE_CLOSED)
return;
reason = dupprintf("due to local error: %s", err);
ssh_channel_close_local(c, reason);
sfree(reason);
c->pending_eof = FALSE; /* this will confuse a zombie channel */
ssh2_channel_check_close(c);
}
int sshfwd_write(struct ssh_channel *c, char *buf, int len)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return 0;
return ssh_send_channel_data(c, buf, len);
}
void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
{
Ssh ssh = c->ssh;
if (ssh->state == SSH_STATE_CLOSED)
return;
ssh_channel_unthrottle(c, bufsize);
}
static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
{
struct queued_handler *qh = ssh->qhead;
assert(qh != NULL);
assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
if (qh->msg1 > 0) {
assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
}
if (qh->msg2 > 0) {
assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
}
if (qh->next) {
ssh->qhead = qh->next;
if (ssh->qhead->msg1 > 0) {
ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
}
if (ssh->qhead->msg2 > 0) {
ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
}
} else {
ssh->qhead = ssh->qtail = NULL;
}
qh->handler(ssh, pktin, qh->ctx);
sfree(qh);
}
static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
chandler_fn_t handler, void *ctx)
{
struct queued_handler *qh;
qh = snew(struct queued_handler);
qh->msg1 = msg1;
qh->msg2 = msg2;
qh->handler = handler;
qh->ctx = ctx;
qh->next = NULL;
if (ssh->qtail == NULL) {
ssh->qhead = qh;
if (qh->msg1 > 0) {
ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
}
if (qh->msg2 > 0) {
ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
}
} else {
ssh->qtail->next = qh;
}
ssh->qtail = qh;
}
static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
{
struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
SSH2_MSG_REQUEST_SUCCESS)) {
logeventf(ssh, "Remote port forwarding from %s enabled",
pf->sportdesc);
} else {
logeventf(ssh, "Remote port forwarding from %s refused",
pf->sportdesc);
rpf = del234(ssh->rportfwds, pf);
assert(rpf == pf);
pf->pfrec->remote = NULL;
free_rportfwd(pf);
}
}
int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
void *share_ctx)
{
struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
pf->dhost = NULL;
pf->dport = 0;
pf->share_ctx = share_ctx;
pf->shost = dupstr(shost);
pf->sport = sport;
pf->sportdesc = NULL;
if (!ssh->rportfwds) {
assert(ssh->version == 2);
ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
}
if (add234(ssh->rportfwds, pf) != pf) {
sfree(pf->shost);
sfree(pf);
return FALSE;
}
return TRUE;
}
static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
void *ctx)
{
share_got_pkt_from_server(ctx, pktin->type,
pktin->body, pktin->length);
}
void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
{
ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
ssh_sharing_global_request_response, share_ctx);
}
static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
{
struct ssh_portfwd *epf;
int i;
char *key, *val;
if (!ssh->portfwds) {
ssh->portfwds = newtree234(ssh_portcmp);
} else {
/*
* Go through the existing port forwardings and tag them
* with status==DESTROY. Any that we want to keep will be
* re-enabled (status==KEEP) as we go through the
* configuration and find out which bits are the same as
* they were before.
*/
struct ssh_portfwd *epf;
int i;
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
epf->status = DESTROY;
}
for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
val != NULL;
val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
char *kp, *kp2, *vp, *vp2;
char address_family, type;
int sport,dport,sserv,dserv;
char *sports, *dports, *saddr, *host;
kp = key;
address_family = 'A';
type = 'L';
if (*kp == 'A' || *kp == '4' || *kp == '6')
address_family = *kp++;
if (*kp == 'L' || *kp == 'R')
type = *kp++;
if ((kp2 = host_strchr(kp, ':')) != NULL) {
/*
* There's a colon in the middle of the source port
* string, which means that the part before it is
* actually a source address.
*/
char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
saddr = host_strduptrim(saddr_tmp);
sfree(saddr_tmp);
sports = kp2+1;
} else {
saddr = NULL;
sports = kp;
}
sport = atoi(sports);
sserv = 0;
if (sport == 0) {
sserv = 1;
sport = net_service_lookup(sports);
if (!sport) {
logeventf(ssh, "Service lookup failed for source"
" port \"%s\"", sports);
}
}
if (type == 'L' && !strcmp(val, "D")) {
/* dynamic forwarding */
host = NULL;
dports = NULL;
dport = -1;
dserv = 0;
type = 'D';
} else {
/* ordinary forwarding */
vp = val;
vp2 = vp + host_strcspn(vp, ":");
host = dupprintf("%.*s", (int)(vp2 - vp), vp);
if (*vp2)
vp2++;
dports = vp2;
dport = atoi(dports);
dserv = 0;
if (dport == 0) {
dserv = 1;
dport = net_service_lookup(dports);
if (!dport) {
logeventf(ssh, "Service lookup failed for destination"
" port \"%s\"", dports);
}
}
}
if (sport && dport) {
/* Set up a description of the source port. */
struct ssh_portfwd *pfrec, *epfrec;
pfrec = snew(struct ssh_portfwd);
pfrec->type = type;
pfrec->saddr = saddr;
pfrec->sserv = sserv ? dupstr(sports) : NULL;
pfrec->sport = sport;
pfrec->daddr = host;
pfrec->dserv = dserv ? dupstr(dports) : NULL;
pfrec->dport = dport;
pfrec->local = NULL;
pfrec->remote = NULL;
pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
address_family == '6' ? ADDRTYPE_IPV6 :
ADDRTYPE_UNSPEC);
epfrec = add234(ssh->portfwds, pfrec);
if (epfrec != pfrec) {
if (epfrec->status == DESTROY) {
/*
* We already have a port forwarding up and running
* with precisely these parameters. Hence, no need
* to do anything; simply re-tag the existing one
* as KEEP.
*/
epfrec->status = KEEP;
}
/*
* Anything else indicates that there was a duplicate
* in our input, which we'll silently ignore.
*/
free_portfwd(pfrec);
} else {
pfrec->status = CREATE;
}
} else {
sfree(saddr);
sfree(host);
}
}
/*
* Now go through and destroy any port forwardings which were
* not re-enabled.
*/
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
if (epf->status == DESTROY) {
char *message;
message = dupprintf("%s port forwarding from %s%s%d",
epf->type == 'L' ? "local" :
epf->type == 'R' ? "remote" : "dynamic",
epf->saddr ? epf->saddr : "",
epf->saddr ? ":" : "",
epf->sport);
if (epf->type != 'D') {
char *msg2 = dupprintf("%s to %s:%d", message,
epf->daddr, epf->dport);
sfree(message);
message = msg2;
}
logeventf(ssh, "Cancelling %s", message);
sfree(message);
/* epf->remote or epf->local may be NULL if setting up a
* forwarding failed. */
if (epf->remote) {
struct ssh_rportfwd *rpf = epf->remote;
struct Packet *pktout;
/*
* Cancel the port forwarding at the server
* end.
*/
if (ssh->version == 1) {
/*
* We cannot cancel listening ports on the
* server side in SSH-1! There's no message
* to support it. Instead, we simply remove
* the rportfwd record from the local end
* so that any connections the server tries
* to make on it are rejected.
*/
} else {
pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
if (epf->saddr) {
ssh2_pkt_addstring(pktout, epf->saddr);
} else if (conf_get_int(conf, CONF_rport_acceptall)) {
/* XXX: rport_acceptall may not represent
* what was used to open the original connection,
* since it's reconfigurable. */
ssh2_pkt_addstring(pktout, "");
} else {
ssh2_pkt_addstring(pktout, "localhost");
}
ssh2_pkt_adduint32(pktout, epf->sport);
ssh2_pkt_send(ssh, pktout);
}
del234(ssh->rportfwds, rpf);
free_rportfwd(rpf);
} else if (epf->local) {
pfl_terminate(epf->local);
}
delpos234(ssh->portfwds, i);
free_portfwd(epf);
i--; /* so we don't skip one in the list */
}
/*
* And finally, set up any new port forwardings (status==CREATE).
*/
for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
if (epf->status == CREATE) {
char *sportdesc, *dportdesc;
sportdesc = dupprintf("%s%s%s%s%d%s",
epf->saddr ? epf->saddr : "",
epf->saddr ? ":" : "",
epf->sserv ? epf->sserv : "",
epf->sserv ? "(" : "",
epf->sport,
epf->sserv ? ")" : "");
if (epf->type == 'D') {
dportdesc = NULL;
} else {
dportdesc = dupprintf("%s:%s%s%d%s",
epf->daddr,
epf->dserv ? epf->dserv : "",
epf->dserv ? "(" : "",
epf->dport,
epf->dserv ? ")" : "");
}
if (epf->type == 'L') {
char *err = pfl_listen(epf->daddr, epf->dport,
epf->saddr, epf->sport,
ssh, conf, &epf->local,
epf->addressfamily);
logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
sportdesc, dportdesc,
err ? " failed: " : "", err ? err : "");
if (err)
sfree(err);
} else if (epf->type == 'D') {
char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
ssh, conf, &epf->local,
epf->addressfamily);
logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
sportdesc,
err ? " failed: " : "", err ? err : "");
if (err)
sfree(err);
} else {
struct ssh_rportfwd *pf;
/*
* Ensure the remote port forwardings tree exists.
*/
if (!ssh->rportfwds) {
if (ssh->version == 1)
ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
else
ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
}
pf = snew(struct ssh_rportfwd);
pf->share_ctx = NULL;
pf->dhost = dupstr(epf->daddr);
pf->dport = epf->dport;
if (epf->saddr) {
pf->shost = dupstr(epf->saddr);
} else if (conf_get_int(conf, CONF_rport_acceptall)) {
pf->shost = dupstr("");
} else {
pf->shost = dupstr("localhost");
}
pf->sport = epf->sport;
if (add234(ssh->rportfwds, pf) != pf) {
logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
epf->daddr, epf->dport);
sfree(pf);
} else {
logeventf(ssh, "Requesting remote port %s"
" forward to %s", sportdesc, dportdesc);
pf->sportdesc = sportdesc;
sportdesc = NULL;
epf->remote = pf;
pf->pfrec = epf;
if (ssh->version == 1) {
send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
PKT_INT, epf->sport,
PKT_STR, epf->daddr,
PKT_INT, epf->dport,
PKT_END);
ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
SSH1_SMSG_FAILURE,
ssh_rportfwd_succfail, pf);
} else {
struct Packet *pktout;
pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
ssh2_pkt_addstring(pktout, "tcpip-forward");
ssh2_pkt_addbool(pktout, 1);/* want reply */
ssh2_pkt_addstring(pktout, pf->shost);
ssh2_pkt_adduint32(pktout, pf->sport);
ssh2_pkt_send(ssh, pktout);
ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
SSH2_MSG_REQUEST_FAILURE,
ssh_rportfwd_succfail, pf);
}
}
}
sfree(sportdesc);
sfree(dportdesc);
}
}
static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
{
char *string;
int stringlen, bufsize;
ssh_pkt_getstring(pktin, &string, &stringlen);
if (string == NULL) {
bombout(("Incoming terminal data packet was badly formed"));
return;
}
bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
string, stringlen);
if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
ssh->v1_stdout_throttling = 1;
ssh_throttle_conn(ssh, +1);
}
}
static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to our
* X-Server. Give them back a local channel number. */
struct ssh_channel *c;
int remoteid = ssh_pkt_getuint32(pktin);
logevent("Received X11 connect request");
/* Refuse if X11 forwarding is disabled. */
if (!ssh->X11_fwd_enabled) {
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
logevent("Rejected X11 connect request");
} else {
c = snew(struct ssh_channel);
c->ssh = ssh;
ssh_channel_init(c);
c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_X11; /* identify channel type */
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT,
c->localid, PKT_END);
logevent("Opened X11 forward channel");
}
}
static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to our
* agent. Give them back a local channel number. */
struct ssh_channel *c;
int remoteid = ssh_pkt_getuint32(pktin);
/* Refuse if agent forwarding is disabled. */
if (!ssh->agentfwd_enabled) {
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
c = snew(struct ssh_channel);
c->ssh = ssh;
ssh_channel_init(c);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_AGENT; /* identify channel type */
c->u.a.lensofar = 0;
c->u.a.message = NULL;
c->u.a.pending = NULL;
c->u.a.outstanding_requests = 0;
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT, c->localid,
PKT_END);
}
}
static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
{
/* Remote side is trying to open a channel to talk to a
* forwarded port. Give them back a local channel number. */
struct ssh_rportfwd pf, *pfp;
int remoteid;
int hostsize, port;
char *host;
char *err;
remoteid = ssh_pkt_getuint32(pktin);
ssh_pkt_getstring(pktin, &host, &hostsize);
port = ssh_pkt_getuint32(pktin);
pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
pf.dport = port;
pfp = find234(ssh->rportfwds, &pf, NULL);
if (pfp == NULL) {
logeventf(ssh, "Rejected remote port open request for %s:%d",
pf.dhost, port);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
struct ssh_channel *c = snew(struct ssh_channel);
c->ssh = ssh;
logeventf(ssh, "Received remote port open request for %s:%d",
pf.dhost, port);
err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
c, ssh->conf, pfp->pfrec->addressfamily);
if (err != NULL) {
logeventf(ssh, "Port open failed: %s", err);
sfree(err);
sfree(c);
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
PKT_INT, remoteid, PKT_END);
} else {
ssh_channel_init(c);
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_SOCKDATA; /* identify channel type */
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT,
c->localid, PKT_END);
logevent("Forwarded port opened successfully");
}
}
sfree(pf.dhost);
}
static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
{
struct ssh_channel *c;
c = ssh_channel_msg(ssh, pktin);
if (c && c->type == CHAN_SOCKDATA) {
c->remoteid = ssh_pkt_getuint32(pktin);
c->halfopen = FALSE;
c->throttling_conn = 0;
pfd_confirm(c->u.pfd.pf);
}
if (c && c->pending_eof) {
/*
* We have a pending close on this channel,
* which we decided on before the server acked
* the channel open. So now we know the
* remoteid, we can close it again.
*/
ssh_channel_try_eof(c);
}
}
c->remoteid = remoteid;
c->halfopen = FALSE;
c->type = CHAN_AGENT; /* identify channel type */
c->u.a.lensofar = 0;
c->u.a.message = NULL;
c->u.a.pending = NULL;
c->u.a.outstanding_requests = 0;
send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
PKT_INT, c->remoteid, PKT_INT, c->localid,
PKT_END);
del234(ssh->channels, c);
sfree(c);
}
}
|
CWE-119
| 178,103 | 233 |
325909590182680995779527787302149618683
| null | null | null |
openssl
|
6e629b5be45face20b4ca71c4fcbfed78b864a2e
| 1 |
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
X509 **pissuer, int *pscore, unsigned int *preasons,
STACK_OF(X509_CRL) *crls)
{
int i, crl_score, best_score = *pscore;
unsigned int reasons, best_reasons = 0;
X509 *x = ctx->current_cert;
X509_CRL *crl, *best_crl = NULL;
X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
for (i = 0; i < sk_X509_CRL_num(crls); i++) {
crl = sk_X509_CRL_value(crls, i);
reasons = *preasons;
crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
if (crl_score < best_score)
continue;
/* If current CRL is equivalent use it if it is newer */
if (crl_score == best_score) {
int day, sec;
if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl),
X509_CRL_get_lastUpdate(crl)) == 0)
continue;
/*
* ASN1_TIME_diff never returns inconsistent signs for |day|
* and |sec|.
*/
if (day <= 0 && sec <= 0)
continue;
}
best_crl = crl;
best_crl_issuer = crl_issuer;
best_score = crl_score;
best_reasons = reasons;
}
if (best_crl) {
if (*pcrl)
X509_CRL_free(*pcrl);
*pcrl = best_crl;
*pissuer = best_crl_issuer;
*pscore = best_score;
*preasons = best_reasons;
CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
if (*pdcrl) {
X509_CRL_free(*pdcrl);
*pdcrl = NULL;
}
get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
}
if (best_score >= CRL_SCORE_VALID)
return 1;
return 0;
}
|
CWE-476
| 178,112 | 234 |
135793188300012979952739633768625629213
| null | null | null |
spice
|
9113dc6a303604a2d9812ac70c17d076ef11886c
| 1 |
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status)
{
VCardAPDU *new_apdu;
*status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE;
if (len < 4) {
*status = VCARD7816_STATUS_ERROR_WRONG_LENGTH;
return NULL;
}
new_apdu = g_new(VCardAPDU, 1);
new_apdu->a_data = g_memdup(raw_apdu, len);
new_apdu->a_len = len;
*status = vcard_apdu_set_class(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
return NULL;
}
*status = vcard_apdu_set_length(new_apdu);
if (*status != VCARD7816_STATUS_SUCCESS) {
g_free(new_apdu);
new_apdu = NULL;
}
return new_apdu;
}
|
CWE-772
| 178,113 | 235 |
336092549544277958136877844795822151529
| null | null | null |
virglrenderer
|
93761787b29f37fa627dea9082cdfc1a1ec608d6
| 1 |
int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
|
CWE-190
| 178,117 | 238 |
277560631509583395850123120925257608076
| null | null | null |
virglrenderer
|
a2f12a1b0f95b13b6f8dc3d05d7b74b4386394e4
| 1 |
static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx,
struct vrend_shader *vs,
struct vrend_shader *fs,
struct vrend_shader *gs)
{
struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program);
char name[16];
int i;
GLuint prog_id;
GLint lret;
int id;
int last_shader;
if (!sprog)
return NULL;
/* need to rewrite VS code to add interpolation params */
if ((gs && gs->compiled_fs_id != fs->id) ||
(!gs && vs->compiled_fs_id != fs->id)) {
bool ret;
if (gs)
vrend_patch_vertex_shader_interpolants(gs->glsl_prog,
&gs->sel->sinfo,
&fs->sel->sinfo, true, fs->key.flatshade);
else
vrend_patch_vertex_shader_interpolants(vs->glsl_prog,
&vs->sel->sinfo,
&fs->sel->sinfo, false, fs->key.flatshade);
ret = vrend_compile_shader(ctx, gs ? gs : vs);
if (ret == false) {
glDeleteShader(gs ? gs->id : vs->id);
free(sprog);
return NULL;
}
if (gs)
gs->compiled_fs_id = fs->id;
else
vs->compiled_fs_id = fs->id;
}
prog_id = glCreateProgram();
glAttachShader(prog_id, vs->id);
if (gs) {
if (gs->id > 0)
glAttachShader(prog_id, gs->id);
set_stream_out_varyings(prog_id, &gs->sel->sinfo);
}
else
set_stream_out_varyings(prog_id, &vs->sel->sinfo);
glAttachShader(prog_id, fs->id);
if (fs->sel->sinfo.num_outputs > 1) {
if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1");
sprog->dual_src_linked = true;
} else {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1");
sprog->dual_src_linked = false;
}
} else
sprog->dual_src_linked = false;
if (vrend_state.have_vertex_attrib_binding) {
uint32_t mask = vs->sel->sinfo.attrib_input_mask;
while (mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "in_%d", i);
glBindAttribLocation(prog_id, i, name);
}
}
glLinkProgram(prog_id);
glGetProgramiv(prog_id, GL_LINK_STATUS, &lret);
if (lret == GL_FALSE) {
char infolog[65536];
int len;
glGetProgramInfoLog(prog_id, 65536, &len, infolog);
fprintf(stderr,"got error linking\n%s\n", infolog);
/* dump shaders */
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0);
fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog);
if (gs)
fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog);
fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog);
glDeleteProgram(prog_id);
return NULL;
}
sprog->ss[PIPE_SHADER_FRAGMENT] = fs;
sprog->ss[PIPE_SHADER_GEOMETRY] = gs;
list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs);
list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs);
if (gs)
list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs);
last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT;
sprog->id = prog_id;
list_addtail(&sprog->head, &ctx->sub->programs);
if (fs->key.pstipple_tex)
sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler");
else
sprog->fs_stipple_loc = -1;
sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust");
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.samplers_used_mask) {
uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask;
int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask);
int index;
sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask;
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) {
sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t));
sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t));
} else {
sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL;
}
sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t));
if (sprog->samp_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
index = 0;
while(mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "%ssamp%d", prefix, i);
sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name);
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) {
snprintf(name, 14, "%sshadmask%d", prefix, i);
sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name);
snprintf(name, 14, "%sshadadd%d", prefix, i);
sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name);
}
index++;
}
}
} else {
sprog->samp_locs[id] = NULL;
sprog->shadow_samp_mask_locs[id] = NULL;
sprog->shadow_samp_add_locs[id] = NULL;
sprog->shadow_samp_mask[id] = 0;
}
sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_consts) {
sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t));
if (sprog->const_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) {
snprintf(name, 16, "%sconst0[%d]", prefix, i);
sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name);
}
}
} else
sprog->const_locs[id] = NULL;
}
if (!vrend_state.have_vertex_attrib_binding) {
if (vs->sel->sinfo.num_inputs) {
sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t));
if (sprog->attrib_locs) {
for (i = 0; i < vs->sel->sinfo.num_inputs; i++) {
snprintf(name, 10, "in_%d", i);
sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name);
}
}
} else
sprog->attrib_locs = NULL;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_ubos) {
const char *prefix = pipe_shader_to_prefix(id);
sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t));
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) {
snprintf(name, 16, "%subo%d", prefix, i + 1);
sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name);
}
} else
sprog->ubo_locs[id] = NULL;
}
if (vs->sel->sinfo.num_ucp) {
for (i = 0; i < vs->sel->sinfo.num_ucp; i++) {
snprintf(name, 10, "clipp[%d]", i);
sprog->clip_locs[i] = glGetUniformLocation(prog_id, name);
}
}
return sprog;
}
|
CWE-772
| 178,118 | 239 |
323217311057867578248239667496178090457
| null | null | null |
virglrenderer
|
0a5dff15912207b83018485f83e067474e818bab
| 1 |
void vrend_renderer_context_destroy(uint32_t handle)
{
struct vrend_decode_ctx *ctx;
bool ret;
if (handle >= VREND_MAX_CTX)
return;
ctx = dec_ctx[handle];
if (!ctx)
return;
vrend_hw_switch_context(dec_ctx[0]->grctx, true);
}
|
CWE-476
| 178,121 | 240 |
248536757234533019908341843286492380403
| null | null | null |
virglrenderer
|
e534b51ca3c3cd25f3990589932a9ed711c59b27
| 1 |
static boolean parse_identifier( const char **pcur, char *ret )
{
const char *cur = *pcur;
int i = 0;
if (is_alpha_underscore( cur )) {
ret[i++] = *cur++;
while (is_alpha_underscore( cur ) || is_digit( cur ))
ret[i++] = *cur++;
ret[i++] = '\0';
*pcur = cur;
return TRUE;
/* Parse floating point.
*/
static boolean parse_float( const char **pcur, float *val )
{
const char *cur = *pcur;
boolean integral_part = FALSE;
boolean fractional_part = FALSE;
if (*cur == '0' && *(cur + 1) == 'x') {
union fi fi;
fi.ui = strtoul(cur, NULL, 16);
*val = fi.f;
cur += 10;
goto out;
}
*val = (float) atof( cur );
if (*cur == '-' || *cur == '+')
cur++;
if (is_digit( cur )) {
cur++;
integral_part = TRUE;
while (is_digit( cur ))
cur++;
}
if (*cur == '.') {
cur++;
if (is_digit( cur )) {
cur++;
fractional_part = TRUE;
while (is_digit( cur ))
cur++;
}
}
if (!integral_part && !fractional_part)
return FALSE;
if (uprcase( *cur ) == 'E') {
cur++;
if (*cur == '-' || *cur == '+')
cur++;
if (is_digit( cur )) {
cur++;
while (is_digit( cur ))
cur++;
}
else
return FALSE;
}
out:
*pcur = cur;
return TRUE;
}
static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1)
{
const char *cur = *pcur;
union {
double dval;
uint32_t uval[2];
} v;
v.dval = strtod(cur, (char**)pcur);
if (*pcur == cur)
return FALSE;
*val0 = v.uval[0];
*val1 = v.uval[1];
return TRUE;
}
struct translate_ctx
{
const char *text;
const char *cur;
struct tgsi_token *tokens;
struct tgsi_token *tokens_cur;
struct tgsi_token *tokens_end;
struct tgsi_header *header;
unsigned processor : 4;
unsigned implied_array_size : 6;
unsigned num_immediates;
};
static void report_error(struct translate_ctx *ctx, const char *format, ...)
{
va_list args;
int line = 1;
int column = 1;
const char *itr = ctx->text;
debug_printf("\nTGSI asm error: ");
va_start(args, format);
_debug_vprintf(format, args);
va_end(args);
while (itr != ctx->cur) {
if (*itr == '\n') {
column = 1;
++line;
}
++column;
++itr;
}
debug_printf(" [%d : %d] \n", line, column);
}
/* Parse shader header.
* Return TRUE for one of the following headers.
* FRAG
* GEOM
* VERT
*/
static boolean parse_header( struct translate_ctx *ctx )
{
uint processor;
if (str_match_nocase_whole( &ctx->cur, "FRAG" ))
processor = TGSI_PROCESSOR_FRAGMENT;
else if (str_match_nocase_whole( &ctx->cur, "VERT" ))
processor = TGSI_PROCESSOR_VERTEX;
else if (str_match_nocase_whole( &ctx->cur, "GEOM" ))
processor = TGSI_PROCESSOR_GEOMETRY;
else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" ))
processor = TGSI_PROCESSOR_TESS_CTRL;
else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" ))
processor = TGSI_PROCESSOR_TESS_EVAL;
else if (str_match_nocase_whole( &ctx->cur, "COMP" ))
processor = TGSI_PROCESSOR_COMPUTE;
else {
report_error( ctx, "Unknown header" );
return FALSE;
}
if (ctx->tokens_cur >= ctx->tokens_end)
return FALSE;
ctx->header = (struct tgsi_header *) ctx->tokens_cur++;
*ctx->header = tgsi_build_header();
if (ctx->tokens_cur >= ctx->tokens_end)
return FALSE;
*(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header );
ctx->processor = processor;
return TRUE;
}
static boolean parse_label( struct translate_ctx *ctx, uint *val )
{
const char *cur = ctx->cur;
if (parse_uint( &cur, val )) {
eat_opt_white( &cur );
if (*cur == ':') {
cur++;
ctx->cur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_file( const char **pcur, uint *file )
{
uint i;
for (i = 0; i < TGSI_FILE_COUNT; i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) {
*pcur = cur;
*file = i;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_opt_writemask(
struct translate_ctx *ctx,
uint *writemask )
{
const char *cur;
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == '.') {
cur++;
*writemask = TGSI_WRITEMASK_NONE;
eat_opt_white( &cur );
if (uprcase( *cur ) == 'X') {
cur++;
*writemask |= TGSI_WRITEMASK_X;
}
if (uprcase( *cur ) == 'Y') {
cur++;
*writemask |= TGSI_WRITEMASK_Y;
}
if (uprcase( *cur ) == 'Z') {
cur++;
*writemask |= TGSI_WRITEMASK_Z;
}
if (uprcase( *cur ) == 'W') {
cur++;
*writemask |= TGSI_WRITEMASK_W;
}
if (*writemask == TGSI_WRITEMASK_NONE) {
report_error( ctx, "Writemask expected" );
return FALSE;
}
ctx->cur = cur;
}
else {
*writemask = TGSI_WRITEMASK_XYZW;
}
return TRUE;
}
/* <register_file_bracket> ::= <file> `['
*/
static boolean
parse_register_file_bracket(
struct translate_ctx *ctx,
uint *file )
{
if (!parse_file( &ctx->cur, file )) {
report_error( ctx, "Unknown register file" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != '[') {
report_error( ctx, "Expected `['" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
/* <register_file_bracket_index> ::= <register_file_bracket> <uint>
*/
static boolean
parse_register_file_bracket_index(
struct translate_ctx *ctx,
uint *file,
int *index )
{
uint uindex;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
*index = (int) uindex;
return TRUE;
}
/* Parse simple 1d register operand.
* <register_dst> ::= <register_file_bracket_index> `]'
*/
static boolean
parse_register_1d(struct translate_ctx *ctx,
uint *file,
int *index )
{
if (!parse_register_file_bracket_index( ctx, file, index ))
return FALSE;
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
struct parsed_bracket {
int index;
uint ind_file;
int ind_index;
uint ind_comp;
uint ind_array;
};
static boolean
parse_register_bracket(
struct translate_ctx *ctx,
struct parsed_bracket *brackets)
{
const char *cur;
uint uindex;
memset(brackets, 0, sizeof(struct parsed_bracket));
eat_opt_white( &ctx->cur );
cur = ctx->cur;
if (parse_file( &cur, &brackets->ind_file )) {
if (!parse_register_1d( ctx, &brackets->ind_file,
&brackets->ind_index ))
return FALSE;
eat_opt_white( &ctx->cur );
if (*ctx->cur == '.') {
ctx->cur++;
eat_opt_white(&ctx->cur);
switch (uprcase(*ctx->cur)) {
case 'X':
brackets->ind_comp = TGSI_SWIZZLE_X;
break;
case 'Y':
brackets->ind_comp = TGSI_SWIZZLE_Y;
break;
case 'Z':
brackets->ind_comp = TGSI_SWIZZLE_Z;
break;
case 'W':
brackets->ind_comp = TGSI_SWIZZLE_W;
break;
default:
report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'");
return FALSE;
}
ctx->cur++;
eat_opt_white(&ctx->cur);
}
if (*ctx->cur == '+' || *ctx->cur == '-')
parse_int( &ctx->cur, &brackets->index );
else
brackets->index = 0;
}
else {
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
brackets->index = (int) uindex;
brackets->ind_file = TGSI_FILE_NULL;
brackets->ind_index = 0;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
if (*ctx->cur == '(') {
ctx->cur++;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &brackets->ind_array )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
return TRUE;
}
static boolean
parse_opt_register_src_bracket(
struct translate_ctx *ctx,
struct parsed_bracket *brackets,
int *parsed_brackets)
{
const char *cur = ctx->cur;
*parsed_brackets = 0;
eat_opt_white( &cur );
if (cur[0] == '[') {
++cur;
ctx->cur = cur;
if (!parse_register_bracket(ctx, brackets))
return FALSE;
*parsed_brackets = 1;
}
return TRUE;
}
/* Parse source register operand.
* <register_src> ::= <register_file_bracket_index> `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' |
* <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]'
*/
static boolean
parse_register_src(
struct translate_ctx *ctx,
uint *file,
struct parsed_bracket *brackets)
{
brackets->ind_comp = TGSI_SWIZZLE_X;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_bracket( ctx, brackets ))
return FALSE;
return TRUE;
}
struct parsed_dcl_bracket {
uint first;
uint last;
};
static boolean
parse_register_dcl_bracket(
struct translate_ctx *ctx,
struct parsed_dcl_bracket *bracket)
{
uint uindex;
memset(bracket, 0, sizeof(struct parsed_dcl_bracket));
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
/* it can be an empty bracket [] which means its range
* is from 0 to some implied size */
if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) {
bracket->first = 0;
bracket->last = ctx->implied_array_size - 1;
goto cleanup;
}
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
bracket->first = uindex;
eat_opt_white( &ctx->cur );
if (ctx->cur[0] == '.' && ctx->cur[1] == '.') {
uint uindex;
ctx->cur += 2;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal integer" );
return FALSE;
}
bracket->last = (int) uindex;
eat_opt_white( &ctx->cur );
}
else {
bracket->last = bracket->first;
}
cleanup:
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]' or `..'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
/* Parse register declaration.
* <register_dcl> ::= <register_file_bracket_index> `]' |
* <register_file_bracket_index> `..' <index> `]'
*/
static boolean
parse_register_dcl(
struct translate_ctx *ctx,
uint *file,
struct parsed_dcl_bracket *brackets,
int *num_brackets)
{
const char *cur;
*num_brackets = 0;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_dcl_bracket( ctx, &brackets[0] ))
return FALSE;
*num_brackets = 1;
cur = ctx->cur;
eat_opt_white( &cur );
if (cur[0] == '[') {
bool is_in = *file == TGSI_FILE_INPUT;
bool is_out = *file == TGSI_FILE_OUTPUT;
++cur;
ctx->cur = cur;
if (!parse_register_dcl_bracket( ctx, &brackets[1] ))
return FALSE;
/* for geometry shader we don't really care about
* the first brackets it's always the size of the
* input primitive. so we want to declare just
* the index relevant to the semantics which is in
* the second bracket */
/* tessellation has similar constraints to geometry shader */
if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) ||
(ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) ||
(ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) {
brackets[0] = brackets[1];
*num_brackets = 1;
} else {
*num_brackets = 2;
}
}
return TRUE;
}
/* Parse destination register operand.*/
static boolean
parse_register_dst(
struct translate_ctx *ctx,
uint *file,
struct parsed_bracket *brackets)
{
brackets->ind_comp = TGSI_SWIZZLE_X;
if (!parse_register_file_bracket( ctx, file ))
return FALSE;
if (!parse_register_bracket( ctx, brackets ))
return FALSE;
return TRUE;
}
static boolean
parse_dst_operand(
struct translate_ctx *ctx,
struct tgsi_full_dst_register *dst )
{
uint file;
uint writemask;
const char *cur;
struct parsed_bracket bracket[2];
int parsed_opt_brackets;
if (!parse_register_dst( ctx, &file, &bracket[0] ))
return FALSE;
if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
if (!parse_opt_writemask( ctx, &writemask ))
return FALSE;
dst->Register.File = file;
if (parsed_opt_brackets) {
dst->Register.Dimension = 1;
dst->Dimension.Indirect = 0;
dst->Dimension.Dimension = 0;
dst->Dimension.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
dst->Dimension.Indirect = 1;
dst->DimIndirect.File = bracket[0].ind_file;
dst->DimIndirect.Index = bracket[0].ind_index;
dst->DimIndirect.Swizzle = bracket[0].ind_comp;
dst->DimIndirect.ArrayID = bracket[0].ind_array;
}
bracket[0] = bracket[1];
}
dst->Register.Index = bracket[0].index;
dst->Register.WriteMask = writemask;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
dst->Register.Indirect = 1;
dst->Indirect.File = bracket[0].ind_file;
dst->Indirect.Index = bracket[0].ind_index;
dst->Indirect.Swizzle = bracket[0].ind_comp;
dst->Indirect.ArrayID = bracket[0].ind_array;
}
return TRUE;
}
static boolean
parse_optional_swizzle(
struct translate_ctx *ctx,
uint *swizzle,
boolean *parsed_swizzle,
int components)
{
const char *cur = ctx->cur;
*parsed_swizzle = FALSE;
eat_opt_white( &cur );
if (*cur == '.') {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < components; i++) {
if (uprcase( *cur ) == 'X')
swizzle[i] = TGSI_SWIZZLE_X;
else if (uprcase( *cur ) == 'Y')
swizzle[i] = TGSI_SWIZZLE_Y;
else if (uprcase( *cur ) == 'Z')
swizzle[i] = TGSI_SWIZZLE_Z;
else if (uprcase( *cur ) == 'W')
swizzle[i] = TGSI_SWIZZLE_W;
else {
report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" );
return FALSE;
}
cur++;
}
*parsed_swizzle = TRUE;
ctx->cur = cur;
}
return TRUE;
}
static boolean
parse_src_operand(
struct translate_ctx *ctx,
struct tgsi_full_src_register *src )
{
uint file;
uint swizzle[4];
boolean parsed_swizzle;
struct parsed_bracket bracket[2];
int parsed_opt_brackets;
if (*ctx->cur == '-') {
ctx->cur++;
eat_opt_white( &ctx->cur );
src->Register.Negate = 1;
}
if (*ctx->cur == '|') {
ctx->cur++;
eat_opt_white( &ctx->cur );
src->Register.Absolute = 1;
}
if (!parse_register_src(ctx, &file, &bracket[0]))
return FALSE;
if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets))
return FALSE;
src->Register.File = file;
if (parsed_opt_brackets) {
src->Register.Dimension = 1;
src->Dimension.Indirect = 0;
src->Dimension.Dimension = 0;
src->Dimension.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
src->Dimension.Indirect = 1;
src->DimIndirect.File = bracket[0].ind_file;
src->DimIndirect.Index = bracket[0].ind_index;
src->DimIndirect.Swizzle = bracket[0].ind_comp;
src->DimIndirect.ArrayID = bracket[0].ind_array;
}
bracket[0] = bracket[1];
}
src->Register.Index = bracket[0].index;
if (bracket[0].ind_file != TGSI_FILE_NULL) {
src->Register.Indirect = 1;
src->Indirect.File = bracket[0].ind_file;
src->Indirect.Index = bracket[0].ind_index;
src->Indirect.Swizzle = bracket[0].ind_comp;
src->Indirect.ArrayID = bracket[0].ind_array;
}
/* Parse optional swizzle.
*/
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
src->Register.SwizzleX = swizzle[0];
src->Register.SwizzleY = swizzle[1];
src->Register.SwizzleZ = swizzle[2];
src->Register.SwizzleW = swizzle[3];
}
}
if (src->Register.Absolute) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != '|') {
report_error( ctx, "Expected `|'" );
return FALSE;
}
ctx->cur++;
}
return TRUE;
}
static boolean
parse_texoffset_operand(
struct translate_ctx *ctx,
struct tgsi_texture_offset *src )
{
uint file;
uint swizzle[3];
boolean parsed_swizzle;
struct parsed_bracket bracket;
if (!parse_register_src(ctx, &file, &bracket))
return FALSE;
src->File = file;
src->Index = bracket.index;
/* Parse optional swizzle.
*/
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) {
if (parsed_swizzle) {
src->SwizzleX = swizzle[0];
src->SwizzleY = swizzle[1];
src->SwizzleZ = swizzle[2];
}
}
return TRUE;
}
static boolean
match_inst(const char **pcur,
unsigned *saturate,
const struct tgsi_opcode_info *info)
{
const char *cur = *pcur;
/* simple case: the whole string matches the instruction name */
if (str_match_nocase_whole(&cur, info->mnemonic)) {
*pcur = cur;
*saturate = 0;
return TRUE;
}
if (str_match_no_case(&cur, info->mnemonic)) {
/* the instruction has a suffix, figure it out */
if (str_match_nocase_whole(&cur, "_SAT")) {
*pcur = cur;
*saturate = 1;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_instruction(
struct translate_ctx *ctx,
boolean has_label )
{
uint i;
uint saturate = 0;
const struct tgsi_opcode_info *info;
struct tgsi_full_instruction inst;
const char *cur;
uint advance;
inst = tgsi_default_full_instruction();
/* Parse predicate.
*/
eat_opt_white( &ctx->cur );
if (*ctx->cur == '(') {
uint file;
int index;
uint swizzle[4];
boolean parsed_swizzle;
inst.Instruction.Predicate = 1;
ctx->cur++;
if (*ctx->cur == '!') {
ctx->cur++;
inst.Predicate.Negate = 1;
}
if (!parse_register_1d( ctx, &file, &index ))
return FALSE;
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
inst.Predicate.SwizzleX = swizzle[0];
inst.Predicate.SwizzleY = swizzle[1];
inst.Predicate.SwizzleZ = swizzle[2];
inst.Predicate.SwizzleW = swizzle[3];
}
}
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
/* Parse instruction name.
*/
eat_opt_white( &ctx->cur );
for (i = 0; i < TGSI_OPCODE_LAST; i++) {
cur = ctx->cur;
info = tgsi_get_opcode_info( i );
if (match_inst(&cur, &saturate, info)) {
if (info->num_dst + info->num_src + info->is_tex == 0) {
ctx->cur = cur;
break;
}
else if (*cur == '\0' || eat_white( &cur )) {
ctx->cur = cur;
break;
}
}
}
if (i == TGSI_OPCODE_LAST) {
if (has_label)
report_error( ctx, "Unknown opcode" );
else
report_error( ctx, "Expected `DCL', `IMM' or a label" );
return FALSE;
}
inst.Instruction.Opcode = i;
inst.Instruction.Saturate = saturate;
inst.Instruction.NumDstRegs = info->num_dst;
inst.Instruction.NumSrcRegs = info->num_src;
if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) {
/*
* These are not considered tex opcodes here (no additional
* target argument) however we're required to set the Texture
* bit so we can set the number of tex offsets.
*/
inst.Instruction.Texture = 1;
inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN;
}
/* Parse instruction operands.
*/
for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) {
if (i > 0) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
if (i < info->num_dst) {
if (!parse_dst_operand( ctx, &inst.Dst[i] ))
return FALSE;
}
else if (i < info->num_dst + info->num_src) {
if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] ))
return FALSE;
}
else {
uint j;
for (j = 0; j < TGSI_TEXTURE_COUNT; j++) {
if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) {
inst.Instruction.Texture = 1;
inst.Texture.Texture = j;
break;
}
}
if (j == TGSI_TEXTURE_COUNT) {
report_error( ctx, "Expected texture target" );
return FALSE;
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
for (i = 0; inst.Instruction.Texture && *cur == ','; i++) {
cur++;
eat_opt_white( &cur );
ctx->cur = cur;
if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] ))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
}
inst.Texture.NumOffsets = i;
cur = ctx->cur;
eat_opt_white( &cur );
if (info->is_branch && *cur == ':') {
uint target;
cur++;
eat_opt_white( &cur );
if (!parse_uint( &cur, &target )) {
report_error( ctx, "Expected a label" );
return FALSE;
}
inst.Instruction.Label = 1;
inst.Label.Label = target;
ctx->cur = cur;
}
advance = tgsi_build_full_instruction(
&inst,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
/* parses a 4-touple of the form {x, y, z, w}
* where x, y, z, w are numbers */
static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type,
union tgsi_immediate_data *values)
{
unsigned i;
int ret;
eat_opt_white( &ctx->cur );
if (*ctx->cur != '{') {
report_error( ctx, "Expected `{'" );
return FALSE;
}
ctx->cur++;
for (i = 0; i < 4; i++) {
eat_opt_white( &ctx->cur );
if (i > 0) {
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
switch (type) {
case TGSI_IMM_FLOAT64:
ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint);
i++;
break;
case TGSI_IMM_FLOAT32:
ret = parse_float(&ctx->cur, &values[i].Float);
break;
case TGSI_IMM_UINT32:
ret = parse_uint(&ctx->cur, &values[i].Uint);
break;
case TGSI_IMM_INT32:
ret = parse_int(&ctx->cur, &values[i].Int);
break;
default:
assert(0);
ret = FALSE;
break;
}
if (!ret) {
report_error( ctx, "Expected immediate constant" );
return FALSE;
}
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != '}') {
report_error( ctx, "Expected `}'" );
return FALSE;
}
ctx->cur++;
return TRUE;
}
static boolean parse_declaration( struct translate_ctx *ctx )
{
struct tgsi_full_declaration decl;
uint file;
struct parsed_dcl_bracket brackets[2];
int num_brackets;
uint writemask;
const char *cur, *cur2;
uint advance;
boolean is_vs_input;
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
if (!parse_register_dcl( ctx, &file, brackets, &num_brackets))
return FALSE;
if (!parse_opt_writemask( ctx, &writemask ))
return FALSE;
decl = tgsi_default_full_declaration();
decl.Declaration.File = file;
decl.Declaration.UsageMask = writemask;
if (num_brackets == 1) {
decl.Range.First = brackets[0].first;
decl.Range.Last = brackets[0].last;
} else {
decl.Range.First = brackets[1].first;
decl.Range.Last = brackets[1].last;
decl.Declaration.Dimension = 1;
decl.Dim.Index2D = brackets[0].first;
}
is_vs_input = (file == TGSI_FILE_INPUT &&
ctx->processor == TGSI_PROCESSOR_VERTEX);
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',') {
cur2 = cur;
cur2++;
eat_opt_white( &cur2 );
if (str_match_nocase_whole( &cur2, "ARRAY" )) {
int arrayid;
if (*cur2 != '(') {
report_error( ctx, "Expected `('" );
return FALSE;
}
cur2++;
eat_opt_white( &cur2 );
if (!parse_int( &cur2, &arrayid )) {
report_error( ctx, "Expected `,'" );
return FALSE;
}
eat_opt_white( &cur2 );
if (*cur2 != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
cur2++;
decl.Declaration.Array = 1;
decl.Array.ArrayID = arrayid;
ctx->cur = cur = cur2;
}
}
if (*cur == ',' && !is_vs_input) {
uint i, j;
cur++;
eat_opt_white( &cur );
if (file == TGSI_FILE_RESOURCE) {
for (i = 0; i < TGSI_TEXTURE_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) {
decl.Resource.Resource = i;
break;
}
}
if (i == TGSI_TEXTURE_COUNT) {
report_error(ctx, "Expected texture target");
return FALSE;
}
cur2 = cur;
eat_opt_white(&cur2);
while (*cur2 == ',') {
cur2++;
eat_opt_white(&cur2);
if (str_match_nocase_whole(&cur2, "RAW")) {
decl.Resource.Raw = 1;
} else if (str_match_nocase_whole(&cur2, "WR")) {
decl.Resource.Writable = 1;
} else {
break;
}
cur = cur2;
eat_opt_white(&cur2);
}
ctx->cur = cur;
} else if (file == TGSI_FILE_SAMPLER_VIEW) {
for (i = 0; i < TGSI_TEXTURE_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) {
decl.SamplerView.Resource = i;
break;
}
}
if (i == TGSI_TEXTURE_COUNT) {
report_error(ctx, "Expected texture target");
return FALSE;
}
eat_opt_white( &cur );
if (*cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
++cur;
eat_opt_white( &cur );
for (j = 0; j < 4; ++j) {
for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) {
if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) {
switch (j) {
case 0:
decl.SamplerView.ReturnTypeX = i;
break;
case 1:
decl.SamplerView.ReturnTypeY = i;
break;
case 2:
decl.SamplerView.ReturnTypeZ = i;
break;
case 3:
decl.SamplerView.ReturnTypeW = i;
break;
default:
assert(0);
}
break;
}
}
if (i == TGSI_RETURN_TYPE_COUNT) {
if (j == 0 || j > 2) {
report_error(ctx, "Expected type name");
return FALSE;
}
break;
} else {
cur2 = cur;
eat_opt_white( &cur2 );
if (*cur2 == ',') {
cur2++;
eat_opt_white( &cur2 );
cur = cur2;
continue;
} else
break;
}
}
if (j < 4) {
decl.SamplerView.ReturnTypeY =
decl.SamplerView.ReturnTypeZ =
decl.SamplerView.ReturnTypeW =
decl.SamplerView.ReturnTypeX;
}
ctx->cur = cur;
} else {
if (str_match_nocase_whole(&cur, "LOCAL")) {
decl.Declaration.Local = 1;
ctx->cur = cur;
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',') {
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) {
if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) {
uint index;
cur2 = cur;
eat_opt_white( &cur2 );
if (*cur2 == '[') {
cur2++;
eat_opt_white( &cur2 );
if (!parse_uint( &cur2, &index )) {
report_error( ctx, "Expected literal integer" );
return FALSE;
}
eat_opt_white( &cur2 );
if (*cur2 != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
cur2++;
decl.Semantic.Index = index;
cur = cur2;
}
decl.Declaration.Semantic = 1;
decl.Semantic.Name = i;
ctx->cur = cur;
break;
}
}
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',' && !is_vs_input) {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) {
if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) {
decl.Declaration.Interpolate = 1;
decl.Interp.Interpolate = i;
ctx->cur = cur;
break;
}
}
if (i == TGSI_INTERPOLATE_COUNT) {
report_error( ctx, "Expected semantic or interpolate attribute" );
return FALSE;
}
}
cur = ctx->cur;
eat_opt_white( &cur );
if (*cur == ',' && !is_vs_input) {
uint i;
cur++;
eat_opt_white( &cur );
for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) {
if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) {
decl.Interp.Location = i;
ctx->cur = cur;
break;
}
}
}
advance = tgsi_build_full_declaration(
&decl,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
static boolean parse_immediate( struct translate_ctx *ctx )
{
struct tgsi_full_immediate imm;
uint advance;
int type;
if (*ctx->cur == '[') {
uint uindex;
++ctx->cur;
eat_opt_white( &ctx->cur );
if (!parse_uint( &ctx->cur, &uindex )) {
report_error( ctx, "Expected literal unsigned integer" );
return FALSE;
}
if (uindex != ctx->num_immediates) {
report_error( ctx, "Immediates must be sorted" );
return FALSE;
}
eat_opt_white( &ctx->cur );
if (*ctx->cur != ']') {
report_error( ctx, "Expected `]'" );
return FALSE;
}
ctx->cur++;
}
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) {
if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type]))
break;
}
if (type == Elements(tgsi_immediate_type_names)) {
report_error( ctx, "Expected immediate type" );
return FALSE;
}
imm = tgsi_default_full_immediate();
imm.Immediate.NrTokens += 4;
imm.Immediate.DataType = type;
parse_immediate_data(ctx, type, imm.u);
advance = tgsi_build_full_immediate(
&imm,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
ctx->num_immediates++;
return TRUE;
}
static boolean
parse_primitive( const char **pcur, uint *primitive )
{
uint i;
for (i = 0; i < PIPE_PRIM_MAX; i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) {
*primitive = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin )
{
uint i;
for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) {
*fs_coord_origin = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean
parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center )
{
uint i;
for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) {
const char *cur = *pcur;
if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) {
*fs_coord_pixel_center = i;
*pcur = cur;
return TRUE;
}
}
return FALSE;
}
static boolean parse_property( struct translate_ctx *ctx )
{
struct tgsi_full_property prop;
uint property_name;
uint values[8];
uint advance;
char id[64];
if (!eat_white( &ctx->cur )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
report_error( ctx, "Syntax error" );
return FALSE;
}
if (!parse_identifier( &ctx->cur, id )) {
report_error( ctx, "Syntax error" );
return FALSE;
}
break;
}
}
|
CWE-119
| 178,123 | 241 |
142817990104108566810102542927701673732
| null | null | null |
virglrenderer
|
114688c526fe45f341d75ccd1d85473c3b08f7a7
| 1 |
int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
|
CWE-119
| 178,126 | 242 |
127813115019639337707795536823961346235
| null | null | null |
virglrenderer
|
a5ac49940c40ae415eac0cf912eac7070b4ba95d
| 1 |
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length)
{
struct pipe_vertex_element *ve = NULL;
int num_elements;
int i;
int ret;
if (length < 1)
return EINVAL;
if ((length - 1) % 4)
return EINVAL;
num_elements = (length - 1) / 4;
if (num_elements) {
ve = calloc(num_elements, sizeof(struct pipe_vertex_element));
if (!ve)
return ENOMEM;
for (i = 0; i < num_elements; i++) {
ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i));
ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i));
ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i));
ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i));
}
}
return ret;
}
|
CWE-125
| 178,129 | 243 |
279616717599430675241465878003165352261
| null | null | null |
infradead
|
14cae65318d3ef1f7d449e463b72b6934e82f1c2
| 1 |
static void set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
|
CWE-119
| 178,132 | 246 |
174272131383202600271920404270020112167
| null | null | null |
openssl
|
2c0d295e26306e15a92eb23a84a1802005c1c137
| 1 |
int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p,
unsigned char *limit, int *al)
{
unsigned short type;
unsigned short size;
unsigned short len;
unsigned char *data = *p;
int renegotiate_seen = 0;
int sigalg_seen = 0;
s->servername_done = 0;
s->tlsext_status_type = -1;
# ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
# endif
# ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
# endif
# ifndef OPENSSL_NO_EC
if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
ssl_check_for_safari(s, data, limit);
# endif /* !OPENSSL_NO_EC */
# ifndef OPENSSL_NO_SRP
if (s->srp_ctx.login != NULL) {
OPENSSL_free(s->srp_ctx.login);
s->srp_ctx.login = NULL;
}
# endif
s->srtp_profile = NULL;
if (data == limit)
goto ri_check;
if (limit - data < 2)
goto err;
n2s(data, len);
if (limit - data != len)
goto err;
while (limit - data >= 4) {
n2s(data, type);
n2s(data, size);
if (limit - data < size)
goto err;
# if 0
fprintf(stderr, "Received extension type %d size %d\n", type, size);
# endif
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
/*-
* The servername extension is treated as follows:
*
* - Only the hostname type is supported with a maximum length of 255.
* - The servername is rejected if too long or if it contains zeros,
* in which case an fatal alert is generated.
* - The servername field is maintained together with the session cache.
* - When a session is resumed, the servername call back invoked in order
* to allow the application to position itself to the right context.
* - The servername is acknowledged if it is new for a session or when
* it is identical to a previously used for the same session.
* Applications can control the behaviour. They can at any time
* set a 'desirable' servername for a new SSL object. This can be the
* case for example with HTTPS when a Host: header field is received and
* a renegotiation is requested. In this case, a possible servername
* presented in the new client hello is only acknowledged if it matches
* the value of the Host: field.
* - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
* if they provide for changing an explicit servername context for the
* session, i.e. when the session has been established with a servername
* extension.
* - On session reconnect, the servername extension may be absent.
*
*/
if (type == TLSEXT_TYPE_server_name) {
unsigned char *sdata;
int servname_type;
int dsize;
if (size < 2)
goto err;
n2s(data, dsize);
size -= 2;
if (dsize > size)
goto err;
sdata = data;
while (dsize > 3) {
servname_type = *(sdata++);
n2s(sdata, len);
dsize -= 3;
if (len > dsize)
goto err;
if (s->servername_done == 0)
switch (servname_type) {
case TLSEXT_NAMETYPE_host_name:
if (!s->hit) {
if (s->session->tlsext_hostname)
goto err;
if (len > TLSEXT_MAXLEN_host_name) {
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
if ((s->session->tlsext_hostname =
OPENSSL_malloc(len + 1)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->session->tlsext_hostname, sdata, len);
s->session->tlsext_hostname[len] = '\0';
if (strlen(s->session->tlsext_hostname) != len) {
OPENSSL_free(s->session->tlsext_hostname);
s->session->tlsext_hostname = NULL;
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
s->servername_done = 1;
} else
s->servername_done = s->session->tlsext_hostname
&& strlen(s->session->tlsext_hostname) == len
&& strncmp(s->session->tlsext_hostname,
(char *)sdata, len) == 0;
break;
default:
break;
}
dsize -= len;
}
if (dsize != 0)
goto err;
}
# ifndef OPENSSL_NO_SRP
else if (type == TLSEXT_TYPE_srp) {
if (size == 0 || ((len = data[0])) != (size - 1))
goto err;
if (s->srp_ctx.login != NULL)
goto err;
if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
return -1;
memcpy(s->srp_ctx.login, &data[1], len);
s->srp_ctx.login[len] = '\0';
if (strlen(s->srp_ctx.login) != len)
goto err;
}
# endif
# ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats) {
unsigned char *sdata = data;
int ecpointformatlist_length = *(sdata++);
if (ecpointformatlist_length != size - 1)
goto err;
if (!s->hit) {
if (s->session->tlsext_ecpointformatlist) {
OPENSSL_free(s->session->tlsext_ecpointformatlist);
s->session->tlsext_ecpointformatlist = NULL;
}
s->session->tlsext_ecpointformatlist_length = 0;
if ((s->session->tlsext_ecpointformatlist =
OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length =
ecpointformatlist_length;
memcpy(s->session->tlsext_ecpointformatlist, sdata,
ecpointformatlist_length);
}
# if 0
fprintf(stderr,
"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ",
s->session->tlsext_ecpointformatlist_length);
sdata = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
fprintf(stderr, "%i ", *(sdata++));
fprintf(stderr, "\n");
# endif
} else if (type == TLSEXT_TYPE_elliptic_curves) {
unsigned char *sdata = data;
int ellipticcurvelist_length = (*(sdata++) << 8);
ellipticcurvelist_length += (*(sdata++));
if (ellipticcurvelist_length != size - 2 ||
ellipticcurvelist_length < 1 ||
/* Each NamedCurve is 2 bytes. */
ellipticcurvelist_length & 1)
goto err;
if (!s->hit) {
if (s->session->tlsext_ellipticcurvelist)
goto err;
s->session->tlsext_ellipticcurvelist_length = 0;
if ((s->session->tlsext_ellipticcurvelist =
OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ellipticcurvelist_length =
ellipticcurvelist_length;
memcpy(s->session->tlsext_ellipticcurvelist, sdata,
ellipticcurvelist_length);
}
# if 0
fprintf(stderr,
"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ",
s->session->tlsext_ellipticcurvelist_length);
sdata = s->session->tlsext_ellipticcurvelist;
for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
fprintf(stderr, "%i ", *(sdata++));
fprintf(stderr, "\n");
# endif
}
# endif /* OPENSSL_NO_EC */
# ifdef TLSEXT_TYPE_opaque_prf_input
else if (type == TLSEXT_TYPE_opaque_prf_input &&
s->version != DTLS1_VERSION) {
unsigned char *sdata = data;
if (size < 2) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input_len != size - 2) {
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->s3->client_opaque_prf_input != NULL) {
/* shouldn't really happen */
OPENSSL_free(s->s3->client_opaque_prf_input);
}
/* dummy byte just to get non-NULL */
if (s->s3->client_opaque_prf_input_len == 0)
s->s3->client_opaque_prf_input = OPENSSL_malloc(1);
else
s->s3->client_opaque_prf_input =
BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input == NULL) {
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
# endif
else if (type == TLSEXT_TYPE_session_ticket) {
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size,
s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
} else if (type == TLSEXT_TYPE_renegotiate) {
if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
return 0;
renegotiate_seen = 1;
} else if (type == TLSEXT_TYPE_signature_algorithms) {
int dsize;
if (sigalg_seen || size < 2)
goto err;
sigalg_seen = 1;
n2s(data, dsize);
size -= 2;
if (dsize != size || dsize & 1)
goto err;
if (!tls1_process_sigalgs(s, data, dsize))
goto err;
} else if (type == TLSEXT_TYPE_status_request &&
s->version != DTLS1_VERSION) {
if (size < 5)
goto err;
s->tlsext_status_type = *data++;
size--;
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
const unsigned char *sdata;
int dsize;
/* Read in responder_id_list */
n2s(data, dsize);
size -= 2;
if (dsize > size)
goto err;
while (dsize > 0) {
OCSP_RESPID *id;
int idsize;
&& !(s->tlsext_ocsp_ids =
sk_OCSP_RESPID_new_null())) {
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
OCSP_RESPID_free(id);
goto err;
}
if (!s->tlsext_ocsp_ids
&& !(s->tlsext_ocsp_ids =
sk_OCSP_RESPID_new_null())) {
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
goto err;
sdata = data;
if (dsize > 0) {
if (s->tlsext_ocsp_exts) {
sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
X509_EXTENSION_free);
}
s->tlsext_ocsp_exts =
d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
if (!s->tlsext_ocsp_exts || (data + dsize != sdata))
goto err;
}
}
/*
* We don't know what to do with any other type * so ignore it.
*/
else
s->tlsext_status_type = -1;
}
# ifndef OPENSSL_NO_HEARTBEATS
else if (type == TLSEXT_TYPE_heartbeat) {
switch (data[0]) {
case 0x01: /* Client allows us to send HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
break;
case 0x02: /* Client doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
break;
default:
*al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
# endif
# ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0) {
/*-
* We shouldn't accept this extension on a
* renegotiation.
*
* s->new_session will be set on renegotiation, but we
* probably shouldn't rely that it couldn't be set on
* the initial renegotation too in certain cases (when
* there's some other reason to disallow resuming an
* earlier session -- the current code won't be doing
* anything like that, but this might change).
*
* A valid sign that there's been a previous handshake
* in this connection is if s->s3->tmp.finish_md_len >
* 0. (We are talking about a check that will happen
* in the Hello protocol round, well before a new
* Finished message could have been computed.)
*/
s->s3->next_proto_neg_seen = 1;
}
# endif
/* session ticket processed earlier */
# ifndef OPENSSL_NO_SRTP
else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
&& type == TLSEXT_TYPE_use_srtp) {
if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
return 0;
}
# endif
data += size;
}
/* Spurious data on the end */
if (data != limit)
goto err;
*p = data;
ri_check:
/* Need RI if renegotiating */
if (!renegotiate_seen && s->renegotiate &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
err:
*al = SSL_AD_DECODE_ERROR;
return 0;
}
|
CWE-399
| 178,136 | 249 |
29224115480775327782453555135433777408
| null | null | null |
openssl
|
e97763c92c655dcf4af2860b3abd2bc4c8a267f9
| 1 |
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
int eticklen, const unsigned char *sess_id,
int sesslen, SSL_SESSION **psess)
{
SSL_SESSION *sess;
unsigned char *sdec;
const unsigned char *p;
int slen, mlen, renew_ticket = 0, ret = -1;
unsigned char tick_hmac[EVP_MAX_MD_SIZE];
HMAC_CTX *hctx = NULL;
EVP_CIPHER_CTX *ctx;
SSL_CTX *tctx = s->initial_ctx;
/* Need at least keyname + iv + some encrypted data */
if (eticklen < 48)
return 2;
/* Initialize session ticket encryption and HMAC contexts */
hctx = HMAC_CTX_new();
if (hctx == NULL)
hctx = HMAC_CTX_new();
if (hctx == NULL)
return -2;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
ret = -2;
goto err;
}
if (tctx->tlsext_ticket_key_cb) {
unsigned char *nctick = (unsigned char *)etick;
int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
ctx, hctx, 0);
if (rv < 0)
goto err;
if (rv == 0) {
ret = 2;
goto err;
}
if (rv == 2)
renew_ticket = 1;
} else {
/* Check key name matches */
if (memcmp(etick, tctx->tlsext_tick_key_name,
sizeof(tctx->tlsext_tick_key_name)) != 0) {
ret = 2;
goto err;
}
if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
sizeof(tctx->tlsext_tick_hmac_key),
EVP_sha256(), NULL) <= 0
|| EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
tctx->tlsext_tick_aes_key,
etick + sizeof(tctx->tlsext_tick_key_name)) <=
0) {
goto err;
}
}
/*
* Attempt to process session ticket, first conduct sanity and integrity
* checks on ticket.
if (mlen < 0) {
goto err;
}
eticklen -= mlen;
/* Check HMAC of encrypted ticket */
if (HMAC_Update(hctx, etick, eticklen) <= 0
if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
EVP_CIPHER_CTX_free(ctx);
return 2;
}
/* Attempt to decrypt session data */
/* Move p after IV to start of encrypted ticket, update length */
p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx);
eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx);
sdec = OPENSSL_malloc(eticklen);
if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) {
EVP_CIPHER_CTX_free(ctx);
OPENSSL_free(sdec);
return -1;
}
if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) {
EVP_CIPHER_CTX_free(ctx);
OPENSSL_free(sdec);
return 2;
}
slen += mlen;
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
p = sdec;
sess = d2i_SSL_SESSION(NULL, &p, slen);
OPENSSL_free(sdec);
if (sess) {
/*
* The session ID, if non-empty, is used by some clients to detect
* that the ticket has been accepted. So we copy it to the session
* structure. If it is empty set length to zero as required by
* standard.
*/
if (sesslen)
memcpy(sess->session_id, sess_id, sesslen);
sess->session_id_length = sesslen;
*psess = sess;
if (renew_ticket)
return 4;
else
return 3;
}
ERR_clear_error();
/*
* For session parse failure, indicate that we need to send a new ticket.
*/
return 2;
err:
EVP_CIPHER_CTX_free(ctx);
HMAC_CTX_free(hctx);
return ret;
}
|
CWE-20
| 178,138 | 250 |
2230119928438274047665345409737174926
| null | null | null |
busybox
|
150dc7a2b483b8338a3e185c478b4b23ee884e71
| 1 |
recv_and_process_client_pkt(void /*int fd*/)
{
ssize_t size;
len_and_sockaddr *to;
struct sockaddr *from;
msg_t msg;
uint8_t query_status;
l_fixedpt_t query_xmttime;
to = get_sock_lsa(G_listen_fd);
from = xzalloc(to->len);
size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
char *addr;
if (size < 0) {
if (errno == EAGAIN)
goto bail;
bb_perror_msg_and_die("recv");
}
addr = xmalloc_sockaddr2dotted_noport(from);
bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
free(addr);
goto bail;
}
query_status = msg.m_status;
query_xmttime = msg.m_xmttime;
msg.m_ppoll = G.poll_exp;
msg.m_precision_exp = G_precision_exp;
/* this time was obtained between poll() and recv() */
msg.m_rectime = d_to_lfp(G.cur_time);
msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
if (G.peer_cnt == 0) {
/* we have no peers: "stratum 1 server" mode. reftime = our own time */
G.reftime = G.cur_time;
}
msg.m_reftime = d_to_lfp(G.reftime);
msg.m_orgtime = query_xmttime;
msg.m_rootdelay = d_to_sfp(G.rootdelay);
msg.m_rootdisp = d_to_sfp(G.rootdisp);
msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
/* We reply from the local address packet was sent to,
* this makes to/from look swapped here: */
do_sendto(G_listen_fd,
/*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
&msg, size);
bail:
free(to);
free(from);
}
|
CWE-399
| 178,139 | 251 |
156100728183473686227543895216612348906
| null | null | null |
savannah
|
5e3cb9c7b5bf0ce665b9d68f5ddf095af5c9ba60
| 1 |
main (int argc, char *argv[])
{
struct gengetopt_args_info args_info;
char *line = NULL;
size_t linelen = 0;
char *p, *r;
uint32_t *q;
unsigned cmdn = 0;
int rc;
setlocale (LC_ALL, "");
set_program_name (argv[0]);
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (cmdline_parser (argc, argv, &args_info) != 0)
return EXIT_FAILURE;
if (args_info.version_given)
{
version_etc (stdout, "idn", PACKAGE_NAME, VERSION,
"Simon Josefsson", (char *) NULL);
return EXIT_SUCCESS;
}
if (args_info.help_given)
usage (EXIT_SUCCESS);
/* Backwards compatibility: -n has always been the documented short
form for --nfkc but, before v1.10, -k was the implemented short
form. We now accept both to avoid documentation changes. */
if (args_info.hidden_nfkc_given)
args_info.nfkc_given = 1;
if (!args_info.stringprep_given &&
!args_info.punycode_encode_given && !args_info.punycode_decode_given &&
!args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given &&
!args_info.nfkc_given)
args_info.idna_to_ascii_given = 1;
if ((args_info.stringprep_given ? 1 : 0) +
(args_info.punycode_encode_given ? 1 : 0) +
(args_info.punycode_decode_given ? 1 : 0) +
(args_info.idna_to_ascii_given ? 1 : 0) +
(args_info.idna_to_unicode_given ? 1 : 0) +
(args_info.nfkc_given ? 1 : 0) != 1)
{
error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified"));
usage (EXIT_FAILURE);
}
if (!args_info.quiet_given
&& args_info.inputs_num == 0
&& isatty (fileno (stdin)))
fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION);
if (args_info.debug_given)
fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ());
if (!args_info.quiet_given
&& args_info.inputs_num == 0
&& isatty (fileno (stdin)))
fprintf (stderr, _("Type each input string on a line by itself, "
"terminated by a newline character.\n"));
do
{
if (cmdn < args_info.inputs_num)
line = strdup (args_info.inputs[cmdn++]);
else if (getline (&line, &linelen, stdin) == -1)
{
if (feof (stdin))
break;
error (EXIT_FAILURE, errno, _("input error"));
}
if (line[strlen (line) - 1] == '\n')
line[strlen (line) - 1] = '\0';
if (args_info.stringprep_given)
{
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
if (!q)
{
free (p);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
free (q);
rc = stringprep_profile (p, &r,
args_info.profile_given ?
args_info.profile_arg : "Nameprep", 0);
free (p);
if (rc != STRINGPREP_OK)
error (EXIT_FAILURE, 0, _("stringprep_profile: %s"),
stringprep_strerror (rc));
q = stringprep_utf8_to_ucs4 (r, -1, NULL);
if (!q)
{
free (r);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
free (q);
p = stringprep_utf8_to_locale (r);
free (r);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.punycode_encode_given)
{
char encbuf[BUFSIZ];
size_t len, len2;
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, &len);
free (p);
if (!q)
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
if (args_info.debug_given)
{
size_t i;
for (i = 0; i < len; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
len2 = BUFSIZ - 1;
rc = punycode_encode (len, q, NULL, &len2, encbuf);
free (q);
if (rc != PUNYCODE_SUCCESS)
error (EXIT_FAILURE, 0, _("punycode_encode: %s"),
punycode_strerror (rc));
encbuf[len2] = '\0';
p = stringprep_utf8_to_locale (encbuf);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.punycode_decode_given)
{
size_t len;
len = BUFSIZ;
q = (uint32_t *) malloc (len * sizeof (q[0]));
if (!q)
error (EXIT_FAILURE, ENOMEM, N_("malloc"));
rc = punycode_decode (strlen (line), line, &len, q, NULL);
if (rc != PUNYCODE_SUCCESS)
{
free (q);
error (EXIT_FAILURE, 0, _("punycode_decode: %s"),
punycode_strerror (rc));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; i < len; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
q[len] = 0;
r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL);
free (q);
if (!r)
error (EXIT_FAILURE, 0,
_("could not convert from UCS-4 to UTF-8"));
p = stringprep_utf8_to_locale (r);
free (r);
if (!r)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.idna_to_ascii_given)
{
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
free (p);
if (!q)
error (EXIT_FAILURE, 0,
_("could not convert from UCS-4 to UTF-8"));
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
rc = idna_to_ascii_4z (q, &p,
(args_info.allow_unassigned_given ?
IDNA_ALLOW_UNASSIGNED : 0) |
(args_info.usestd3asciirules_given ?
IDNA_USE_STD3_ASCII_RULES : 0));
free (q);
if (rc != IDNA_SUCCESS)
error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"),
idna_strerror (rc));
#ifdef WITH_TLD
if (args_info.tld_flag && !args_info.no_tld_flag)
{
size_t errpos;
rc = idna_to_unicode_8z4z (p, &q,
(args_info.allow_unassigned_given ?
IDNA_ALLOW_UNASSIGNED : 0) |
(args_info.usestd3asciirules_given ?
IDNA_USE_STD3_ASCII_RULES : 0));
if (rc != IDNA_SUCCESS)
error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"),
idna_strerror (rc));
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "tld[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
rc = tld_check_4z (q, &errpos, NULL);
free (q);
if (rc == TLD_INVALID)
error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"),
(unsigned long) errpos, tld_strerror (rc));
if (rc != TLD_SUCCESS)
error (EXIT_FAILURE, 0, _("tld_check_4z: %s"),
tld_strerror (rc));
}
#endif
if (args_info.debug_given)
{
size_t i;
for (i = 0; p[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, p[i]);
}
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.idna_to_unicode_given)
{
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
if (!q)
{
free (p);
error (EXIT_FAILURE, 0,
_("could not convert from UCS-4 to UTF-8"));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
free (q);
rc = idna_to_unicode_8z4z (p, &q,
(args_info.allow_unassigned_given ?
IDNA_ALLOW_UNASSIGNED : 0) |
(args_info.usestd3asciirules_given ?
IDNA_USE_STD3_ASCII_RULES : 0));
free (p);
if (rc != IDNA_SUCCESS)
error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"),
idna_strerror (rc));
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
#ifdef WITH_TLD
if (args_info.tld_flag)
{
size_t errpos;
rc = tld_check_4z (q, &errpos, NULL);
if (rc == TLD_INVALID)
{
free (q);
error (EXIT_FAILURE, 0,
_("tld_check_4z (position %lu): %s"),
(unsigned long) errpos, tld_strerror (rc));
}
if (rc != TLD_SUCCESS)
{
free (q);
error (EXIT_FAILURE, 0, _("tld_check_4z: %s"),
tld_strerror (rc));
}
}
#endif
r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL);
free (q);
if (!r)
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
p = stringprep_utf8_to_locale (r);
free (r);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.nfkc_given)
{
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
if (args_info.debug_given)
{
size_t i;
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
if (!q)
{
free (p);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
free (q);
}
r = stringprep_utf8_nfkc_normalize (p, -1);
free (p);
if (!r)
error (EXIT_FAILURE, 0, _("could not do NFKC normalization"));
if (args_info.debug_given)
{
size_t i;
q = stringprep_utf8_to_ucs4 (r, -1, NULL);
if (!q)
{
free (r);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
for (i = 0; q[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
free (q);
}
p = stringprep_utf8_to_locale (r);
free (r);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
fflush (stdout);
}
while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 ||
cmdn < args_info.inputs_num));
free (line);
return EXIT_SUCCESS;
}
|
CWE-125
| 178,157 | 252 |
336554870084234386632359019600938342414
| null | null | null |
savannah
|
45a3c76b547511fa9d97aca34b150a0663257375
| 1 |
FT_Stream_EnterFrame( FT_Stream stream,
FT_ULong count )
{
FT_Error error = FT_Err_Ok;
FT_ULong read_bytes;
/* check for nested frame access */
FT_ASSERT( stream && stream->cursor == 0 );
if ( stream->read )
{
/* allocate the frame in memory */
FT_Memory memory = stream->memory;
/* simple sanity check */
if ( count > stream->size )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" frame size (%lu) larger than stream size (%lu)\n",
count, stream->size ));
error = FT_Err_Invalid_Stream_Operation;
goto Exit;
}
#ifdef FT_DEBUG_MEMORY
/* assume _ft_debug_file and _ft_debug_lineno are already set */
stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error );
if ( error )
goto Exit;
#else
if ( FT_QALLOC( stream->base, count ) )
goto Exit;
#endif
/* read it */
read_bytes = stream->read( stream, stream->pos,
stream->base, count );
if ( read_bytes < count )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" invalid read; expected %lu bytes, got %lu\n",
count, read_bytes ));
FT_FREE( stream->base );
error = FT_Err_Invalid_Stream_Operation;
}
stream->cursor = stream->base;
stream->limit = stream->cursor + count;
stream->pos += read_bytes;
}
else
{
/* check current and new position */
if ( stream->pos >= stream->size ||
stream->pos + count > stream->size )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n",
stream->pos, count, stream->size ));
error = FT_Err_Invalid_Stream_Operation;
goto Exit;
}
/* set cursor */
stream->cursor = stream->base + stream->pos;
stream->limit = stream->cursor + count;
stream->pos += count;
}
Exit:
return error;
}
|
CWE-20
| 178,158 | 253 |
171308526437072917405338067244329397761
| null | null | null |
virglrenderer
|
28894a30a17a84529be102b21118e55d6c9f23fa
| 1 |
parse_instruction(
struct translate_ctx *ctx,
boolean has_label )
{
uint i;
uint saturate = 0;
const struct tgsi_opcode_info *info;
struct tgsi_full_instruction inst;
const char *cur;
uint advance;
inst = tgsi_default_full_instruction();
/* Parse predicate.
*/
eat_opt_white( &ctx->cur );
if (*ctx->cur == '(') {
uint file;
int index;
uint swizzle[4];
boolean parsed_swizzle;
inst.Instruction.Predicate = 1;
ctx->cur++;
if (*ctx->cur == '!') {
ctx->cur++;
inst.Predicate.Negate = 1;
}
if (!parse_register_1d( ctx, &file, &index ))
return FALSE;
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
inst.Predicate.SwizzleX = swizzle[0];
inst.Predicate.SwizzleY = swizzle[1];
inst.Predicate.SwizzleZ = swizzle[2];
inst.Predicate.SwizzleW = swizzle[3];
}
}
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
/* Parse instruction name.
*/
eat_opt_white( &ctx->cur );
for (i = 0; i < TGSI_OPCODE_LAST; i++) {
cur = ctx->cur;
info = tgsi_get_opcode_info( i );
if (match_inst(&cur, &saturate, info)) {
if (info->num_dst + info->num_src + info->is_tex == 0) {
ctx->cur = cur;
break;
}
else if (*cur == '\0' || eat_white( &cur )) {
ctx->cur = cur;
break;
}
}
}
if (i == TGSI_OPCODE_LAST) {
if (has_label)
report_error( ctx, "Unknown opcode" );
else
report_error( ctx, "Expected `DCL', `IMM' or a label" );
return FALSE;
}
inst.Instruction.Opcode = i;
inst.Instruction.Saturate = saturate;
inst.Instruction.NumDstRegs = info->num_dst;
inst.Instruction.NumSrcRegs = info->num_src;
if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) {
/*
* These are not considered tex opcodes here (no additional
* target argument) however we're required to set the Texture
* bit so we can set the number of tex offsets.
*/
inst.Instruction.Texture = 1;
inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN;
}
/* Parse instruction operands.
*/
for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) {
if (i > 0) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
if (i < info->num_dst) {
if (!parse_dst_operand( ctx, &inst.Dst[i] ))
return FALSE;
}
else if (i < info->num_dst + info->num_src) {
if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] ))
return FALSE;
}
else {
uint j;
for (j = 0; j < TGSI_TEXTURE_COUNT; j++) {
if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) {
inst.Instruction.Texture = 1;
inst.Texture.Texture = j;
break;
}
}
if (j == TGSI_TEXTURE_COUNT) {
report_error( ctx, "Expected texture target" );
return FALSE;
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
for (i = 0; inst.Instruction.Texture && *cur == ','; i++) {
cur++;
eat_opt_white( &cur );
ctx->cur = cur;
if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] ))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
}
inst.Texture.NumOffsets = i;
cur = ctx->cur;
eat_opt_white( &cur );
if (info->is_branch && *cur == ':') {
uint target;
cur++;
eat_opt_white( &cur );
if (!parse_uint( &cur, &target )) {
report_error( ctx, "Expected a label" );
return FALSE;
}
inst.Instruction.Label = 1;
inst.Label.Label = target;
ctx->cur = cur;
}
advance = tgsi_build_full_instruction(
&inst,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
|
CWE-119
| 178,159 | 254 |
207706300612945852467345419819110560855
| null | null | null |
haproxy
|
b4d05093bc89f71377230228007e69a1434c1a0c
| 1 |
int http_request_forward_body(struct session *s, struct channel *req, int an_bit)
{
struct http_txn *txn = &s->txn;
struct http_msg *msg = &s->txn.req;
if (unlikely(msg->msg_state < HTTP_MSG_BODY))
return 0;
if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) ||
((req->flags & CF_SHUTW) && (req->to_forward || req->buf->o))) {
/* Output closed while we were sending data. We must abort and
* wake the other side up.
*/
msg->msg_state = HTTP_MSG_ERROR;
http_resync_states(s);
return 1;
}
/* Note that we don't have to send 100-continue back because we don't
* need the data to complete our job, and it's up to the server to
* decide whether to return 100, 417 or anything else in return of
* an "Expect: 100-continue" header.
*/
if (msg->sov > 0) {
/* we have msg->sov which points to the first byte of message
* body, and req->buf.p still points to the beginning of the
* message. We forward the headers now, as we don't need them
* anymore, and we want to flush them.
*/
b_adv(req->buf, msg->sov);
msg->next -= msg->sov;
msg->sov = 0;
/* The previous analysers guarantee that the state is somewhere
* between MSG_BODY and the first MSG_DATA. So msg->sol and
* msg->next are always correct.
*/
if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) {
if (msg->flags & HTTP_MSGF_TE_CHNK)
msg->msg_state = HTTP_MSG_CHUNK_SIZE;
else
msg->msg_state = HTTP_MSG_DATA;
}
}
/* Some post-connect processing might want us to refrain from starting to
* forward data. Currently, the only reason for this is "balance url_param"
* whichs need to parse/process the request after we've enabled forwarding.
*/
if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) {
if (!(s->rep->flags & CF_READ_ATTACHED)) {
channel_auto_connect(req);
req->flags |= CF_WAKE_CONNECT;
goto missing_data;
}
msg->flags &= ~HTTP_MSGF_WAIT_CONN;
}
/* in most states, we should abort in case of early close */
channel_auto_close(req);
if (req->to_forward) {
/* We can't process the buffer's contents yet */
req->flags |= CF_WAKE_WRITE;
goto missing_data;
}
while (1) {
if (msg->msg_state == HTTP_MSG_DATA) {
/* must still forward */
/* we may have some pending data starting at req->buf->p */
if (msg->chunk_len > req->buf->i - msg->next) {
req->flags |= CF_WAKE_WRITE;
goto missing_data;
}
msg->next += msg->chunk_len;
msg->chunk_len = 0;
/* nothing left to forward */
if (msg->flags & HTTP_MSGF_TE_CHNK)
msg->msg_state = HTTP_MSG_CHUNK_CRLF;
else
msg->msg_state = HTTP_MSG_DONE;
}
else if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) {
/* read the chunk size and assign it to ->chunk_len, then
* set ->next to point to the body and switch to DATA or
* TRAILERS state.
*/
int ret = http_parse_chunk_size(msg);
if (ret == 0)
goto missing_data;
else if (ret < 0) {
session_inc_http_err_ctr(s);
if (msg->err_pos >= 0)
http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_SIZE, s->be);
goto return_bad_req;
}
/* otherwise we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state */
}
else if (msg->msg_state == HTTP_MSG_CHUNK_CRLF) {
/* we want the CRLF after the data */
int ret = http_skip_chunk_crlf(msg);
if (ret == 0)
goto missing_data;
else if (ret < 0) {
session_inc_http_err_ctr(s);
if (msg->err_pos >= 0)
http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_CRLF, s->be);
goto return_bad_req;
}
/* we're in MSG_CHUNK_SIZE now */
}
else if (msg->msg_state == HTTP_MSG_TRAILERS) {
int ret = http_forward_trailers(msg);
if (ret == 0)
goto missing_data;
else if (ret < 0) {
session_inc_http_err_ctr(s);
if (msg->err_pos >= 0)
http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_TRAILERS, s->be);
goto return_bad_req;
}
/* we're in HTTP_MSG_DONE now */
}
else {
int old_state = msg->msg_state;
/* other states, DONE...TUNNEL */
/* we may have some pending data starting at req->buf->p
* such as last chunk of data or trailers.
*/
b_adv(req->buf, msg->next);
if (unlikely(!(s->rep->flags & CF_READ_ATTACHED)))
msg->sov -= msg->next;
msg->next = 0;
/* for keep-alive we don't want to forward closes on DONE */
if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL ||
(txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL)
channel_dont_close(req);
if (http_resync_states(s)) {
/* some state changes occurred, maybe the analyser
* was disabled too.
*/
if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) {
if (req->flags & CF_SHUTW) {
/* request errors are most likely due to
* the server aborting the transfer.
*/
goto aborted_xfer;
}
if (msg->err_pos >= 0)
http_capture_bad_message(&s->fe->invalid_req, s, msg, old_state, s->be);
goto return_bad_req;
}
return 1;
}
/* If "option abortonclose" is set on the backend, we
* want to monitor the client's connection and forward
* any shutdown notification to the server, which will
* decide whether to close or to go on processing the
* request.
*/
if (s->be->options & PR_O_ABRT_CLOSE) {
channel_auto_read(req);
channel_auto_close(req);
}
else if (s->txn.meth == HTTP_METH_POST) {
/* POST requests may require to read extra CRLF
* sent by broken browsers and which could cause
* an RST to be sent upon close on some systems
* (eg: Linux).
*/
channel_auto_read(req);
}
return 0;
}
}
missing_data:
/* we may have some pending data starting at req->buf->p */
b_adv(req->buf, msg->next);
if (unlikely(!(s->rep->flags & CF_READ_ATTACHED)))
msg->sov -= msg->next + MIN(msg->chunk_len, req->buf->i);
msg->next = 0;
msg->chunk_len -= channel_forward(req, msg->chunk_len);
/* stop waiting for data if the input is closed before the end */
if (req->flags & CF_SHUTR) {
if (!(s->flags & SN_ERR_MASK))
s->flags |= SN_ERR_CLICL;
if (!(s->flags & SN_FINST_MASK)) {
if (txn->rsp.msg_state < HTTP_MSG_ERROR)
s->flags |= SN_FINST_H;
else
s->flags |= SN_FINST_D;
}
s->fe->fe_counters.cli_aborts++;
s->be->be_counters.cli_aborts++;
if (objt_server(s->target))
objt_server(s->target)->counters.cli_aborts++;
goto return_bad_req_stats_ok;
}
/* waiting for the last bits to leave the buffer */
if (req->flags & CF_SHUTW)
goto aborted_xfer;
/* When TE: chunked is used, we need to get there again to parse remaining
* chunks even if the client has closed, so we don't want to set CF_DONTCLOSE.
*/
if (msg->flags & HTTP_MSGF_TE_CHNK)
channel_dont_close(req);
/* We know that more data are expected, but we couldn't send more that
* what we did. So we always set the CF_EXPECT_MORE flag so that the
* system knows it must not set a PUSH on this first part. Interactive
* modes are already handled by the stream sock layer. We must not do
* this in content-length mode because it could present the MSG_MORE
* flag with the last block of forwarded data, which would cause an
* additional delay to be observed by the receiver.
*/
if (msg->flags & HTTP_MSGF_TE_CHNK)
req->flags |= CF_EXPECT_MORE;
return 0;
return_bad_req: /* let's centralize all bad requests */
s->fe->fe_counters.failed_req++;
if (s->listener->counters)
s->listener->counters->failed_req++;
return_bad_req_stats_ok:
/* we may have some pending data starting at req->buf->p */
b_adv(req->buf, msg->next);
msg->next = 0;
txn->req.msg_state = HTTP_MSG_ERROR;
if (txn->status) {
/* Note: we don't send any error if some data were already sent */
stream_int_retnclose(req->prod, NULL);
} else {
txn->status = 400;
stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400));
}
req->analysers = 0;
s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */
if (!(s->flags & SN_ERR_MASK))
s->flags |= SN_ERR_PRXCOND;
if (!(s->flags & SN_FINST_MASK)) {
if (txn->rsp.msg_state < HTTP_MSG_ERROR)
s->flags |= SN_FINST_H;
else
s->flags |= SN_FINST_D;
}
return 0;
aborted_xfer:
txn->req.msg_state = HTTP_MSG_ERROR;
if (txn->status) {
/* Note: we don't send any error if some data were already sent */
stream_int_retnclose(req->prod, NULL);
} else {
txn->status = 502;
stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_502));
}
req->analysers = 0;
s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */
s->fe->fe_counters.srv_aborts++;
s->be->be_counters.srv_aborts++;
if (objt_server(s->target))
objt_server(s->target)->counters.srv_aborts++;
if (!(s->flags & SN_ERR_MASK))
s->flags |= SN_ERR_SRVCL;
if (!(s->flags & SN_FINST_MASK)) {
if (txn->rsp.msg_state < HTTP_MSG_ERROR)
s->flags |= SN_FINST_H;
else
s->flags |= SN_FINST_D;
}
return 0;
}
|
CWE-189
| 178,162 | 256 |
74231898713312769363715897872246138359
| null | null | null |
kde
|
82fdfd24d46966a117fa625b68784735a40f9065
| 1 |
void Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget());
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
|
CWE-78
| 178,164 | 257 |
127189817454680839187942616776907215530
| null | null | null |
savannah
|
888cd1843e935fe675cf2ac303116d4ed5b9d54b
| 1 |
Ins_IUP( INS_ARG )
{
IUP_WorkerRec V;
FT_Byte mask;
FT_UInt first_point; /* first point of contour */
FT_UInt end_point; /* end point (last+1) of contour */
FT_UInt first_touched; /* first touched point in contour */
FT_UInt cur_touched; /* current touched point in contour */
FT_UInt point; /* current point */
FT_Short contour; /* current contour */
FT_UNUSED_ARG;
/* ignore empty outlines */
if ( CUR.pts.n_contours == 0 )
return;
if ( CUR.opcode & 1 )
{
mask = FT_CURVE_TAG_TOUCH_X;
V.orgs = CUR.pts.org;
V.curs = CUR.pts.cur;
V.orus = CUR.pts.orus;
}
else
{
mask = FT_CURVE_TAG_TOUCH_Y;
V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 );
V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 );
V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 );
}
V.max_points = CUR.pts.n_points;
contour = 0;
point = 0;
do
{
end_point = CUR.pts.contours[contour] - CUR.pts.first_point;
first_point = point;
if ( CUR.pts.n_points <= end_point )
end_point = CUR.pts.n_points;
while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 )
point++;
if ( point <= end_point )
{
first_touched = point;
cur_touched = point;
point++;
while ( point <= end_point )
{
if ( ( CUR.pts.tags[point] & mask ) != 0 )
{
if ( point > 0 )
_iup_worker_interpolate( &V,
cur_touched + 1,
point - 1,
cur_touched,
point );
cur_touched = point;
}
point++;
}
if ( cur_touched == first_touched )
_iup_worker_shift( &V, first_point, end_point, cur_touched );
else
{
_iup_worker_interpolate( &V,
(FT_UShort)( cur_touched + 1 ),
end_point,
cur_touched,
first_touched );
if ( first_touched > 0 )
_iup_worker_interpolate( &V,
first_point,
first_touched - 1,
cur_touched,
first_touched );
}
}
contour++;
} while ( contour < CUR.pts.n_contours );
}
|
CWE-119
| 178,174 | 263 |
271982803099189327229111379866845675067
| null | null | null |
savannah
|
b2ea64bcc6c385a8e8318f9c759450a07df58b6d
| 1 |
Mac_Read_POST_Resource( FT_Library library,
FT_Stream stream,
FT_Long *offsets,
FT_Long resource_cnt,
FT_Long face_index,
FT_Face *aface )
{
FT_Error error = FT_Err_Cannot_Open_Resource;
FT_Memory memory = library->memory;
FT_Byte* pfb_data;
int i, type, flags;
FT_Long len;
FT_Long pfb_len, pfb_pos, pfb_lenpos;
FT_Long rlen, temp;
if ( face_index == -1 )
face_index = 0;
if ( face_index != 0 )
return error;
/* Find the length of all the POST resources, concatenated. Assume */
/* worst case (each resource in its own section). */
pfb_len = 0;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit;
if ( FT_READ_LONG( temp ) )
goto Exit;
pfb_len += temp + 6;
}
if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) )
goto Exit;
pfb_data[0] = 0x80;
pfb_data[1] = 1; /* Ascii section */
pfb_data[2] = 0; /* 4-byte length, fill in later */
pfb_data[3] = 0;
pfb_data[4] = 0;
pfb_data[5] = 0;
pfb_pos = 6;
pfb_lenpos = 2;
len = 0;
type = 1;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit2;
if ( FT_READ_LONG( rlen ) )
goto Exit;
if ( FT_READ_USHORT( flags ) )
goto Exit;
FT_TRACE3(( "POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\n",
i, offsets[i], rlen, flags ));
/* the flags are part of the resource, so rlen >= 2. */
/* but some fonts declare rlen = 0 for empty fragment */
if ( rlen > 2 )
if ( ( flags >> 8 ) == type )
len += rlen;
else
{
if ( pfb_lenpos + 3 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
if ( ( flags >> 8 ) == 5 ) /* End of font mark */
break;
if ( pfb_pos + 6 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_pos++] = 0x80;
type = flags >> 8;
len = rlen;
pfb_data[pfb_pos++] = (FT_Byte)type;
pfb_lenpos = pfb_pos;
pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
}
error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen );
if ( error )
goto Exit2;
pfb_pos += rlen;
}
if ( pfb_pos + 2 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_pos++] = 0x80;
pfb_data[pfb_pos++] = 3;
if ( pfb_lenpos + 3 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
return open_face_from_buffer( library,
pfb_data,
pfb_pos,
face_index,
"type1",
aface );
Exit2:
FT_FREE( pfb_data );
Exit:
return error;
}
|
CWE-119
| 178,175 | 264 |
239474837185248719277265167606864341043
| null | null | null |
savannah
|
6305b869d86ff415a33576df6d43729673c66eee
| 1 |
gray_render_span( int y,
int count,
const FT_Span* spans,
PWorker worker )
{
unsigned char* p;
FT_Bitmap* map = &worker->target;
/* first of all, compute the scanline offset */
p = (unsigned char*)map->buffer - y * map->pitch;
if ( map->pitch >= 0 )
p += ( map->rows - 1 ) * map->pitch;
for ( ; count > 0; count--, spans++ )
{
unsigned char coverage = spans->coverage;
if ( coverage )
{
/* For small-spans it is faster to do it by ourselves than
* calling `memset'. This is mainly due to the cost of the
* function call.
*/
if ( spans->len >= 8 )
FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len );
else
{
unsigned char* q = p + spans->x;
switch ( spans->len )
{
case 7: *q++ = (unsigned char)coverage;
case 6: *q++ = (unsigned char)coverage;
case 5: *q++ = (unsigned char)coverage;
case 4: *q++ = (unsigned char)coverage;
case 3: *q++ = (unsigned char)coverage;
case 2: *q++ = (unsigned char)coverage;
case 1: *q = (unsigned char)coverage;
default:
;
}
}
}
}
}
|
CWE-189
| 178,176 | 265 |
233903124056505689403424392136593938770
| null | null | null |
savannah
|
c69891a1345640096fbf396e8dd567fe879ce233
| 1 |
Mac_Read_POST_Resource( FT_Library library,
FT_Stream stream,
FT_Long *offsets,
FT_Long resource_cnt,
FT_Long face_index,
FT_Face *aface )
{
FT_Error error = FT_Err_Cannot_Open_Resource;
FT_Memory memory = library->memory;
FT_Byte* pfb_data;
int i, type, flags;
FT_Long len;
FT_Long pfb_len, pfb_pos, pfb_lenpos;
FT_Long rlen, temp;
if ( face_index == -1 )
face_index = 0;
if ( face_index != 0 )
return error;
/* Find the length of all the POST resources, concatenated. Assume */
/* worst case (each resource in its own section). */
pfb_len = 0;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit;
if ( FT_READ_LONG( temp ) )
goto Exit;
pfb_len += temp + 6;
}
if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) )
goto Exit;
pfb_data[0] = 0x80;
pfb_data[1] = 1; /* Ascii section */
pfb_data[2] = 0; /* 4-byte length, fill in later */
pfb_data[3] = 0;
pfb_data[4] = 0;
pfb_data[5] = 0;
pfb_pos = 6;
pfb_lenpos = 2;
len = 0;
type = 1;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit2;
if ( FT_READ_LONG( rlen ) )
goto Exit;
if ( FT_READ_USHORT( flags ) )
goto Exit;
rlen -= 2; /* the flags are part of the resource */
if ( ( flags >> 8 ) == type )
len += rlen;
else
{
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
if ( ( flags >> 8 ) == 5 ) /* End of font mark */
break;
pfb_data[pfb_pos++] = 0x80;
type = flags >> 8;
len = rlen;
pfb_data[pfb_pos++] = (FT_Byte)type;
pfb_lenpos = pfb_pos;
pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
}
error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen );
pfb_pos += rlen;
}
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
return open_face_from_buffer( library,
pfb_data,
pfb_pos,
face_index,
"type1",
aface );
Exit2:
FT_FREE( pfb_data );
Exit:
return error;
}
|
CWE-119
| 178,178 | 267 |
66761366277063878236162927407801840545
| null | null | null |
savannah
|
8d22746c9e5af80ff4304aef440986403a5072e2
| 1 |
psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
first = mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
next = mask->end_point;
FT_Int count;
next = mask->end_point;
count = next - first;
if ( count > 0 )
{
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
|
CWE-399
| 178,179 | 268 |
238917502809110546701210284595052003786
| null | null | null |
savannah
|
7d3d2cc4fef72c6be9c454b3809c387e12b44cfc
| 1 |
cff_decoder_parse_charstrings( CFF_Decoder* decoder,
FT_Byte* charstring_base,
FT_ULong charstring_len )
{
FT_Error error;
CFF_Decoder_Zone* zone;
FT_Byte* ip;
FT_Byte* limit;
CFF_Builder* builder = &decoder->builder;
FT_Pos x, y;
FT_Fixed seed;
FT_Fixed* stack;
FT_Int charstring_type =
decoder->cff->top_font.font_dict.charstring_type;
T2_Hints_Funcs hinter;
/* set default width */
decoder->num_hints = 0;
decoder->read_width = 1;
/* compute random seed from stack address of parameter */
seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^
(FT_PtrDist)(char*)&decoder ^
(FT_PtrDist)(char*)&charstring_base ) &
FT_ULONG_MAX ) ;
seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL;
if ( seed == 0 )
seed = 0x7384;
/* initialize the decoder */
decoder->top = decoder->stack;
decoder->zone = decoder->zones;
zone = decoder->zones;
stack = decoder->top;
hinter = (T2_Hints_Funcs)builder->hints_funcs;
builder->path_begun = 0;
zone->base = charstring_base;
limit = zone->limit = charstring_base + charstring_len;
ip = zone->cursor = zone->base;
error = CFF_Err_Ok;
x = builder->pos_x;
y = builder->pos_y;
/* begin hints recording session, if any */
if ( hinter )
hinter->open( hinter->hints );
/* now execute loop */
while ( ip < limit )
{
CFF_Operator op;
FT_Byte v;
/********************************************************************/
/* */
/* Decode operator or operand */
/* */
v = *ip++;
if ( v >= 32 || v == 28 )
{
FT_Int shift = 16;
FT_Int32 val;
/* this is an operand, push it on the stack */
if ( v == 28 )
{
if ( ip + 1 >= limit )
goto Syntax_Error;
val = (FT_Short)( ( (FT_Short)ip[0] << 8 ) | ip[1] );
ip += 2;
}
else if ( v < 247 )
val = (FT_Int32)v - 139;
else if ( v < 251 )
{
if ( ip >= limit )
goto Syntax_Error;
val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108;
}
else if ( v < 255 )
{
if ( ip >= limit )
goto Syntax_Error;
val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108;
}
else
{
if ( ip + 3 >= limit )
goto Syntax_Error;
val = ( (FT_Int32)ip[0] << 24 ) |
( (FT_Int32)ip[1] << 16 ) |
( (FT_Int32)ip[2] << 8 ) |
ip[3];
ip += 4;
if ( charstring_type == 2 )
shift = 0;
}
if ( decoder->top - stack >= CFF_MAX_OPERANDS )
goto Stack_Overflow;
val <<= shift;
*decoder->top++ = val;
#ifdef FT_DEBUG_LEVEL_TRACE
if ( !( val & 0xFFFFL ) )
FT_TRACE4(( " %ld", (FT_Int32)( val >> 16 ) ));
else
FT_TRACE4(( " %.2f", val / 65536.0 ));
#endif
}
else
{
/* The specification says that normally arguments are to be taken */
/* from the bottom of the stack. However, this seems not to be */
/* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */
/* arguments similar to a PS interpreter. */
FT_Fixed* args = decoder->top;
FT_Int num_args = (FT_Int)( args - decoder->stack );
FT_Int req_args;
/* find operator */
op = cff_op_unknown;
switch ( v )
{
case 1:
op = cff_op_hstem;
break;
case 3:
op = cff_op_vstem;
break;
case 4:
op = cff_op_vmoveto;
break;
case 5:
op = cff_op_rlineto;
break;
case 6:
op = cff_op_hlineto;
break;
case 7:
op = cff_op_vlineto;
break;
case 8:
op = cff_op_rrcurveto;
break;
case 9:
op = cff_op_closepath;
break;
case 10:
op = cff_op_callsubr;
break;
case 11:
op = cff_op_return;
break;
case 12:
{
if ( ip >= limit )
goto Syntax_Error;
v = *ip++;
switch ( v )
{
case 0:
op = cff_op_dotsection;
break;
case 1: /* this is actually the Type1 vstem3 operator */
op = cff_op_vstem;
break;
case 2: /* this is actually the Type1 hstem3 operator */
op = cff_op_hstem;
break;
case 3:
op = cff_op_and;
break;
case 4:
op = cff_op_or;
break;
case 5:
op = cff_op_not;
break;
case 6:
op = cff_op_seac;
break;
case 7:
op = cff_op_sbw;
break;
case 8:
op = cff_op_store;
break;
case 9:
op = cff_op_abs;
break;
case 10:
op = cff_op_add;
break;
case 11:
op = cff_op_sub;
break;
case 12:
op = cff_op_div;
break;
case 13:
op = cff_op_load;
break;
case 14:
op = cff_op_neg;
break;
case 15:
op = cff_op_eq;
break;
case 16:
op = cff_op_callothersubr;
break;
case 17:
op = cff_op_pop;
break;
case 18:
op = cff_op_drop;
break;
case 20:
op = cff_op_put;
break;
case 21:
op = cff_op_get;
break;
case 22:
op = cff_op_ifelse;
break;
case 23:
op = cff_op_random;
break;
case 24:
op = cff_op_mul;
break;
case 26:
op = cff_op_sqrt;
break;
case 27:
op = cff_op_dup;
break;
case 28:
op = cff_op_exch;
break;
case 29:
op = cff_op_index;
break;
case 30:
op = cff_op_roll;
break;
case 33:
op = cff_op_setcurrentpoint;
break;
case 34:
op = cff_op_hflex;
break;
case 35:
op = cff_op_flex;
break;
case 36:
op = cff_op_hflex1;
break;
case 37:
op = cff_op_flex1;
break;
default:
/* decrement ip for syntax error message */
ip--;
}
}
break;
case 13:
op = cff_op_hsbw;
break;
case 14:
op = cff_op_endchar;
break;
case 16:
op = cff_op_blend;
break;
case 18:
op = cff_op_hstemhm;
break;
case 19:
op = cff_op_hintmask;
break;
case 20:
op = cff_op_cntrmask;
break;
case 21:
op = cff_op_rmoveto;
break;
case 22:
op = cff_op_hmoveto;
break;
case 23:
op = cff_op_vstemhm;
break;
case 24:
op = cff_op_rcurveline;
break;
case 25:
op = cff_op_rlinecurve;
break;
case 26:
op = cff_op_vvcurveto;
break;
case 27:
op = cff_op_hhcurveto;
break;
case 29:
op = cff_op_callgsubr;
break;
case 30:
op = cff_op_vhcurveto;
break;
case 31:
op = cff_op_hvcurveto;
break;
default:
break;
}
if ( op == cff_op_unknown )
goto Syntax_Error;
/* check arguments */
req_args = cff_argument_counts[op];
if ( req_args & CFF_COUNT_CHECK_WIDTH )
{
if ( num_args > 0 && decoder->read_width )
{
/* If `nominal_width' is non-zero, the number is really a */
/* difference against `nominal_width'. Else, the number here */
/* is truly a width, not a difference against `nominal_width'. */
/* If the font does not set `nominal_width', then */
/* `nominal_width' defaults to zero, and so we can set */
/* `glyph_width' to `nominal_width' plus number on the stack */
/* -- for either case. */
FT_Int set_width_ok;
switch ( op )
{
case cff_op_hmoveto:
case cff_op_vmoveto:
set_width_ok = num_args & 2;
break;
case cff_op_hstem:
case cff_op_vstem:
case cff_op_hstemhm:
case cff_op_vstemhm:
case cff_op_rmoveto:
case cff_op_hintmask:
case cff_op_cntrmask:
set_width_ok = num_args & 1;
break;
case cff_op_endchar:
/* If there is a width specified for endchar, we either have */
/* 1 argument or 5 arguments. We like to argue. */
set_width_ok = ( num_args == 5 ) || ( num_args == 1 );
break;
default:
set_width_ok = 0;
break;
}
if ( set_width_ok )
{
decoder->glyph_width = decoder->nominal_width +
( stack[0] >> 16 );
if ( decoder->width_only )
{
/* we only want the advance width; stop here */
break;
}
/* Consumed an argument. */
num_args--;
}
}
decoder->read_width = 0;
req_args = 0;
}
req_args &= 0x000F;
if ( num_args < req_args )
goto Stack_Underflow;
args -= req_args;
num_args -= req_args;
/* At this point, `args' points to the first argument of the */
/* operand in case `req_args' isn't zero. Otherwise, we have */
/* to adjust `args' manually. */
/* Note that we only pop arguments from the stack which we */
/* really need and can digest so that we can continue in case */
/* of superfluous stack elements. */
switch ( op )
{
case cff_op_hstem:
case cff_op_vstem:
case cff_op_hstemhm:
case cff_op_vstemhm:
/* the number of arguments is always even here */
FT_TRACE4((
op == cff_op_hstem ? " hstem\n" :
( op == cff_op_vstem ? " vstem\n" :
( op == cff_op_hstemhm ? " hstemhm\n" : " vstemhm\n" ) ) ));
if ( hinter )
hinter->stems( hinter->hints,
( op == cff_op_hstem || op == cff_op_hstemhm ),
num_args / 2,
args - ( num_args & ~1 ) );
decoder->num_hints += num_args / 2;
args = stack;
break;
case cff_op_hintmask:
case cff_op_cntrmask:
FT_TRACE4(( op == cff_op_hintmask ? " hintmask" : " cntrmask" ));
/* implement vstem when needed -- */
/* the specification doesn't say it, but this also works */
/* with the 'cntrmask' operator */
/* */
if ( num_args > 0 )
{
if ( hinter )
hinter->stems( hinter->hints,
0,
num_args / 2,
args - ( num_args & ~1 ) );
decoder->num_hints += num_args / 2;
}
if ( hinter )
{
if ( op == cff_op_hintmask )
hinter->hintmask( hinter->hints,
builder->current->n_points,
decoder->num_hints,
ip );
else
hinter->counter( hinter->hints,
decoder->num_hints,
ip );
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_UInt maskbyte;
FT_TRACE4(( " (maskbytes: " ));
for ( maskbyte = 0;
maskbyte < (FT_UInt)(( decoder->num_hints + 7 ) >> 3);
maskbyte++, ip++ )
FT_TRACE4(( "0x%02X", *ip ));
FT_TRACE4(( ")\n" ));
}
#else
ip += ( decoder->num_hints + 7 ) >> 3;
#endif
if ( ip >= limit )
goto Syntax_Error;
args = stack;
break;
case cff_op_rmoveto:
FT_TRACE4(( " rmoveto\n" ));
cff_builder_close_contour( builder );
builder->path_begun = 0;
x += args[-2];
y += args[-1];
args = stack;
break;
case cff_op_vmoveto:
FT_TRACE4(( " vmoveto\n" ));
cff_builder_close_contour( builder );
builder->path_begun = 0;
y += args[-1];
args = stack;
break;
case cff_op_hmoveto:
FT_TRACE4(( " hmoveto\n" ));
cff_builder_close_contour( builder );
builder->path_begun = 0;
x += args[-1];
args = stack;
break;
case cff_op_rlineto:
FT_TRACE4(( " rlineto\n" ));
if ( cff_builder_start_point ( builder, x, y ) ||
check_points( builder, num_args / 2 ) )
goto Fail;
if ( num_args < 2 )
goto Stack_Underflow;
args -= num_args & ~1;
while ( args < decoder->top )
{
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 1 );
args += 2;
}
args = stack;
break;
case cff_op_hlineto:
case cff_op_vlineto:
{
FT_Int phase = ( op == cff_op_hlineto );
FT_TRACE4(( op == cff_op_hlineto ? " hlineto\n"
: " vlineto\n" ));
if ( num_args < 1 )
goto Stack_Underflow;
if ( cff_builder_start_point ( builder, x, y ) ||
check_points( builder, num_args ) )
goto Fail;
args = stack;
while ( args < decoder->top )
{
if ( phase )
x += args[0];
else
y += args[0];
if ( cff_builder_add_point1( builder, x, y ) )
goto Fail;
args++;
phase ^= 1;
}
args = stack;
}
break;
case cff_op_rrcurveto:
{
FT_Int nargs;
FT_TRACE4(( " rrcurveto\n" ));
if ( num_args < 6 )
goto Stack_Underflow;
nargs = num_args - num_args % 6;
if ( cff_builder_start_point ( builder, x, y ) ||
check_points( builder, nargs / 2 ) )
goto Fail;
args -= nargs;
while ( args < decoder->top )
{
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 0 );
x += args[2];
y += args[3];
cff_builder_add_point( builder, x, y, 0 );
x += args[4];
y += args[5];
cff_builder_add_point( builder, x, y, 1 );
args += 6;
}
args = stack;
}
break;
case cff_op_vvcurveto:
{
FT_Int nargs;
FT_TRACE4(( " vvcurveto\n" ));
if ( num_args < 4 )
goto Stack_Underflow;
/* if num_args isn't of the form 4n or 4n+1, */
/* we reduce it to 4n+1 */
nargs = num_args - num_args % 4;
if ( num_args - nargs > 0 )
nargs += 1;
if ( cff_builder_start_point( builder, x, y ) )
goto Fail;
args -= nargs;
if ( nargs & 1 )
{
x += args[0];
args++;
nargs--;
}
if ( check_points( builder, 3 * ( nargs / 4 ) ) )
goto Fail;
while ( args < decoder->top )
{
y += args[0];
cff_builder_add_point( builder, x, y, 0 );
x += args[1];
y += args[2];
cff_builder_add_point( builder, x, y, 0 );
y += args[3];
cff_builder_add_point( builder, x, y, 1 );
args += 4;
}
args = stack;
}
break;
case cff_op_hhcurveto:
{
FT_Int nargs;
FT_TRACE4(( " hhcurveto\n" ));
if ( num_args < 4 )
goto Stack_Underflow;
/* if num_args isn't of the form 4n or 4n+1, */
/* we reduce it to 4n+1 */
nargs = num_args - num_args % 4;
if ( num_args - nargs > 0 )
nargs += 1;
if ( cff_builder_start_point( builder, x, y ) )
goto Fail;
args -= nargs;
if ( nargs & 1 )
{
y += args[0];
args++;
nargs--;
}
if ( check_points( builder, 3 * ( nargs / 4 ) ) )
goto Fail;
while ( args < decoder->top )
{
x += args[0];
cff_builder_add_point( builder, x, y, 0 );
x += args[1];
y += args[2];
cff_builder_add_point( builder, x, y, 0 );
x += args[3];
cff_builder_add_point( builder, x, y, 1 );
args += 4;
}
args = stack;
}
break;
case cff_op_vhcurveto:
case cff_op_hvcurveto:
{
FT_Int phase;
FT_Int nargs;
FT_TRACE4(( op == cff_op_vhcurveto ? " vhcurveto\n"
: " hvcurveto\n" ));
if ( cff_builder_start_point( builder, x, y ) )
goto Fail;
if ( num_args < 4 )
goto Stack_Underflow;
/* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */
/* we reduce it to the largest one which fits */
nargs = num_args - num_args % 4;
if ( num_args - nargs > 0 )
nargs += 1;
args -= nargs;
if ( check_points( builder, ( nargs / 4 ) * 3 ) )
goto Stack_Underflow;
phase = ( op == cff_op_hvcurveto );
while ( nargs >= 4 )
{
nargs -= 4;
if ( phase )
{
x += args[0];
cff_builder_add_point( builder, x, y, 0 );
x += args[1];
y += args[2];
cff_builder_add_point( builder, x, y, 0 );
y += args[3];
if ( nargs == 1 )
x += args[4];
cff_builder_add_point( builder, x, y, 1 );
}
else
{
y += args[0];
cff_builder_add_point( builder, x, y, 0 );
x += args[1];
y += args[2];
cff_builder_add_point( builder, x, y, 0 );
x += args[3];
if ( nargs == 1 )
y += args[4];
cff_builder_add_point( builder, x, y, 1 );
}
args += 4;
phase ^= 1;
}
args = stack;
}
break;
case cff_op_rlinecurve:
{
FT_Int num_lines;
FT_Int nargs;
FT_TRACE4(( " rlinecurve\n" ));
if ( num_args < 8 )
goto Stack_Underflow;
nargs = num_args & ~1;
num_lines = ( nargs - 6 ) / 2;
if ( cff_builder_start_point( builder, x, y ) ||
check_points( builder, num_lines + 3 ) )
goto Fail;
args -= nargs;
/* first, add the line segments */
while ( num_lines > 0 )
{
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 1 );
args += 2;
num_lines--;
}
/* then the curve */
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 0 );
x += args[2];
y += args[3];
cff_builder_add_point( builder, x, y, 0 );
x += args[4];
y += args[5];
cff_builder_add_point( builder, x, y, 1 );
args = stack;
}
break;
case cff_op_rcurveline:
{
FT_Int num_curves;
FT_Int nargs;
FT_TRACE4(( " rcurveline\n" ));
if ( num_args < 8 )
goto Stack_Underflow;
nargs = num_args - 2;
nargs = nargs - nargs % 6 + 2;
num_curves = ( nargs - 2 ) / 6;
if ( cff_builder_start_point ( builder, x, y ) ||
check_points( builder, num_curves * 3 + 2 ) )
goto Fail;
args -= nargs;
/* first, add the curves */
while ( num_curves > 0 )
{
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 0 );
x += args[2];
y += args[3];
cff_builder_add_point( builder, x, y, 0 );
x += args[4];
y += args[5];
cff_builder_add_point( builder, x, y, 1 );
args += 6;
num_curves--;
}
/* then the final line */
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 1 );
args = stack;
}
break;
case cff_op_hflex1:
{
FT_Pos start_y;
FT_TRACE4(( " hflex1\n" ));
/* adding five more points: 4 control points, 1 on-curve point */
/* -- make sure we have enough space for the start point if it */
/* needs to be added */
if ( cff_builder_start_point( builder, x, y ) ||
check_points( builder, 6 ) )
goto Fail;
/* record the starting point's y position for later use */
start_y = y;
/* first control point */
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y, 0 );
/* second control point */
x += args[2];
y += args[3];
cff_builder_add_point( builder, x, y, 0 );
/* join point; on curve, with y-value the same as the last */
/* control point's y-value */
x += args[4];
cff_builder_add_point( builder, x, y, 1 );
/* third control point, with y-value the same as the join */
/* point's y-value */
x += args[5];
cff_builder_add_point( builder, x, y, 0 );
/* fourth control point */
x += args[6];
y += args[7];
cff_builder_add_point( builder, x, y, 0 );
/* ending point, with y-value the same as the start */
x += args[8];
y = start_y;
cff_builder_add_point( builder, x, y, 1 );
args = stack;
break;
}
case cff_op_hflex:
{
FT_Pos start_y;
FT_TRACE4(( " hflex\n" ));
/* adding six more points; 4 control points, 2 on-curve points */
if ( cff_builder_start_point( builder, x, y ) ||
check_points( builder, 6 ) )
goto Fail;
/* record the starting point's y-position for later use */
start_y = y;
/* first control point */
x += args[0];
cff_builder_add_point( builder, x, y, 0 );
/* second control point */
x += args[1];
y += args[2];
cff_builder_add_point( builder, x, y, 0 );
/* join point; on curve, with y-value the same as the last */
/* control point's y-value */
x += args[3];
cff_builder_add_point( builder, x, y, 1 );
/* third control point, with y-value the same as the join */
/* point's y-value */
x += args[4];
cff_builder_add_point( builder, x, y, 0 );
/* fourth control point */
x += args[5];
y = start_y;
cff_builder_add_point( builder, x, y, 0 );
/* ending point, with y-value the same as the start point's */
/* y-value -- we don't add this point, though */
x += args[6];
cff_builder_add_point( builder, x, y, 1 );
args = stack;
break;
}
case cff_op_flex1:
{
FT_Pos start_x, start_y; /* record start x, y values for */
/* alter use */
FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */
/* algorithm below */
FT_Int horizontal, count;
FT_Fixed* temp;
FT_TRACE4(( " flex1\n" ));
/* adding six more points; 4 control points, 2 on-curve points */
if ( cff_builder_start_point( builder, x, y ) ||
check_points( builder, 6 ) )
goto Fail;
/* record the starting point's x, y position for later use */
start_x = x;
start_y = y;
/* XXX: figure out whether this is supposed to be a horizontal */
/* or vertical flex; the Type 2 specification is vague... */
temp = args;
/* grab up to the last argument */
for ( count = 5; count > 0; count-- )
{
dx += temp[0];
dy += temp[1];
temp += 2;
}
if ( dx < 0 )
dx = -dx;
if ( dy < 0 )
dy = -dy;
/* strange test, but here it is... */
horizontal = ( dx > dy );
for ( count = 5; count > 0; count-- )
{
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y,
(FT_Bool)( count == 3 ) );
args += 2;
}
/* is last operand an x- or y-delta? */
if ( horizontal )
{
x += args[0];
y = start_y;
}
else
{
x = start_x;
y += args[0];
}
cff_builder_add_point( builder, x, y, 1 );
args = stack;
break;
}
case cff_op_flex:
{
FT_UInt count;
FT_TRACE4(( " flex\n" ));
if ( cff_builder_start_point( builder, x, y ) ||
check_points( builder, 6 ) )
goto Fail;
for ( count = 6; count > 0; count-- )
{
x += args[0];
y += args[1];
cff_builder_add_point( builder, x, y,
(FT_Bool)( count == 4 || count == 1 ) );
args += 2;
}
args = stack;
}
break;
case cff_op_seac:
FT_TRACE4(( " seac\n" ));
error = cff_operator_seac( decoder,
args[0], args[1], args[2],
(FT_Int)( args[3] >> 16 ),
(FT_Int)( args[4] >> 16 ) );
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
/* return now! */
FT_TRACE4(( "\n" ));
return error;
case cff_op_endchar:
FT_TRACE4(( " endchar\n" ));
/* We are going to emulate the seac operator. */
if ( num_args >= 4 )
{
/* Save glyph width so that the subglyphs don't overwrite it. */
FT_Pos glyph_width = decoder->glyph_width;
error = cff_operator_seac( decoder,
0L, args[-4], args[-3],
(FT_Int)( args[-2] >> 16 ),
(FT_Int)( args[-1] >> 16 ) );
decoder->glyph_width = glyph_width;
}
else
{
if ( !error )
error = CFF_Err_Ok;
cff_builder_close_contour( builder );
/* close hints recording session */
if ( hinter )
{
if ( hinter->close( hinter->hints,
builder->current->n_points ) )
goto Syntax_Error;
/* apply hints to the loaded glyph outline now */
hinter->apply( hinter->hints,
builder->current,
(PSH_Globals)builder->hints_globals,
decoder->hint_mode );
}
/* add current outline to the glyph slot */
FT_GlyphLoader_Add( builder->loader );
}
/* return now! */
FT_TRACE4(( "\n" ));
return error;
case cff_op_abs:
FT_TRACE4(( " abs\n" ));
if ( args[0] < 0 )
args[0] = -args[0];
args++;
break;
case cff_op_add:
FT_TRACE4(( " add\n" ));
args[0] += args[1];
args++;
break;
case cff_op_sub:
FT_TRACE4(( " sub\n" ));
args[0] -= args[1];
args++;
break;
case cff_op_div:
FT_TRACE4(( " div\n" ));
args[0] = FT_DivFix( args[0], args[1] );
args++;
break;
case cff_op_neg:
FT_TRACE4(( " neg\n" ));
args[0] = -args[0];
args++;
break;
case cff_op_random:
{
FT_Fixed Rand;
FT_TRACE4(( " rand\n" ));
Rand = seed;
if ( Rand >= 0x8000L )
Rand++;
args[0] = Rand;
seed = FT_MulFix( seed, 0x10000L - seed );
if ( seed == 0 )
seed += 0x2873;
args++;
}
break;
case cff_op_mul:
FT_TRACE4(( " mul\n" ));
args[0] = FT_MulFix( args[0], args[1] );
args++;
break;
case cff_op_sqrt:
FT_TRACE4(( " sqrt\n" ));
if ( args[0] > 0 )
{
FT_Int count = 9;
FT_Fixed root = args[0];
FT_Fixed new_root;
for (;;)
{
new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1;
if ( new_root == root || count <= 0 )
break;
root = new_root;
}
args[0] = new_root;
}
else
args[0] = 0;
args++;
break;
case cff_op_drop:
/* nothing */
FT_TRACE4(( " drop\n" ));
break;
case cff_op_exch:
{
FT_Fixed tmp;
FT_TRACE4(( " exch\n" ));
tmp = args[0];
args[0] = args[1];
args[1] = tmp;
args += 2;
}
break;
case cff_op_index:
{
FT_Int idx = (FT_Int)( args[0] >> 16 );
FT_TRACE4(( " index\n" ));
if ( idx < 0 )
idx = 0;
else if ( idx > num_args - 2 )
idx = num_args - 2;
args[0] = args[-( idx + 1 )];
args++;
}
break;
case cff_op_roll:
{
FT_Int count = (FT_Int)( args[0] >> 16 );
FT_Int idx = (FT_Int)( args[1] >> 16 );
FT_TRACE4(( " roll\n" ));
if ( count <= 0 )
count = 1;
args -= count;
if ( args < stack )
goto Stack_Underflow;
if ( idx >= 0 )
{
while ( idx > 0 )
{
FT_Fixed tmp = args[count - 1];
FT_Int i;
for ( i = count - 2; i >= 0; i-- )
args[i + 1] = args[i];
args[0] = tmp;
idx--;
}
}
else
{
while ( idx < 0 )
{
FT_Fixed tmp = args[0];
FT_Int i;
for ( i = 0; i < count - 1; i++ )
args[i] = args[i + 1];
args[count - 1] = tmp;
idx++;
}
}
args += count;
}
break;
case cff_op_dup:
FT_TRACE4(( " dup\n" ));
args[1] = args[0];
args += 2;
break;
case cff_op_put:
{
FT_Fixed val = args[0];
FT_Int idx = (FT_Int)( args[1] >> 16 );
FT_TRACE4(( " put\n" ));
if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS )
decoder->buildchar[idx] = val;
}
break;
case cff_op_get:
{
FT_Int idx = (FT_Int)( args[0] >> 16 );
FT_Fixed val = 0;
FT_TRACE4(( " get\n" ));
if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS )
val = decoder->buildchar[idx];
args[0] = val;
args++;
}
break;
case cff_op_store:
FT_TRACE4(( " store\n"));
goto Unimplemented;
case cff_op_load:
FT_TRACE4(( " load\n" ));
goto Unimplemented;
case cff_op_dotsection:
/* this operator is deprecated and ignored by the parser */
FT_TRACE4(( " dotsection\n" ));
break;
case cff_op_closepath:
/* this is an invalid Type 2 operator; however, there */
/* exist fonts which are incorrectly converted from probably */
/* Type 1 to CFF, and some parsers seem to accept it */
FT_TRACE4(( " closepath (invalid op)\n" ));
args = stack;
break;
case cff_op_hsbw:
/* this is an invalid Type 2 operator; however, there */
/* exist fonts which are incorrectly converted from probably */
/* Type 1 to CFF, and some parsers seem to accept it */
FT_TRACE4(( " hsbw (invalid op)\n" ));
decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 );
decoder->builder.left_bearing.x = args[0];
decoder->builder.left_bearing.y = 0;
x = decoder->builder.pos_x + args[0];
y = decoder->builder.pos_y;
args = stack;
break;
case cff_op_sbw:
/* this is an invalid Type 2 operator; however, there */
/* exist fonts which are incorrectly converted from probably */
/* Type 1 to CFF, and some parsers seem to accept it */
FT_TRACE4(( " sbw (invalid op)\n" ));
decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 );
decoder->builder.left_bearing.x = args[0];
decoder->builder.left_bearing.y = args[1];
x = decoder->builder.pos_x + args[0];
y = decoder->builder.pos_y + args[1];
args = stack;
break;
case cff_op_setcurrentpoint:
/* this is an invalid Type 2 operator; however, there */
/* exist fonts which are incorrectly converted from probably */
/* Type 1 to CFF, and some parsers seem to accept it */
FT_TRACE4(( " setcurrentpoint (invalid op)\n" ));
x = decoder->builder.pos_x + args[0];
y = decoder->builder.pos_y + args[1];
args = stack;
break;
case cff_op_callothersubr:
/* this is an invalid Type 2 operator; however, there */
/* exist fonts which are incorrectly converted from probably */
/* Type 1 to CFF, and some parsers seem to accept it */
FT_TRACE4(( " callothersubr (invalid op)\n" ));
/* subsequent `pop' operands should add the arguments, */
/* this is the implementation described for `unknown' other */
/* subroutines in the Type1 spec. */
args -= 2 + ( args[-2] >> 16 );
break;
case cff_op_pop:
/* Type 1 to CFF, and some parsers seem to accept it */
FT_TRACE4(( " pop (invalid op)\n" ));
args++;
break;
case cff_op_and:
{
FT_Fixed cond = args[0] && args[1];
FT_TRACE4(( " and\n" ));
args[0] = cond ? 0x10000L : 0;
args++;
}
break;
case cff_op_or:
{
FT_Fixed cond = args[0] || args[1];
FT_TRACE4(( " or\n" ));
args[0] = cond ? 0x10000L : 0;
args++;
}
break;
case cff_op_eq:
{
FT_Fixed cond = !args[0];
FT_TRACE4(( " eq\n" ));
args[0] = cond ? 0x10000L : 0;
args++;
}
break;
case cff_op_ifelse:
{
FT_Fixed cond = ( args[2] <= args[3] );
FT_TRACE4(( " ifelse\n" ));
if ( !cond )
args[0] = args[1];
args++;
}
break;
case cff_op_callsubr:
{
FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) +
decoder->locals_bias );
FT_TRACE4(( " callsubr(%d)\n", idx ));
if ( idx >= decoder->num_locals )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" invalid local subr index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
zone->base = decoder->locals[idx];
zone->limit = decoder->locals[idx + 1];
zone->cursor = zone->base;
if ( !zone->base || zone->limit == zone->base )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
}
break;
case cff_op_callgsubr:
{
FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) +
decoder->globals_bias );
FT_TRACE4(( " callgsubr(%d)\n", idx ));
if ( idx >= decoder->num_globals )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" invalid global subr index\n" ));
goto Syntax_Error;
}
if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" too many nested subrs\n" ));
goto Syntax_Error;
}
zone->cursor = ip; /* save current instruction pointer */
zone++;
zone->base = decoder->globals[idx];
zone->limit = decoder->globals[idx + 1];
zone->cursor = zone->base;
if ( !zone->base || zone->limit == zone->base )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" invoking empty subrs\n" ));
goto Syntax_Error;
}
decoder->zone = zone;
ip = zone->base;
limit = zone->limit;
}
break;
case cff_op_return:
FT_TRACE4(( " return\n" ));
if ( decoder->zone <= decoder->zones )
{
FT_ERROR(( "cff_decoder_parse_charstrings:"
" unexpected return\n" ));
goto Syntax_Error;
}
decoder->zone--;
zone = decoder->zone;
ip = zone->cursor;
limit = zone->limit;
break;
default:
Unimplemented:
FT_ERROR(( "Unimplemented opcode: %d", ip[-1] ));
if ( ip[-1] == 12 )
FT_ERROR(( " %d", ip[0] ));
FT_ERROR(( "\n" ));
return CFF_Err_Unimplemented_Feature;
}
decoder->top = args;
} /* general operator processing */
} /* while ip < limit */
FT_TRACE4(( "..end..\n\n" ));
Fail:
return error;
Syntax_Error:
FT_TRACE4(( "cff_decoder_parse_charstrings: syntax error\n" ));
return CFF_Err_Invalid_File_Format;
Stack_Underflow:
FT_TRACE4(( "cff_decoder_parse_charstrings: stack underflow\n" ));
return CFF_Err_Too_Few_Arguments;
Stack_Overflow:
FT_TRACE4(( "cff_decoder_parse_charstrings: stack overflow\n" ));
return CFF_Err_Stack_Overflow;
}
|
CWE-189
| 178,180 | 269 |
78533740565488192289380822412773176149
| null | null | null |
libXv
|
d9da580b46a28ab497de2e94fdc7b9ff953dab17
| 1 |
XvQueryAdaptors(
Display *dpy,
Window window,
unsigned int *p_nAdaptors,
XvAdaptorInfo **p_pAdaptors)
{
XExtDisplayInfo *info = xv_find_display(dpy);
xvQueryAdaptorsReq *req;
xvQueryAdaptorsReply rep;
size_t size;
unsigned int ii, jj;
char *name;
XvAdaptorInfo *pas = NULL, *pa;
XvFormat *pfs, *pf;
char *buffer = NULL;
char *buffer;
char *string;
xvAdaptorInfo *pa;
xvFormat *pf;
} u;
|
CWE-125
| 178,181 | 270 |
25138831966304988672154482243921916552
| null | null | null |
accountsservice
|
bd51aa4cdac380f55d607f4ffdf2ab3c00d08721
| 1 |
method_invocation_get_uid (GDBusMethodInvocation *context)
{
const gchar *sender;
PolkitSubject *busname;
PolkitSubject *process;
uid_t uid;
sender = g_dbus_method_invocation_get_sender (context);
busname = polkit_system_bus_name_new (sender);
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (busname), NULL, NULL);
uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (busname);
g_object_unref (process);
return uid;
}
|
CWE-362
| 178,182 | 271 |
24980212968361356668634529334558755546
| null | null | null |
accountsservice
|
26213aa0e0d8dca5f36cc23f6942525224cbe9f5
| 1 |
get_caller_uid (GDBusMethodInvocation *context, gint *uid)
{
PolkitSubject *subject;
PolkitSubject *process;
subject = polkit_system_bus_name_new (g_dbus_method_invocation_get_sender (context));
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, NULL);
if (!process) {
g_object_unref (subject);
return FALSE;
}
*uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (subject);
g_object_unref (process);
return TRUE;
}
|
CWE-362
| 178,183 | 272 |
338964098978064792638046410608178684563
| null | null | null |
savannah
|
f290f48a621867084884bfff87f8093c15195e6a
| 1 |
intuit_diff_type (bool need_header, mode_t *p_file_type)
{
file_offset this_line = 0;
file_offset first_command_line = -1;
char first_ed_command_letter = 0;
lin fcl_line = 0; /* Pacify 'gcc -W'. */
bool this_is_a_command = false;
bool stars_this_line = false;
bool extended_headers = false;
enum nametype i;
struct stat st[3];
int stat_errno[3];
int version_controlled[3];
enum diff retval;
mode_t file_type;
size_t indent = 0;
for (i = OLD; i <= INDEX; i++)
if (p_name[i]) {
free (p_name[i]);
p_name[i] = 0;
}
for (i = 0; i < ARRAY_SIZE (invalid_names); i++)
invalid_names[i] = NULL;
for (i = OLD; i <= NEW; i++)
if (p_timestr[i])
{
free(p_timestr[i]);
p_timestr[i] = 0;
}
for (i = OLD; i <= NEW; i++)
if (p_sha1[i])
{
free (p_sha1[i]);
p_sha1[i] = 0;
}
p_git_diff = false;
for (i = OLD; i <= NEW; i++)
{
p_mode[i] = 0;
p_copy[i] = false;
p_rename[i] = false;
}
/* Ed and normal format patches don't have filename headers. */
if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF)
need_header = false;
version_controlled[OLD] = -1;
version_controlled[NEW] = -1;
version_controlled[INDEX] = -1;
p_rfc934_nesting = 0;
p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1;
p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
Fseek (pfp, p_base, SEEK_SET);
p_input_line = p_bline - 1;
for (;;) {
char *s;
char *t;
file_offset previous_line = this_line;
bool last_line_was_command = this_is_a_command;
bool stars_last_line = stars_this_line;
size_t indent_last_line = indent;
char ed_command_letter;
bool strip_trailing_cr;
size_t chars_read;
indent = 0;
this_line = file_tell (pfp);
chars_read = pget_line (0, 0, false, false);
if (chars_read == (size_t) -1)
xalloc_die ();
if (! chars_read) {
if (first_ed_command_letter) {
/* nothing but deletes!? */
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
else {
p_start = this_line;
p_sline = p_input_line;
if (extended_headers)
{
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
return NO_DIFF;
}
}
strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r';
for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
if (*s == '\t')
indent = (indent + 8) & ~7;
else
indent++;
}
if (ISDIGIT (*s))
{
for (t = s + 1; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
if (*t == 'd' || *t == 'c' || *t == 'a')
{
for (t++; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
for (; *t == ' ' || *t == '\t'; t++)
/* do nothing */ ;
if (*t == '\r')
t++;
this_is_a_command = (*t == '\n');
}
}
if (! need_header
&& first_command_line < 0
&& ((ed_command_letter = get_ed_command_letter (s))
|| this_is_a_command)) {
first_command_line = this_line;
first_ed_command_letter = ed_command_letter;
fcl_line = p_input_line;
p_indent = indent; /* assume this for now */
p_strip_trailing_cr = strip_trailing_cr;
}
if (!stars_last_line && strnEQ(s, "*** ", 4))
{
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
}
else if (strnEQ(s, "+++ ", 4))
{
/* Swap with NEW below. */
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Index:", 6))
{
fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Prereq:", 7))
{
for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
/* do nothing */ ;
revision = t;
for (t = revision; *t; t++)
if (ISSPACE ((unsigned char) *t))
{
char const *u;
for (u = t + 1; ISSPACE ((unsigned char) *u); u++)
/* do nothing */ ;
if (*u)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("Prereq: with multiple words at line %s of patch\n",
format_linenum (numbuf, this_line));
}
break;
}
if (t == revision)
revision = 0;
else {
char oldc = *t;
*t = '\0';
revision = xstrdup (revision);
*t = oldc;
}
}
else if (strnEQ (s, "diff --git ", 11))
{
char const *u;
if (extended_headers)
{
p_start = this_line;
p_sline = p_input_line;
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u))
&& ISSPACE ((unsigned char) *u)
&& (p_name[NEW] = parse_name (u, strippath, &u))
&& (u = skip_spaces (u), ! *u)))
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
p_git_diff = true;
need_header = false;
}
else if (p_git_diff && strnEQ (s, "index ", 6))
{
char const *u, *v;
if ((u = skip_hex_digits (s + 6))
&& u[0] == '.' && u[1] == '.'
&& (v = skip_hex_digits (u + 2))
&& (! *v || ISSPACE ((unsigned char) *v)))
{
get_sha1(&p_sha1[OLD], s + 6, u);
get_sha1(&p_sha1[NEW], u + 2, v);
p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]);
p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]);
if (*(v = skip_spaces (v)))
p_mode[OLD] = p_mode[NEW] = fetchmode (v);
extended_headers = true;
}
}
else if (p_git_diff && strnEQ (s, "old mode ", 9))
{
p_mode[OLD] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new mode ", 9))
{
p_mode[NEW] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "deleted file mode ", 18))
{
p_mode[OLD] = fetchmode (s + 18);
p_says_nonexistent[NEW] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new file mode ", 14))
{
p_mode[NEW] = fetchmode (s + 14);
p_says_nonexistent[OLD] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename from ", 12))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename to ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy from ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy to ", 8))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "GIT binary patch", 16))
{
p_start = this_line;
p_sline = p_input_line;
retval = GIT_BINARY_DIFF;
goto scan_exit;
}
else
{
for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
/* do nothing */ ;
if (strnEQ(t, "--- ", 4))
{
struct timespec timestamp;
timestamp.tv_sec = -1;
fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW],
×tamp);
need_header = false;
if (timestamp.tv_sec != -1)
{
p_timestamp[NEW] = timestamp;
p_rfc934_nesting = (t - s) >> 1;
}
p_strip_trailing_cr = strip_trailing_cr;
}
}
if (need_header)
continue;
if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
first_command_line >= 0 &&
strEQ(s, ".\n") ) {
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
&& strnEQ(s, "@@ -", 4)) {
/* 'p_name', 'p_timestr', and 'p_timestamp' are backwards;
swap them. */
struct timespec ti = p_timestamp[OLD];
p_timestamp[OLD] = p_timestamp[NEW];
p_timestamp[NEW] = ti;
t = p_name[OLD];
p_name[OLD] = p_name[NEW];
p_name[NEW] = t;
t = p_timestr[OLD];
p_timestr[OLD] = p_timestr[NEW];
p_timestr[NEW] = t;
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
while (*s != ' ' && *s != '\n')
s++;
while (*s == ' ')
s++;
if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
p_indent = indent;
p_start = this_line;
p_sline = p_input_line;
retval = UNI_DIFF;
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for unified diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
stars_this_line = strnEQ(s, "********", 8);
if ((diff_type == NO_DIFF
|| diff_type == CONTEXT_DIFF
|| diff_type == NEW_CONTEXT_DIFF)
&& stars_last_line && indent_last_line == indent
&& strnEQ (s, "*** ", 4)) {
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
/* if this is a new context diff the character just before */
/* the newline is a '*'. */
while (*s != '\n')
s++;
p_indent = indent;
p_strip_trailing_cr = strip_trailing_cr;
p_start = previous_line;
p_sline = p_input_line - 1;
retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
{
/* Scan the first hunk to see whether the file contents
appear to have been deleted. */
file_offset saved_p_base = p_base;
lin saved_p_bline = p_bline;
Fseek (pfp, previous_line, SEEK_SET);
p_input_line -= 2;
if (another_hunk (retval, false)
&& ! p_repl_lines && p_newfirst == 1)
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
next_intuit_at (saved_p_base, saved_p_bline);
}
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for context diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
last_line_was_command &&
(strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
p_start = previous_line;
p_sline = p_input_line - 1;
p_indent = indent;
retval = NORMAL_DIFF;
goto scan_exit;
}
}
scan_exit:
/* The old, new, or old and new file types may be defined. When both
file types are defined, make sure they are the same, or else assume
we do not know the file type. */
file_type = p_mode[OLD] & S_IFMT;
if (file_type)
{
mode_t new_file_type = p_mode[NEW] & S_IFMT;
if (new_file_type && file_type != new_file_type)
file_type = 0;
}
else
{
file_type = p_mode[NEW] & S_IFMT;
if (! file_type)
file_type = S_IFREG;
}
*p_file_type = file_type;
/* To intuit 'inname', the name of the file to patch,
use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599
(with some modifications if posixly_correct is zero):
- Take the old and new names from the context header if present,
and take the index name from the 'Index:' line if present and
if either the old and new names are both absent
or posixly_correct is nonzero.
Consider the file names to be in the order (old, new, index).
- If some named files exist, use the first one if posixly_correct
is nonzero, the best one otherwise.
- If patch_get is nonzero, and no named files exist,
but an RCS or SCCS master file exists,
use the first named file with an RCS or SCCS master.
- If no named files exist, no RCS or SCCS master was found,
some names are given, posixly_correct is zero,
and the patch appears to create a file, then use the best name
requiring the creation of the fewest directories.
- Otherwise, report failure by setting 'inname' to 0;
this causes our invoker to ask the user for a file name. */
i = NONE;
if (!inname)
{
enum nametype i0 = NONE;
if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX])
{
free (p_name[INDEX]);
p_name[INDEX] = 0;
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0)
{
/* It's the same name as before; reuse stat results. */
stat_errno[i] = stat_errno[i0];
if (! stat_errno[i])
st[i] = st[i0];
}
else
{
stat_errno[i] = stat_file (p_name[i], &st[i]);
if (! stat_errno[i])
{
if (lookup_file_id (&st[i]) == DELETE_LATER)
stat_errno[i] = ENOENT;
else if (posixly_correct && name_is_valid (p_name[i]))
break;
}
}
i0 = i;
}
if (! posixly_correct)
{
/* The best of all existing files. */
i = best_name (p_name, stat_errno);
if (i == NONE && patch_get)
{
enum nametype nope = NONE;
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
char const *cs;
char *getbuf;
char *diffbuf;
bool readonly = (outfile
&& strcmp (outfile, p_name[i]) != 0);
if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0)
{
cs = (version_controller
(p_name[i], readonly, (struct stat *) 0,
&getbuf, &diffbuf));
version_controlled[i] = !! cs;
if (cs)
{
if (version_get (p_name[i], cs, false, readonly,
getbuf, &st[i]))
stat_errno[i] = 0;
else
version_controlled[i] = 0;
free (getbuf);
free (diffbuf);
if (! stat_errno[i])
break;
}
}
nope = i;
}
}
if (i0 != NONE
&& (i == NONE || (st[i].st_mode & S_IFMT) == file_type)
&& maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE,
i == NONE || st[i].st_size == 0)
&& i == NONE)
i = i0;
if (i == NONE && p_says_nonexistent[reverse])
{
int newdirs[3];
int newdirs_min = INT_MAX;
int distance_from_minimum[3];
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
newdirs[i] = (prefix_components (p_name[i], false)
- prefix_components (p_name[i], true));
if (newdirs[i] < newdirs_min)
newdirs_min = newdirs[i];
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
distance_from_minimum[i] = newdirs[i] - newdirs_min;
/* The best of the filenames which create the fewest directories. */
i = best_name (p_name, distance_from_minimum);
}
}
}
if ((pch_rename () || pch_copy ())
&& ! inname
&& ! ((i == OLD || i == NEW) &&
p_name[! reverse] &&
name_is_valid (p_name[! reverse])))
{
say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy");
}
if (i == NONE)
{
if (inname)
{
inerrno = stat_file (inname, &instat);
if (inerrno || (instat.st_mode & S_IFMT) == file_type)
maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0);
}
else
inerrno = -1;
}
else
{
inname = xstrdup (p_name[i]);
inerrno = stat_errno[i];
invc = version_controlled[i];
instat = st[i];
}
return retval;
}
|
CWE-476
| 178,192 | 274 |
119977677141531301071259218660699705481
| null | null | null |
savannah
|
29c759284e305ec428703c9a5831d0b1fc3497ef
| 1 |
Ins_GETVARIATION( TT_ExecContext exc,
FT_Long* args )
{
FT_UInt num_axes = exc->face->blend->num_axis;
FT_Fixed* coords = exc->face->blend->normalizedcoords;
FT_UInt i;
if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) )
{
exc->error = FT_THROW( Stack_Overflow );
return;
}
for ( i = 0; i < num_axes; i++ )
args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */
}
|
CWE-476
| 178,193 | 275 |
139567459660525946313428439964298096333
| null | null | null |
openssl
|
83764a989dcc87fbea337da5f8f86806fe767b7e
| 1 |
int ssl3_get_server_hello(SSL *s)
{
STACK_OF(SSL_CIPHER) *sk;
const SSL_CIPHER *c;
unsigned char *p,*d;
int i,al,ok;
unsigned int j;
long n;
#ifndef OPENSSL_NO_COMP
SSL_COMP *comp;
#endif
n=s->method->ssl_get_message(s,
SSL3_ST_CR_SRVR_HELLO_A,
SSL3_ST_CR_SRVR_HELLO_B,
-1,
20000, /* ?? */
&ok);
if (!ok) return((int)n);
if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
{
if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
{
if ( s->d1->send_cookie == 0)
{
s->s3->tmp.reuse_message = 1;
return 1;
}
else /* already sent a cookie */
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
goto f_err;
}
}
}
if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
{
al=SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
goto f_err;
}
d=p=(unsigned char *)s->init_msg;
if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
{
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
s->version=(s->version&0xff00)|p[1];
al=SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
p+=2;
/* load the server hello data */
/* load the server random */
memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
p+=SSL3_RANDOM_SIZE;
/* get the session-id */
j= *(p++);
if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
goto f_err;
}
#ifndef OPENSSL_NO_TLSEXT
/* check if we want to resume the session based on external pre-shared secret */
if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
{
SSL_CIPHER *pref_cipher=NULL;
s->session->master_key_length=sizeof(s->session->master_key);
if (s->tls_session_secret_cb(s, s->session->master_key,
&s->session->master_key_length,
NULL, &pref_cipher,
s->tls_session_secret_cb_arg))
{
s->session->cipher = pref_cipher ?
pref_cipher : ssl_get_cipher_by_char(s, p+j);
s->s3->flags |= SSL3_FLAGS_CCS_OK;
}
}
#endif /* OPENSSL_NO_TLSEXT */
if (j != 0 && j == s->session->session_id_length
&& memcmp(p,s->session->session_id,j) == 0)
{
if(s->sid_ctx_length != s->session->sid_ctx_length
|| memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
{
/* actually a client application bug */
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
goto f_err;
}
s->s3->flags |= SSL3_FLAGS_CCS_OK;
s->hit=1;
}
else /* a miss or crap from the other end */
{
/* If we were trying for session-id reuse, make a new
* SSL_SESSION so we don't stuff up other people */
s->hit=0;
if (s->session->session_id_length > 0)
{
if (!ssl_get_new_session(s,0))
{
al=SSL_AD_INTERNAL_ERROR;
goto f_err;
}
}
s->session->session_id_length=j;
memcpy(s->session->session_id,p,j); /* j could be 0 */
}
p+=j;
c=ssl_get_cipher_by_char(s,p);
if (c == NULL)
{
/* unknown cipher */
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
goto f_err;
}
/* TLS v1.2 only ciphersuites require v1.2 or later */
if ((c->algorithm_ssl & SSL_TLSV1_2) &&
(TLS1_get_version(s) < TLS1_2_VERSION))
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
goto f_err;
}
p+=ssl_put_cipher_by_char(s,NULL,NULL);
sk=ssl_get_ciphers_by_id(s);
/* Depending on the session caching (internal/external), the cipher
and/or cipher_id values may not be set. Make sure that
cipher_id is set and use it for comparison. */
if (s->session->cipher)
s->session->cipher_id = s->session->cipher->id;
if (s->hit && (s->session->cipher_id != c->id))
{
/* Workaround is now obsolete */
#if 0
if (!(s->options &
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
#endif
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
goto f_err;
}
}
s->s3->tmp.new_cipher=c;
/* Don't digest cached records if TLS v1.2: we may need them for
* client authentication.
*/
if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s))
{
al = SSL_AD_INTERNAL_ERROR;
goto f_err;
}
/* lets get the compression algorithm */
/* COMPRESSION */
#ifdef OPENSSL_NO_COMP
if (*(p++) != 0)
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
goto f_err;
}
/* If compression is disabled we'd better not try to resume a session
* using compression.
*/
if (s->session->compress_meth != 0)
{
al=SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
#else
j= *(p++);
if (s->hit && j != s->session->compress_meth)
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
goto f_err;
}
if (j == 0)
comp=NULL;
else if (s->options & SSL_OP_NO_COMPRESSION)
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED);
goto f_err;
}
else
comp=ssl3_comp_find(s->ctx->comp_methods,j);
if ((j != 0) && (comp == NULL))
{
al=SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
goto f_err;
}
else
{
s->s3->tmp.new_compression=comp;
}
#endif
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions*/
if (s->version >= SSL3_VERSION)
{
if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al))
{
/* 'al' set by ssl_parse_serverhello_tlsext */
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
goto f_err;
}
if (ssl_check_serverhello_tlsext(s) <= 0)
{
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
goto err;
}
}
#endif
if (p != (d+n))
{
/* wrong packet length */
al=SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
goto f_err;
}
return(1);
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,al);
err:
return(-1);
}
| 178,194 | 276 |
277497504299456757679652544715041856567
| null | null | null |
|
openssl
|
80bd7b41b30af6ee96f519e629463583318de3b0
| 1 |
void ssl_set_client_disabled(SSL *s)
{
CERT *c = s->cert;
c->mask_a = 0;
c->mask_k = 0;
/* Don't allow TLS 1.2 only ciphers if we don't suppport them */
if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
c->mask_ssl = SSL_TLSV1_2;
else
c->mask_ssl = 0;
ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK);
/* Disable static DH if we don't include any appropriate
* signature algorithms.
*/
if (c->mask_a & SSL_aRSA)
c->mask_k |= SSL_kDHr|SSL_kECDHr;
if (c->mask_a & SSL_aDSS)
c->mask_k |= SSL_kDHd;
if (c->mask_a & SSL_aECDSA)
c->mask_k |= SSL_kECDHe;
#ifndef OPENSSL_NO_KRB5
if (!kssl_tgt_is_available(s->kssl_ctx))
{
c->mask_a |= SSL_aKRB5;
c->mask_k |= SSL_kKRB5;
}
#endif
#ifndef OPENSSL_NO_PSK
/* with PSK there must be client callback set */
if (!s->psk_client_callback)
{
c->mask_a |= SSL_aPSK;
c->mask_k |= SSL_kPSK;
}
#endif /* OPENSSL_NO_PSK */
c->valid = 1;
}
| 178,195 | 277 |
145190138964748869120683088287665695350
| null | null | null |
|
kde
|
9db872df82c258315c6ebad800af59e81ffb9212
| 1 |
void DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacros(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
|
CWE-78
| 178,196 | 278 |
185460399545264476872601191691271963408
| null | null | null |
kde
|
8164beac15ea34ec0d1564f0557fe3e742bdd938
| 1 |
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id,
const QString &app_icon, const QString &summary, const QString &body,
const QStringList &actions, const QVariantMap &hints, int timeout)
{
uint partOf = 0;
const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString();
const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString();
const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool();
if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) {
partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt();
}
qDebug() << "Currrent active notifications:" << m_activeNotifications;
qDebug() << "Guessing partOf as:" << partOf;
qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf;
QString _body;
if (partOf > 0) {
const QString source = QStringLiteral("notification %1").arg(partOf);
Plasma::DataContainer *container = containerForSource(source);
if (container) {
_body = container->data()[QStringLiteral("body")].toString();
if (_body != body) {
_body.append("\n").append(body);
} else {
_body = body;
}
replaces_id = partOf;
CloseNotification(partOf);
}
}
uint id = replaces_id ? replaces_id : m_nextId++;
if (m_alwaysReplaceAppsList.contains(app_name)) {
if (m_notificationsFromReplaceableApp.contains(app_name)) {
id = m_notificationsFromReplaceableApp.value(app_name);
} else {
m_notificationsFromReplaceableApp.insert(app_name, id);
}
}
QString appname_str = app_name;
if (appname_str.isEmpty()) {
appname_str = i18n("Unknown Application");
}
bool isPersistent = timeout == 0;
const int AVERAGE_WORD_LENGTH = 6;
const int WORD_PER_MINUTE = 250;
int count = summary.length() + body.length();
timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE;
timeout = 2000 + qMax(timeout, 3000);
}
|
CWE-200
| 178,197 | 279 |
66626965994794909671436631171592255350
| null | null | null |
kde
|
5bc696b5abcdb460c1017592e80b2d7f6ed3107c
| 1 |
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id,
const QString &app_icon, const QString &summary, const QString &body,
const QStringList &actions, const QVariantMap &hints, int timeout)
{
uint partOf = 0;
const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString();
const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString();
const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool();
if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) {
partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt();
}
qDebug() << "Currrent active notifications:" << m_activeNotifications;
qDebug() << "Guessing partOf as:" << partOf;
qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf;
QString _body;
if (partOf > 0) {
const QString source = QStringLiteral("notification %1").arg(partOf);
Plasma::DataContainer *container = containerForSource(source);
if (container) {
_body = container->data()[QStringLiteral("body")].toString();
if (_body != body) {
_body.append("\n").append(body);
} else {
_body = body;
}
replaces_id = partOf;
CloseNotification(partOf);
}
}
uint id = replaces_id ? replaces_id : m_nextId++;
if (m_alwaysReplaceAppsList.contains(app_name)) {
if (m_notificationsFromReplaceableApp.contains(app_name)) {
id = m_notificationsFromReplaceableApp.value(app_name);
} else {
m_notificationsFromReplaceableApp.insert(app_name, id);
}
}
QString appname_str = app_name;
if (appname_str.isEmpty()) {
appname_str = i18n("Unknown Application");
}
bool isPersistent = timeout == 0;
const int AVERAGE_WORD_LENGTH = 6;
const int WORD_PER_MINUTE = 250;
int count = summary.length() + body.length();
if (timeout <= 0) {
timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE;
timeout = 2000 + qMax(timeout, 3000);
}
const QString source = QStringLiteral("notification %1").arg(id);
const QString source = QStringLiteral("notification %1").arg(id);
QString bodyFinal = (partOf == 0 ? body : _body);
bodyFinal = bodyFinal.trimmed();
bodyFinal = bodyFinal.replace(QLatin1String("\n"), QLatin1String("<br/>"));
bodyFinal = bodyFinal.simplified();
bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>"));
bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&"));
bodyFinal.replace(QLatin1String("'"), QChar('\''));
Plasma::DataEngine::Data notificationData;
notificationData.insert(QStringLiteral("id"), QString::number(id));
bodyFinal = bodyFinal.simplified();
bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>"));
bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&"));
bodyFinal.replace(QLatin1String("'"), QChar('\''));
Plasma::DataEngine::Data notificationData;
notificationData.insert(QStringLiteral("id"), QString::number(id));
notificationData.insert(QStringLiteral("eventId"), eventId);
notificationData.insert(QStringLiteral("appName"), appname_str);
notificationData.insert(QStringLiteral("appIcon"), app_icon);
notificationData.insert(QStringLiteral("summary"), summary);
notificationData.insert(QStringLiteral("body"), bodyFinal);
notificationData.insert(QStringLiteral("actions"), actions);
notificationData.insert(QStringLiteral("isPersistent"), isPersistent);
notificationData.insert(QStringLiteral("expireTimeout"), timeout);
bool configurable = false;
if (!appRealName.isEmpty()) {
if (m_configurableApplications.contains(appRealName)) {
configurable = m_configurableApplications.value(appRealName);
} else {
QScopedPointer<KConfig> config(new KConfig(appRealName + QStringLiteral(".notifyrc"), KConfig::NoGlobals));
config->addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
QStringLiteral("knotifications5/") + appRealName + QStringLiteral(".notifyrc")));
const QRegularExpression regexp(QStringLiteral("^Event/([^/]*)$"));
configurable = !config->groupList().filter(regexp).isEmpty();
m_configurableApplications.insert(appRealName, configurable);
}
}
notificationData.insert(QStringLiteral("appRealName"), appRealName);
notificationData.insert(QStringLiteral("configurable"), configurable);
QImage image;
if (hints.contains(QStringLiteral("image-data"))) {
QDBusArgument arg = hints[QStringLiteral("image-data")].value<QDBusArgument>();
image = decodeNotificationSpecImageHint(arg);
} else if (hints.contains(QStringLiteral("image_data"))) {
QDBusArgument arg = hints[QStringLiteral("image_data")].value<QDBusArgument>();
image = decodeNotificationSpecImageHint(arg);
} else if (hints.contains(QStringLiteral("image-path"))) {
QString path = findImageForSpecImagePath(hints[QStringLiteral("image-path")].toString());
if (!path.isEmpty()) {
image.load(path);
}
} else if (hints.contains(QStringLiteral("image_path"))) {
QString path = findImageForSpecImagePath(hints[QStringLiteral("image_path")].toString());
if (!path.isEmpty()) {
image.load(path);
}
} else if (hints.contains(QStringLiteral("icon_data"))) {
QDBusArgument arg = hints[QStringLiteral("icon_data")].value<QDBusArgument>();
image = decodeNotificationSpecImageHint(arg);
}
notificationData.insert(QStringLiteral("image"), image.isNull() ? QVariant() : image);
if (hints.contains(QStringLiteral("urgency"))) {
notificationData.insert(QStringLiteral("urgency"), hints[QStringLiteral("urgency")].toInt());
}
setData(source, notificationData);
m_activeNotifications.insert(source, app_name + summary);
return id;
}
|
CWE-200
| 178,198 | 280 |
49080920792690681565819742613436372042
| null | null | null |
savannah
|
9fb46e120655ac481b2af8f865d5ae56c39b831a
| 1 |
dns_stricmp(const char* str1, const char* str2)
{
char c1, c2;
*----------------------------------------------------------------------------*/
/* DNS variables */
static struct udp_pcb *dns_pcb;
static u8_t dns_seqno;
static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS];
if (c1_upc != c2_upc) {
/* still not equal */
/* don't care for < or > */
return 1;
}
} else {
/* characters are not equal but none is in the alphabet range */
return 1;
}
|
CWE-345
| 178,220 | 283 |
181259810056970673184917548254526485235
| null | null | null |
samba
|
9280051bfba337458722fb157f3082f93cbd9f2b
| 1 |
static void reply_sesssetup_and_X_spnego(struct smb_request *req)
{
const uint8 *p;
DATA_BLOB blob1;
size_t bufrem;
char *tmp;
const char *native_os;
const char *native_lanman;
const char *primary_domain;
const char *p2;
uint16 data_blob_len = SVAL(req->vwv+7, 0);
enum remote_arch_types ra_type = get_remote_arch();
int vuid = req->vuid;
user_struct *vuser = NULL;
NTSTATUS status = NT_STATUS_OK;
uint16 smbpid = req->smbpid;
struct smbd_server_connection *sconn = smbd_server_conn;
DEBUG(3,("Doing spnego session setup\n"));
if (global_client_caps == 0) {
global_client_caps = IVAL(req->vwv+10, 0);
if (!(global_client_caps & CAP_STATUS32)) {
remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES);
}
}
p = req->buf;
if (data_blob_len == 0) {
/* an invalid request */
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
return;
}
bufrem = smbreq_bufrem(req, p);
/* pull the spnego blob */
blob1 = data_blob(p, MIN(bufrem, data_blob_len));
#if 0
file_save("negotiate.dat", blob1.data, blob1.length);
#endif
p2 = (char *)req->buf + data_blob_len;
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_os = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
native_lanman = tmp ? tmp : "";
p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2,
STR_TERMINATE);
primary_domain = tmp ? tmp : "";
DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n",
native_os, native_lanman, primary_domain));
if ( ra_type == RA_WIN2K ) {
/* Vista sets neither the OS or lanman strings */
if ( !strlen(native_os) && !strlen(native_lanman) )
set_remote_arch(RA_VISTA);
/* Windows 2003 doesn't set the native lanman string,
but does set primary domain which is a bug I think */
if ( !strlen(native_lanman) ) {
ra_lanman_string( primary_domain );
} else {
ra_lanman_string( native_lanman );
}
}
/* Did we get a valid vuid ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, then try and see if this is an intermediate sessionsetup
* for a large SPNEGO packet. */
struct pending_auth_data *pad;
pad = get_pending_auth_data(sconn, smbpid);
if (pad) {
DEBUG(10,("reply_sesssetup_and_X_spnego: found "
"pending vuid %u\n",
(unsigned int)pad->vuid ));
vuid = pad->vuid;
}
}
/* Do we have a valid vuid now ? */
if (!is_partial_auth_vuid(sconn, vuid)) {
/* No, start a new authentication setup. */
vuid = register_initial_vuid(sconn);
if (vuid == UID_FIELD_INVALID) {
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(
NT_STATUS_INVALID_PARAMETER));
return;
}
}
vuser = get_partial_auth_user_struct(sconn, vuid);
/* This MUST be valid. */
if (!vuser) {
smb_panic("reply_sesssetup_and_X_spnego: invalid vuid.");
}
/* Large (greater than 4k) SPNEGO blobs are split into multiple
* sessionsetup requests as the Windows limit on the security blob
* field is 4k. Bug #4400. JRA.
*/
status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1);
if (!NT_STATUS_IS_OK(status)) {
if (!NT_STATUS_EQUAL(status,
NT_STATUS_MORE_PROCESSING_REQUIRED)) {
/* Real error - kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
}
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
if (blob1.data[0] == ASN1_APPLICATION(0)) {
/* its a negTokenTarg packet */
reply_spnego_negotiate(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (blob1.data[0] == ASN1_CONTEXT(1)) {
/* its a auth packet */
reply_spnego_auth(req, vuid, blob1,
&vuser->auth_ntlmssp_state);
data_blob_free(&blob1);
return;
}
if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) {
DATA_BLOB chal;
if (!vuser->auth_ntlmssp_state) {
status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state);
if (!NT_STATUS_IS_OK(status)) {
/* Kill the intermediate vuid */
invalidate_vuid(sconn, vuid);
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(status));
return;
}
}
status = auth_ntlmssp_update(vuser->auth_ntlmssp_state,
blob1, &chal);
data_blob_free(&blob1);
reply_spnego_ntlmssp(req, vuid,
&vuser->auth_ntlmssp_state,
&chal, status, OID_NTLMSSP, false);
data_blob_free(&chal);
return;
}
/* what sort of packet is this? */
DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n"));
data_blob_free(&blob1);
reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE));
}
|
CWE-119
| 178,226 | 287 |
252100526266913255109910552885875245221
| null | null | null |
savannah
|
f435825c0f527a8e52e6ffbc3ad0bc60531d537e
| 1 |
_asn1_extract_der_octet (asn1_node node, const unsigned char *der,
int der_len, unsigned flags)
{
int len2, len3;
int counter, counter_end;
int result;
len2 = asn1_get_length_der (der, der_len, &len3);
if (len2 < -1)
return ASN1_DER_ERROR;
counter = len3 + 1;
DECR_LEN(der_len, len3);
if (len2 == -1)
counter_end = der_len - 2;
else
counter_end = der_len;
while (counter < counter_end)
{
DECR_LEN(der_len, 1);
if (len2 >= 0)
{
DECR_LEN(der_len, len2+len3);
_asn1_append_value (node, der + counter + len3, len2);
}
else
{ /* indefinite */
DECR_LEN(der_len, len3);
result =
_asn1_extract_der_octet (node, der + counter + len3,
der_len, flags);
if (result != ASN1_SUCCESS)
return result;
len2 = 0;
}
counter += len2 + len3 + 1;
}
return ASN1_SUCCESS;
cleanup:
return result;
}
|
CWE-399
| 178,249 | 288 |
199202175349742229581148475563569699182
| null | null | null |
enlightment
|
37a96801663b7b4cd3fbe56cc0eb8b6a17e766a8
| 1 |
load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
break;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = calloc(w, sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
if (!rows)
{
goto quit2;
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
{
r = cmap->Colors[bg].Red;
g = cmap->Colors[bg].Green;
b = cmap->Colors[bg].Blue;
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
{
for (j = 0; j < w; j++)
{
if (rows[i][j] == transp)
{
r = cmap->Colors[bg].Red;
g = cmap->Colors[bg].Green;
b = cmap->Colors[bg].Blue;
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
}
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
}
finish:
if (progress)
progress(im, 100, 0, last_y, w, h);
}
rc = 1; /* Success */
quit:
for (i = 0; i < h; i++)
free(rows[i]);
free(rows);
quit2:
#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1)
DGifCloseFile(gif, NULL);
#else
DGifCloseFile(gif);
#endif
return rc;
}
|
CWE-119
| 178,251 | 289 |
29413401693515776488286177132255863480
| null | null | null |
enlightment
|
ce94edca1ccfbe314cb7cd9453433fad404ec7ef
| 1 |
__imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax)
{
ImlibUpdate *nu = NULL, *uu;
struct _tile *t;
int tw, th, x, y, i;
int *gaps = NULL;
/* if theres no rects to process.. return NULL */
if (!u)
return NULL;
tw = w >> TB;
if (w & TM)
tw++;
th = h >> TB;
if (h & TM)
th++;
t = malloc(tw * th * sizeof(struct _tile));
/* fill in tiles to be all not used */
for (i = 0, y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
t[i++].used = T_UNUSED;
}
/* fill in all tiles */
for (uu = u; uu; uu = uu->next)
{
CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h);
for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++)
{
for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++)
T(x, y).used = T_USED;
}
}
/* scan each line - if > hgapmax gaps between tiles, then fill smallest */
gaps = malloc(tw * sizeof(int));
for (y = 0; y < th; y++)
{
int hgaps = 0, start = -1, min;
char have = 1, gap = 0;
for (x = 0; x < tw; x++)
gaps[x] = 0;
for (x = 0; x < tw; x++)
{
if ((have) && (T(x, y).used == T_UNUSED))
{
start = x;
gap = 1;
have = 0;
}
else if ((!have) && (gap) && (T(x, y).used & T_USED))
{
gap = 0;
hgaps++;
have = 1;
gaps[start] = x - start;
}
else if (T(x, y).used & T_USED)
have = 1;
}
while (hgaps > hgapmax)
{
start = -1;
min = tw;
for (x = 0; x < tw; x++)
{
if ((gaps[x] > 0) && (gaps[x] < min))
{
start = x;
min = gaps[x];
}
}
if (start >= 0)
{
gaps[start] = 0;
for (x = start;
T(x, y).used == T_UNUSED; T(x++, y).used = T_USED);
hgaps--;
}
}
}
free(gaps);
/* coalesce tiles into larger blocks and make new rect list */
for (y = 0; y < th; y++)
{
for (x = 0; x < tw; x++)
{
if (T(x, y).used & T_USED)
{
int xx, yy, ww, hh, ok, xww;
for (xx = x + 1, ww = 1;
(T(xx, y).used & T_USED) && (xx < tw); xx++, ww++);
xww = x + ww;
for (yy = y + 1, hh = 1, ok = 1;
(yy < th) && (ok); yy++, hh++)
{
for (xx = x; xx < xww; xx++)
{
if (!(T(xx, yy).used & T_USED))
{
ok = 0;
hh--;
break;
}
}
}
for (yy = y; yy < (y + hh); yy++)
{
for (xx = x; xx < xww; xx++)
T(xx, yy).used = T_UNUSED;
}
nu = __imlib_AddUpdate(nu, (x << TB), (y << TB),
(ww << TB), (hh << TB));
}
}
}
free(t);
__imlib_FreeUpdates(u);
return nu;
}
|
CWE-119
| 178,252 | 290 |
36599931638812584056030971307038057704
| null | null | null |
savannah
|
422214868061370aeeb0ac9cd0f021a5c350a57d
| 1 |
_gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type,
record_parameters_st * params)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
uint8_t pad;
int length;
uint16_t blocksize;
int ret, i, pad_failed = 0;
opaque preamble[PREAMBLE_SIZE];
int preamble_size;
int ver = gnutls_protocol_get_version (session);
int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm);
blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
/* actual decryption (inplace)
*/
switch (_gnutls_cipher_is_block (params->cipher_algorithm))
{
case CIPHER_STREAM:
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (_gnutls_version_has_explicit_iv
(session->security_parameters.version))
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
if (ciphertext.size == 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
if ((int) pad > (int) ciphertext.size - hash_size)
if ((int) pad > (int) ciphertext.size - hash_size)
{
gnutls_assert ();
_gnutls_record_log
("REC[%p]: Short record length %d > %d - %d (under attack?)\n",
session, pad, ciphertext.size, hash_size);
/* We do not fail here. We check below for the
* the pad_failed. If zero means success.
*/
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
length = ciphertext.size - hash_size - pad;
/* Check the pading bytes (TLS 1.x)
*/
if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0)
for (i = 2; i < pad; i++)
{
if (ciphertext.data[ciphertext.size - i] !=
ciphertext.data[ciphertext.size - 1])
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
break;
default:
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (params->mac_algorithm != GNUTLS_MAC_NULL)
{
digest_hd_st td;
ret = mac_init (&td, params->mac_algorithm,
params->read.mac_secret.data,
params->read.mac_secret.size, ver);
if (ret < 0)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
preamble_size =
make_preamble (UINT64DATA
(params->read.sequence_number), type,
c_length, ver, preamble);
mac_hash (&td, preamble, preamble_size, ver);
if (length > 0)
mac_hash (&td, ciphertext.data, length, ver);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
{
gnutls_assert ();
return pad_failed;
}
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
}
|
CWE-310
| 178,253 | 291 |
124737111803029213599184263327276296012
| null | null | null |
samba
|
7706303828fcde524222babb2833864a4bd09e07
| 1 |
int parse_arguments(int *argc_p, const char ***argv_p)
{
static poptContext pc;
char *ref = lp_refuse_options(module_id);
const char *arg, **argv = *argv_p;
int argc = *argc_p;
int opt;
if (ref && *ref)
set_refuse_options(ref);
set_refuse_options("log-file*");
#ifdef ICONV_OPTION
if (!*lp_charset(module_id))
set_refuse_options("iconv");
#endif
}
| 178,306 | 332 |
43904054426680477619840961774865216896
| null | null | null |
|
openssl
|
08229ad838c50f644d7e928e2eef147b4308ad64
| 1 |
int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
BIO *dcont, BIO *out, unsigned int flags)
{
int r;
BIO *cont;
if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) {
CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA);
return 0;
}
if (!dcont && !check_content(cms))
return 0;
if (flags & CMS_DEBUG_DECRYPT)
cms->d.envelopedData->encryptedContentInfo->debug = 1;
else
cms->d.envelopedData->encryptedContentInfo->debug = 0;
if (!pk && !cert && !dcont && !out)
return 1;
if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert))
r = cms_copy_content(out, cont, flags);
do_free_upto(cont, dcont);
return r;
}
|
CWE-311
| 178,310 | 336 |
64941400402061506868395705688794168956
| null | null | null |
savannah
|
bc8102405fda11ea00ca3b42acc4f4bce9d6e97b
| 1 |
_gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
uint8_t pad;
int length;
digest_hd_st td;
uint16_t blocksize;
int ret, i, pad_failed = 0;
uint8_t major, minor;
gnutls_protocol_t ver;
int hash_size =
_gnutls_hash_get_algo_len (session->security_parameters.
read_mac_algorithm);
ver = gnutls_protocol_get_version (session);
minor = _gnutls_version_get_minor (ver);
major = _gnutls_version_get_major (ver);
blocksize = _gnutls_cipher_get_block_size (session->security_parameters.
read_bulk_cipher_algorithm);
/* initialize MAC
*/
ret = mac_init (&td, session->security_parameters.read_mac_algorithm,
session->connection_state.read_mac_secret.data,
session->connection_state.read_mac_secret.size, ver);
if (ret < 0
&& session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
/* actual decryption (inplace)
*/
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret = _gnutls_cipher_decrypt (&session->connection_state.
read_cipher_state,
ciphertext.data,
ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (session->security_parameters.version >= GNUTLS_TLS1_1)
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
if (ciphertext.size == 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
/* We do not fail here. We check below for the
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
/* Check the pading bytes (TLS 1.x)
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
_gnutls_hmac (&td,
UINT64DATA (session->connection_state.
read_sequence_number), 8);
_gnutls_hmac (&td, &type, 1);
if (ver >= GNUTLS_TLS1)
{ /* TLS 1.x */
_gnutls_hmac (&td, &major, 1);
_gnutls_hmac (&td, &minor, 1);
}
_gnutls_hmac (&td, &c_length, 2);
if (length > 0)
_gnutls_hmac (&td, ciphertext.data, length);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
return pad_failed;
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
}
|
CWE-189
| 178,318 | 344 |
240557542046470369478162712950471631896
| null | null | null |
strongswan
|
0acd1ab4d08d53d80393b1a37b8781f6e7b2b996
| 1 |
static bool on_accept(private_stroke_socket_t *this, stream_t *stream)
{
stroke_msg_t *msg;
uint16_t len;
FILE *out;
/* read length */
if (!stream->read_all(stream, &len, sizeof(len)))
{
if (errno != EWOULDBLOCK)
{
DBG1(DBG_CFG, "reading length of stroke message failed: %s",
strerror(errno));
}
return FALSE;
}
/* read message (we need an additional byte to terminate the buffer) */
msg = malloc(len + 1);
DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno));
}
|
CWE-787
| 178,324 | 346 |
76812337795623017581325005365702278382
| null | null | null |
openssl
|
392fa7a952e97d82eac6958c81ed1e256e6b8ca5
| 1 |
int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->version < TLS1_2_VERSION && tls1_suiteb(s))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);
goto err;
}
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format
* Client Hello, can we? Error condition should be
* '>' otherweise */
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
s->method = ssl23_get_server_method(s->version);
if (s->method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 178,325 | 347 |
302715900060521114174962037430669439370
| null | null | null |
|
openssl
|
6ce9687b5aba5391fc0de50e18779eb676d0e04d
| 1 |
int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format
* Client Hello, can we? Error condition should be
* '>' otherweise */
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
s->method = ssl23_get_server_method(s->version);
if (s->method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 178,326 | 348 |
14016091918145812112657304672562481249
| null | null | null |
|
openssl
|
b82924741b4bd590da890619be671f4635e46c2b
| 1 |
int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
s->method = ssl23_get_server_method(s->version);
if (s->method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 178,327 | 349 |
321379236827848909394746101848506513421
| null | null | null |
|
openssl
|
7fd4ce6a997be5f5c9e744ac527725c2850de203
| 1 |
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
const unsigned char *sess_id, int sesslen,
SSL_SESSION **psess)
{
SSL_SESSION *sess;
unsigned char *sdec;
const unsigned char *p;
int slen, mlen, renew_ticket = 0;
unsigned char tick_hmac[EVP_MAX_MD_SIZE];
HMAC_CTX hctx;
EVP_CIPHER_CTX ctx;
SSL_CTX *tctx = s->initial_ctx;
/* Need at least keyname + iv + some encrypted data */
if (eticklen < 48)
return 2;
/* Initialize session ticket encryption and HMAC contexts */
HMAC_CTX_init(&hctx);
EVP_CIPHER_CTX_init(&ctx);
if (tctx->tlsext_ticket_key_cb)
{
unsigned char *nctick = (unsigned char *)etick;
int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
&ctx, &hctx, 0);
if (rv < 0)
return -1;
if (rv == 0)
return 2;
if (rv == 2)
renew_ticket = 1;
}
else
{
/* Check key name matches */
if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
return 2;
HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
tlsext_tick_md(), NULL);
EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
tctx->tlsext_tick_aes_key, etick + 16);
}
/* Attempt to process session ticket, first conduct sanity and
* integrity checks on ticket.
*/
mlen = HMAC_size(&hctx);
if (mlen < 0)
{
EVP_CIPHER_CTX_cleanup(&ctx);
return -1;
}
eticklen -= mlen;
/* Check HMAC of encrypted ticket */
HMAC_Update(&hctx, etick, eticklen);
HMAC_Final(&hctx, tick_hmac, NULL);
HMAC_CTX_cleanup(&hctx);
if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
return 2;
/* Attempt to decrypt session data */
/* Move p after IV to start of encrypted ticket, update length */
p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
{
EVP_CIPHER_CTX_cleanup(&ctx);
return -1;
}
EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
{
EVP_CIPHER_CTX_cleanup(&ctx);
OPENSSL_free(sdec);
return 2;
}
slen += mlen;
EVP_CIPHER_CTX_cleanup(&ctx);
p = sdec;
sess = d2i_SSL_SESSION(NULL, &p, slen);
OPENSSL_free(sdec);
if (sess)
{
/* The session ID, if non-empty, is used by some clients to
* detect that the ticket has been accepted. So we copy it to
* the session structure. If it is empty set length to zero
* as required by standard.
*/
if (sesslen)
memcpy(sess->session_id, sess_id, sesslen);
sess->session_id_length = sesslen;
*psess = sess;
if (renew_ticket)
return 4;
else
return 3;
}
ERR_clear_error();
/* For session parse failure, indicate that we need to send a new
* ticket. */
return 2;
}
|
CWE-20
| 178,331 | 353 |
40405055518110017250724029860459243757
| null | null | null |
gnupg
|
2cbd76f7911fc215845e89b50d6af5ff4a83dd77
| 1 |
status_handler (void *opaque, int fd)
{
struct io_cb_data *data = (struct io_cb_data *) opaque;
engine_gpgsm_t gpgsm = (engine_gpgsm_t) data->handler_value;
gpgme_error_t err = 0;
char *line;
size_t linelen;
do
{
err = assuan_read_line (gpgsm->assuan_ctx, &line, &linelen);
if (err)
{
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (gpgsm->assuan_ctx, "BYE"); */
TRACE3 (DEBUG_CTX, "gpgme:status_handler", gpgsm,
"fd 0x%x: error from assuan (%d) getting status line : %s",
fd, err, gpg_strerror (err));
}
else if (linelen >= 3
&& line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
&& (line[3] == '\0' || line[3] == ' '))
{
if (line[3] == ' ')
err = atoi (&line[4]);
if (! err)
err = gpg_error (GPG_ERR_GENERAL);
TRACE2 (DEBUG_CTX, "gpgme:status_handler", gpgsm,
"fd 0x%x: ERR line - mapped to: %s",
fd, err ? gpg_strerror (err) : "ok");
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (gpgsm->assuan_ctx, "BYE"); */
}
else if (linelen >= 2
&& line[0] == 'O' && line[1] == 'K'
&& (line[2] == '\0' || line[2] == ' '))
{
if (gpgsm->status.fnc)
err = gpgsm->status.fnc (gpgsm->status.fnc_value,
GPGME_STATUS_EOF, "");
if (!err && gpgsm->colon.fnc && gpgsm->colon.any)
{
/* We must tell a colon function about the EOF. We do
this only when we have seen any data lines. Note
that this inlined use of colon data lines will
eventually be changed into using a regular data
channel. */
gpgsm->colon.any = 0;
err = gpgsm->colon.fnc (gpgsm->colon.fnc_value, NULL);
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", gpgsm,
"fd 0x%x: OK line - final status: %s",
fd, err ? gpg_strerror (err) : "ok");
_gpgme_io_close (gpgsm->status_cb.fd);
return err;
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& gpgsm->colon.fnc)
{
/* We are using the colon handler even for plain inline data
- strange name for that function but for historic reasons
we keep it. */
/* FIXME We can't use this for binary data because we
assume this is a string. For the current usage of colon
output it is correct. */
char *src = line + 2;
char *end = line + linelen;
char *dst;
char **aline = &gpgsm->colon.attic.line;
int *alinelen = &gpgsm->colon.attic.linelen;
if (gpgsm->colon.attic.linesize < *alinelen + linelen + 1)
{
char *newline = realloc (*aline, *alinelen + linelen + 1);
if (!newline)
err = gpg_error_from_syserror ();
else
{
*aline = newline;
gpgsm->colon.attic.linesize += linelen + 1;
}
}
if (!err)
{
dst = *aline + *alinelen;
while (!err && src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst = _gpgme_hextobyte (src);
(*alinelen)++;
src += 2;
}
else
{
*dst = *src++;
(*alinelen)++;
}
if (*dst == '\n')
{
/* Terminate the pending line, pass it to the colon
handler and reset it. */
gpgsm->colon.any = 1;
if (*alinelen > 1 && *(dst - 1) == '\r')
dst--;
*dst = '\0';
/* FIXME How should we handle the return code? */
err = gpgsm->colon.fnc (gpgsm->colon.fnc_value, *aline);
if (!err)
{
dst = *aline;
*alinelen = 0;
}
}
else
dst++;
}
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", gpgsm,
"fd 0x%x: D line; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& gpgsm->inline_data)
{
char *src = line + 2;
char *end = line + linelen;
char *dst = src;
gpgme_ssize_t nwritten;
linelen = 0;
while (src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst++ = _gpgme_hextobyte (src);
src += 2;
}
else
*dst++ = *src++;
linelen++;
}
src = line + 2;
while (linelen > 0)
{
nwritten = gpgme_data_write (gpgsm->inline_data, src, linelen);
if (!nwritten || (nwritten < 0 && errno != EINTR)
|| nwritten > linelen)
{
err = gpg_error_from_syserror ();
break;
}
src += nwritten;
linelen -= nwritten;
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", gpgsm,
"fd 0x%x: D inlinedata; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'S' && line[1] == ' ')
{
char *rest;
gpgme_status_code_t r;
rest = strchr (line + 2, ' ');
if (!rest)
rest = line + linelen; /* set to an empty string */
else
*(rest++) = 0;
r = _gpgme_parse_status (line + 2);
if (r >= 0)
{
if (gpgsm->status.fnc)
err = gpgsm->status.fnc (gpgsm->status.fnc_value, r, rest);
}
else
fprintf (stderr, "[UNKNOWN STATUS]%s %s", line + 2, rest);
TRACE3 (DEBUG_CTX, "gpgme:status_handler", gpgsm,
"fd 0x%x: S line (%s) - final status: %s",
fd, line+2, err? gpg_strerror (err):"ok");
}
else if (linelen >= 7
&& line[0] == 'I' && line[1] == 'N' && line[2] == 'Q'
&& line[3] == 'U' && line[4] == 'I' && line[5] == 'R'
&& line[6] == 'E'
&& (line[7] == '\0' || line[7] == ' '))
{
char *keyword = line+7;
while (*keyword == ' ')
keyword++;;
default_inq_cb (gpgsm, keyword);
assuan_write_line (gpgsm->assuan_ctx, "END");
}
}
while (!err && assuan_pending_line (gpgsm->assuan_ctx));
return err;
}
|
CWE-119
| 178,333 | 354 |
7203629874001971214417650726602123623
| null | null | null |
gnupg
|
2cbd76f7911fc215845e89b50d6af5ff4a83dd77
| 1 |
status_handler (void *opaque, int fd)
{
struct io_cb_data *data = (struct io_cb_data *) opaque;
engine_uiserver_t uiserver = (engine_uiserver_t) data->handler_value;
gpgme_error_t err = 0;
char *line;
size_t linelen;
do
{
err = assuan_read_line (uiserver->assuan_ctx, &line, &linelen);
if (err)
{
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: error from assuan (%d) getting status line : %s",
fd, err, gpg_strerror (err));
}
else if (linelen >= 3
&& line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
&& (line[3] == '\0' || line[3] == ' '))
{
if (line[3] == ' ')
err = atoi (&line[4]);
if (! err)
err = gpg_error (GPG_ERR_GENERAL);
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: ERR line - mapped to: %s",
fd, err ? gpg_strerror (err) : "ok");
/* Try our best to terminate the connection friendly. */
/* assuan_write_line (uiserver->assuan_ctx, "BYE"); */
}
else if (linelen >= 2
&& line[0] == 'O' && line[1] == 'K'
&& (line[2] == '\0' || line[2] == ' '))
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value,
GPGME_STATUS_EOF, "");
if (!err && uiserver->colon.fnc && uiserver->colon.any)
{
/* We must tell a colon function about the EOF. We do
this only when we have seen any data lines. Note
that this inlined use of colon data lines will
eventually be changed into using a regular data
channel. */
uiserver->colon.any = 0;
err = uiserver->colon.fnc (uiserver->colon.fnc_value, NULL);
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: OK line - final status: %s",
fd, err ? gpg_strerror (err) : "ok");
_gpgme_io_close (uiserver->status_cb.fd);
return err;
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->colon.fnc)
{
/* We are using the colon handler even for plain inline data
- strange name for that function but for historic reasons
we keep it. */
/* FIXME We can't use this for binary data because we
assume this is a string. For the current usage of colon
output it is correct. */
char *src = line + 2;
char *end = line + linelen;
char *dst;
char **aline = &uiserver->colon.attic.line;
int *alinelen = &uiserver->colon.attic.linelen;
if (uiserver->colon.attic.linesize < *alinelen + linelen + 1)
{
char *newline = realloc (*aline, *alinelen + linelen + 1);
if (!newline)
err = gpg_error_from_syserror ();
else
{
*aline = newline;
uiserver->colon.attic.linesize += linelen + 1;
}
}
if (!err)
{
dst = *aline + *alinelen;
while (!err && src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst = _gpgme_hextobyte (src);
(*alinelen)++;
src += 2;
}
else
{
*dst = *src++;
(*alinelen)++;
}
if (*dst == '\n')
{
/* Terminate the pending line, pass it to the colon
handler and reset it. */
uiserver->colon.any = 1;
if (*alinelen > 1 && *(dst - 1) == '\r')
dst--;
*dst = '\0';
/* FIXME How should we handle the return code? */
err = uiserver->colon.fnc (uiserver->colon.fnc_value, *aline);
if (!err)
{
dst = *aline;
*alinelen = 0;
}
}
else
dst++;
}
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D line; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'D' && line[1] == ' '
&& uiserver->inline_data)
{
char *src = line + 2;
char *end = line + linelen;
char *dst = src;
gpgme_ssize_t nwritten;
linelen = 0;
while (src < end)
{
if (*src == '%' && src + 2 < end)
{
/* Handle escaped characters. */
++src;
*dst++ = _gpgme_hextobyte (src);
src += 2;
}
else
*dst++ = *src++;
linelen++;
}
src = line + 2;
while (linelen > 0)
{
nwritten = gpgme_data_write (uiserver->inline_data, src, linelen);
if (!nwritten || (nwritten < 0 && errno != EINTR)
|| nwritten > linelen)
{
err = gpg_error_from_syserror ();
break;
}
src += nwritten;
linelen -= nwritten;
}
TRACE2 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: D inlinedata; final status: %s",
fd, err? gpg_strerror (err):"ok");
}
else if (linelen > 2
&& line[0] == 'S' && line[1] == ' ')
{
char *rest;
gpgme_status_code_t r;
rest = strchr (line + 2, ' ');
if (!rest)
rest = line + linelen; /* set to an empty string */
else
*(rest++) = 0;
r = _gpgme_parse_status (line + 2);
if (r >= 0)
{
if (uiserver->status.fnc)
err = uiserver->status.fnc (uiserver->status.fnc_value, r, rest);
}
else
fprintf (stderr, "[UNKNOWN STATUS]%s %s", line + 2, rest);
TRACE3 (DEBUG_CTX, "gpgme:status_handler", uiserver,
"fd 0x%x: S line (%s) - final status: %s",
fd, line+2, err? gpg_strerror (err):"ok");
}
else if (linelen >= 7
&& line[0] == 'I' && line[1] == 'N' && line[2] == 'Q'
&& line[3] == 'U' && line[4] == 'I' && line[5] == 'R'
&& line[6] == 'E'
&& (line[7] == '\0' || line[7] == ' '))
{
char *keyword = line+7;
while (*keyword == ' ')
keyword++;;
default_inq_cb (uiserver, keyword);
assuan_write_line (uiserver->assuan_ctx, "END");
}
}
while (!err && assuan_pending_line (uiserver->assuan_ctx));
return err;
}
|
CWE-119
| 178,334 | 355 |
77372948009689993078192342243939039842
| null | null | null |
openssl
|
280b1f1ad12131defcd986676a8fc9717aaa601b
| 1 |
int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply assume TLS 1.0 to avoid protocol version downgrade
* attacks. */
if (p[3] == 0 && p[4] < 6)
{
#if 0
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
#else
v[1] = TLS1_VERSION_MINOR;
#endif
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
else if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
else if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
if (s->version < TLS1_2_VERSION && tls1_suiteb(s))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE);
goto err;
}
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW);
goto err;
}
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
j=ssl23_read_bytes(s,n+2);
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
if (!ssl_init_wbio_buffer(s,1)) goto err;
/* we are in this state */
s->state=SSL3_ST_SR_CLNT_HELLO_A;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
if (s->version == TLS1_2_VERSION)
s->method = TLSv1_2_server_method();
else if (s->version == TLS1_1_VERSION)
s->method = TLSv1_1_server_method();
else if (s->version == TLS1_VERSION)
s->method = TLSv1_server_method();
else
s->method = SSLv3_server_method();
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 178,346 | 361 |
320820661878830943101551248404697759629
| null | null | null |
|
openssl
|
fb0bc2b273bcc2d5401dd883fe869af4fc74bb21
| 1 |
static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
{
unsigned short length;
unsigned short type;
unsigned short size;
unsigned char *data = *p;
int tlsext_servername = 0;
int renegotiate_seen = 0;
#ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
#endif
if (s->s3->alpn_selected)
{
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = NULL;
}
#ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
#endif
#ifdef TLSEXT_TYPE_encrypt_then_mac
s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
#endif
if (data >= (d+n-2))
goto ri_check;
n2s(data,length);
if (data+length != d+n)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
while(data <= (d+n-4))
{
n2s(data,type);
n2s(data,size);
if (data+size > (d+n))
goto ri_check;
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 1, type, data, size,
s->tlsext_debug_arg);
if (type == TLSEXT_TYPE_server_name)
{
if (s->tlsext_hostname == NULL || size > 0)
{
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
tlsext_servername = 1;
}
#ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats)
{
unsigned char *sdata = data;
int ecpointformatlist_length = *(sdata++);
if (ecpointformatlist_length != size - 1)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length = 0;
if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
#if 0
fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
sdata = s->session->tlsext_ecpointformatlist;
#endif
}
#endif /* OPENSSL_NO_EC */
else if (type == TLSEXT_TYPE_session_ticket)
{
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
if (!tls_use_ticket(s) || (size > 0))
{
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
s->tlsext_ticket_expected = 1;
}
#ifdef TLSEXT_TYPE_opaque_prf_input
else if (type == TLSEXT_TYPE_opaque_prf_input)
{
unsigned char *sdata = data;
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(sdata, s->s3->server_opaque_prf_input_len);
if (s->s3->server_opaque_prf_input_len != size - 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
OPENSSL_free(s->s3->server_opaque_prf_input);
if (s->s3->server_opaque_prf_input_len == 0)
s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
else
s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
if (s->s3->server_opaque_prf_input == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
#endif
else if (type == TLSEXT_TYPE_status_request)
{
/* MUST be empty and only sent if we've requested
* a status request message.
*/
if ((s->tlsext_status_type == -1) || (size > 0))
{
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/* Set flag to expect CertificateStatus message */
s->tlsext_status_expected = 1;
}
#ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0)
{
unsigned char *selected;
unsigned char selected_len;
/* We must have requested it. */
if (s->ctx->next_proto_select_cb == NULL)
{
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
/* The data must be valid */
if (!ssl_next_proto_validate(data, size))
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->next_proto_negotiated = OPENSSL_malloc(selected_len);
if (!s->next_proto_negotiated)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->next_proto_negotiated, selected, selected_len);
s->next_proto_negotiated_len = selected_len;
s->s3->next_proto_neg_seen = 1;
}
#endif
else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
{
unsigned len;
/* We must have requested it. */
if (s->alpn_client_proto_list == NULL)
{
*al = TLS1_AD_UNSUPPORTED_EXTENSION;
return 0;
}
if (size < 4)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
/* The extension data consists of:
* uint16 list_length
* uint8 proto_length;
* uint8 proto[proto_length]; */
len = data[0];
len <<= 8;
len |= data[1];
if (len != (unsigned) size - 2)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
len = data[2];
if (len != (unsigned) size - 3)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (s->s3->alpn_selected)
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = OPENSSL_malloc(len);
if (!s->s3->alpn_selected)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->s3->alpn_selected, data + 3, len);
s->s3->alpn_selected_len = len;
}
else if (type == TLSEXT_TYPE_renegotiate)
{
if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
return 0;
renegotiate_seen = 1;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (type == TLSEXT_TYPE_heartbeat)
{
switch(data[0])
{
case 0x01: /* Server allows us to send HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
break;
case 0x02: /* Server doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
break;
default: *al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
#endif
else if (type == TLSEXT_TYPE_use_srtp)
{
if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
al))
return 0;
}
/* If this extension type was not otherwise handled, but
* matches a custom_cli_ext_record, then send it to the c
* callback */
else if (s->ctx->custom_cli_ext_records_count)
{
size_t i;
custom_cli_ext_record* record;
for (i = 0; i < s->ctx->custom_cli_ext_records_count; i++)
{
record = &s->ctx->custom_cli_ext_records[i];
if (record->ext_type == type)
{
if (record->fn2 && !record->fn2(s, type, data, size, al, record->arg))
return 0;
break;
}
}
}
#ifdef TLSEXT_TYPE_encrypt_then_mac
else if (type == TLSEXT_TYPE_encrypt_then_mac)
{
/* Ignore if inappropriate ciphersuite */
if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD)
s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
}
#endif
data += size;
}
if (data != d+n)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!s->hit && tlsext_servername == 1)
{
if (s->tlsext_hostname)
{
if (s->session->tlsext_hostname == NULL)
{
s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
if (!s->session->tlsext_hostname)
{
*al = SSL_AD_UNRECOGNIZED_NAME;
return 0;
}
}
else
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
}
*p = data;
ri_check:
/* Determine if we need to see RI. Strictly speaking if we want to
* avoid an attack we should *always* see RI even on initial server
* hello because the client doesn't see any renegotiation during an
* attack. However this would mean we could not connect to any server
* which doesn't support RI so for the immediate future tolerate RI
* absence on initial connect only.
*/
if (!renegotiate_seen
&& !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
}
|
CWE-362
| 178,347 | 362 |
26039161783827061921975058784343045283
| null | null | null |
openssl
|
0042fb5fd1c9d257d713b15a1f45da05cf5c1c87
| 1 |
int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name)
{
int i,n=0,len,nid, first, use_bn;
BIGNUM *bl;
unsigned long l;
const unsigned char *p;
char tbuf[DECIMAL_SIZE(i)+DECIMAL_SIZE(l)+2];
if ((a == NULL) || (a->data == NULL)) {
buf[0]='\0';
return(0);
}
if (!no_name && (nid=OBJ_obj2nid(a)) != NID_undef)
{
s=OBJ_nid2ln(nid);
if (s == NULL)
s=OBJ_nid2sn(nid);
if (s)
{
if (buf)
BUF_strlcpy(buf,s,buf_len);
n=strlen(s);
return n;
}
}
len=a->length;
p=a->data;
first = 1;
bl = NULL;
while (len > 0)
{
l=0;
use_bn = 0;
for (;;)
{
unsigned char c = *p++;
len--;
if ((len == 0) && (c & 0x80))
goto err;
if (use_bn)
{
if (!BN_add_word(bl, c & 0x7f))
goto err;
}
else
l |= c & 0x7f;
if (!(c & 0x80))
break;
if (!use_bn && (l > (ULONG_MAX >> 7L)))
{
if (!bl && !(bl = BN_new()))
goto err;
if (!BN_set_word(bl, l))
goto err;
use_bn = 1;
}
if (use_bn)
{
if (!BN_lshift(bl, bl, 7))
goto err;
}
else
l<<=7L;
}
if (first)
{
first = 0;
if (l >= 80)
{
i = 2;
if (use_bn)
{
if (!BN_sub_word(bl, 80))
goto err;
}
else
l -= 80;
}
else
{
i=(int)(l/40);
i=(int)(l/40);
l-=(long)(i*40);
}
if (buf && (buf_len > 0))
{
*buf++ = i + '0';
buf_len--;
}
n++;
if (use_bn)
{
char *bndec;
bndec = BN_bn2dec(bl);
if (!bndec)
goto err;
i = strlen(bndec);
if (buf)
i = strlen(bndec);
if (buf)
{
if (buf_len > 0)
{
*buf++ = '.';
buf_len--;
}
BUF_strlcpy(buf,bndec,buf_len);
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n++;
n += i;
OPENSSL_free(bndec);
}
else
{
BIO_snprintf(tbuf,sizeof tbuf,".%lu",l);
i=strlen(tbuf);
if (buf && (buf_len > 0))
{
BUF_strlcpy(buf,tbuf,buf_len);
if (i > buf_len)
{
buf += buf_len;
buf_len = 0;
}
else
{
buf+=i;
buf_len-=i;
}
}
n+=i;
l=0;
}
}
if (bl)
BN_free(bl);
return n;
err:
if (bl)
BN_free(bl);
return -1;
}
|
CWE-200
| 178,348 | 363 |
297699367960060599539119269244361477361
| null | null | null |
savannah
|
1c3ccb3e040bf13e342ee60bc23b21b97b11923f
| 1 |
asn1_get_bit_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *bit_len)
{
int len_len, len_byte;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
len_byte = asn1_get_length_der (der, der_len, &len_len) - 1;
if (len_byte < 0)
return ASN1_DER_ERROR;
*ret_len = len_byte + len_len + 1;
*bit_len = len_byte * 8 - der[len_len];
if (str_size >= len_byte)
memcpy (str, der + len_len + 1, len_byte);
}
|
CWE-189
| 178,349 | 364 |
41675434541008202288249540494015225926
| null | null | null |
openafs
|
396240cf070a806b91fea81131d034e1399af1e0
| 1 |
newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid,
afs_int32 *aid, afs_int32 *cid)
{
afs_int32 code;
struct ubik_trans *tt;
int admin;
char cname[PR_MAXNAMELEN];
stolower(aname);
code = Initdb();
if (code)
return code;
code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt);
if (code)
return code;
code = ubik_SetLock(tt, 1, 1, LOCKWRITE);
if (code)
ABORT_WITH(tt, code);
code = read_DbHeader(tt);
if (code)
ABORT_WITH(tt, code);
/* this is for cross-cell self registration. It is not added in the
* SPR_INewEntry because we want self-registration to only do
* automatic id assignment.
*/
code = WhoIsThisWithName(call, tt, cid, cname);
if (code != 2) { /* 2 specifies that this is a foreign cell request */
if (code)
ABORT_WITH(tt, PRPERM);
admin = IsAMemberOf(tt, *cid, SYSADMINID);
} else {
admin = ((!restricted && !strcmp(aname, cname))) || IsAMemberOf(tt, *cid, SYSADMINID);
oid = *cid = SYSADMINID;
}
if (!CreateOK(tt, *cid, oid, flag, admin))
ABORT_WITH(tt, PRPERM);
if (code)
return code;
return PRSUCCESS;
}
|
CWE-284
| 178,351 | 366 |
260875174871501419682775678302497067796
| null | null | null |
openssl
|
578b956fe741bf8e84055547b1e83c28dd902c73
| 1 |
_dopr(char **sbuffer,
char **buffer,
size_t *maxlen,
size_t *retlen, int *truncated, const char *format, va_list args)
{
char ch;
LLONG value;
LDOUBLE fvalue;
char *strvalue;
int min;
int max;
int state;
int flags;
int cflags;
size_t currlen;
state = DP_S_DEFAULT;
flags = currlen = cflags = min = 0;
max = -1;
ch = *format++;
while (state != DP_S_DONE) {
if (ch == '\0' || (buffer == NULL && currlen >= *maxlen))
state = DP_S_DONE;
switch (state) {
case DP_S_DEFAULT:
if (ch == '%')
state = DP_S_FLAGS;
else
doapr_outch(sbuffer, buffer, &currlen, maxlen, ch);
ch = *format++;
break;
case DP_S_FLAGS:
case '-':
flags |= DP_F_MINUS;
ch = *format++;
break;
case '+':
flags |= DP_F_PLUS;
ch = *format++;
break;
case ' ':
flags |= DP_F_SPACE;
ch = *format++;
break;
case '#':
flags |= DP_F_NUM;
ch = *format++;
break;
case '0':
flags |= DP_F_ZERO;
ch = *format++;
break;
default:
state = DP_S_MIN;
break;
}
break;
case DP_S_MIN:
if (isdigit((unsigned char)ch)) {
min = 10 * min + char_to_int(ch);
ch = *format++;
} else if (ch == '*') {
min = va_arg(args, int);
ch = *format++;
state = DP_S_DOT;
} else
state = DP_S_DOT;
break;
case DP_S_DOT:
if (ch == '.') {
state = DP_S_MAX;
ch = *format++;
} else
state = DP_S_MOD;
break;
case DP_S_MAX:
if (isdigit((unsigned char)ch)) {
if (max < 0)
max = 0;
max = 10 * max + char_to_int(ch);
ch = *format++;
} else if (ch == '*') {
max = va_arg(args, int);
ch = *format++;
state = DP_S_MOD;
} else
state = DP_S_MOD;
break;
case DP_S_MOD:
switch (ch) {
case 'h':
cflags = DP_C_SHORT;
ch = *format++;
break;
case 'l':
if (*format == 'l') {
cflags = DP_C_LLONG;
format++;
} else
cflags = DP_C_LONG;
ch = *format++;
break;
case 'q':
cflags = DP_C_LLONG;
ch = *format++;
break;
case 'L':
cflags = DP_C_LDOUBLE;
ch = *format++;
break;
default:
break;
}
state = DP_S_CONV;
break;
case DP_S_CONV:
switch (ch) {
case 'd':
case 'i':
switch (cflags) {
case DP_C_SHORT:
value = (short int)va_arg(args, int);
break;
case DP_C_LONG:
value = va_arg(args, long int);
break;
case DP_C_LLONG:
value = va_arg(args, LLONG);
break;
default:
value = va_arg(args, int);
value = va_arg(args, int);
break;
}
fmtint(sbuffer, buffer, &currlen, maxlen,
value, 10, min, max, flags);
break;
case 'X':
flags |= DP_F_UP;
case 'o':
case 'u':
flags |= DP_F_UNSIGNED;
switch (cflags) {
case DP_C_SHORT:
value = (unsigned short int)va_arg(args, unsigned int);
break;
case DP_C_LONG:
value = (LLONG) va_arg(args, unsigned long int);
break;
case DP_C_LLONG:
value = va_arg(args, unsigned LLONG);
break;
default:
value = (LLONG) va_arg(args, unsigned int);
break;
value = (LLONG) va_arg(args, unsigned int);
break;
}
fmtint(sbuffer, buffer, &currlen, maxlen, value,
ch == 'o' ? 8 : (ch == 'u' ? 10 : 16),
min, max, flags);
break;
case 'f':
if (cflags == DP_C_LDOUBLE)
fvalue = va_arg(args, LDOUBLE);
else
fvalue = va_arg(args, double);
fmtfp(sbuffer, buffer, &currlen, maxlen,
fvalue, min, max, flags);
break;
case 'E':
flags |= DP_F_UP;
fvalue = va_arg(args, double);
break;
case 'G':
flags |= DP_F_UP;
case 'g':
if (cflags == DP_C_LDOUBLE)
fvalue = va_arg(args, LDOUBLE);
else
fvalue = va_arg(args, double);
break;
case 'c':
doapr_outch(sbuffer, buffer, &currlen, maxlen,
fvalue = va_arg(args, double);
break;
case 'c':
doapr_outch(sbuffer, buffer, &currlen, maxlen,
va_arg(args, int));
break;
case 's':
strvalue = va_arg(args, char *);
}
fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue,
flags, min, max);
else
max = *maxlen;
}
fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue,
flags, min, max);
break;
case 'p':
value = (long)va_arg(args, void *);
fmtint(sbuffer, buffer, &currlen, maxlen,
value, 16, min, max, flags | DP_F_NUM);
break;
case 'n': /* XXX */
if (cflags == DP_C_SHORT) {
} else if (cflags == DP_C_LLONG) { /* XXX */
LLONG *num;
num = va_arg(args, LLONG *);
*num = (LLONG) currlen;
} else {
int *num;
num = va_arg(args, int *);
*num = currlen;
}
break;
case '%':
doapr_outch(sbuffer, buffer, &currlen, maxlen, ch);
break;
case 'w':
/* not supported yet, treat as next char */
}
|
CWE-119
| 178,355 | 367 |
309192226193988062421957531577393101030
| null | null | null |
savannah
|
a3bc7e9400b214a0f078fdb19596ba54214a1442
| 1 |
bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr,
struct bgp_nlri *packet)
{
u_char *pnt;
u_char *lim;
struct prefix p;
int psize;
int prefixlen;
u_int16_t type;
struct rd_as rd_as;
struct rd_ip rd_ip;
struct prefix_rd prd;
u_char *tagpnt;
/* Check peer status. */
if (peer->status != Established)
return 0;
/* Make prefix_rd */
prd.family = AF_UNSPEC;
prd.prefixlen = 64;
pnt = packet->nlri;
lim = pnt + packet->length;
for (; pnt < lim; pnt += psize)
{
/* Clear prefix structure. */
/* Fetch prefix length. */
prefixlen = *pnt++;
p.family = AF_INET;
psize = PSIZE (prefixlen);
if (prefixlen < 88)
{
zlog_err ("prefix length is less than 88: %d", prefixlen);
return -1;
}
/* Copyr label to prefix. */
tagpnt = pnt;;
/* Copy routing distinguisher to rd. */
memcpy (&prd.val, pnt + 3, 8);
else if (type == RD_TYPE_IP)
zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip),
rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen);
#endif /* 0 */
if (pnt + psize > lim)
return -1;
if (attr)
bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN,
ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0);
else
return -1;
}
p.prefixlen = prefixlen - 88;
memcpy (&p.u.prefix, pnt + 11, psize - 11);
#if 0
if (type == RD_TYPE_AS)
}
|
CWE-119
| 178,361 | 368 |
189301502052689275853315045175183465473
| null | null | null |
openssl
|
1fb9fdc3027b27d8eb6a1e6a846435b070980770
| 1 |
int dtls1_process_buffered_records(SSL *s)
{
pitem *item;
SSL3_BUFFER *rb;
item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q);
if (item) {
/* Check if epoch is current. */
if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch)
return (1); /* Nothing to do. */
rb = RECORD_LAYER_get_rbuf(&s->rlayer);
*/
return 1;
}
/* Process all the records. */
while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
if (!dtls1_process_record(s))
return (0);
if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
/* Process all the records. */
while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
if (!dtls1_process_record(s))
return (0);
if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
SSL3_RECORD_get_seq_num(s->rlayer.rrec)) <
0)
return -1;
}
}
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
return (1);
}
|
CWE-189
| 178,366 | 371 |
299136167801831334632170022306068067325
| null | null | null |
openssl
|
2919516136a4227d9e6d8f2fe66ef976aaf8c561
| 1 |
char *X509_NAME_oneline(X509_NAME *a, char *buf, int len)
{
X509_NAME_ENTRY *ne;
int i;
int n, lold, l, l1, l2, num, j, type;
const char *s;
char *p;
unsigned char *q;
BUF_MEM *b = NULL;
static const char hex[17] = "0123456789ABCDEF";
int gs_doit[4];
char tmp_buf[80];
#ifdef CHARSET_EBCDIC
char ebcdic_buf[1024];
#endif
if (buf == NULL) {
if ((b = BUF_MEM_new()) == NULL)
goto err;
if (!BUF_MEM_grow(b, 200))
goto err;
b->data[0] = '\0';
len = 200;
} else if (len == 0) {
return NULL;
}
if (a == NULL) {
if (b) {
buf = b->data;
OPENSSL_free(b);
}
strncpy(buf, "NO X509_NAME", len);
buf[len - 1] = '\0';
return buf;
}
len--; /* space for '\0' */
l = 0;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
ne = sk_X509_NAME_ENTRY_value(a->entries, i);
n = OBJ_obj2nid(ne->object);
if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object);
s = tmp_buf;
}
l1 = strlen(s);
type = ne->value->type;
num = ne->value->length;
if (num > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
q = ne->value->data;
#ifdef CHARSET_EBCDIC
if (type == V_ASN1_GENERALSTRING ||
type == V_ASN1_VISIBLESTRING ||
type == V_ASN1_PRINTABLESTRING ||
type == V_ASN1_TELETEXSTRING ||
type == V_ASN1_VISIBLESTRING || type == V_ASN1_IA5STRING) {
ascii2ebcdic(ebcdic_buf, q, (num > sizeof ebcdic_buf)
? sizeof ebcdic_buf : num);
q = ebcdic_buf;
}
#endif
if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) {
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0;
for (j = 0; j < num; j++)
if (q[j] != 0)
gs_doit[j & 3] = 1;
if (gs_doit[0] | gs_doit[1] | gs_doit[2])
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
else {
gs_doit[0] = gs_doit[1] = gs_doit[2] = 0;
gs_doit[3] = 1;
}
} else
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
for (l2 = j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
l2++;
#ifndef CHARSET_EBCDIC
if ((q[j] < ' ') || (q[j] > '~'))
l2 += 3;
#else
if ((os_toascii[q[j]] < os_toascii[' ']) ||
(os_toascii[q[j]] > os_toascii['~']))
l2 += 3;
#endif
}
lold = l;
l += 1 + l1 + 1 + l2;
if (l > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
if (b != NULL) {
if (!BUF_MEM_grow(b, l + 1))
goto err;
p = &(b->data[lold]);
} else if (l > len) {
break;
} else
p = &(buf[lold]);
*(p++) = '/';
memcpy(p, s, (unsigned int)l1);
p += l1;
*(p++) = '=';
#ifndef CHARSET_EBCDIC /* q was assigned above already. */
q = ne->value->data;
#endif
for (j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
#ifndef CHARSET_EBCDIC
n = q[j];
if ((n < ' ') || (n > '~')) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = n;
#else
n = os_toascii[q[j]];
if ((n < os_toascii[' ']) || (n > os_toascii['~'])) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = q[j];
#endif
}
*p = '\0';
}
if (b != NULL) {
p = b->data;
OPENSSL_free(b);
} else
p = buf;
if (i == 0)
*p = '\0';
return (p);
err:
X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE);
end:
BUF_MEM_free(b);
return (NULL);
}
|
CWE-119
| 178,379 | 383 |
92428507097973547653884047469651088423
| null | null | null |
samba
|
0dedfbce2c1b851684ba658861fe9d620636c56a
| 1 |
static const char *check_secret(int module, const char *user, const char *group,
const char *challenge, const char *pass)
{
char line[1024];
char pass2[MAX_DIGEST_LEN*2];
const char *fname = lp_secrets_file(module);
STRUCT_STAT st;
int fd, ok = 1;
int user_len = strlen(user);
int group_len = group ? strlen(group) : 0;
char *err;
if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0)
return "no secrets file";
if (do_fstat(fd, &st) == -1) {
rsyserr(FLOG, errno, "fstat(%s)", fname);
ok = 0;
} else if (lp_strict_modes(module)) {
rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
ok = 0;
} else if (MY_UID() == 0 && st.st_uid != 0) {
rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
ok = 0;
}
}
|
CWE-20
| 178,380 | 384 |
212902940744913922862229672762941300732
| null | null | null |
openssl
|
3f3582139fbb259a1c3cbb0a25236500a409bf26
| 1 |
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = ctx->cipher->do_cipher(ctx, out, in, inl);
if (i < 0)
return 0;
else
*outl = i;
return 1;
}
if (inl <= 0) {
*outl = 0;
return inl == 0;
}
if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
*outl = inl;
return 1;
} else {
*outl = 0;
return 0;
}
}
i = ctx->buf_len;
bl = ctx->cipher->block_size;
OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
if (i != 0) {
if (i + inl < bl) {
memcpy(&(ctx->buf[i]), in, inl);
ctx->buf_len += inl;
*outl = 0;
return 1;
} else {
j = bl - i;
memcpy(&(ctx->buf[i]), in, j);
if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
return 0;
inl -= j;
in += j;
out += bl;
*outl = bl;
}
} else
*outl = 0;
i = inl & (bl - 1);
inl -= i;
if (inl > 0) {
if (!ctx->cipher->do_cipher(ctx, out, in, inl))
return 0;
*outl += inl;
}
if (i != 0)
memcpy(ctx->buf, &(in[inl]), i);
ctx->buf_len = i;
return 1;
}
|
CWE-189
| 178,388 | 390 |
136934056290217214609523870578341166755
| null | null | null |
openssl
|
5b814481f3573fa9677f3a31ee51322e2a22ee6a
| 1 |
void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j;
unsigned int total = 0;
*outl = 0;
if (inl <= 0)
return;
OPENSSL_assert(ctx->length <= (int)sizeof(ctx->enc_data));
if ((ctx->num + inl) < ctx->length) {
memcpy(&(ctx->enc_data[ctx->num]), in, inl);
ctx->num += inl;
return;
}
if (ctx->num != 0) {
i = ctx->length - ctx->num;
memcpy(&(ctx->enc_data[ctx->num]), in, i);
in += i;
inl -= i;
j = EVP_EncodeBlock(out, ctx->enc_data, ctx->length);
ctx->num = 0;
out += j;
*(out++) = '\n';
*out = '\0';
total = j + 1;
}
while (inl >= ctx->length) {
j = EVP_EncodeBlock(out, in, ctx->length);
in += ctx->length;
inl -= ctx->length;
out += j;
*(out++) = '\n';
*out = '\0';
total += j + 1;
}
if (inl != 0)
memcpy(&(ctx->enc_data[0]), in, inl);
ctx->num = inl;
*outl = total;
}
|
CWE-189
| 178,389 | 391 |
270135404994675151022539958893968212454
| null | null | null |
infradead
|
3e18948f17148e6a3c4255bdeaaf01ef6081ceeb
| 1 |
void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
{
void *buf = n->nm_nlh;
size_t nlmsg_len = n->nm_nlh->nlmsg_len;
size_t tlen;
tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
if ((tlen + nlmsg_len) > n->nm_size)
n->nm_nlh->nlmsg_len += tlen;
if (tlen > len)
memset(buf + len, 0, tlen - len);
NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
n, tlen, len, pad, n->nm_nlh->nlmsg_len);
return buf;
}
|
CWE-190
| 178,390 | 392 |
240126035042790297576269866332571113695
| null | null | null |
gnupg
|
da780c8183cccc8f533c8ace8211ac2cb2bdee7b
| 1 |
ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms)
{
unsigned int nbits;
gpg_err_code_t rc;
struct pk_encoding_ctx ctx;
gcry_sexp_t l1 = NULL;
gcry_mpi_t data_e = NULL;
ECC_secret_key sk;
gcry_mpi_t mpi_g = NULL;
char *curvename = NULL;
mpi_ec_t ec = NULL;
mpi_point_struct kG;
mpi_point_struct R;
gcry_mpi_t r = NULL;
int flags = 0;
memset (&sk, 0, sizeof sk);
point_init (&kG);
point_init (&R);
_gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT,
(nbits = ecc_get_nbits (keyparms)));
/* Look for flags. */
l1 = sexp_find_token (keyparms, "flags", 0);
if (l1)
{
rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL);
if (rc)
goto leave;
}
sexp_release (l1);
l1 = NULL;
/*
* Extract the data.
*/
rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx);
if (rc)
goto leave;
rc = sexp_extract_param (l1, NULL, "e", &data_e, NULL);
if (rc)
goto leave;
if (DBG_CIPHER)
log_printmpi ("ecc_decrypt d_e", data_e);
if (mpi_is_opaque (data_e))
{
rc = GPG_ERR_INV_DATA;
goto leave;
}
/*
* Extract the key.
*/
rc = sexp_extract_param (keyparms, NULL, "-p?a?b?g?n?h?+d",
&sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n,
&sk.E.h, &sk.d, NULL);
if (rc)
goto leave;
if (mpi_g)
{
point_init (&sk.E.G);
rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g);
if (rc)
goto leave;
}
/* Add missing parameters using the optional curve parameter. */
sexp_release (l1);
l1 = sexp_find_token (keyparms, "curve", 5);
if (l1)
{
curvename = sexp_nth_string (l1, 1);
if (curvename)
{
rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL);
if (rc)
goto leave;
}
}
/* Guess required fields if a curve parameter has not been given. */
if (!curvename)
{
sk.E.model = MPI_EC_WEIERSTRASS;
sk.E.dialect = ECC_DIALECT_STANDARD;
if (!sk.E.h)
sk.E.h = mpi_const (MPI_C_ONE);
}
if (DBG_CIPHER)
{
log_debug ("ecc_decrypt info: %s/%s\n",
_gcry_ecc_model2str (sk.E.model),
_gcry_ecc_dialect2str (sk.E.dialect));
if (sk.E.name)
log_debug ("ecc_decrypt name: %s\n", sk.E.name);
log_printmpi ("ecc_decrypt p", sk.E.p);
log_printmpi ("ecc_decrypt a", sk.E.a);
log_printmpi ("ecc_decrypt b", sk.E.b);
log_printpnt ("ecc_decrypt g", &sk.E.G, NULL);
log_printmpi ("ecc_decrypt n", sk.E.n);
log_printmpi ("ecc_decrypt h", sk.E.h);
if (!fips_mode ())
log_printmpi ("ecc_decrypt d", sk.d);
}
if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d)
{
rc = GPG_ERR_NO_OBJ;
goto leave;
}
ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags,
sk.E.p, sk.E.a, sk.E.b);
/*
* Compute the plaintext.
*/
if (ec->model == MPI_EC_MONTGOMERY)
rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG);
else
rc = _gcry_ecc_os2ec (&kG, data_e);
if (rc)
goto leave;
if (DBG_CIPHER)
log_printpnt ("ecc_decrypt kG", &kG, NULL);
if (!(flags & PUBKEY_FLAG_DJB_TWEAK)
/* For X25519, by its definition, validation should not be done. */
&& !_gcry_mpi_ec_curve_point (&kG, ec))
{
rc = GPG_ERR_INV_DATA;
goto leave;
y = mpi_new (0);
if (_gcry_mpi_ec_get_affine (x, y, &R, ec))
{
rc = GPG_ERR_INV_DATA;
goto leave;
/*
* Note for X25519.
*
* By the definition of X25519, this is the case where X25519
* returns 0, mapping infinity to zero. However, we
* deliberately let it return an error.
*
* For X25519 ECDH, comming here means that it might be
* decrypted by anyone with the shared secret of 0 (the result
* of this function could be always 0 by other scalar values,
* other than the private key of SK.D).
*
* So, it looks like an encrypted message but it can be
* decrypted by anyone, or at least something wrong
* happens. Recipient should not proceed as if it were
* properly encrypted message.
*
* This handling is needed for our major usage of GnuPG,
* where it does the One-Pass Diffie-Hellman method,
* C(1, 1, ECC CDH), with an ephemeral key.
*/
}
if (y)
r = _gcry_ecc_ec2os (x, y, sk.E.p);
else
{
unsigned char *rawmpi;
unsigned int rawmpilen;
rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1,
&rawmpilen, NULL);
if (!rawmpi)
{
rc = gpg_err_code_from_syserror ();
goto leave;
}
else
{
rawmpi[0] = 0x40;
rawmpilen++;
r = mpi_new (0);
mpi_set_opaque (r, rawmpi, rawmpilen*8);
}
}
if (!r)
rc = gpg_err_code_from_syserror ();
else
rc = 0;
mpi_free (x);
mpi_free (y);
}
if (DBG_CIPHER)
log_printmpi ("ecc_decrypt res", r);
if (!rc)
rc = sexp_build (r_plain, NULL, "(value %m)", r);
leave:
point_free (&R);
point_free (&kG);
_gcry_mpi_release (r);
_gcry_mpi_release (sk.E.p);
_gcry_mpi_release (sk.E.a);
_gcry_mpi_release (sk.E.b);
_gcry_mpi_release (mpi_g);
point_free (&sk.E.G);
_gcry_mpi_release (sk.E.n);
_gcry_mpi_release (sk.E.h);
_gcry_mpi_release (sk.d);
_gcry_mpi_release (data_e);
xfree (curvename);
sexp_release (l1);
_gcry_mpi_ec_free (ec);
_gcry_pk_util_free_encoding_ctx (&ctx);
if (DBG_CIPHER)
log_debug ("ecc_decrypt => %s\n", gpg_strerror (rc));
return rc;
}
|
CWE-200
| 178,392 | 393 |
65141540687160865752138954513842149463
| null | null | null |
savannah
|
135c3faebb96f8f550bd4f318716f2e1e095a969
| 1 |
cf2_initGlobalRegionBuffer( CFF_Decoder* decoder,
CF2_UInt idx,
CF2_Buffer buf )
{
FT_ASSERT( decoder && decoder->globals );
FT_ZERO( buf );
idx += decoder->globals_bias;
if ( idx >= decoder->num_globals )
return TRUE; /* error */
buf->start =
buf->ptr = decoder->globals[idx];
buf->end = decoder->globals[idx + 1];
}
|
CWE-20
| 178,393 | 394 |
57508056900925331860444886992748368704
| null | null | null |
ghostscript
|
60dabde18d7fe12b19da8b509bdfee9cc886aafc
| 1 |
xps_parse_color(xps_document *doc, char *base_uri, char *string,
fz_colorspace **csp, float *samples)
{
char *p;
int i, n;
char buf[1024];
char *profile;
*csp = fz_device_rgb(doc->ctx);
samples[0] = 1;
samples[1] = 0;
samples[3] = 0;
if (string[0] == '#')
{
if (strlen(string) == 9)
{
samples[0] = unhex(string[1]) * 16 + unhex(string[2]);
samples[1] = unhex(string[3]) * 16 + unhex(string[4]);
samples[2] = unhex(string[5]) * 16 + unhex(string[6]);
samples[3] = unhex(string[7]) * 16 + unhex(string[8]);
}
else
{
samples[0] = 255;
samples[1] = unhex(string[1]) * 16 + unhex(string[2]);
samples[2] = unhex(string[3]) * 16 + unhex(string[4]);
samples[3] = unhex(string[5]) * 16 + unhex(string[6]);
}
samples[0] /= 255;
samples[1] /= 255;
samples[2] /= 255;
samples[3] /= 255;
}
else if (string[0] == 's' && string[1] == 'c' && string[2] == '#')
{
if (count_commas(string) == 2)
sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3);
if (count_commas(string) == 3)
sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3);
}
else if (strstr(string, "ContextColor ") == string)
{
/* Crack the string for profile name and sample values */
fz_strlcpy(buf, string, sizeof buf);
profile = strchr(buf, ' ');
profile = strchr(buf, ' ');
if (!profile)
{
fz_warn(doc->ctx, "cannot find icc profile uri in '%s'", string);
return;
}
p = strchr(profile, ' ');
p = strchr(profile, ' ');
if (!p)
{
fz_warn(doc->ctx, "cannot find component values in '%s'", profile);
return;
}
*p++ = 0;
n = count_commas(p) + 1;
i = 0;
while (i < n)
{
p ++;
}
while (i < n)
{
samples[i++] = 0;
}
/* TODO: load ICC profile */
switch (n)
{
case 2: *csp = fz_device_gray(doc->ctx); break;
case 4: *csp = fz_device_rgb(doc->ctx); break;
case 5: *csp = fz_device_cmyk(doc->ctx); break;
/* TODO: load ICC profile */
switch (n)
{
case 2: *csp = fz_device_gray(doc->ctx); break;
case 4: *csp = fz_device_rgb(doc->ctx); break;
case 5: *csp = fz_device_cmyk(doc->ctx); break;
default: *csp = fz_device_gray(doc->ctx); break;
}
}
}
for (i = 0; i < colorspace->n; i++)
doc->color[i] = samples[i + 1];
doc->alpha = samples[0] * doc->opacity[doc->opacity_top];
}
|
CWE-119
| 178,400 | 398 |
173680462593951007227148221492379395830
| null | null | null |
lxde
|
f99163c6ff8b2f57c5f37b1ce5d62cf7450d4648
| 1 |
gboolean lxterminal_socket_initialize(LXTermWindow * lxtermwin, gint argc, gchar * * argv)
{
/* Normally, LXTerminal uses one process to control all of its windows.
* The first process to start will create a Unix domain socket in /tmp.
* It will then bind and listen on this socket.
* The subsequent processes will connect to the controller that owns the Unix domain socket.
* They will pass their command line over the socket and exit.
*
* If for any reason both the connect and bind fail, we will fall back to having that
* process be standalone; it will not be either the controller or a user of the controller.
* This behavior was introduced in response to a problem report (2973537).
*
* This function returns TRUE if this process should keep running and FALSE if it should exit. */
/* Formulate the path for the Unix domain socket. */
gchar * socket_path = g_strdup_printf("/tmp/.lxterminal-socket%s-%s", gdk_display_get_name(gdk_display_get_default()), g_get_user_name());
/* Create socket. */
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
{
g_warning("Socket create failed: %s\n", g_strerror(errno));
g_free(socket_path);
return TRUE;
}
/* Initialize socket address for Unix domain socket. */
struct sockaddr_un sock_addr;
memset(&sock_addr, 0, sizeof(sock_addr));
sock_addr.sun_family = AF_UNIX;
snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", socket_path);
/* Try to connect to an existing LXTerminal process. */
if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
/* Connect failed. We are the controller, unless something fails. */
unlink(socket_path);
g_free(socket_path);
/* Bind to socket. */
if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0)
{
g_warning("Bind on socket failed: %s\n", g_strerror(errno));
close(fd);
return TRUE;
}
/* Listen on socket. */
if (listen(fd, 5) < 0)
{
g_warning("Listen on socket failed: %s\n", g_strerror(errno));
close(fd);
return TRUE;
}
/* Create a glib I/O channel. */
GIOChannel * gio = g_io_channel_unix_new(fd);
if (gio == NULL)
{
g_warning("Cannot create GIOChannel\n");
close(fd);
return TRUE;
}
/* Set up GIOChannel. */
g_io_channel_set_encoding(gio, NULL, NULL);
g_io_channel_set_buffered(gio, FALSE);
g_io_channel_set_close_on_unref(gio, TRUE);
/* Add I/O channel to the main event loop. */
if ( ! g_io_add_watch(gio, G_IO_IN | G_IO_HUP, (GIOFunc) lxterminal_socket_accept_client, lxtermwin))
{
g_warning("Cannot add watch on GIOChannel\n");
close(fd);
g_io_channel_unref(gio);
return TRUE;
}
/* Channel will automatically shut down when the watch returns FALSE. */
g_io_channel_set_close_on_unref(gio, TRUE);
g_io_channel_unref(gio);
return TRUE;
}
else
{
g_free(socket_path);
/* Create a glib I/O channel. */
GIOChannel * gio = g_io_channel_unix_new(fd);
g_io_channel_set_encoding(gio, NULL, NULL);
/* Push current dir in case it is needed later */
gchar * cur_dir = g_get_current_dir();
g_io_channel_write_chars(gio, cur_dir, -1, NULL, NULL);
/* Use "" as a pointer to '\0' since g_io_channel_write_chars() won't accept NULL */
g_io_channel_write_chars(gio, "", 1, NULL, NULL);
g_free(cur_dir);
/* push all of argv. */
gint i;
for (i = 0; i < argc; i ++)
{
g_io_channel_write_chars(gio, argv[i], -1, NULL, NULL);
g_io_channel_write_chars(gio, "", 1, NULL, NULL);
}
g_io_channel_flush(gio, NULL);
g_io_channel_unref(gio);
return FALSE;
}
}
|
CWE-284
| 178,404 | 402 |
132577294360438396002961072749352070730
| null | null | null |
savannah
|
fa481c116e65ccf9137c7ddc8abc3cf05dc12f55
| 1 |
nsPluginInstance::setupCookies(const std::string& pageurl)
{
std::string::size_type pos;
pos = pageurl.find("/", pageurl.find("//", 0) + 2) + 1;
std::string url = pageurl.substr(0, pos);
std::string ncookie;
char *cookie = 0;
uint32_t length = 0;
NPError rv = NPERR_GENERIC_ERROR;
#if NPAPI_VERSION != 190
if (NPNFuncs.getvalueforurl) {
rv = NPN_GetValueForURL(_instance, NPNURLVCookie, url.c_str(),
&cookie, &length);
} else {
LOG_ONCE( gnash::log_debug("Browser doesn't support getvalueforurl") );
}
#endif
if (rv == NPERR_GENERIC_ERROR) {
log_debug("Trying window.document.cookie for cookies");
ncookie = getDocumentProp("cookie");
}
if (cookie) {
ncookie.assign(cookie, length);
NPN_MemFree(cookie);
}
if (ncookie.empty()) {
gnash::log_debug("No stored Cookie for %s", url);
return;
}
gnash::log_debug("The Cookie for %s is %s", url, ncookie);
std::ofstream cookiefile;
std::stringstream ss;
ss << "/tmp/gnash-cookies." << getpid();
cookiefile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
typedef boost::char_separator<char> char_sep;
typedef boost::tokenizer<char_sep> tokenizer;
tokenizer tok(ncookie, char_sep(";"));
for (tokenizer::iterator it=tok.begin(); it != tok.end(); ++it) {
cookiefile << "Set-Cookie: " << *it << std::endl;
}
cookiefile.close();
if (setenv("GNASH_COOKIES_IN", ss.str().c_str(), 1) < 0) {
gnash::log_error(
"Couldn't set environment variable GNASH_COOKIES_IN to %s",
ncookie);
}
}
|
CWE-264
| 178,405 | 403 |
40274614371620023740345762208670376695
| null | null | null |
ghostscript
|
d621292fb2c8157d9899dcd83fd04dd250e30fe4
| 1 |
pdf14_pop_transparency_group(gs_gstate *pgs, pdf14_ctx *ctx,
const pdf14_nonseparable_blending_procs_t * pblend_procs,
int tos_num_color_comp, cmm_profile_t *curr_icc_profile, gx_device *dev)
{
pdf14_buf *tos = ctx->stack;
pdf14_buf *nos = tos->saved;
pdf14_mask_t *mask_stack = tos->mask_stack;
pdf14_buf *maskbuf;
int x0, x1, y0, y1;
byte *new_data_buf = NULL;
int num_noncolor_planes, new_num_planes;
int num_cols, num_rows, nos_num_color_comp;
bool icc_match;
gsicc_rendering_param_t rendering_params;
gsicc_link_t *icc_link;
gsicc_bufferdesc_t input_buff_desc;
gsicc_bufferdesc_t output_buff_desc;
pdf14_device *pdev = (pdf14_device *)dev;
bool overprint = pdev->overprint;
gx_color_index drawn_comps = pdev->drawn_comps;
bool nonicc_conversion = true;
nos_num_color_comp = nos->parent_color_info_procs->num_components - nos->num_spots;
tos_num_color_comp = tos_num_color_comp - tos->num_spots;
if (mask_stack == NULL) {
maskbuf = NULL;
} else {
maskbuf = mask_stack->rc_mask->mask_buf;
}
if (nos == NULL)
return_error(gs_error_rangecheck);
/* Sanitise the dirty rectangles, in case some of the drawing routines
* have made them overly large. */
rect_intersect(tos->dirty, tos->rect);
rect_intersect(nos->dirty, nos->rect);
/* dirty = the marked bbox. rect = the entire bounds of the buffer. */
/* Everything marked on tos that fits onto nos needs to be merged down. */
y0 = max(tos->dirty.p.y, nos->rect.p.y);
y1 = min(tos->dirty.q.y, nos->rect.q.y);
x0 = max(tos->dirty.p.x, nos->rect.p.x);
x1 = min(tos->dirty.q.x, nos->rect.q.x);
if (ctx->mask_stack) {
/* This can occur when we have a situation where we are ending out of
a group that has internal to it a soft mask and another group.
The soft mask left over from the previous trans group pop is put
into ctx->masbuf, since it is still active if another trans group
push occurs to use it. If one does not occur, but instead we find
ourselves popping from a parent group, then this softmask is no
longer needed. We will rc_decrement and set it to NULL. */
rc_decrement(ctx->mask_stack->rc_mask, "pdf14_pop_transparency_group");
if (ctx->mask_stack->rc_mask == NULL ){
gs_free_object(ctx->memory, ctx->mask_stack, "pdf14_pop_transparency_group");
}
ctx->mask_stack = NULL;
}
ctx->mask_stack = mask_stack; /* Restore the mask saved by pdf14_push_transparency_group. */
tos->mask_stack = NULL; /* Clean the pointer sinse the mask ownership is now passed to ctx. */
if (tos->idle)
goto exit;
if (maskbuf != NULL && maskbuf->data == NULL && maskbuf->alpha == 255)
goto exit;
#if RAW_DUMP
/* Dump the current buffer to see what we have. */
dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y,
ctx->stack->rowstride, ctx->stack->n_planes,
ctx->stack->planestride, ctx->stack->rowstride,
"aaTrans_Group_Pop",ctx->stack->data);
#endif
/* Note currently if a pattern space has transparency, the ICC profile is not used
for blending purposes. Instead we rely upon the gray, rgb, or cmyk parent space.
This is partially due to the fact that pdf14_pop_transparency_group and
pdf14_push_transparnecy_group have no real ICC interaction and those are the
operations called in the tile transparency code. Instead we may want to
look at pdf14_begin_transparency_group and pdf14_end_transparency group which
is where all the ICC information is handled. We will return to look at that later */
if (nos->parent_color_info_procs->icc_profile != NULL) {
icc_match = (nos->parent_color_info_procs->icc_profile->hashcode !=
curr_icc_profile->hashcode);
} else {
/* Let the other tests make the decision if we need to transform */
icc_match = false;
}
/* If the color spaces are different and we actually did do a swap of
the procs for color */
if ((nos->parent_color_info_procs->parent_color_mapping_procs != NULL &&
nos_num_color_comp != tos_num_color_comp) || icc_match) {
if (x0 < x1 && y0 < y1) {
/* The NOS blending color space is different than that of the
TOS. It is necessary to transform the TOS buffer data to the
color space of the NOS prior to doing the pdf14_compose_group
operation. */
num_noncolor_planes = tos->n_planes - tos_num_color_comp;
new_num_planes = num_noncolor_planes + nos_num_color_comp;
/* See if we are doing ICC based conversion */
if (nos->parent_color_info_procs->icc_profile != NULL &&
curr_icc_profile != NULL) {
/* Use the ICC color management for buffer color conversion */
/* Define the rendering intents */
rendering_params.black_point_comp = gsBLACKPTCOMP_ON;
rendering_params.graphics_type_tag = GS_IMAGE_TAG;
rendering_params.override_icc = false;
rendering_params.preserve_black = gsBKPRESNOTSPECIFIED;
rendering_params.rendering_intent = gsPERCEPTUAL;
rendering_params.cmm = gsCMM_DEFAULT;
/* Request the ICC link for the transform that we will need to use */
/* Note that if pgs is NULL we assume the same color space. This
is due to a call to pop the group from fill_mask when filling
with a mask with transparency. In that case, the parent
and the child will have the same color space anyway */
icc_link = gsicc_get_link_profile(pgs, dev, curr_icc_profile,
nos->parent_color_info_procs->icc_profile,
&rendering_params, pgs->memory, false);
if (icc_link != NULL) {
/* if problem with link we will do non-ICC approach */
nonicc_conversion = false;
/* If the link is the identity, then we don't need to do
any color conversions */
if ( !(icc_link->is_identity) ) {
/* Before we do any allocations check if we can get away with
reusing the existing buffer if it is the same size ( if it is
smaller go ahead and allocate). We could reuse it in this
case too. We need to do a bit of testing to determine what
would be best. */
/* FIXME: RJW: Could we get away with just color converting
* the area that's actually active (i.e. dirty, not rect)?
*/
if(nos_num_color_comp != tos_num_color_comp) {
/* Different size. We will need to allocate */
new_data_buf = gs_alloc_bytes(ctx->memory,
tos->planestride * new_num_planes,
"pdf14_pop_transparency_group");
if (new_data_buf == NULL)
return_error(gs_error_VMerror);
/* Copy over the noncolor planes. */
memcpy(new_data_buf + tos->planestride * nos_num_color_comp,
tos->data + tos->planestride * tos_num_color_comp,
tos->planestride * num_noncolor_planes);
} else {
/* In place color conversion! */
new_data_buf = tos->data;
}
/* Set up the buffer descriptors. Note that pdf14 always has
the alpha channels at the back end (last planes).
We will just handle that here and let the CMM know
nothing about it */
num_rows = tos->rect.q.y - tos->rect.p.y;
num_cols = tos->rect.q.x - tos->rect.p.x;
gsicc_init_buffer(&input_buff_desc, tos_num_color_comp, 1,
false, false, true,
tos->planestride, tos->rowstride,
num_rows, num_cols);
gsicc_init_buffer(&output_buff_desc, nos_num_color_comp,
1, false, false, true, tos->planestride,
tos->rowstride, num_rows, num_cols);
/* Transform the data. Since the pdf14 device should be
using RGB, CMYK or Gray buffers, this transform
does not need to worry about the cmap procs of
the target device. Those are handled when we do
the pdf14 put image operation */
(icc_link->procs.map_buffer)(dev, icc_link, &input_buff_desc,
&output_buff_desc, tos->data,
new_data_buf);
}
/* Release the link */
gsicc_release_link(icc_link);
/* free the old object if the color spaces were different sizes */
if(!(icc_link->is_identity) &&
nos_num_color_comp != tos_num_color_comp) {
gs_free_object(ctx->memory, tos->data,
"pdf14_pop_transparency_group");
tos->data = new_data_buf;
}
}
}
if (nonicc_conversion) {
/* Non ICC based transform */
new_data_buf = gs_alloc_bytes(ctx->memory,
tos->planestride * new_num_planes,
"pdf14_pop_transparency_group");
if (new_data_buf == NULL)
return_error(gs_error_VMerror);
gs_transform_color_buffer_generic(tos->data, tos->rowstride,
tos->planestride, tos_num_color_comp, tos->rect,
new_data_buf, nos_num_color_comp, num_noncolor_planes);
/* Free the old object */
gs_free_object(ctx->memory, tos->data,
"pdf14_pop_transparency_group");
tos->data = new_data_buf;
}
/* Adjust the plane and channel size now */
tos->n_chan = nos->n_chan;
tos->n_planes = nos->n_planes;
#if RAW_DUMP
/* Dump the current buffer to see what we have. */
dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y,
ctx->stack->rowstride, ctx->stack->n_chan,
ctx->stack->planestride, ctx->stack->rowstride,
"aCMTrans_Group_ColorConv",ctx->stack->data);
#endif
/* compose. never do overprint in this case */
pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan,
nos->parent_color_info_procs->isadditive,
nos->parent_color_info_procs->parent_blending_procs,
false, drawn_comps, ctx->memory, dev);
}
} else {
/* Group color spaces are the same. No color conversions needed */
if (x0 < x1 && y0 < y1)
pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan,
ctx->additive, pblend_procs, overprint,
drawn_comps, ctx->memory, dev);
}
exit:
ctx->stack = nos;
/* We want to detect the cases where we have luminosity soft masks embedded
within one another. The "alpha" channel really needs to be merged into
the luminosity channel in this case. This will occur during the mask pop */
if (ctx->smask_depth > 0 && maskbuf != NULL) {
/* Set the trigger so that we will blend if not alpha. Since
we have softmasks embedded in softmasks */
ctx->smask_blend = true;
}
if_debug1m('v', ctx->memory, "[v]pop buf, idle=%d\n", tos->idle);
pdf14_buf_free(tos, ctx->memory);
return 0;
}
|
CWE-476
| 178,407 | 404 |
248910136039266602369854574320600069873
| null | null | null |
xserver
|
b67581cf825940fdf52bf2e0af4330e695d724a4
| 1 |
LockServer(void)
{
char tmp[PATH_MAX], pid_str[12];
int lfd, i, haslock, l_pid, t;
char *tmppath = NULL;
int len;
char port[20];
if (nolock) return;
/*
* Path names
*/
tmppath = LOCK_DIR;
sprintf(port, "%d", atoi(display));
len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
strlen(LOCK_TMP_PREFIX);
len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1;
if (len > sizeof(LockFile))
FatalError("Display name `%s' is too long\n", port);
(void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
(void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
/*
* Create a temporary file containing our PID. Attempt three times
* to create the file.
*/
StillLocking = TRUE;
i = 0;
do {
i++;
lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (lfd < 0)
sleep(2);
else
break;
} while (i < 3);
if (lfd < 0) {
unlink(tmp);
i = 0;
do {
i++;
lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (lfd < 0)
sleep(2);
else
break;
} while (i < 3);
}
if (lfd < 0)
FatalError("Could not create lock file in %s\n", tmp);
(void) sprintf(pid_str, "%10ld\n", (long)getpid());
(void) write(lfd, pid_str, 11);
(void) chmod(tmp, 0444);
(void) close(lfd);
/*
* OK. Now the tmp file exists. Try three times to move it in place
* for the lock.
*/
i = 0;
haslock = 0;
while ((!haslock) && (i++ < 3)) {
haslock = (link(tmp,LockFile) == 0);
if (haslock) {
/*
* We're done.
*/
break;
}
else {
/*
* Read the pid from the existing file
*/
lfd = open(LockFile, O_RDONLY|O_NOFOLLOW);
if (lfd < 0) {
unlink(tmp);
FatalError("Can't read lock file %s\n", LockFile);
}
pid_str[0] = '\0';
if (read(lfd, pid_str, 11) != 11) {
/*
* Bogus lock file.
*/
unlink(LockFile);
close(lfd);
continue;
}
pid_str[11] = '\0';
sscanf(pid_str, "%d", &l_pid);
close(lfd);
/*
* Now try to kill the PID to see if it exists.
*/
errno = 0;
t = kill(l_pid, 0);
if ((t< 0) && (errno == ESRCH)) {
/*
* Stale lock file.
*/
unlink(LockFile);
continue;
}
else if (((t < 0) && (errno == EPERM)) || (t == 0)) {
/*
* Process is still active.
*/
unlink(tmp);
FatalError("Server is already active for display %s\n%s %s\n%s\n",
port, "\tIf this server is no longer running, remove",
LockFile, "\tand start again.");
}
}
}
unlink(tmp);
if (!haslock)
FatalError("Could not create server lock file: %s\n", LockFile);
StillLocking = FALSE;
}
|
CWE-362
| 178,408 | 405 |
72009230071133363257853371640950296465
| null | null | null |
xserver
|
6ba44b91e37622ef8c146d8f2ac92d708a18ed34
| 1 |
LockServer(void)
{
char tmp[PATH_MAX], pid_str[12];
int lfd, i, haslock, l_pid, t;
char *tmppath = NULL;
int len;
char port[20];
if (nolock) return;
/*
* Path names
*/
tmppath = LOCK_DIR;
sprintf(port, "%d", atoi(display));
len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
strlen(LOCK_TMP_PREFIX);
len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1;
if (len > sizeof(LockFile))
FatalError("Display name `%s' is too long\n", port);
(void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
(void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
/*
* Create a temporary file containing our PID. Attempt three times
* to create the file.
*/
StillLocking = TRUE;
i = 0;
do {
i++;
lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (lfd < 0)
sleep(2);
else
break;
} while (i < 3);
if (lfd < 0) {
unlink(tmp);
i = 0;
do {
i++;
lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (lfd < 0)
sleep(2);
else
break;
} while (i < 3);
}
if (lfd < 0)
FatalError("Could not create lock file in %s\n", tmp);
(void) sprintf(pid_str, "%10ld\n", (long)getpid());
(void) write(lfd, pid_str, 11);
(void) chmod(tmp, 0444);
(void) close(lfd);
/*
* OK. Now the tmp file exists. Try three times to move it in place
* for the lock.
*/
i = 0;
haslock = 0;
while ((!haslock) && (i++ < 3)) {
haslock = (link(tmp,LockFile) == 0);
if (haslock) {
/*
* We're done.
*/
break;
}
else {
/*
* Read the pid from the existing file
*/
lfd = open(LockFile, O_RDONLY);
if (lfd < 0) {
unlink(tmp);
FatalError("Can't read lock file %s\n", LockFile);
}
pid_str[0] = '\0';
if (read(lfd, pid_str, 11) != 11) {
/*
* Bogus lock file.
*/
unlink(LockFile);
close(lfd);
continue;
}
pid_str[11] = '\0';
sscanf(pid_str, "%d", &l_pid);
close(lfd);
/*
* Now try to kill the PID to see if it exists.
*/
errno = 0;
t = kill(l_pid, 0);
if ((t< 0) && (errno == ESRCH)) {
/*
* Stale lock file.
*/
unlink(LockFile);
continue;
}
else if (((t < 0) && (errno == EPERM)) || (t == 0)) {
/*
* Process is still active.
*/
unlink(tmp);
FatalError("Server is already active for display %s\n%s %s\n%s\n",
port, "\tIf this server is no longer running, remove",
LockFile, "\tand start again.");
}
}
}
unlink(tmp);
if (!haslock)
FatalError("Could not create server lock file: %s\n", LockFile);
StillLocking = FALSE;
}
|
CWE-59
| 178,409 | 406 |
20891641801682437742426402633668824466
| null | null | null |
libXpm
|
d1167418f0fd02a27f617ec5afd6db053afbe185
| 1 |
XpmCreateDataFromXpmImage(
char ***data_return,
XpmImage *image,
XpmInfo *info)
{
/* calculation variables */
int ErrorStatus;
char buf[BUFSIZ];
char **header = NULL, **data, **sptr, **sptr2, *s;
unsigned int header_size, header_nlines;
unsigned int data_size, data_nlines;
unsigned int extensions = 0, ext_size = 0, ext_nlines = 0;
unsigned int offset, l, n;
*data_return = NULL;
extensions = info && (info->valuemask & XpmExtensions)
&& info->nextensions;
/* compute the number of extensions lines and size */
if (extensions)
CountExtensions(info->extensions, info->nextensions,
&ext_size, &ext_nlines);
/*
* alloc a temporary array of char pointer for the header section which
*/
header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */
/* 2nd check superfluous if we do not need header_nlines any further */
if(header_nlines <= image->ncolors ||
header_nlines >= UINT_MAX / sizeof(char *))
return(XpmNoMemory);
header_size = sizeof(char *) * header_nlines;
if (header_size >= UINT_MAX / sizeof(char *))
return (XpmNoMemory);
header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */
if (!header)
return (XpmNoMemory);
/* print the hints line */
s = buf;
#ifndef VOID_SPRINTF
s +=
#endif
sprintf(s, "%d %d %d %d", image->width, image->height,
image->ncolors, image->cpp);
#ifdef VOID_SPRINTF
s += strlen(s);
#endif
if (info && (info->valuemask & XpmHotspot)) {
#ifndef VOID_SPRINTF
s +=
#endif
sprintf(s, " %d %d", info->x_hotspot, info->y_hotspot);
#ifdef VOID_SPRINTF
s += strlen(s);
#endif
}
if (extensions) {
strcpy(s, " XPMEXT");
s += 7;
}
l = s - buf + 1;
*header = (char *) XpmMalloc(l);
if (!*header)
RETURN(XpmNoMemory);
header_size += l;
strcpy(*header, buf);
/* print colors */
ErrorStatus = CreateColors(header + 1, &header_size,
image->colorTable, image->ncolors, image->cpp);
if (ErrorStatus != XpmSuccess)
RETURN(ErrorStatus);
/* now we know the size needed, alloc the data and copy the header lines */
offset = image->width * image->cpp + 1;
if(offset <= image->width || offset <= image->cpp)
if(offset <= image->width || offset <= image->cpp)
RETURN(XpmNoMemory);
if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *))
RETURN(XpmNoMemory);
data_size = (image->height + ext_nlines) * sizeof(char *);
RETURN(XpmNoMemory);
data_size += image->height * offset;
RETURN(XpmNoMemory);
data_size += image->height * offset;
if( (header_size + ext_size) >= (UINT_MAX - data_size) )
RETURN(XpmNoMemory);
data_size += header_size + ext_size;
data_nlines = header_nlines + image->height + ext_nlines;
*data = (char *) (data + data_nlines);
/* can header have less elements then n suggests? */
n = image->ncolors;
for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) {
strcpy(*sptr, *sptr2);
*(sptr + 1) = *sptr + strlen(*sptr2) + 1;
}
/* print pixels */
data[header_nlines] = (char *) data + header_size
+ (image->height + ext_nlines) * sizeof(char *);
CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height,
image->cpp, image->data, image->colorTable);
/* print extensions */
if (extensions)
CreateExtensions(data + header_nlines + image->height - 1,
data_size - header_nlines - image->height + 1, offset,
info->extensions, info->nextensions,
ext_nlines);
*data_return = data;
ErrorStatus = XpmSuccess;
/* exit point, free only locally allocated variables */
exit:
if (header) {
for (l = 0; l < header_nlines; l++)
if (header[l])
XpmFree(header[l]);
XpmFree(header);
}
return(ErrorStatus);
}
|
CWE-787
| 178,410 | 407 |
265801679414920102856048697133914647403
| null | null | null |
libav
|
635bcfccd439480003b74a665b5aa7c872c1ad6b
| 1 |
static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
{
const uint8_t* as_pack;
int freq, stype, smpls, quant, i, ach;
as_pack = dv_extract_pack(frame, dv_audio_source);
if (!as_pack || !c->sys) { /* No audio ? */
c->ach = 0;
return 0;
}
smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
/* note: ach counts PAIRS of channels (i.e. stereo channels) */
ach = ((int[4]){ 1, 0, 2, 4})[stype];
if (ach == 1 && quant && freq == 2)
if (!c->ast[i])
break;
avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
av_init_packet(&c->audio_pkt[i]);
c->audio_pkt[i].size = 0;
c->audio_pkt[i].data = c->audio_buf[i];
c->audio_pkt[i].stream_index = c->ast[i]->index;
c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY;
}
|
CWE-20
| 178,415 | 408 |
278522087006542116303016430885015911931
| null | null | null |
libav
|
5a396bb3a66a61a68b80f2369d0249729bf85e04
| 1 |
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
uint8_t* buf, int buf_size)
{
int size, i;
uint8_t *ppcm[4] = {0};
if (buf_size < DV_PROFILE_BYTES ||
!(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) ||
buf_size < c->sys->frame_size) {
return -1; /* Broken frame, or not enough data */
}
/* Queueing audio packet */
/* FIXME: in case of no audio/bad audio we have to do something */
size = dv_extract_audio_info(c, buf);
for (i = 0; i < c->ach; i++) {
c->audio_pkt[i].size = size;
c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
ppcm[i] = c->audio_buf[i];
}
dv_extract_audio(buf, ppcm, c->sys);
/* We work with 720p frames split in half, thus even frames have
* channels 0,1 and odd 2,3. */
if (buf[1] & 0x0C) {
c->audio_pkt[2].size = c->audio_pkt[3].size = 0;
} else {
c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
c->abytes += size;
}
} else {
c->abytes += size;
}
|
CWE-119
| 178,416 | 409 |
106330760518707613007105817589614452739
| null | null | null |
harfbuzz
|
81c8ef785b079980ad5b46be4fe7c7bf156dbf65
| 1 |
static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi,
HB_GPOS_SubTable* st,
HB_Buffer buffer,
HB_UShort flags,
HB_UShort context_length,
int nesting_level )
{
HB_UShort i, j, mark1_index, mark2_index, property, class;
HB_Fixed x_mark1_value, y_mark1_value,
x_mark2_value, y_mark2_value;
HB_Error error;
HB_GPOSHeader* gpos = gpi->gpos;
HB_MarkMarkPos* mmp = &st->markmark;
HB_MarkArray* ma1;
HB_Mark2Array* ma2;
HB_Mark2Record* m2r;
HB_Anchor* mark1_anchor;
HB_Anchor* mark2_anchor;
HB_Position o;
HB_UNUSED(nesting_level);
if ( context_length != 0xFFFF && context_length < 1 )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS )
return HB_Err_Not_Covered;
if ( CHECK_Property( gpos->gdef, IN_CURITEM(),
flags, &property ) )
return error;
error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(),
&mark1_index );
if ( error )
return error;
/* now we search backwards for a suitable mark glyph until a non-mark
glyph */
if ( buffer->in_pos == 0 )
return HB_Err_Not_Covered;
i = 1;
j = buffer->in_pos - 1;
while ( i <= buffer->in_pos )
{
error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ),
&property );
if ( error )
return error;
if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS )
{
if ( property == (flags & 0xFF00) )
break;
}
else
break;
i++;
j--;
}
error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ),
&mark2_index );
if ( error )
if ( mark1_index >= ma1->MarkCount )
return ERR(HB_Err_Invalid_SubTable);
class = ma1->MarkRecord[mark1_index].Class;
mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor;
if ( class >= mmp->ClassCount )
return ERR(HB_Err_Invalid_SubTable);
ma2 = &mmp->Mark2Array;
if ( mark2_index >= ma2->Mark2Count )
return ERR(HB_Err_Invalid_SubTable);
m2r = &ma2->Mark2Record[mark2_index];
mark2_anchor = &m2r->Mark2Anchor[class];
error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(),
&x_mark1_value, &y_mark1_value );
if ( error )
return error;
error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ),
&x_mark2_value, &y_mark2_value );
if ( error )
return error;
/* anchor points are not cumulative */
o = POSITION( buffer->in_pos );
o->x_pos = x_mark2_value - x_mark1_value;
o->y_pos = y_mark2_value - y_mark1_value;
o->x_advance = 0;
o->y_advance = 0;
o->back = 1;
(buffer->in_pos)++;
return HB_Err_Ok;
}
|
CWE-119
| 178,418 | 410 |
311194674003134329769297107152985881683
| null | null | null |
openssl
|
259b664f950c2ba66fbf4b0fe5281327904ead21
| 1 |
SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)
{
int i;
SRP_user_pwd *user;
unsigned char digv[SHA_DIGEST_LENGTH];
unsigned char digs[SHA_DIGEST_LENGTH];
EVP_MD_CTX ctxt;
if (vb == NULL)
return NULL;
for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) {
user = sk_SRP_user_pwd_value(vb->users_pwd, i);
if (strcmp(user->id, username) == 0)
return user;
}
if ((vb->seed_key == NULL) ||
(vb->default_g == NULL) || (vb->default_N == NULL))
return NULL;
if (!(len = t_fromb64(tmp, N)))
goto err;
N_bn = BN_bin2bn(tmp, len, NULL);
if (!(len = t_fromb64(tmp, g)))
goto err;
g_bn = BN_bin2bn(tmp, len, NULL);
defgNid = "*";
} else {
SRP_gN *gN = SRP_get_gN_by_id(g, NULL);
if (gN == NULL)
goto err;
N_bn = gN->N;
g_bn = gN->g;
defgNid = gN->id;
}
|
CWE-399
| 178,420 | 412 |
289337390467611969166521682004549666137
| null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.