id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_1184_0
/****************************************************************************** * * Project: OGR * Purpose: Convenience function for parsing with Expat library * Author: Even Rouault, even dot rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2009-2012, Even Rouault <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifdef HAVE_EXPAT #include "cpl_port.h" #include "cpl_conv.h" #include "cpl_string.h" #include "ogr_expat.h" #include <cstddef> #include <cstdlib> #include "cpl_error.h" CPL_CVSID("$Id$") constexpr size_t OGR_EXPAT_MAX_ALLOWED_ALLOC = 10000000; static void* OGRExpatMalloc( size_t size ) CPL_WARN_UNUSED_RESULT; static void* OGRExpatRealloc( void *ptr, size_t size ) CPL_WARN_UNUSED_RESULT; /************************************************************************/ /* CanAlloc() */ /************************************************************************/ static bool CanAlloc( size_t size ) { if( size < OGR_EXPAT_MAX_ALLOWED_ALLOC ) return true; if( CPLTestBool(CPLGetConfigOption("OGR_EXPAT_UNLIMITED_MEM_ALLOC", "NO")) ) return true; CPLError(CE_Failure, CPLE_OutOfMemory, "Expat tried to malloc %d bytes. File probably corrupted. " "This may also happen in case of a very big XML comment, in which case " "you may define the OGR_EXPAT_UNLIMITED_MEM_ALLOC configuration " "option to YES to remove that protection.", static_cast<int>(size)); return false; } /************************************************************************/ /* OGRExpatMalloc() */ /************************************************************************/ static void* OGRExpatMalloc( size_t size ) { if( CanAlloc(size) ) return malloc(size); return nullptr; } /************************************************************************/ /* OGRExpatRealloc() */ /************************************************************************/ // Caller must replace the pointer with the returned pointer. static void* OGRExpatRealloc( void *ptr, size_t size ) { if( CanAlloc(size) ) return realloc(ptr, size); return nullptr; } /************************************************************************/ /* FillWINDOWS1252() */ /************************************************************************/ static void FillWINDOWS1252( XML_Encoding *info ) { // Map CP1252 bytes to Unicode values. for( int i = 0; i < 0x80; ++i ) info->map[i] = i; info->map[0x80] = 0x20AC; info->map[0x81] = -1; info->map[0x82] = 0x201A; info->map[0x83] = 0x0192; info->map[0x84] = 0x201E; info->map[0x85] = 0x2026; info->map[0x86] = 0x2020; info->map[0x87] = 0x2021; info->map[0x88] = 0x02C6; info->map[0x89] = 0x2030; info->map[0x8A] = 0x0160; info->map[0x8B] = 0x2039; info->map[0x8C] = 0x0152; info->map[0x8D] = -1; info->map[0x8E] = 0x017D; info->map[0x8F] = -1; info->map[0x90] = -1; info->map[0x91] = 0x2018; info->map[0x92] = 0x2019; info->map[0x93] = 0x201C; info->map[0x94] = 0x201D; info->map[0x95] = 0x2022; info->map[0x96] = 0x2013; info->map[0x97] = 0x2014; info->map[0x98] = 0x02DC; info->map[0x99] = 0x2122; info->map[0x9A] = 0x0161; info->map[0x9B] = 0x203A; info->map[0x9C] = 0x0153; info->map[0x9D] = -1; info->map[0x9E] = 0x017E; info->map[0x9F] = 0x0178; for( int i = 0xA0; i <= 0xFF; ++i ) info->map[i] = i; } /************************************************************************/ /* FillISO885915() */ /************************************************************************/ static void FillISO885915( XML_Encoding *info ) { // Map ISO-8859-15 bytes to Unicode values. // Generated by generate_encoding_table.c. for( int i = 0x00; i < 0xA4; ++i) info->map[i] = i; info->map[0xA4] = 0x20AC; info->map[0xA5] = 0xA5; info->map[0xA6] = 0x0160; info->map[0xA7] = 0xA7; info->map[0xA8] = 0x0161; for( int i = 0xA9; i < 0xB4; ++i ) info->map[i] = i; info->map[0xB4] = 0x017D; for( int i = 0xB5; i < 0xB8; ++i ) info->map[i] = i; info->map[0xB8] = 0x017E; for( int i = 0xB9; i < 0xBC; ++i ) info->map[i] = i; info->map[0xBC] = 0x0152; info->map[0xBD] = 0x0153; info->map[0xBE] = 0x0178; for( int i = 0xBF; i < 0x100; ++i ) info->map[i] = i; } /************************************************************************/ /* OGRExpatUnknownEncodingHandler() */ /************************************************************************/ static int OGRExpatUnknownEncodingHandler( void * /* unused_encodingHandlerData */, const XML_Char *name, XML_Encoding *info ) { if( EQUAL(name, "WINDOWS-1252") ) FillWINDOWS1252(info); else if( EQUAL(name, "ISO-8859-15") ) FillISO885915(info); else { CPLDebug("OGR", "Unhandled encoding %s", name); return XML_STATUS_ERROR; } info->data = nullptr; info->convert = nullptr; info->release = nullptr; return XML_STATUS_OK; } /************************************************************************/ /* OGRCreateExpatXMLParser() */ /************************************************************************/ XML_Parser OGRCreateExpatXMLParser() { XML_Memory_Handling_Suite memsuite; memsuite.malloc_fcn = OGRExpatMalloc; memsuite.realloc_fcn = OGRExpatRealloc; memsuite.free_fcn = free; XML_Parser hParser = XML_ParserCreate_MM(nullptr, &memsuite, nullptr); XML_SetUnknownEncodingHandler(hParser, OGRExpatUnknownEncodingHandler, nullptr); return hParser; } #endif // HAVE_EXPAT
./CrossVul/dataset_final_sorted/CWE-415/cpp/good_1184_0
crossvul-cpp_data_bad_1184_0
/****************************************************************************** * * Project: OGR * Purpose: Convenience function for parsing with Expat library * Author: Even Rouault, even dot rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2009-2012, Even Rouault <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifdef HAVE_EXPAT #include "cpl_port.h" #include "cpl_conv.h" #include "cpl_string.h" #include "ogr_expat.h" #include <cstddef> #include <cstdlib> #include "cpl_error.h" CPL_CVSID("$Id$") constexpr size_t OGR_EXPAT_MAX_ALLOWED_ALLOC = 10000000; static void* OGRExpatMalloc( size_t size ) CPL_WARN_UNUSED_RESULT; static void* OGRExpatRealloc( void *ptr, size_t size ) CPL_WARN_UNUSED_RESULT; /************************************************************************/ /* CanAlloc() */ /************************************************************************/ static bool CanAlloc( size_t size ) { if( size < OGR_EXPAT_MAX_ALLOWED_ALLOC ) return true; if( CPLTestBool(CPLGetConfigOption("OGR_EXPAT_UNLIMITED_MEM_ALLOC", "NO")) ) return true; CPLError(CE_Failure, CPLE_OutOfMemory, "Expat tried to malloc %d bytes. File probably corrupted. " "This may also happen in case of a very big XML comment, in which case " "you may define the OGR_EXPAT_UNLIMITED_MEM_ALLOC configuration " "option to YES to remove that protection.", static_cast<int>(size)); return false; } /************************************************************************/ /* OGRExpatMalloc() */ /************************************************************************/ static void* OGRExpatMalloc( size_t size ) { if( CanAlloc(size) ) return malloc(size); return nullptr; } /************************************************************************/ /* OGRExpatRealloc() */ /************************************************************************/ // Caller must replace the pointer with the returned pointer. static void* OGRExpatRealloc( void *ptr, size_t size ) { if( CanAlloc(size) ) return realloc(ptr, size); free(ptr); return nullptr; } /************************************************************************/ /* FillWINDOWS1252() */ /************************************************************************/ static void FillWINDOWS1252( XML_Encoding *info ) { // Map CP1252 bytes to Unicode values. for( int i = 0; i < 0x80; ++i ) info->map[i] = i; info->map[0x80] = 0x20AC; info->map[0x81] = -1; info->map[0x82] = 0x201A; info->map[0x83] = 0x0192; info->map[0x84] = 0x201E; info->map[0x85] = 0x2026; info->map[0x86] = 0x2020; info->map[0x87] = 0x2021; info->map[0x88] = 0x02C6; info->map[0x89] = 0x2030; info->map[0x8A] = 0x0160; info->map[0x8B] = 0x2039; info->map[0x8C] = 0x0152; info->map[0x8D] = -1; info->map[0x8E] = 0x017D; info->map[0x8F] = -1; info->map[0x90] = -1; info->map[0x91] = 0x2018; info->map[0x92] = 0x2019; info->map[0x93] = 0x201C; info->map[0x94] = 0x201D; info->map[0x95] = 0x2022; info->map[0x96] = 0x2013; info->map[0x97] = 0x2014; info->map[0x98] = 0x02DC; info->map[0x99] = 0x2122; info->map[0x9A] = 0x0161; info->map[0x9B] = 0x203A; info->map[0x9C] = 0x0153; info->map[0x9D] = -1; info->map[0x9E] = 0x017E; info->map[0x9F] = 0x0178; for( int i = 0xA0; i <= 0xFF; ++i ) info->map[i] = i; } /************************************************************************/ /* FillISO885915() */ /************************************************************************/ static void FillISO885915( XML_Encoding *info ) { // Map ISO-8859-15 bytes to Unicode values. // Generated by generate_encoding_table.c. for( int i = 0x00; i < 0xA4; ++i) info->map[i] = i; info->map[0xA4] = 0x20AC; info->map[0xA5] = 0xA5; info->map[0xA6] = 0x0160; info->map[0xA7] = 0xA7; info->map[0xA8] = 0x0161; for( int i = 0xA9; i < 0xB4; ++i ) info->map[i] = i; info->map[0xB4] = 0x017D; for( int i = 0xB5; i < 0xB8; ++i ) info->map[i] = i; info->map[0xB8] = 0x017E; for( int i = 0xB9; i < 0xBC; ++i ) info->map[i] = i; info->map[0xBC] = 0x0152; info->map[0xBD] = 0x0153; info->map[0xBE] = 0x0178; for( int i = 0xBF; i < 0x100; ++i ) info->map[i] = i; } /************************************************************************/ /* OGRExpatUnknownEncodingHandler() */ /************************************************************************/ static int OGRExpatUnknownEncodingHandler( void * /* unused_encodingHandlerData */, const XML_Char *name, XML_Encoding *info ) { if( EQUAL(name, "WINDOWS-1252") ) FillWINDOWS1252(info); else if( EQUAL(name, "ISO-8859-15") ) FillISO885915(info); else { CPLDebug("OGR", "Unhandled encoding %s", name); return XML_STATUS_ERROR; } info->data = nullptr; info->convert = nullptr; info->release = nullptr; return XML_STATUS_OK; } /************************************************************************/ /* OGRCreateExpatXMLParser() */ /************************************************************************/ XML_Parser OGRCreateExpatXMLParser() { XML_Memory_Handling_Suite memsuite; memsuite.malloc_fcn = OGRExpatMalloc; memsuite.realloc_fcn = OGRExpatRealloc; memsuite.free_fcn = free; XML_Parser hParser = XML_ParserCreate_MM(nullptr, &memsuite, nullptr); XML_SetUnknownEncodingHandler(hParser, OGRExpatUnknownEncodingHandler, nullptr); return hParser; } #endif // HAVE_EXPAT
./CrossVul/dataset_final_sorted/CWE-415/cpp/bad_1184_0
crossvul-cpp_data_good_348_3
/* * card-tcos.c: Support for TCOS cards * * Copyright (C) 2011 Peter Koch <pk@opensc-project.org> * Copyright (C) 2002 g10 Code GmbH * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <ctype.h> #include <time.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table tcos_atrs[] = { /* Infineon SLE44 */ { "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66S */ { "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX320P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX322P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Philips P5CT072 */ { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, /* Philips P5CT080 */ { "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_card_operations tcos_ops; static struct sc_card_driver tcos_drv = { "TCOS 3.0", "tcos", &tcos_ops, NULL, 0, NULL }; static const struct sc_card_operations *iso_ops = NULL; typedef struct tcos_data_st { unsigned int pad_flags; unsigned int next_sign; } tcos_data; static int tcos_finish(sc_card_t *card) { free(card->drv_data); return 0; } static int tcos_match_card(sc_card_t *card) { int i; i = _sc_match_atr(card, tcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int tcos_init(sc_card_t *card) { unsigned long flags; tcos_data *data = malloc(sizeof(tcos_data)); if (!data) return SC_ERROR_OUT_OF_MEMORY; card->name = "TCOS"; card->drv_data = (void *)data; card->cla = 0x00; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); if (card->type == SC_CARD_TYPE_TCOS_V3) { card->caps |= SC_CARD_CAP_APDU_EXT; _sc_card_add_rsa_alg(card, 1280, flags, 0); _sc_card_add_rsa_alg(card, 1536, flags, 0); _sc_card_add_rsa_alg(card, 1792, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return 0; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static int tcos_construct_fci(const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; size_t n; /* FIXME: possible buffer overflow */ *p++ = 0x6F; /* FCI */ p++; /* File size */ buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x81, buf, 2, p, 16, &p); /* File descriptor */ n = 0; buf[n] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_WORKING_EF: break; case SC_FILE_TYPE_DF: buf[0] |= 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } buf[n++] |= file->ef_structure & 7; if ( (file->ef_structure & 7) > 1) { /* record structured file */ buf[n++] = 0x41; /* indicate 3rd byte */ buf[n++] = file->record_length; } sc_asn1_put_tag(0x82, buf, n, p, 8, &p); /* File identifier */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, 16, &p); /* Directory name */ if (file->type == SC_FILE_TYPE_DF) { if (file->namelen) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, 16, &p); } else { /* TCOS needs one, so we use a faked one */ snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu", (unsigned long) time (NULL)); sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p); } } /* File descriptor extension */ if (file->prop_attr_len && file->prop_attr) { n = file->prop_attr_len; memcpy(buf, file->prop_attr, n); } else { n = 0; buf[n++] = 0x01; /* not invalidated, permanent */ if (file->type == SC_FILE_TYPE_WORKING_EF) buf[n++] = 0x00; /* generic data file */ } sc_asn1_put_tag(0x85, buf, n, p, 16, &p); /* Security attributes */ if (file->sec_attr_len && file->sec_attr) { memcpy(buf, file->sec_attr, file->sec_attr_len); n = file->sec_attr_len; } else { /* no attributes given - fall back to default one */ memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */ memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */ memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */ memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/ n = 24; } sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p); /* fixup length of FCI */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int tcos_create_file(sc_card_t *card, sc_file_t *file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; len = SC_MAX_APDU_BUFFER_SIZE; r = tcos_construct_fci(file, sbuf, &len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.cla |= 0x80; /* this is an proprietary extension */ apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static unsigned int map_operations (int commandbyte ) { unsigned int op = (unsigned int)-1; switch ( (commandbyte & 0xfe) ) { case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break; case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break; case 0xe0: /* create */ op = SC_AC_OP_CREATE; break; case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break; case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break; case 0x82: /* external auth */ op = SC_AC_OP_READ; break; case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break; case 0x88: /* internal auth */ op = SC_AC_OP_READ; break; case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break; case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break; case 0xb0: /* read binary */ op = SC_AC_OP_READ; break; case 0xb2: /* read record */ op = SC_AC_OP_READ; break; case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break; case 0xa4: /* select */ op = SC_AC_OP_SELECT; break; case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break; case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break; case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break; case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break; case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break; case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break; } return op; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static void parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { unsigned int op; /* list directory is not covered by ACLs - so always add an entry */ sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES, SC_AC_NONE, SC_AC_KEY_REF_NONE); /* FIXME: check for what LOCK is used */ sc_file_add_acl_entry (file, SC_AC_OP_LOCK, SC_AC_NONE, SC_AC_KEY_REF_NONE); for (; len >= 6; len -= 6, buf += 6) { /* FIXME: temporary hacks */ if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */ sc_file_add_acl_entry (file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/ sc_file_add_acl_entry (file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/ sc_file_add_acl_entry (file, SC_AC_OP_UPDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */ sc_file_add_acl_entry (file, SC_AC_OP_WRITE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_CREATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else { /* the first byte tells use the command or the command group. We have to mask bit 0 because this one distinguish between AND/OR combination of PINs*/ op = map_operations (buf[0]); if (op == (unsigned int)-1) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown security command byte %02x\n", buf[0]); continue; } if (!buf[1]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_CHV, buf[1]); if (!buf[2] && !buf[3]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_TERM, (buf[2]<<8)|buf[3]); } } } static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ size_t j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: file->namelen = MIN(sizeof file->name, len); memcpy(file->name, d, file->namelen); break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1; int r, count = 0; assert(card != NULL); ctx = card->ctx; for (p1=1; p1<=2; p1++) { sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n", apdu.resplen / 2, p1 == 1 ? "DF" : "EF"); memcpy(buf, apdu.resp, apdu.resplen); buf += apdu.resplen; buflen -= apdu.resplen; count += apdu.resplen; } return count; } static int tcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r; u8 sbuf[2]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } sbuf[0] = path->value[0]; sbuf[1] = path->value[1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_context_t *ctx; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p; int r, default_key, tcos3; tcos_data *data; assert(card != NULL && env != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "No Key-Reference in SecEnvironment\n"); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n", env->key_ref[0], env->key_ref_len); /* Key-Reference 0x80 ?? */ default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n", tcos3, !!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); data->pad_flags = env->algorithm_flags; data->next_sign = default_key; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8); p = sbuf; *p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10; if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { *p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } apdu.data = sbuf; apdu.lc = apdu.datalen = (p - sbuf); r=sc_transmit_apdu(card, &apdu); if (r) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Detected Signature-Only key\n"); if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS; } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_restore_security_env(sc_card_t *card, int se_num) { return 0; } static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { size_t i, dlen=datalen; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int tcos3, r; assert(card != NULL && data != NULL && out != NULL); tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); if(((tcos_data *)card->drv_data)->next_sign){ if(datalen>48){ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A); memcpy(sbuf, data, datalen); dlen=datalen; } else { int keylen= tcos3 ? 256 : 128; sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = tcos3 ? 256 : 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) { int keylen=128; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); } if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len = apdu.resplen>outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){ offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset; offset=(offset<len-1) ? offset+1 : 0; } memcpy(out, apdu.resp+offset, len-offset); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the NullPIN method will be activated, otherwise the permanent operation will be done on the active file. */ static int tcos_setperm(sc_card_t *card, int enable_nullpin) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 0; apdu.datalen = 0; apdu.data = NULL; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; if (!serial) return SC_ERROR_INVALID_ARGUMENTS; /* see if we have cached serial number */ if (card->serialnr.len) { memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } card->serialnr.len = sizeof card->serialnr.value; r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0); if (r < 0) { card->serialnr.len = 0; return r; } /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_TCOS_SETPERM: return tcos_setperm(card, !!ptr); case SC_CARDCTL_GET_SERIALNR: return tcos_get_serialnr(card, (sc_serial_number_t *)ptr); } return SC_ERROR_NOT_SUPPORTED; } struct sc_card_driver * sc_get_tcos_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; tcos_ops = *iso_drv->ops; tcos_ops.match_card = tcos_match_card; tcos_ops.init = tcos_init; tcos_ops.finish = tcos_finish; tcos_ops.create_file = tcos_create_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.select_file = tcos_select_file; tcos_ops.list_files = tcos_list_files; tcos_ops.delete_file = tcos_delete_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.compute_signature = tcos_compute_signature; tcos_ops.decipher = tcos_decipher; tcos_ops.restore_security_env = tcos_restore_security_env; tcos_ops.card_ctl = tcos_card_ctl; return &tcos_drv; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_3
crossvul-cpp_data_good_3342_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Support for INET connection oriented protocols. * * Authors: See the TCP sources * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or(at your option) any later version. */ #include <linux/module.h> #include <linux/jhash.h> #include <net/inet_connection_sock.h> #include <net/inet_hashtables.h> #include <net/inet_timewait_sock.h> #include <net/ip.h> #include <net/route.h> #include <net/tcp_states.h> #include <net/xfrm.h> #include <net/tcp.h> #include <net/sock_reuseport.h> #ifdef INET_CSK_DEBUG const char inet_csk_timer_bug_msg[] = "inet_csk BUG: unknown timer value\n"; EXPORT_SYMBOL(inet_csk_timer_bug_msg); #endif #if IS_ENABLED(CONFIG_IPV6) /* match_wildcard == true: IPV6_ADDR_ANY equals to any IPv6 addresses if IPv6 * only, and any IPv4 addresses if not IPv6 only * match_wildcard == false: addresses must be exactly the same, i.e. * IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY, * and 0.0.0.0 equals to 0.0.0.0 only */ static int ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6, const struct in6_addr *sk2_rcv_saddr6, __be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr, bool sk1_ipv6only, bool sk2_ipv6only, bool match_wildcard) { int addr_type = ipv6_addr_type(sk1_rcv_saddr6); int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED; /* if both are mapped, treat as IPv4 */ if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) { if (!sk2_ipv6only) { if (sk1_rcv_saddr == sk2_rcv_saddr) return 1; if (!sk1_rcv_saddr || !sk2_rcv_saddr) return match_wildcard; } return 0; } if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY) return 1; if (addr_type2 == IPV6_ADDR_ANY && match_wildcard && !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED)) return 1; if (addr_type == IPV6_ADDR_ANY && match_wildcard && !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED)) return 1; if (sk2_rcv_saddr6 && ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6)) return 1; return 0; } #endif /* match_wildcard == true: 0.0.0.0 equals to any IPv4 addresses * match_wildcard == false: addresses must be exactly the same, i.e. * 0.0.0.0 only equals to 0.0.0.0 */ static int ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr, bool sk2_ipv6only, bool match_wildcard) { if (!sk2_ipv6only) { if (sk1_rcv_saddr == sk2_rcv_saddr) return 1; if (!sk1_rcv_saddr || !sk2_rcv_saddr) return match_wildcard; } return 0; } int inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2, bool match_wildcard) { #if IS_ENABLED(CONFIG_IPV6) if (sk->sk_family == AF_INET6) return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr, inet6_rcv_saddr(sk2), sk->sk_rcv_saddr, sk2->sk_rcv_saddr, ipv6_only_sock(sk), ipv6_only_sock(sk2), match_wildcard); #endif return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr, ipv6_only_sock(sk2), match_wildcard); } EXPORT_SYMBOL(inet_rcv_saddr_equal); void inet_get_local_port_range(struct net *net, int *low, int *high) { unsigned int seq; do { seq = read_seqbegin(&net->ipv4.ip_local_ports.lock); *low = net->ipv4.ip_local_ports.range[0]; *high = net->ipv4.ip_local_ports.range[1]; } while (read_seqretry(&net->ipv4.ip_local_ports.lock, seq)); } EXPORT_SYMBOL(inet_get_local_port_range); static int inet_csk_bind_conflict(const struct sock *sk, const struct inet_bind_bucket *tb, bool relax, bool reuseport_ok) { struct sock *sk2; bool reuse = sk->sk_reuse; bool reuseport = !!sk->sk_reuseport && reuseport_ok; kuid_t uid = sock_i_uid((struct sock *)sk); /* * Unlike other sk lookup places we do not check * for sk_net here, since _all_ the socks listed * in tb->owners list belong to the same net - the * one this bucket belongs to. */ sk_for_each_bound(sk2, &tb->owners) { if (sk != sk2 && (!sk->sk_bound_dev_if || !sk2->sk_bound_dev_if || sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) { if ((!reuse || !sk2->sk_reuse || sk2->sk_state == TCP_LISTEN) && (!reuseport || !sk2->sk_reuseport || rcu_access_pointer(sk->sk_reuseport_cb) || (sk2->sk_state != TCP_TIME_WAIT && !uid_eq(uid, sock_i_uid(sk2))))) { if (inet_rcv_saddr_equal(sk, sk2, true)) break; } if (!relax && reuse && sk2->sk_reuse && sk2->sk_state != TCP_LISTEN) { if (inet_rcv_saddr_equal(sk, sk2, true)) break; } } } return sk2 != NULL; } /* * Find an open port number for the socket. Returns with the * inet_bind_hashbucket lock held. */ static struct inet_bind_hashbucket * inet_csk_find_open_port(struct sock *sk, struct inet_bind_bucket **tb_ret, int *port_ret) { struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo; int port = 0; struct inet_bind_hashbucket *head; struct net *net = sock_net(sk); int i, low, high, attempt_half; struct inet_bind_bucket *tb; u32 remaining, offset; attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0; other_half_scan: inet_get_local_port_range(net, &low, &high); high++; /* [32768, 60999] -> [32768, 61000[ */ if (high - low < 4) attempt_half = 0; if (attempt_half) { int half = low + (((high - low) >> 2) << 1); if (attempt_half == 1) high = half; else low = half; } remaining = high - low; if (likely(remaining > 1)) remaining &= ~1U; offset = prandom_u32() % remaining; /* __inet_hash_connect() favors ports having @low parity * We do the opposite to not pollute connect() users. */ offset |= 1U; other_parity_scan: port = low + offset; for (i = 0; i < remaining; i += 2, port += 2) { if (unlikely(port >= high)) port -= remaining; if (inet_is_local_reserved_port(net, port)) continue; head = &hinfo->bhash[inet_bhashfn(net, port, hinfo->bhash_size)]; spin_lock_bh(&head->lock); inet_bind_bucket_for_each(tb, &head->chain) if (net_eq(ib_net(tb), net) && tb->port == port) { if (!inet_csk_bind_conflict(sk, tb, false, false)) goto success; goto next_port; } tb = NULL; goto success; next_port: spin_unlock_bh(&head->lock); cond_resched(); } offset--; if (!(offset & 1)) goto other_parity_scan; if (attempt_half == 1) { /* OK we now try the upper half of the range */ attempt_half = 2; goto other_half_scan; } return NULL; success: *port_ret = port; *tb_ret = tb; return head; } static inline int sk_reuseport_match(struct inet_bind_bucket *tb, struct sock *sk) { kuid_t uid = sock_i_uid(sk); if (tb->fastreuseport <= 0) return 0; if (!sk->sk_reuseport) return 0; if (rcu_access_pointer(sk->sk_reuseport_cb)) return 0; if (!uid_eq(tb->fastuid, uid)) return 0; /* We only need to check the rcv_saddr if this tb was once marked * without fastreuseport and then was reset, as we can only know that * the fast_*rcv_saddr doesn't have any conflicts with the socks on the * owners list. */ if (tb->fastreuseport == FASTREUSEPORT_ANY) return 1; #if IS_ENABLED(CONFIG_IPV6) if (tb->fast_sk_family == AF_INET6) return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr, &sk->sk_v6_rcv_saddr, tb->fast_rcv_saddr, sk->sk_rcv_saddr, tb->fast_ipv6_only, ipv6_only_sock(sk), true); #endif return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr, ipv6_only_sock(sk), true); } /* Obtain a reference to a local port for the given sock, * if snum is zero it means select any available local port. * We try to allocate an odd port (and leave even ports for connect()) */ int inet_csk_get_port(struct sock *sk, unsigned short snum) { bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN; struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo; int ret = 1, port = snum; struct inet_bind_hashbucket *head; struct net *net = sock_net(sk); struct inet_bind_bucket *tb = NULL; kuid_t uid = sock_i_uid(sk); if (!port) { head = inet_csk_find_open_port(sk, &tb, &port); if (!head) return ret; if (!tb) goto tb_not_found; goto success; } head = &hinfo->bhash[inet_bhashfn(net, port, hinfo->bhash_size)]; spin_lock_bh(&head->lock); inet_bind_bucket_for_each(tb, &head->chain) if (net_eq(ib_net(tb), net) && tb->port == port) goto tb_found; tb_not_found: tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep, net, head, port); if (!tb) goto fail_unlock; tb_found: if (!hlist_empty(&tb->owners)) { if (sk->sk_reuse == SK_FORCE_REUSE) goto success; if ((tb->fastreuse > 0 && reuse) || sk_reuseport_match(tb, sk)) goto success; if (inet_csk_bind_conflict(sk, tb, true, true)) goto fail_unlock; } success: if (!hlist_empty(&tb->owners)) { tb->fastreuse = reuse; if (sk->sk_reuseport) { tb->fastreuseport = FASTREUSEPORT_ANY; tb->fastuid = uid; tb->fast_rcv_saddr = sk->sk_rcv_saddr; tb->fast_ipv6_only = ipv6_only_sock(sk); #if IS_ENABLED(CONFIG_IPV6) tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr; #endif } else { tb->fastreuseport = 0; } } else { if (!reuse) tb->fastreuse = 0; if (sk->sk_reuseport) { /* We didn't match or we don't have fastreuseport set on * the tb, but we have sk_reuseport set on this socket * and we know that there are no bind conflicts with * this socket in this tb, so reset our tb's reuseport * settings so that any subsequent sockets that match * our current socket will be put on the fast path. * * If we reset we need to set FASTREUSEPORT_STRICT so we * do extra checking for all subsequent sk_reuseport * socks. */ if (!sk_reuseport_match(tb, sk)) { tb->fastreuseport = FASTREUSEPORT_STRICT; tb->fastuid = uid; tb->fast_rcv_saddr = sk->sk_rcv_saddr; tb->fast_ipv6_only = ipv6_only_sock(sk); #if IS_ENABLED(CONFIG_IPV6) tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr; #endif } } else { tb->fastreuseport = 0; } } if (!inet_csk(sk)->icsk_bind_hash) inet_bind_hash(sk, tb, port); WARN_ON(inet_csk(sk)->icsk_bind_hash != tb); ret = 0; fail_unlock: spin_unlock_bh(&head->lock); return ret; } EXPORT_SYMBOL_GPL(inet_csk_get_port); /* * Wait for an incoming connection, avoid race conditions. This must be called * with the socket locked. */ static int inet_csk_wait_for_connect(struct sock *sk, long timeo) { struct inet_connection_sock *icsk = inet_csk(sk); DEFINE_WAIT(wait); int err; /* * True wake-one mechanism for incoming connections: only * one process gets woken up, not the 'whole herd'. * Since we do not 'race & poll' for established sockets * anymore, the common case will execute the loop only once. * * Subtle issue: "add_wait_queue_exclusive()" will be added * after any current non-exclusive waiters, and we know that * it will always _stay_ after any new non-exclusive waiters * because all non-exclusive waiters are added at the * beginning of the wait-queue. As such, it's ok to "drop" * our exclusiveness temporarily when we get woken up without * having to remove and re-insert us on the wait queue. */ for (;;) { prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); release_sock(sk); if (reqsk_queue_empty(&icsk->icsk_accept_queue)) timeo = schedule_timeout(timeo); sched_annotate_sleep(); lock_sock(sk); err = 0; if (!reqsk_queue_empty(&icsk->icsk_accept_queue)) break; err = -EINVAL; if (sk->sk_state != TCP_LISTEN) break; err = sock_intr_errno(timeo); if (signal_pending(current)) break; err = -EAGAIN; if (!timeo) break; } finish_wait(sk_sleep(sk), &wait); return err; } /* * This will accept the next outstanding connection. */ struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern) { struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; struct request_sock *req; struct sock *newsk; int error; lock_sock(sk); /* We need to make sure that this socket is listening, * and that it has something pending. */ error = -EINVAL; if (sk->sk_state != TCP_LISTEN) goto out_err; /* Find already established connection */ if (reqsk_queue_empty(queue)) { long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); /* If this is a non blocking socket don't sleep */ error = -EAGAIN; if (!timeo) goto out_err; error = inet_csk_wait_for_connect(sk, timeo); if (error) goto out_err; } req = reqsk_queue_remove(queue, sk); newsk = req->sk; if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) { spin_lock_bh(&queue->fastopenq.lock); if (tcp_rsk(req)->tfo_listener) { /* We are still waiting for the final ACK from 3WHS * so can't free req now. Instead, we set req->sk to * NULL to signify that the child socket is taken * so reqsk_fastopen_remove() will free the req * when 3WHS finishes (or is aborted). */ req->sk = NULL; req = NULL; } spin_unlock_bh(&queue->fastopenq.lock); } out: release_sock(sk); if (req) reqsk_put(req); return newsk; out_err: newsk = NULL; req = NULL; *err = error; goto out; } EXPORT_SYMBOL(inet_csk_accept); /* * Using different timers for retransmit, delayed acks and probes * We may wish use just one timer maintaining a list of expire jiffies * to optimize. */ void inet_csk_init_xmit_timers(struct sock *sk, void (*retransmit_handler)(unsigned long), void (*delack_handler)(unsigned long), void (*keepalive_handler)(unsigned long)) { struct inet_connection_sock *icsk = inet_csk(sk); setup_timer(&icsk->icsk_retransmit_timer, retransmit_handler, (unsigned long)sk); setup_timer(&icsk->icsk_delack_timer, delack_handler, (unsigned long)sk); setup_timer(&sk->sk_timer, keepalive_handler, (unsigned long)sk); icsk->icsk_pending = icsk->icsk_ack.pending = 0; } EXPORT_SYMBOL(inet_csk_init_xmit_timers); void inet_csk_clear_xmit_timers(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0; sk_stop_timer(sk, &icsk->icsk_retransmit_timer); sk_stop_timer(sk, &icsk->icsk_delack_timer); sk_stop_timer(sk, &sk->sk_timer); } EXPORT_SYMBOL(inet_csk_clear_xmit_timers); void inet_csk_delete_keepalive_timer(struct sock *sk) { sk_stop_timer(sk, &sk->sk_timer); } EXPORT_SYMBOL(inet_csk_delete_keepalive_timer); void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len) { sk_reset_timer(sk, &sk->sk_timer, jiffies + len); } EXPORT_SYMBOL(inet_csk_reset_keepalive_timer); struct dst_entry *inet_csk_route_req(const struct sock *sk, struct flowi4 *fl4, const struct request_sock *req) { const struct inet_request_sock *ireq = inet_rsk(req); struct net *net = read_pnet(&ireq->ireq_net); struct ip_options_rcu *opt = ireq->opt; struct rtable *rt; flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr, ireq->ir_loc_addr, ireq->ir_rmt_port, htons(ireq->ir_num), sk->sk_uid); security_req_classify_flow(req, flowi4_to_flowi(fl4)); rt = ip_route_output_flow(net, fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway) goto route_err; return &rt->dst; route_err: ip_rt_put(rt); no_route: __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES); return NULL; } EXPORT_SYMBOL_GPL(inet_csk_route_req); struct dst_entry *inet_csk_route_child_sock(const struct sock *sk, struct sock *newsk, const struct request_sock *req) { const struct inet_request_sock *ireq = inet_rsk(req); struct net *net = read_pnet(&ireq->ireq_net); struct inet_sock *newinet = inet_sk(newsk); struct ip_options_rcu *opt; struct flowi4 *fl4; struct rtable *rt; fl4 = &newinet->cork.fl.u.ip4; rcu_read_lock(); opt = rcu_dereference(newinet->inet_opt); flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr, ireq->ir_loc_addr, ireq->ir_rmt_port, htons(ireq->ir_num), sk->sk_uid); security_req_classify_flow(req, flowi4_to_flowi(fl4)); rt = ip_route_output_flow(net, fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway) goto route_err; rcu_read_unlock(); return &rt->dst; route_err: ip_rt_put(rt); no_route: rcu_read_unlock(); __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES); return NULL; } EXPORT_SYMBOL_GPL(inet_csk_route_child_sock); #if IS_ENABLED(CONFIG_IPV6) #define AF_INET_FAMILY(fam) ((fam) == AF_INET) #else #define AF_INET_FAMILY(fam) true #endif /* Decide when to expire the request and when to resend SYN-ACK */ static inline void syn_ack_recalc(struct request_sock *req, const int thresh, const int max_retries, const u8 rskq_defer_accept, int *expire, int *resend) { if (!rskq_defer_accept) { *expire = req->num_timeout >= thresh; *resend = 1; return; } *expire = req->num_timeout >= thresh && (!inet_rsk(req)->acked || req->num_timeout >= max_retries); /* * Do not resend while waiting for data after ACK, * start to resend on end of deferring period to give * last chance for data or ACK to create established socket. */ *resend = !inet_rsk(req)->acked || req->num_timeout >= rskq_defer_accept - 1; } int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req) { int err = req->rsk_ops->rtx_syn_ack(parent, req); if (!err) req->num_retrans++; return err; } EXPORT_SYMBOL(inet_rtx_syn_ack); /* return true if req was found in the ehash table */ static bool reqsk_queue_unlink(struct request_sock_queue *queue, struct request_sock *req) { struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo; bool found = false; if (sk_hashed(req_to_sk(req))) { spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash); spin_lock(lock); found = __sk_nulls_del_node_init_rcu(req_to_sk(req)); spin_unlock(lock); } if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer)) reqsk_put(req); return found; } void inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req) { if (reqsk_queue_unlink(&inet_csk(sk)->icsk_accept_queue, req)) { reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req); reqsk_put(req); } } EXPORT_SYMBOL(inet_csk_reqsk_queue_drop); void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req) { inet_csk_reqsk_queue_drop(sk, req); reqsk_put(req); } EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put); static void reqsk_timer_handler(unsigned long data) { struct request_sock *req = (struct request_sock *)data; struct sock *sk_listener = req->rsk_listener; struct net *net = sock_net(sk_listener); struct inet_connection_sock *icsk = inet_csk(sk_listener); struct request_sock_queue *queue = &icsk->icsk_accept_queue; int qlen, expire = 0, resend = 0; int max_retries, thresh; u8 defer_accept; if (sk_state_load(sk_listener) != TCP_LISTEN) goto drop; max_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries; thresh = max_retries; /* Normally all the openreqs are young and become mature * (i.e. converted to established socket) for first timeout. * If synack was not acknowledged for 1 second, it means * one of the following things: synack was lost, ack was lost, * rtt is high or nobody planned to ack (i.e. synflood). * When server is a bit loaded, queue is populated with old * open requests, reducing effective size of queue. * When server is well loaded, queue size reduces to zero * after several minutes of work. It is not synflood, * it is normal operation. The solution is pruning * too old entries overriding normal timeout, when * situation becomes dangerous. * * Essentially, we reserve half of room for young * embrions; and abort old ones without pity, if old * ones are about to clog our table. */ qlen = reqsk_queue_len(queue); if ((qlen << 1) > max(8U, sk_listener->sk_max_ack_backlog)) { int young = reqsk_queue_len_young(queue) << 1; while (thresh > 2) { if (qlen < young) break; thresh--; young <<= 1; } } defer_accept = READ_ONCE(queue->rskq_defer_accept); if (defer_accept) max_retries = defer_accept; syn_ack_recalc(req, thresh, max_retries, defer_accept, &expire, &resend); req->rsk_ops->syn_ack_timeout(req); if (!expire && (!resend || !inet_rtx_syn_ack(sk_listener, req) || inet_rsk(req)->acked)) { unsigned long timeo; if (req->num_timeout++ == 0) atomic_dec(&queue->young); timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX); mod_timer(&req->rsk_timer, jiffies + timeo); return; } drop: inet_csk_reqsk_queue_drop_and_put(sk_listener, req); } static void reqsk_queue_hash_req(struct request_sock *req, unsigned long timeout) { req->num_retrans = 0; req->num_timeout = 0; req->sk = NULL; setup_pinned_timer(&req->rsk_timer, reqsk_timer_handler, (unsigned long)req); mod_timer(&req->rsk_timer, jiffies + timeout); inet_ehash_insert(req_to_sk(req), NULL); /* before letting lookups find us, make sure all req fields * are committed to memory and refcnt initialized. */ smp_wmb(); atomic_set(&req->rsk_refcnt, 2 + 1); } void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req, unsigned long timeout) { reqsk_queue_hash_req(req, timeout); inet_csk_reqsk_queue_added(sk); } EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add); /** * inet_csk_clone_lock - clone an inet socket, and lock its clone * @sk: the socket to clone * @req: request_sock * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc) * * Caller must unlock socket even in error path (bh_unlock_sock(newsk)) */ struct sock *inet_csk_clone_lock(const struct sock *sk, const struct request_sock *req, const gfp_t priority) { struct sock *newsk = sk_clone_lock(sk, priority); if (newsk) { struct inet_connection_sock *newicsk = inet_csk(newsk); newsk->sk_state = TCP_SYN_RECV; newicsk->icsk_bind_hash = NULL; inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port; inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num; inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num); newsk->sk_write_space = sk_stream_write_space; /* listeners have SOCK_RCU_FREE, not the children */ sock_reset_flag(newsk, SOCK_RCU_FREE); inet_sk(newsk)->mc_list = NULL; newsk->sk_mark = inet_rsk(req)->ir_mark; atomic64_set(&newsk->sk_cookie, atomic64_read(&inet_rsk(req)->ir_cookie)); newicsk->icsk_retransmits = 0; newicsk->icsk_backoff = 0; newicsk->icsk_probes_out = 0; /* Deinitialize accept_queue to trap illegal accesses. */ memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue)); security_inet_csk_clone(newsk, req); } return newsk; } EXPORT_SYMBOL_GPL(inet_csk_clone_lock); /* * At this point, there should be no process reference to this * socket, and thus no user references at all. Therefore we * can assume the socket waitqueue is inactive and nobody will * try to jump onto it. */ void inet_csk_destroy_sock(struct sock *sk) { WARN_ON(sk->sk_state != TCP_CLOSE); WARN_ON(!sock_flag(sk, SOCK_DEAD)); /* It cannot be in hash table! */ WARN_ON(!sk_unhashed(sk)); /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */ WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash); sk->sk_prot->destroy(sk); sk_stream_kill_queues(sk); xfrm_sk_free_policy(sk); sk_refcnt_debug_release(sk); percpu_counter_dec(sk->sk_prot->orphan_count); sock_put(sk); } EXPORT_SYMBOL(inet_csk_destroy_sock); /* This function allows to force a closure of a socket after the call to * tcp/dccp_create_openreq_child(). */ void inet_csk_prepare_forced_close(struct sock *sk) __releases(&sk->sk_lock.slock) { /* sk_clone_lock locked the socket and set refcnt to 2 */ bh_unlock_sock(sk); sock_put(sk); /* The below has to be done to allow calling inet_csk_destroy_sock */ sock_set_flag(sk, SOCK_DEAD); percpu_counter_inc(sk->sk_prot->orphan_count); inet_sk(sk)->inet_num = 0; } EXPORT_SYMBOL(inet_csk_prepare_forced_close); int inet_csk_listen_start(struct sock *sk, int backlog) { struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet = inet_sk(sk); int err = -EADDRINUSE; reqsk_queue_alloc(&icsk->icsk_accept_queue); sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; inet_csk_delack_init(sk); /* There is race window here: we announce ourselves listening, * but this transition is still not validated by get_port(). * It is OK, because this socket enters to hash table only * after validation is complete. */ sk_state_store(sk, TCP_LISTEN); if (!sk->sk_prot->get_port(sk, inet->inet_num)) { inet->inet_sport = htons(inet->inet_num); sk_dst_reset(sk); err = sk->sk_prot->hash(sk); if (likely(!err)) return 0; } sk->sk_state = TCP_CLOSE; return err; } EXPORT_SYMBOL_GPL(inet_csk_listen_start); static void inet_child_forget(struct sock *sk, struct request_sock *req, struct sock *child) { sk->sk_prot->disconnect(child, O_NONBLOCK); sock_orphan(child); percpu_counter_inc(sk->sk_prot->orphan_count); if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) { BUG_ON(tcp_sk(child)->fastopen_rsk != req); BUG_ON(sk != req->rsk_listener); /* Paranoid, to prevent race condition if * an inbound pkt destined for child is * blocked by sock lock in tcp_v4_rcv(). * Also to satisfy an assertion in * tcp_v4_destroy_sock(). */ tcp_sk(child)->fastopen_rsk = NULL; } inet_csk_destroy_sock(child); reqsk_put(req); } struct sock *inet_csk_reqsk_queue_add(struct sock *sk, struct request_sock *req, struct sock *child) { struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue; spin_lock(&queue->rskq_lock); if (unlikely(sk->sk_state != TCP_LISTEN)) { inet_child_forget(sk, req, child); child = NULL; } else { req->sk = child; req->dl_next = NULL; if (queue->rskq_accept_head == NULL) queue->rskq_accept_head = req; else queue->rskq_accept_tail->dl_next = req; queue->rskq_accept_tail = req; sk_acceptq_added(sk); } spin_unlock(&queue->rskq_lock); return child; } EXPORT_SYMBOL(inet_csk_reqsk_queue_add); struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child, struct request_sock *req, bool own_req) { if (own_req) { inet_csk_reqsk_queue_drop(sk, req); reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req); if (inet_csk_reqsk_queue_add(sk, req, child)) return child; } /* Too bad, another child took ownership of the request, undo. */ bh_unlock_sock(child); sock_put(child); return NULL; } EXPORT_SYMBOL(inet_csk_complete_hashdance); /* * This routine closes sockets which have been at least partially * opened, but not yet accepted. */ void inet_csk_listen_stop(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; struct request_sock *next, *req; /* Following specs, it would be better either to send FIN * (and enter FIN-WAIT-1, it is normal close) * or to send active reset (abort). * Certainly, it is pretty dangerous while synflood, but it is * bad justification for our negligence 8) * To be honest, we are not able to make either * of the variants now. --ANK */ while ((req = reqsk_queue_remove(queue, sk)) != NULL) { struct sock *child = req->sk; local_bh_disable(); bh_lock_sock(child); WARN_ON(sock_owned_by_user(child)); sock_hold(child); inet_child_forget(sk, req, child); bh_unlock_sock(child); local_bh_enable(); sock_put(child); cond_resched(); } if (queue->fastopenq.rskq_rst_head) { /* Free all the reqs queued in rskq_rst_head. */ spin_lock_bh(&queue->fastopenq.lock); req = queue->fastopenq.rskq_rst_head; queue->fastopenq.rskq_rst_head = NULL; spin_unlock_bh(&queue->fastopenq.lock); while (req != NULL) { next = req->dl_next; reqsk_put(req); req = next; } } WARN_ON_ONCE(sk->sk_ack_backlog); } EXPORT_SYMBOL_GPL(inet_csk_listen_stop); void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr) { struct sockaddr_in *sin = (struct sockaddr_in *)uaddr; const struct inet_sock *inet = inet_sk(sk); sin->sin_family = AF_INET; sin->sin_addr.s_addr = inet->inet_daddr; sin->sin_port = inet->inet_dport; } EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr); #ifdef CONFIG_COMPAT int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { const struct inet_connection_sock *icsk = inet_csk(sk); if (icsk->icsk_af_ops->compat_getsockopt) return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname, optval, optlen); return icsk->icsk_af_ops->getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt); int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { const struct inet_connection_sock *icsk = inet_csk(sk); if (icsk->icsk_af_ops->compat_setsockopt) return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname, optval, optlen); return icsk->icsk_af_ops->setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt); #endif static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; struct flowi4 *fl4; struct rtable *rt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; fl4 = &fl->u.ip4; rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (IS_ERR(rt)) rt = NULL; if (rt) sk_setup_caps(sk, &rt->dst); rcu_read_unlock(); return &rt->dst; } struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu) { struct dst_entry *dst = __sk_dst_check(sk, 0); struct inet_sock *inet = inet_sk(sk); if (!dst) { dst = inet_csk_rebuild_route(sk, &inet->cork.fl); if (!dst) goto out; } dst->ops->update_pmtu(dst, sk, NULL, mtu); dst = __sk_dst_check(sk, 0); if (!dst) dst = inet_csk_rebuild_route(sk, &inet->cork.fl); out: return dst; } EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);
./CrossVul/dataset_final_sorted/CWE-415/c/good_3342_0
crossvul-cpp_data_bad_349_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid= fs->cache.array[x].objectId.id; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count+=2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_349_2
crossvul-cpp_data_bad_347_4
/* * PKCS15 emulation layer for EstEID card. * * Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net> * Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "internal.h" #include "opensc.h" #include "pkcs15.h" #include "esteid.h" int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *); static void set_string (char **strp, const char *value) { if (*strp) free (*strp); *strp = value ? strdup (value) : NULL; } int select_esteid_df (sc_card_t * card) { int r; sc_path_t tmppath; sc_format_path ("3F00EEEE", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed"); return r; } static int sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[r] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } static int esteid_detect_card(sc_pkcs15_card_t *p15card) { if (is_esteid_card(p15card->card)) return SC_SUCCESS; else return SC_ERROR_WRONG_CARD; } int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_esteid_init(p15card); else { int r = esteid_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_esteid_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_347_4
crossvul-cpp_data_good_349_10
/* * util.c: utility functions used by OpenSC command line tools. * * Copyright (C) 2011 OpenSC Project developers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifndef _WIN32 #include <termios.h> #else #include <conio.h> #endif #include <ctype.h> #include "util.h" #include "ui/notify.h" int is_string_valid_atr(const char *atr_str) { unsigned char atr[SC_MAX_ATR_SIZE]; size_t atr_len = sizeof(atr); if (sc_hex_to_bin(atr_str, atr, &atr_len)) return 0; if (atr_len < 2) return 0; if (atr[0] != 0x3B && atr[0] != 0x3F) return 0; return 1; } int util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int do_lock, int verbose) { struct sc_reader *reader = NULL, *found = NULL; struct sc_card *card = NULL; int r; sc_notify_init(); if (do_wait) { unsigned int event; if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "Waiting for a reader to be attached...\n"); r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r)); return 3; } r = sc_ctx_detect_readers(ctx); if (r < 0) { fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r)); return 3; } } fprintf(stderr, "Waiting for a card to be inserted...\n"); r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r)); return 3; } reader = found; } else if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "No smart card readers found.\n"); return 1; } else { if (!reader_id) { unsigned int i; /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { reader = sc_ctx_get_reader(ctx, i); if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) { fprintf(stderr, "Using reader with a card: %s\n", reader->name); goto autofound; } } /* If no reader had a card, default to the first reader */ reader = sc_ctx_get_reader(ctx, 0); } else { /* If the reader identifier looks like an ATR, try to find the reader with that card */ if (is_string_valid_atr(reader_id)) { unsigned char atr_buf[SC_MAX_ATR_SIZE]; size_t atr_buf_len = sizeof(atr_buf); unsigned int i; sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len); /* Loop readers, looking for a card with ATR */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { struct sc_reader *rdr = sc_ctx_get_reader(ctx, i); if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT)) continue; else if (rdr->atr.len != atr_buf_len) continue; else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len)) continue; fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name); reader = rdr; goto autofound; } } else { char *endptr = NULL; unsigned int num; errno = 0; num = strtol(reader_id, &endptr, 0); if (!errno && endptr && *endptr == '\0') reader = sc_ctx_get_reader(ctx, num); else reader = sc_ctx_get_reader_by_name(ctx, reader_id); } } autofound: if (!reader) { fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n", reader_id, sc_ctx_get_reader_count(ctx)); return 1; } if (sc_detect_card_presence(reader) <= 0) { fprintf(stderr, "Card not present.\n"); return 3; } } if (verbose) printf("Connecting to card in reader %s...\n", reader->name); r = sc_connect_card(reader, &card); if (r < 0) { fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Using card driver %s.\n", card->driver->name); if (do_lock) { r = sc_lock(card); if (r < 0) { fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r)); sc_disconnect_card(card); return 1; } } *cardp = card; return 0; } int util_connect_card(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int verbose) { return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose); } void util_print_binary(FILE *f, const u8 *buf, int count) { int i; for (i = 0; i < count; i++) { unsigned char c = buf[i]; const char *format; if (!isprint(c)) format = "\\x%02X"; else format = "%c"; fprintf(f, format, c); } (void) fflush(f); } void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep) { int i; for (i = 0; i < len; i++) { if (sep != NULL && i) fprintf(f, "%s", sep); fprintf(f, "%02X", in[i]); } } void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr) { int lines = 0; while (count) { char ascbuf[17]; size_t i; if (addr >= 0) { fprintf(f, "%08X: ", addr); addr += 16; } for (i = 0; i < count && i < 16; i++) { fprintf(f, "%02X ", *in); if (isprint(*in)) ascbuf[i] = *in; else ascbuf[i] = '.'; in++; } count -= i; ascbuf[i] = 0; for (; i < 16 && lines; i++) fprintf(f, " "); fprintf(f, "%s\n", ascbuf); lines++; } } NORETURN void util_print_usage_and_die(const char *app_name, const struct option options[], const char *option_help[], const char *args) { int i; int header_shown = 0; if (args) printf("Usage: %s [OPTIONS] %s\n", app_name, args); else printf("Usage: %s [OPTIONS]\n", app_name); for (i = 0; options[i].name; i++) { char buf[40]; const char *arg_str; /* Skip "hidden" options */ if (option_help[i] == NULL) continue; if (!header_shown++) printf("Options:\n"); switch (options[i].has_arg) { case 1: arg_str = " <arg>"; break; case 2: arg_str = " [arg]"; break; default: arg_str = ""; break; } if (isascii(options[i].val) && isprint(options[i].val) && !isspace(options[i].val)) sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str); else sprintf(buf, " --%s%s", options[i].name, arg_str); /* print the line - wrap if necessary */ if (strlen(buf) > 28) { printf(" %s\n", buf); buf[0] = '\0'; } printf(" %-28s %s\n", buf, option_help[i]); } exit(2); } const char * util_acl_to_str(const sc_acl_entry_t *e) { static char line[80], buf[20]; unsigned int acl; if (e == NULL) return "N/A"; line[0] = 0; while (e != NULL) { acl = e->method; switch (acl) { case SC_AC_UNKNOWN: return "N/A"; case SC_AC_NEVER: return "NEVR"; case SC_AC_NONE: return "NONE"; case SC_AC_CHV: strcpy(buf, "CHV"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "%d", e->key_ref); break; case SC_AC_TERM: strcpy(buf, "TERM"); break; case SC_AC_PRO: strcpy(buf, "PROT"); break; case SC_AC_AUT: strcpy(buf, "AUTH"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 4, "%d", e->key_ref); break; case SC_AC_SEN: strcpy(buf, "Sec.Env. "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; case SC_AC_SCB: strcpy(buf, "Sec.ControlByte "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "Ox%X", e->key_ref); break; case SC_AC_IDA: strcpy(buf, "PKCS#15 AuthID "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; default: strcpy(buf, "????"); break; } strncat(line, buf, sizeof line); strncat(line, " ", sizeof line); e = e->next; } line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */ line[strlen(line)-1] = 0; /* get rid of trailing space */ return line; } NORETURN void util_fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\nAborting.\n"); va_end(ap); sc_notify_close(); exit(1); } void util_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void util_warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "warning: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } int util_getpass (char **lineptr, size_t *len, FILE *stream) { #define MAX_PASS_SIZE 128 char *buf; size_t i; int ch = 0; #ifndef _WIN32 struct termios old, new; fflush(stdout); if (tcgetattr (fileno (stdout), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0) return -1; #endif buf = calloc(1, MAX_PASS_SIZE); if (!buf) return -1; for (i = 0; i < MAX_PASS_SIZE - 1; i++) { #ifndef _WIN32 ch = getchar(); #else ch = _getch(); #endif if (ch == 0 || ch == 3) break; if (ch == '\n' || ch == '\r') break; buf[i] = (char) ch; } #ifndef _WIN32 tcsetattr (fileno (stdout), TCSAFLUSH, &old); fputs("\n", stdout); #endif if (ch == 0 || ch == 3) { free(buf); return -1; } if (*lineptr && (!len || *len < i+1)) { free(*lineptr); *lineptr = NULL; } if (*lineptr) { memcpy(*lineptr,buf,i+1); memset(buf, 0, MAX_PASS_SIZE); free(buf); } else { *lineptr = buf; if (len) *len = MAX_PASS_SIZE; } return i; } size_t util_get_pin(const char *input, const char **pin) { size_t inputlen = strlen(input); size_t pinlen = 0; if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) { // Get a PIN from a environment variable *pin = getenv(input + 4); pinlen = *pin ? strlen(*pin) : 0; } else { //Just use the input *pin = input; pinlen = inputlen; } return pinlen; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_10
crossvul-cpp_data_bad_745_0
#include "osxkeychain_darwin.h" #include <CoreFoundation/CoreFoundation.h> #include <Foundation/NSValue.h> #include <stdio.h> #include <string.h> char *get_error(OSStatus status) { char *buf = malloc(128); CFStringRef str = SecCopyErrorMessageString(status, NULL); int success = CFStringGetCString(str, buf, 128, kCFStringEncodingUTF8); if (!success) { strncpy(buf, "Unknown error", 128); } return buf; } char *keychain_add(struct Server *server, char *label, char *username, char *secret) { SecKeychainItemRef item; OSStatus status = SecKeychainAddInternetPassword( NULL, strlen(server->host), server->host, 0, NULL, strlen(username), username, strlen(server->path), server->path, server->port, server->proto, kSecAuthenticationTypeDefault, strlen(secret), secret, &item ); if (status) { return get_error(status); } SecKeychainAttribute attribute; SecKeychainAttributeList attrs; attribute.tag = kSecLabelItemAttr; attribute.data = label; attribute.length = strlen(label); attrs.count = 1; attrs.attr = &attribute; status = SecKeychainItemModifyContent(item, &attrs, 0, NULL); if (status) { return get_error(status); } return NULL; } char *keychain_get(struct Server *server, unsigned int *username_l, char **username, unsigned int *secret_l, char **secret) { char *tmp; SecKeychainItemRef item; OSStatus status = SecKeychainFindInternetPassword( NULL, strlen(server->host), server->host, 0, NULL, 0, NULL, strlen(server->path), server->path, server->port, server->proto, kSecAuthenticationTypeDefault, secret_l, (void **)&tmp, &item); if (status) { return get_error(status); } *secret = strdup(tmp); SecKeychainItemFreeContent(NULL, tmp); SecKeychainAttributeList list; SecKeychainAttribute attr; list.count = 1; list.attr = &attr; attr.tag = kSecAccountItemAttr; status = SecKeychainItemCopyContent(item, NULL, &list, NULL, NULL); if (status) { return get_error(status); } *username = strdup(attr.data); *username_l = attr.length; SecKeychainItemFreeContent(&list, NULL); return NULL; } char *keychain_delete(struct Server *server) { SecKeychainItemRef item; OSStatus status = SecKeychainFindInternetPassword( NULL, strlen(server->host), server->host, 0, NULL, 0, NULL, strlen(server->path), server->path, server->port, server->proto, kSecAuthenticationTypeDefault, 0, NULL, &item); if (status) { return get_error(status); } status = SecKeychainItemDelete(item); if (status) { return get_error(status); } return NULL; } char * CFStringToCharArr(CFStringRef aString) { if (aString == NULL) { return NULL; } CFIndex length = CFStringGetLength(aString); CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char *buffer = (char *)malloc(maxSize); if (CFStringGetCString(aString, buffer, maxSize, kCFStringEncodingUTF8)) { return buffer; } return NULL; } char *keychain_list(char *credsLabel, char *** paths, char *** accts, unsigned int *list_l) { CFStringRef credsLabelCF = CFStringCreateWithCString(NULL, credsLabel, kCFStringEncodingUTF8); CFMutableDictionaryRef query = CFDictionaryCreateMutable (NULL, 1, NULL, NULL); CFDictionaryAddValue(query, kSecClass, kSecClassInternetPassword); CFDictionaryAddValue(query, kSecReturnAttributes, kCFBooleanTrue); CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitAll); CFDictionaryAddValue(query, kSecAttrLabel, credsLabelCF); //Use this query dictionary CFTypeRef result= NULL; OSStatus status = SecItemCopyMatching( query, &result); CFRelease(credsLabelCF); //Ran a search and store the results in result if (status) { return get_error(status); } CFIndex numKeys = CFArrayGetCount(result); *paths = (char **) malloc((int)sizeof(char *)*numKeys); *accts = (char **) malloc((int)sizeof(char *)*numKeys); //result is of type CFArray for(CFIndex i=0; i<numKeys; i++) { CFDictionaryRef currKey = CFArrayGetValueAtIndex(result,i); CFStringRef protocolTmp = CFDictionaryGetValue(currKey, CFSTR("ptcl")); if (protocolTmp != NULL) { CFStringRef protocolStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), protocolTmp); if (CFStringCompare(protocolStr, CFSTR("htps"), 0) == kCFCompareEqualTo) { protocolTmp = CFSTR("https://"); } else { protocolTmp = CFSTR("http://"); } CFRelease(protocolStr); } else { char * path = "0"; char * acct = "0"; (*paths)[i] = (char *) malloc(sizeof(char)*(strlen(path))); memcpy((*paths)[i], path, sizeof(char)*(strlen(path))); (*accts)[i] = (char *) malloc(sizeof(char)*(strlen(acct))); memcpy((*accts)[i], acct, sizeof(char)*(strlen(acct))); continue; } CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 0, protocolTmp); CFStringRef serverTmp = CFDictionaryGetValue(currKey, CFSTR("srvr")); if (serverTmp != NULL) { CFStringAppend(str, serverTmp); } CFStringRef pathTmp = CFDictionaryGetValue(currKey, CFSTR("path")); if (pathTmp != NULL) { CFStringAppend(str, pathTmp); } const NSNumber * portTmp = CFDictionaryGetValue(currKey, CFSTR("port")); if (portTmp != NULL && portTmp.integerValue != 0) { CFStringRef portStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), portTmp); CFStringAppend(str, CFSTR(":")); CFStringAppend(str, portStr); CFRelease(portStr); } CFStringRef acctTmp = CFDictionaryGetValue(currKey, CFSTR("acct")); if (acctTmp == NULL) { acctTmp = CFSTR("account not defined"); } char * path = CFStringToCharArr(str); char * acct = CFStringToCharArr(acctTmp); //We now have all we need, username and servername. Now export this to .go (*paths)[i] = (char *) malloc(sizeof(char)*(strlen(path)+1)); memcpy((*paths)[i], path, sizeof(char)*(strlen(path)+1)); (*accts)[i] = (char *) malloc(sizeof(char)*(strlen(acct)+1)); memcpy((*accts)[i], acct, sizeof(char)*(strlen(acct)+1)); CFRelease(str); } *list_l = (int)numKeys; return NULL; } void freeListData(char *** data, unsigned int length) { for(int i=0; i<length; i++) { free((*data)[i]); } free(*data); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_745_0
crossvul-cpp_data_good_347_4
/* * PKCS15 emulation layer for EstEID card. * * Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net> * Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "internal.h" #include "opensc.h" #include "pkcs15.h" #include "esteid.h" int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *); static void set_string (char **strp, const char *value) { if (*strp) free (*strp); *strp = value ? strdup (value) : NULL; } int select_esteid_df (sc_card_t * card) { int r; sc_path_t tmppath; sc_format_path ("3F00EEEE", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed"); return r; } static int sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[MIN((size_t) r, (sizeof buff)-1)] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } static int esteid_detect_card(sc_pkcs15_card_t *p15card) { if (is_esteid_card(p15card->card)) return SC_SUCCESS; else return SC_ERROR_WRONG_CARD; } int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_esteid_init(p15card); else { int r = esteid_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_esteid_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_4
crossvul-cpp_data_good_745_0
#include "osxkeychain_darwin.h" #include <CoreFoundation/CoreFoundation.h> #include <Foundation/NSValue.h> #include <stdio.h> #include <string.h> char *get_error(OSStatus status) { char *buf = malloc(128); CFStringRef str = SecCopyErrorMessageString(status, NULL); int success = CFStringGetCString(str, buf, 128, kCFStringEncodingUTF8); if (!success) { strncpy(buf, "Unknown error", 128); } return buf; } char *keychain_add(struct Server *server, char *label, char *username, char *secret) { SecKeychainItemRef item; OSStatus status = SecKeychainAddInternetPassword( NULL, strlen(server->host), server->host, 0, NULL, strlen(username), username, strlen(server->path), server->path, server->port, server->proto, kSecAuthenticationTypeDefault, strlen(secret), secret, &item ); if (status) { return get_error(status); } SecKeychainAttribute attribute; SecKeychainAttributeList attrs; attribute.tag = kSecLabelItemAttr; attribute.data = label; attribute.length = strlen(label); attrs.count = 1; attrs.attr = &attribute; status = SecKeychainItemModifyContent(item, &attrs, 0, NULL); if (status) { return get_error(status); } return NULL; } char *keychain_get(struct Server *server, unsigned int *username_l, char **username, unsigned int *secret_l, char **secret) { char *tmp; SecKeychainItemRef item; OSStatus status = SecKeychainFindInternetPassword( NULL, strlen(server->host), server->host, 0, NULL, 0, NULL, strlen(server->path), server->path, server->port, server->proto, kSecAuthenticationTypeDefault, secret_l, (void **)&tmp, &item); if (status) { return get_error(status); } *secret = strdup(tmp); SecKeychainItemFreeContent(NULL, tmp); SecKeychainAttributeList list; SecKeychainAttribute attr; list.count = 1; list.attr = &attr; attr.tag = kSecAccountItemAttr; status = SecKeychainItemCopyContent(item, NULL, &list, NULL, NULL); if (status) { return get_error(status); } *username = strdup(attr.data); *username_l = attr.length; SecKeychainItemFreeContent(&list, NULL); return NULL; } char *keychain_delete(struct Server *server) { SecKeychainItemRef item; OSStatus status = SecKeychainFindInternetPassword( NULL, strlen(server->host), server->host, 0, NULL, 0, NULL, strlen(server->path), server->path, server->port, server->proto, kSecAuthenticationTypeDefault, 0, NULL, &item); if (status) { return get_error(status); } status = SecKeychainItemDelete(item); if (status) { return get_error(status); } return NULL; } char * CFStringToCharArr(CFStringRef aString) { if (aString == NULL) { return NULL; } CFIndex length = CFStringGetLength(aString); CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char *buffer = (char *)malloc(maxSize); if (CFStringGetCString(aString, buffer, maxSize, kCFStringEncodingUTF8)) { return buffer; } return NULL; } char *keychain_list(char *credsLabel, char *** paths, char *** accts, unsigned int *list_l) { CFStringRef credsLabelCF = CFStringCreateWithCString(NULL, credsLabel, kCFStringEncodingUTF8); CFMutableDictionaryRef query = CFDictionaryCreateMutable (NULL, 1, NULL, NULL); CFDictionaryAddValue(query, kSecClass, kSecClassInternetPassword); CFDictionaryAddValue(query, kSecReturnAttributes, kCFBooleanTrue); CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitAll); CFDictionaryAddValue(query, kSecAttrLabel, credsLabelCF); //Use this query dictionary CFTypeRef result= NULL; OSStatus status = SecItemCopyMatching( query, &result); CFRelease(credsLabelCF); //Ran a search and store the results in result if (status) { return get_error(status); } CFIndex numKeys = CFArrayGetCount(result); *paths = (char **) malloc((int)sizeof(char *)*numKeys); *accts = (char **) malloc((int)sizeof(char *)*numKeys); //result is of type CFArray for(CFIndex i=0; i<numKeys; i++) { CFDictionaryRef currKey = CFArrayGetValueAtIndex(result,i); CFStringRef protocolTmp = CFDictionaryGetValue(currKey, CFSTR("ptcl")); if (protocolTmp != NULL) { CFStringRef protocolStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), protocolTmp); if (CFStringCompare(protocolStr, CFSTR("htps"), 0) == kCFCompareEqualTo) { protocolTmp = CFSTR("https://"); } else { protocolTmp = CFSTR("http://"); } CFRelease(protocolStr); } else { char * path = "0"; char * acct = "0"; (*paths)[i] = (char *) malloc(sizeof(char)*(strlen(path))); memcpy((*paths)[i], path, sizeof(char)*(strlen(path))); (*accts)[i] = (char *) malloc(sizeof(char)*(strlen(acct))); memcpy((*accts)[i], acct, sizeof(char)*(strlen(acct))); continue; } CFMutableStringRef str = CFStringCreateMutableCopy(NULL, 0, protocolTmp); CFStringRef serverTmp = CFDictionaryGetValue(currKey, CFSTR("srvr")); if (serverTmp != NULL) { CFStringAppend(str, serverTmp); } CFStringRef pathTmp = CFDictionaryGetValue(currKey, CFSTR("path")); if (pathTmp != NULL) { CFStringAppend(str, pathTmp); } const NSNumber * portTmp = CFDictionaryGetValue(currKey, CFSTR("port")); if (portTmp != NULL && portTmp.integerValue != 0) { CFStringRef portStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), portTmp); CFStringAppend(str, CFSTR(":")); CFStringAppend(str, portStr); CFRelease(portStr); } CFStringRef acctTmp = CFDictionaryGetValue(currKey, CFSTR("acct")); if (acctTmp == NULL) { acctTmp = CFSTR("account not defined"); } char * path = CFStringToCharArr(str); char * acct = CFStringToCharArr(acctTmp); //We now have all we need, username and servername. Now export this to .go (*paths)[i] = (char *) malloc(sizeof(char)*(strlen(path)+1)); memcpy((*paths)[i], path, sizeof(char)*(strlen(path)+1)); (*accts)[i] = (char *) malloc(sizeof(char)*(strlen(acct)+1)); memcpy((*accts)[i], acct, sizeof(char)*(strlen(acct)+1)); CFRelease(str); } *list_l = (int)numKeys; return NULL; } void freeListData(char *** data, unsigned int length) { for(int i=0; i<length; i++) { free((*data)[i]); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_745_0
crossvul-cpp_data_good_4998_1
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Etienne Kneuss <colder@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "zend_exceptions.h" #include "zend_hash.h" #include "php_spl.h" #include "ext/standard/info.h" #include "ext/standard/php_var.h" #include "zend_smart_str.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_dllist.h" #include "spl_exceptions.h" zend_object_handlers spl_handler_SplDoublyLinkedList; PHPAPI zend_class_entry *spl_ce_SplDoublyLinkedList; PHPAPI zend_class_entry *spl_ce_SplQueue; PHPAPI zend_class_entry *spl_ce_SplStack; #define SPL_LLIST_DELREF(elem) if(!--(elem)->rc) { \ efree(elem); \ } #define SPL_LLIST_CHECK_DELREF(elem) if((elem) && !--(elem)->rc) { \ efree(elem); \ } #define SPL_LLIST_ADDREF(elem) (elem)->rc++ #define SPL_LLIST_CHECK_ADDREF(elem) if(elem) (elem)->rc++ #define SPL_DLLIST_IT_DELETE 0x00000001 /* Delete flag makes the iterator delete the current element on next */ #define SPL_DLLIST_IT_LIFO 0x00000002 /* LIFO flag makes the iterator traverse the structure as a LastInFirstOut */ #define SPL_DLLIST_IT_MASK 0x00000003 /* Mask to isolate flags related to iterators */ #define SPL_DLLIST_IT_FIX 0x00000004 /* Backward/Forward bit is fixed */ #ifdef accept #undef accept #endif typedef struct _spl_ptr_llist_element { struct _spl_ptr_llist_element *prev; struct _spl_ptr_llist_element *next; int rc; zval data; } spl_ptr_llist_element; typedef void (*spl_ptr_llist_dtor_func)(spl_ptr_llist_element *); typedef void (*spl_ptr_llist_ctor_func)(spl_ptr_llist_element *); typedef struct _spl_ptr_llist { spl_ptr_llist_element *head; spl_ptr_llist_element *tail; spl_ptr_llist_dtor_func dtor; spl_ptr_llist_ctor_func ctor; int count; } spl_ptr_llist; typedef struct _spl_dllist_object spl_dllist_object; typedef struct _spl_dllist_it spl_dllist_it; struct _spl_dllist_object { spl_ptr_llist *llist; int traverse_position; spl_ptr_llist_element *traverse_pointer; int flags; zend_function *fptr_offset_get; zend_function *fptr_offset_set; zend_function *fptr_offset_has; zend_function *fptr_offset_del; zend_function *fptr_count; zend_class_entry *ce_get_iterator; zval *gc_data; int gc_data_count; zend_object std; }; /* define an overloaded iterator structure */ struct _spl_dllist_it { zend_user_iterator intern; spl_ptr_llist_element *traverse_pointer; int traverse_position; int flags; }; static inline spl_dllist_object *spl_dllist_from_obj(zend_object *obj) /* {{{ */ { return (spl_dllist_object*)((char*)(obj) - XtOffsetOf(spl_dllist_object, std)); } /* }}} */ #define Z_SPLDLLIST_P(zv) spl_dllist_from_obj(Z_OBJ_P((zv))) /* {{{ spl_ptr_llist */ static void spl_ptr_llist_zval_dtor(spl_ptr_llist_element *elem) { /* {{{ */ if (!Z_ISUNDEF(elem->data)) { zval_ptr_dtor(&elem->data); ZVAL_UNDEF(&elem->data); } } /* }}} */ static void spl_ptr_llist_zval_ctor(spl_ptr_llist_element *elem) { /* {{{ */ if (Z_REFCOUNTED(elem->data)) { Z_ADDREF(elem->data); } } /* }}} */ static spl_ptr_llist *spl_ptr_llist_init(spl_ptr_llist_ctor_func ctor, spl_ptr_llist_dtor_func dtor) /* {{{ */ { spl_ptr_llist *llist = emalloc(sizeof(spl_ptr_llist)); llist->head = NULL; llist->tail = NULL; llist->count = 0; llist->dtor = dtor; llist->ctor = ctor; return llist; } /* }}} */ static zend_long spl_ptr_llist_count(spl_ptr_llist *llist) /* {{{ */ { return (zend_long)llist->count; } /* }}} */ static void spl_ptr_llist_destroy(spl_ptr_llist *llist) /* {{{ */ { spl_ptr_llist_element *current = llist->head, *next; spl_ptr_llist_dtor_func dtor = llist->dtor; while (current) { next = current->next; if (dtor) { dtor(current); } SPL_LLIST_DELREF(current); current = next; } efree(llist); } /* }}} */ static spl_ptr_llist_element *spl_ptr_llist_offset(spl_ptr_llist *llist, zend_long offset, int backward) /* {{{ */ { spl_ptr_llist_element *current; int pos = 0; if (backward) { current = llist->tail; } else { current = llist->head; } while (current && pos < offset) { pos++; if (backward) { current = current->prev; } else { current = current->next; } } return current; } /* }}} */ static void spl_ptr_llist_unshift(spl_ptr_llist *llist, zval *data) /* {{{ */ { spl_ptr_llist_element *elem = emalloc(sizeof(spl_ptr_llist_element)); elem->rc = 1; elem->prev = NULL; elem->next = llist->head; ZVAL_COPY_VALUE(&elem->data, data); if (llist->head) { llist->head->prev = elem; } else { llist->tail = elem; } llist->head = elem; llist->count++; if (llist->ctor) { llist->ctor(elem); } } /* }}} */ static void spl_ptr_llist_push(spl_ptr_llist *llist, zval *data) /* {{{ */ { spl_ptr_llist_element *elem = emalloc(sizeof(spl_ptr_llist_element)); elem->rc = 1; elem->prev = llist->tail; elem->next = NULL; ZVAL_COPY_VALUE(&elem->data, data); if (llist->tail) { llist->tail->next = elem; } else { llist->head = elem; } llist->tail = elem; llist->count++; if (llist->ctor) { llist->ctor(elem); } } /* }}} */ static void spl_ptr_llist_pop(spl_ptr_llist *llist, zval *ret) /* {{{ */ { spl_ptr_llist_element *tail = llist->tail; if (tail == NULL) { ZVAL_UNDEF(ret); return; } if (tail->prev) { tail->prev->next = NULL; } else { llist->head = NULL; } llist->tail = tail->prev; llist->count--; ZVAL_COPY(ret, &tail->data); if (llist->dtor) { llist->dtor(tail); } ZVAL_UNDEF(&tail->data); SPL_LLIST_DELREF(tail); } /* }}} */ static zval *spl_ptr_llist_last(spl_ptr_llist *llist) /* {{{ */ { spl_ptr_llist_element *tail = llist->tail; if (tail == NULL) { return NULL; } else { return &tail->data; } } /* }}} */ static zval *spl_ptr_llist_first(spl_ptr_llist *llist) /* {{{ */ { spl_ptr_llist_element *head = llist->head; if (head == NULL) { return NULL; } else { return &head->data; } } /* }}} */ static void spl_ptr_llist_shift(spl_ptr_llist *llist, zval *ret) /* {{{ */ { spl_ptr_llist_element *head = llist->head; if (head == NULL) { ZVAL_UNDEF(ret); return; } if (head->next) { head->next->prev = NULL; } else { llist->tail = NULL; } llist->head = head->next; llist->count--; ZVAL_COPY(ret, &head->data); if (llist->dtor) { llist->dtor(head); } ZVAL_UNDEF(&head->data); SPL_LLIST_DELREF(head); } /* }}} */ static void spl_ptr_llist_copy(spl_ptr_llist *from, spl_ptr_llist *to) /* {{{ */ { spl_ptr_llist_element *current = from->head, *next; //??? spl_ptr_llist_ctor_func ctor = from->ctor; while (current) { next = current->next; /*??? FIXME if (ctor) { ctor(current); } */ spl_ptr_llist_push(to, &current->data); current = next; } } /* }}} */ /* }}} */ static void spl_dllist_object_free_storage(zend_object *object) /* {{{ */ { spl_dllist_object *intern = spl_dllist_from_obj(object); zval tmp; zend_object_std_dtor(&intern->std); while (intern->llist->count > 0) { spl_ptr_llist_pop(intern->llist, &tmp); zval_ptr_dtor(&tmp); } if (intern->gc_data != NULL) { efree(intern->gc_data); }; spl_ptr_llist_destroy(intern->llist); SPL_LLIST_CHECK_DELREF(intern->traverse_pointer); } /* }}} */ zend_object_iterator *spl_dllist_get_iterator(zend_class_entry *ce, zval *object, int by_ref); static zend_object *spl_dllist_object_new_ex(zend_class_entry *class_type, zval *orig, int clone_orig) /* {{{ */ { spl_dllist_object *intern; zend_class_entry *parent = class_type; int inherited = 0; intern = ecalloc(1, sizeof(spl_dllist_object) + zend_object_properties_size(parent)); zend_object_std_init(&intern->std, class_type); object_properties_init(&intern->std, class_type); intern->flags = 0; intern->traverse_position = 0; if (orig) { spl_dllist_object *other = Z_SPLDLLIST_P(orig); intern->ce_get_iterator = other->ce_get_iterator; if (clone_orig) { intern->llist = (spl_ptr_llist *)spl_ptr_llist_init(other->llist->ctor, other->llist->dtor); spl_ptr_llist_copy(other->llist, intern->llist); intern->traverse_pointer = intern->llist->head; SPL_LLIST_CHECK_ADDREF(intern->traverse_pointer); } else { intern->llist = other->llist; intern->traverse_pointer = intern->llist->head; SPL_LLIST_CHECK_ADDREF(intern->traverse_pointer); } intern->flags = other->flags; } else { intern->llist = (spl_ptr_llist *)spl_ptr_llist_init(spl_ptr_llist_zval_ctor, spl_ptr_llist_zval_dtor); intern->traverse_pointer = intern->llist->head; SPL_LLIST_CHECK_ADDREF(intern->traverse_pointer); } while (parent) { if (parent == spl_ce_SplStack) { intern->flags |= (SPL_DLLIST_IT_FIX | SPL_DLLIST_IT_LIFO); intern->std.handlers = &spl_handler_SplDoublyLinkedList; } else if (parent == spl_ce_SplQueue) { intern->flags |= SPL_DLLIST_IT_FIX; intern->std.handlers = &spl_handler_SplDoublyLinkedList; } if (parent == spl_ce_SplDoublyLinkedList) { intern->std.handlers = &spl_handler_SplDoublyLinkedList; break; } parent = parent->parent; inherited = 1; } if (!parent) { /* this must never happen */ php_error_docref(NULL, E_COMPILE_ERROR, "Internal compiler error, Class is not child of SplDoublyLinkedList"); } if (inherited) { intern->fptr_offset_get = zend_hash_str_find_ptr(&class_type->function_table, "offsetget", sizeof("offsetget") - 1); if (intern->fptr_offset_get->common.scope == parent) { intern->fptr_offset_get = NULL; } intern->fptr_offset_set = zend_hash_str_find_ptr(&class_type->function_table, "offsetset", sizeof("offsetset") - 1); if (intern->fptr_offset_set->common.scope == parent) { intern->fptr_offset_set = NULL; } intern->fptr_offset_has = zend_hash_str_find_ptr(&class_type->function_table, "offsetexists", sizeof("offsetexists") - 1); if (intern->fptr_offset_has->common.scope == parent) { intern->fptr_offset_has = NULL; } intern->fptr_offset_del = zend_hash_str_find_ptr(&class_type->function_table, "offsetunset", sizeof("offsetunset") - 1); if (intern->fptr_offset_del->common.scope == parent) { intern->fptr_offset_del = NULL; } intern->fptr_count = zend_hash_str_find_ptr(&class_type->function_table, "count", sizeof("count") - 1); if (intern->fptr_count->common.scope == parent) { intern->fptr_count = NULL; } } return &intern->std; } /* }}} */ static zend_object *spl_dllist_object_new(zend_class_entry *class_type) /* {{{ */ { return spl_dllist_object_new_ex(class_type, NULL, 0); } /* }}} */ static zend_object *spl_dllist_object_clone(zval *zobject) /* {{{ */ { zend_object *old_object; zend_object *new_object; old_object = Z_OBJ_P(zobject); new_object = spl_dllist_object_new_ex(old_object->ce, zobject, 1); zend_objects_clone_members(new_object, old_object); return new_object; } /* }}} */ static int spl_dllist_object_count_elements(zval *object, zend_long *count) /* {{{ */ { spl_dllist_object *intern = Z_SPLDLLIST_P(object); if (intern->fptr_count) { zval rv; zend_call_method_with_0_params(object, intern->std.ce, &intern->fptr_count, "count", &rv); if (!Z_ISUNDEF(rv)) { *count = zval_get_long(&rv); zval_ptr_dtor(&rv); return SUCCESS; } *count = 0; return FAILURE; } *count = spl_ptr_llist_count(intern->llist); return SUCCESS; } /* }}} */ static HashTable* spl_dllist_object_get_debug_info(zval *obj, int *is_temp) /* {{{{ */ { spl_dllist_object *intern = Z_SPLDLLIST_P(obj); spl_ptr_llist_element *current = intern->llist->head, *next; zval tmp, dllist_array; zend_string *pnstr; int i = 0; HashTable *debug_info; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(debug_info); zend_hash_init(debug_info, 1, NULL, ZVAL_PTR_DTOR, 0); zend_hash_copy(debug_info, intern->std.properties, (copy_ctor_func_t) zval_add_ref); pnstr = spl_gen_private_prop_name(spl_ce_SplDoublyLinkedList, "flags", sizeof("flags")-1); ZVAL_LONG(&tmp, intern->flags); zend_hash_add(debug_info, pnstr, &tmp); zend_string_release(pnstr); array_init(&dllist_array); while (current) { next = current->next; add_index_zval(&dllist_array, i, &current->data); if (Z_REFCOUNTED(current->data)) { Z_ADDREF(current->data); } i++; current = next; } pnstr = spl_gen_private_prop_name(spl_ce_SplDoublyLinkedList, "dllist", sizeof("dllist")-1); zend_hash_add(debug_info, pnstr, &dllist_array); zend_string_release(pnstr); return debug_info; } /* }}}} */ static HashTable *spl_dllist_object_get_gc(zval *obj, zval **gc_data, int *gc_data_count) /* {{{ */ { spl_dllist_object *intern = Z_SPLDLLIST_P(obj); spl_ptr_llist_element *current = intern->llist->head; int i = 0; if (intern->gc_data_count < intern->llist->count) { intern->gc_data_count = intern->llist->count; intern->gc_data = safe_erealloc(intern->gc_data, intern->gc_data_count, sizeof(zval), 0); } while (current) { ZVAL_COPY_VALUE(&intern->gc_data[i++], &current->data); current = current->next; } *gc_data = intern->gc_data; *gc_data_count = i; return zend_std_get_properties(obj); } /* }}} */ /* {{{ proto bool SplDoublyLinkedList::push(mixed value) Push $value on the SplDoublyLinkedList */ SPL_METHOD(SplDoublyLinkedList, push) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); spl_ptr_llist_push(intern->llist, value); RETURN_TRUE; } /* }}} */ /* {{{ proto bool SplDoublyLinkedList::unshift(mixed value) Unshift $value on the SplDoublyLinkedList */ SPL_METHOD(SplDoublyLinkedList, unshift) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); spl_ptr_llist_unshift(intern->llist, value); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed SplDoublyLinkedList::pop() Pop an element out of the SplDoublyLinkedList */ SPL_METHOD(SplDoublyLinkedList, pop) { spl_dllist_object *intern; if (zend_parse_parameters_none() == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); spl_ptr_llist_pop(intern->llist, return_value); if (Z_ISUNDEF_P(return_value)) { zend_throw_exception(spl_ce_RuntimeException, "Can't pop from an empty datastructure", 0); RETURN_NULL(); } } /* }}} */ /* {{{ proto mixed SplDoublyLinkedList::shift() Shift an element out of the SplDoublyLinkedList */ SPL_METHOD(SplDoublyLinkedList, shift) { spl_dllist_object *intern; if (zend_parse_parameters_none() == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); spl_ptr_llist_shift(intern->llist, return_value); if (Z_ISUNDEF_P(return_value)) { zend_throw_exception(spl_ce_RuntimeException, "Can't shift from an empty datastructure", 0); RETURN_NULL(); } } /* }}} */ /* {{{ proto mixed SplDoublyLinkedList::top() Peek at the top element of the SplDoublyLinkedList */ SPL_METHOD(SplDoublyLinkedList, top) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters_none() == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); value = spl_ptr_llist_last(intern->llist); if (value == NULL || Z_ISUNDEF_P(value)) { zend_throw_exception(spl_ce_RuntimeException, "Can't peek at an empty datastructure", 0); return; } ZVAL_DEREF(value); ZVAL_COPY(return_value, value); } /* }}} */ /* {{{ proto mixed SplDoublyLinkedList::bottom() Peek at the bottom element of the SplDoublyLinkedList */ SPL_METHOD(SplDoublyLinkedList, bottom) { zval *value; spl_dllist_object *intern; if (zend_parse_parameters_none() == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); value = spl_ptr_llist_first(intern->llist); if (value == NULL || Z_ISUNDEF_P(value)) { zend_throw_exception(spl_ce_RuntimeException, "Can't peek at an empty datastructure", 0); return; } ZVAL_DEREF(value); ZVAL_COPY(return_value, value); } /* }}} */ /* {{{ proto int SplDoublyLinkedList::count() Return the number of elements in the datastructure. */ SPL_METHOD(SplDoublyLinkedList, count) { zend_long count; spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } count = spl_ptr_llist_count(intern->llist); RETURN_LONG(count); } /* }}} */ /* {{{ proto int SplDoublyLinkedList::isEmpty() Return true if the SplDoublyLinkedList is empty. */ SPL_METHOD(SplDoublyLinkedList, isEmpty) { zend_long count; if (zend_parse_parameters_none() == FAILURE) { return; } spl_dllist_object_count_elements(getThis(), &count); RETURN_BOOL(count == 0); } /* }}} */ /* {{{ proto int SplDoublyLinkedList::setIteratorMode(int flags) Set the mode of iteration */ SPL_METHOD(SplDoublyLinkedList, setIteratorMode) { zend_long value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (intern->flags & SPL_DLLIST_IT_FIX && (intern->flags & SPL_DLLIST_IT_LIFO) != (value & SPL_DLLIST_IT_LIFO)) { zend_throw_exception(spl_ce_RuntimeException, "Iterators' LIFO/FIFO modes for SplStack/SplQueue objects are frozen", 0); return; } intern->flags = value & SPL_DLLIST_IT_MASK; RETURN_LONG(intern->flags); } /* }}} */ /* {{{ proto int SplDoublyLinkedList::getIteratorMode() Return the mode of iteration */ SPL_METHOD(SplDoublyLinkedList, getIteratorMode) { spl_dllist_object *intern; if (zend_parse_parameters_none() == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); RETURN_LONG(intern->flags); } /* }}} */ /* {{{ proto bool SplDoublyLinkedList::offsetExists(mixed index) Returns whether the requested $index exists. */ SPL_METHOD(SplDoublyLinkedList, offsetExists) { zval *zindex; spl_dllist_object *intern; zend_long index; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); index = spl_offset_convert_to_long(zindex); RETURN_BOOL(index >= 0 && index < intern->llist->count); } /* }}} */ /* {{{ proto mixed SplDoublyLinkedList::offsetGet(mixed index) Returns the value at the specified $index. */ SPL_METHOD(SplDoublyLinkedList, offsetGet) { zval *zindex; zend_long index; spl_dllist_object *intern; spl_ptr_llist_element *element; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { zval *value = &element->data; ZVAL_DEREF(value); ZVAL_COPY(return_value, value); } else { zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetSet(mixed index, mixed newval) Sets the value at the specified $index to $newval. */ SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index) Unsets the value at the specified $index. */ SPL_METHOD(SplDoublyLinkedList, offsetUnset) { zval *zindex; zend_long index; spl_dllist_object *intern; spl_ptr_llist_element *element; spl_ptr_llist *llist; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zindex) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); index = spl_offset_convert_to_long(zindex); llist = intern->llist; if (index < 0 || index >= intern->llist->count) { zend_throw_exception(spl_ce_OutOfRangeException, "Offset out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* connect the neightbors */ if (element->prev) { element->prev->next = element->next; } if (element->next) { element->next->prev = element->prev; } /* take care of head/tail */ if (element == llist->head) { llist->head = element->next; } if (element == llist->tail) { llist->tail = element->prev; } /* finally, delete the element */ llist->count--; if(llist->dtor) { llist->dtor(element); } if (intern->traverse_pointer == element) { SPL_LLIST_DELREF(element); intern->traverse_pointer = NULL; } zval_ptr_dtor(&element->data); ZVAL_UNDEF(&element->data); SPL_LLIST_DELREF(element); } else { zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } /* }}} */ static void spl_dllist_it_dtor(zend_object_iterator *iter) /* {{{ */ { spl_dllist_it *iterator = (spl_dllist_it *)iter; SPL_LLIST_CHECK_DELREF(iterator->traverse_pointer); zend_user_it_invalidate_current(iter); zval_ptr_dtor(&iterator->intern.it.data); } /* }}} */ static void spl_dllist_it_helper_rewind(spl_ptr_llist_element **traverse_pointer_ptr, int *traverse_position_ptr, spl_ptr_llist *llist, int flags) /* {{{ */ { SPL_LLIST_CHECK_DELREF(*traverse_pointer_ptr); if (flags & SPL_DLLIST_IT_LIFO) { *traverse_position_ptr = llist->count-1; *traverse_pointer_ptr = llist->tail; } else { *traverse_position_ptr = 0; *traverse_pointer_ptr = llist->head; } SPL_LLIST_CHECK_ADDREF(*traverse_pointer_ptr); } /* }}} */ static void spl_dllist_it_helper_move_forward(spl_ptr_llist_element **traverse_pointer_ptr, int *traverse_position_ptr, spl_ptr_llist *llist, int flags) /* {{{ */ { if (*traverse_pointer_ptr) { spl_ptr_llist_element *old = *traverse_pointer_ptr; if (flags & SPL_DLLIST_IT_LIFO) { *traverse_pointer_ptr = old->prev; (*traverse_position_ptr)--; if (flags & SPL_DLLIST_IT_DELETE) { zval prev; spl_ptr_llist_pop(llist, &prev); zval_ptr_dtor(&prev); } } else { *traverse_pointer_ptr = old->next; if (flags & SPL_DLLIST_IT_DELETE) { zval prev; spl_ptr_llist_shift(llist, &prev); zval_ptr_dtor(&prev); } else { (*traverse_position_ptr)++; } } SPL_LLIST_DELREF(old); SPL_LLIST_CHECK_ADDREF(*traverse_pointer_ptr); } } /* }}} */ static void spl_dllist_it_rewind(zend_object_iterator *iter) /* {{{ */ { spl_dllist_it *iterator = (spl_dllist_it *)iter; spl_dllist_object *object = Z_SPLDLLIST_P(&iter->data); spl_ptr_llist *llist = object->llist; spl_dllist_it_helper_rewind(&iterator->traverse_pointer, &iterator->traverse_position, llist, object->flags); } /* }}} */ static int spl_dllist_it_valid(zend_object_iterator *iter) /* {{{ */ { spl_dllist_it *iterator = (spl_dllist_it *)iter; spl_ptr_llist_element *element = iterator->traverse_pointer; return (element != NULL ? SUCCESS : FAILURE); } /* }}} */ static zval *spl_dllist_it_get_current_data(zend_object_iterator *iter) /* {{{ */ { spl_dllist_it *iterator = (spl_dllist_it *)iter; spl_ptr_llist_element *element = iterator->traverse_pointer; if (element == NULL || Z_ISUNDEF(element->data)) { return NULL; } return &element->data; } /* }}} */ static void spl_dllist_it_get_current_key(zend_object_iterator *iter, zval *key) /* {{{ */ { spl_dllist_it *iterator = (spl_dllist_it *)iter; ZVAL_LONG(key, iterator->traverse_position); } /* }}} */ static void spl_dllist_it_move_forward(zend_object_iterator *iter) /* {{{ */ { spl_dllist_it *iterator = (spl_dllist_it *)iter; spl_dllist_object *object = Z_SPLDLLIST_P(&iter->data); zend_user_it_invalidate_current(iter); spl_dllist_it_helper_move_forward(&iterator->traverse_pointer, &iterator->traverse_position, object->llist, object->flags); } /* }}} */ /* {{{ proto int SplDoublyLinkedList::key() Return current array key */ SPL_METHOD(SplDoublyLinkedList, key) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->traverse_position); } /* }}} */ /* {{{ proto void SplDoublyLinkedList::prev() Move to next entry */ SPL_METHOD(SplDoublyLinkedList, prev) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } spl_dllist_it_helper_move_forward(&intern->traverse_pointer, &intern->traverse_position, intern->llist, intern->flags ^ SPL_DLLIST_IT_LIFO); } /* }}} */ /* {{{ proto void SplDoublyLinkedList::next() Move to next entry */ SPL_METHOD(SplDoublyLinkedList, next) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } spl_dllist_it_helper_move_forward(&intern->traverse_pointer, &intern->traverse_position, intern->llist, intern->flags); } /* }}} */ /* {{{ proto bool SplDoublyLinkedList::valid() Check whether the datastructure contains more entries */ SPL_METHOD(SplDoublyLinkedList, valid) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->traverse_pointer != NULL); } /* }}} */ /* {{{ proto void SplDoublyLinkedList::rewind() Rewind the datastructure back to the start */ SPL_METHOD(SplDoublyLinkedList, rewind) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } spl_dllist_it_helper_rewind(&intern->traverse_pointer, &intern->traverse_position, intern->llist, intern->flags); } /* }}} */ /* {{{ proto mixed|NULL SplDoublyLinkedList::current() Return current datastructure entry */ SPL_METHOD(SplDoublyLinkedList, current) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); spl_ptr_llist_element *element = intern->traverse_pointer; if (zend_parse_parameters_none() == FAILURE) { return; } if (element == NULL || Z_ISUNDEF(element->data)) { RETURN_NULL(); } else { zval *value = &element->data; ZVAL_DEREF(value); ZVAL_COPY(return_value, value); } } /* }}} */ /* {{{ proto string SplDoublyLinkedList::serialize() Serializes storage */ SPL_METHOD(SplDoublyLinkedList, serialize) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); smart_str buf = {0}; spl_ptr_llist_element *current = intern->llist->head, *next; zval flags; php_serialize_data_t var_hash; if (zend_parse_parameters_none() == FAILURE) { return; } PHP_VAR_SERIALIZE_INIT(var_hash); /* flags */ ZVAL_LONG(&flags, intern->flags); php_var_serialize(&buf, &flags, &var_hash); zval_ptr_dtor(&flags); /* elements */ while (current) { smart_str_appendc(&buf, ':'); next = current->next; php_var_serialize(&buf, &current->data, &var_hash); current = next; } smart_str_0(&buf); /* done */ PHP_VAR_SERIALIZE_DESTROY(var_hash); if (buf.s) { RETURN_NEW_STR(buf.s); } else { RETURN_NULL(); } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::unserialize(string serialized) Unserializes storage */ SPL_METHOD(SplDoublyLinkedList, unserialize) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); zval *flags, *elem; char *buf; size_t buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { return; } s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); /* flags */ flags = var_tmp_var(&var_hash); if (!php_var_unserialize(flags, &p, s + buf_len, &var_hash) || Z_TYPE_P(flags) != IS_LONG) { goto error; } intern->flags = (int)Z_LVAL_P(flags); /* elements */ while(*p == ':') { ++p; elem = var_tmp_var(&var_hash); if (!php_var_unserialize(elem, &p, s + buf_len, &var_hash)) { goto error; } var_push_dtor(&var_hash, elem); spl_ptr_llist_push(intern->llist, elem); } if (*p != '\0') { goto error; } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; error: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ proto void SplDoublyLinkedList::add(mixed index, mixed newval) Inserts a new entry before the specified $index consisting of $newval. */ SPL_METHOD(SplDoublyLinkedList, add) { zval *zindex, *value; spl_dllist_object *intern; spl_ptr_llist_element *element; zend_long index; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); index = spl_offset_convert_to_long(zindex); if (index < 0 || index > intern->llist->count) { zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } if (Z_REFCOUNTED_P(value)) { Z_ADDREF_P(value); } if (index == intern->llist->count) { /* If index is the last entry+1 then we do a push because we're not inserting before any entry */ spl_ptr_llist_push(intern->llist, value); } else { /* Create the new element we want to insert */ spl_ptr_llist_element *elem = emalloc(sizeof(spl_ptr_llist_element)); /* Get the element we want to insert before */ element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); ZVAL_COPY_VALUE(&elem->data, value); elem->rc = 1; /* connect to the neighbours */ elem->next = element; elem->prev = element->prev; /* connect the neighbours to this new element */ if (elem->prev == NULL) { intern->llist->head = elem; } else { element->prev->next = elem; } element->prev = elem; intern->llist->count++; if (intern->llist->ctor) { intern->llist->ctor(elem); } } } /* }}} */ /* {{{ iterator handler table */ zend_object_iterator_funcs spl_dllist_it_funcs = { spl_dllist_it_dtor, spl_dllist_it_valid, spl_dllist_it_get_current_data, spl_dllist_it_get_current_key, spl_dllist_it_move_forward, spl_dllist_it_rewind }; /* }}} */ zend_object_iterator *spl_dllist_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */ { spl_dllist_it *iterator; spl_dllist_object *dllist_object = Z_SPLDLLIST_P(object); if (by_ref) { zend_throw_exception(spl_ce_RuntimeException, "An iterator cannot be used with foreach by reference", 0); return NULL; } iterator = emalloc(sizeof(spl_dllist_it)); zend_iterator_init((zend_object_iterator*)iterator); ZVAL_COPY(&iterator->intern.it.data, object); iterator->intern.it.funcs = &spl_dllist_it_funcs; iterator->intern.ce = ce; iterator->traverse_position = dllist_object->traverse_position; iterator->traverse_pointer = dllist_object->traverse_pointer; iterator->flags = dllist_object->flags & SPL_DLLIST_IT_MASK; ZVAL_UNDEF(&iterator->intern.value); SPL_LLIST_CHECK_ADDREF(iterator->traverse_pointer); return &iterator->intern.it; } /* }}} */ /* Function/Class/Method definitions */ ZEND_BEGIN_ARG_INFO(arginfo_dllist_setiteratormode, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dllist_push, 0) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_dllist_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_dllist_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, newval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dllist_void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dllist_serialized, 0) ZEND_ARG_INFO(0, serialized) ZEND_END_ARG_INFO(); static const zend_function_entry spl_funcs_SplQueue[] = { SPL_MA(SplQueue, enqueue, SplDoublyLinkedList, push, arginfo_dllist_push, ZEND_ACC_PUBLIC) SPL_MA(SplQueue, dequeue, SplDoublyLinkedList, shift, arginfo_dllist_void, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_funcs_SplDoublyLinkedList[] = { SPL_ME(SplDoublyLinkedList, pop, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, shift, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, push, arginfo_dllist_push, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, unshift, arginfo_dllist_push, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, top, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, bottom, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, isEmpty, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, setIteratorMode, arginfo_dllist_setiteratormode, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, getIteratorMode, arginfo_dllist_void, ZEND_ACC_PUBLIC) /* Countable */ SPL_ME(SplDoublyLinkedList, count, arginfo_dllist_void, ZEND_ACC_PUBLIC) /* ArrayAccess */ SPL_ME(SplDoublyLinkedList, offsetExists, arginfo_dllist_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, offsetGet, arginfo_dllist_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, offsetSet, arginfo_dllist_offsetSet, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, offsetUnset, arginfo_dllist_offsetGet, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, add, arginfo_dllist_offsetSet, ZEND_ACC_PUBLIC) /* Iterator */ SPL_ME(SplDoublyLinkedList, rewind, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, current, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, key, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, next, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, prev, arginfo_dllist_void, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, valid, arginfo_dllist_void, ZEND_ACC_PUBLIC) /* Serializable */ SPL_ME(SplDoublyLinkedList, unserialize, arginfo_dllist_serialized, ZEND_ACC_PUBLIC) SPL_ME(SplDoublyLinkedList, serialize, arginfo_dllist_void, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(spl_dllist) /* {{{ */ { REGISTER_SPL_STD_CLASS_EX(SplDoublyLinkedList, spl_dllist_object_new, spl_funcs_SplDoublyLinkedList); memcpy(&spl_handler_SplDoublyLinkedList, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_SplDoublyLinkedList.offset = XtOffsetOf(spl_dllist_object, std); spl_handler_SplDoublyLinkedList.clone_obj = spl_dllist_object_clone; spl_handler_SplDoublyLinkedList.count_elements = spl_dllist_object_count_elements; spl_handler_SplDoublyLinkedList.get_debug_info = spl_dllist_object_get_debug_info; spl_handler_SplDoublyLinkedList.get_gc = spl_dllist_object_get_gc; spl_handler_SplDoublyLinkedList.dtor_obj = zend_objects_destroy_object; spl_handler_SplDoublyLinkedList.free_obj = spl_dllist_object_free_storage; REGISTER_SPL_CLASS_CONST_LONG(SplDoublyLinkedList, "IT_MODE_LIFO", SPL_DLLIST_IT_LIFO); REGISTER_SPL_CLASS_CONST_LONG(SplDoublyLinkedList, "IT_MODE_FIFO", 0); REGISTER_SPL_CLASS_CONST_LONG(SplDoublyLinkedList, "IT_MODE_DELETE",SPL_DLLIST_IT_DELETE); REGISTER_SPL_CLASS_CONST_LONG(SplDoublyLinkedList, "IT_MODE_KEEP", 0); REGISTER_SPL_IMPLEMENTS(SplDoublyLinkedList, Iterator); REGISTER_SPL_IMPLEMENTS(SplDoublyLinkedList, Countable); REGISTER_SPL_IMPLEMENTS(SplDoublyLinkedList, ArrayAccess); REGISTER_SPL_IMPLEMENTS(SplDoublyLinkedList, Serializable); spl_ce_SplDoublyLinkedList->get_iterator = spl_dllist_get_iterator; REGISTER_SPL_SUB_CLASS_EX(SplQueue, SplDoublyLinkedList, spl_dllist_object_new, spl_funcs_SplQueue); REGISTER_SPL_SUB_CLASS_EX(SplStack, SplDoublyLinkedList, spl_dllist_object_new, NULL); spl_ce_SplQueue->get_iterator = spl_dllist_get_iterator; spl_ce_SplStack->get_iterator = spl_dllist_get_iterator; return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-415/c/good_4998_1
crossvul-cpp_data_good_347_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include "libopensc/internal.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = MIN(file->size, sizeof buf); sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = MIN(file->size, sizeof buf); sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_8
crossvul-cpp_data_good_1407_0
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" /* Code drawn from ppmtogif.c, from the pbmplus package ** ** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>. A ** Lempel-Zim compression based on "compress". ** ** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl> ** ** Copyright (C) 1989 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. ** ** The Graphics Interchange Format(c) is the Copyright property of ** CompuServe Incorporated. GIF(sm) is a Service Mark property of ** CompuServe Incorporated. */ /* * a code_int must be able to hold 2**GIFBITS values of type int, and also -1 */ typedef int code_int; #ifdef SIGNED_COMPARE_SLOW typedef unsigned long int count_int; typedef unsigned short int count_short; #else /*SIGNED_COMPARE_SLOW*/ typedef long int count_int; #endif /*SIGNED_COMPARE_SLOW*/ /* 2.0.28: threadsafe */ #define maxbits GIFBITS /* should NEVER generate this code */ #define maxmaxcode ((code_int)1 << GIFBITS) #define HSIZE 5003 /* 80% occupancy */ #define hsize HSIZE /* Apparently invariant, left over from compress */ typedef struct { int Width, Height; int curx, cury; long CountDown; int Pass; int Interlace; int n_bits; /* number of bits/code */ code_int maxcode; /* maximum code, given n_bits */ count_int htab [HSIZE]; unsigned short codetab [HSIZE]; code_int free_ent; /* first unused entry */ /* * block compression parameters -- after all codes are used up, * and compression rate changes, start over. */ int clear_flg; int offset; long int in_count; /* length of input */ long int out_count; /* # of codes output (for debugging) */ int g_init_bits; gdIOCtx * g_outfile; int ClearCode; int EOFCode; unsigned long cur_accum; int cur_bits; /* * Number of characters so far in this 'packet' */ int a_count; /* * Define the storage for the packet accumulator */ char accum[ 256 ]; } GifCtx; static int gifPutWord(int w, gdIOCtx *out); static int colorstobpp(int colors); static void BumpPixel (GifCtx *ctx); static int GIFNextPixel (gdImagePtr im, GifCtx *ctx); static void GIFEncode (gdIOCtxPtr fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im); static void compress (int init_bits, gdIOCtx *outfile, gdImagePtr im, GifCtx *ctx); static void output (code_int code, GifCtx *ctx); static void cl_block (GifCtx *ctx); static void cl_hash (register count_int chsize, GifCtx *ctx); static void char_init (GifCtx *ctx); static void char_out (int c, GifCtx *ctx); static void flush_char (GifCtx *ctx); static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out); void * gdImageGifPtr (gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); if (!_gdImageGifCtx(im, out)) { rv = gdDPExtractData(out, size); } else { rv = NULL; } out->gd_free (out); return rv; } void gdImageGif (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx (outFile); gdImageGifCtx (im, out); out->gd_free (out); } void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { _gdImageGifCtx(im, out); } /* returns 0 on success, 1 on failure */ static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if (im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if (!pim) { return 1; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if (pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } return 0; } static int colorstobpp(int colors) { int bpp = 0; if ( colors <= 2 ) bpp = 1; else if ( colors <= 4 ) bpp = 2; else if ( colors <= 8 ) bpp = 3; else if ( colors <= 16 ) bpp = 4; else if ( colors <= 32 ) bpp = 5; else if ( colors <= 64 ) bpp = 6; else if ( colors <= 128 ) bpp = 7; else if ( colors <= 256 ) bpp = 8; return bpp; } /***************************************************************************** * * GIFENCODE.C - GIF Image compression interface * * GIFEncode( FName, GHeight, GWidth, GInterlace, Background, Transparent, * BitsPerPixel, Red, Green, Blue, gdImagePtr ) * *****************************************************************************/ #define TRUE 1 #define FALSE 0 /* * Bump the 'curx' and 'cury' to point to the next pixel */ static void BumpPixel(GifCtx *ctx) { /* * Bump the current X position */ ++(ctx->curx); /* * If we are at the end of a scan line, set curx back to the beginning * If we are interlaced, bump the cury to the appropriate spot, * otherwise, just increment it. */ if( ctx->curx == ctx->Width ) { ctx->curx = 0; if( !ctx->Interlace ) ++(ctx->cury); else { switch( ctx->Pass ) { case 0: ctx->cury += 8; if( ctx->cury >= ctx->Height ) { ++(ctx->Pass); ctx->cury = 4; } break; case 1: ctx->cury += 8; if( ctx->cury >= ctx->Height ) { ++(ctx->Pass); ctx->cury = 2; } break; case 2: ctx->cury += 4; if( ctx->cury >= ctx->Height ) { ++(ctx->Pass); ctx->cury = 1; } break; case 3: ctx->cury += 2; break; } } } } /* * Return the next pixel from the image */ static int GIFNextPixel(gdImagePtr im, GifCtx *ctx) { int r; if( ctx->CountDown == 0 ) return EOF; --(ctx->CountDown); r = gdImageGetPixel(im, ctx->curx, ctx->cury); BumpPixel(ctx); return r; } /* public */ static void GIFEncode(gdIOCtxPtr fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im) { int B; int RWidth, RHeight; int LeftOfs, TopOfs; int Resolution; int ColorMapSize; int InitCodeSize; int i; GifCtx ctx; memset(&ctx, 0, sizeof(ctx)); ctx.Interlace = GInterlace; ctx.in_count = 1; ColorMapSize = 1 << BitsPerPixel; RWidth = ctx.Width = GWidth; RHeight = ctx.Height = GHeight; LeftOfs = TopOfs = 0; Resolution = BitsPerPixel; /* * Calculate number of bits we are expecting */ ctx.CountDown = (long)ctx.Width * (long)ctx.Height; /* * Indicate which pass we are on (if interlace) */ ctx.Pass = 0; /* * The initial code size */ if( BitsPerPixel <= 1 ) InitCodeSize = 2; else InitCodeSize = BitsPerPixel; /* * Set up the current x and y position */ ctx.curx = ctx.cury = 0; /* * Write the Magic header */ gdPutBuf(Transparent < 0 ? "GIF87a" : "GIF89a", 6, fp ); /* * Write out the screen width and height */ gifPutWord( RWidth, fp ); gifPutWord( RHeight, fp ); /* * Indicate that there is a global colour map */ B = 0x80; /* Yes, there is a color map */ /* * OR in the resolution */ B |= (Resolution - 1) << 5; /* * OR in the Bits per Pixel */ B |= (BitsPerPixel - 1); /* * Write it out */ gdPutC( B, fp ); /* * Write out the Background colour */ gdPutC( Background, fp ); /* * Byte of 0's (future expansion) */ gdPutC( 0, fp ); /* * Write out the Global Colour Map */ for( i=0; i<ColorMapSize; ++i ) { gdPutC( Red[i], fp ); gdPutC( Green[i], fp ); gdPutC( Blue[i], fp ); } /* * Write out extension for transparent colour index, if necessary. */ if ( Transparent >= 0 ) { gdPutC( '!', fp ); gdPutC( 0xf9, fp ); gdPutC( 4, fp ); gdPutC( 1, fp ); gdPutC( 0, fp ); gdPutC( 0, fp ); gdPutC( (unsigned char) Transparent, fp ); gdPutC( 0, fp ); } /* * Write an Image separator */ gdPutC( ',', fp ); /* * Write the Image header */ gifPutWord( LeftOfs, fp ); gifPutWord( TopOfs, fp ); gifPutWord( ctx.Width, fp ); gifPutWord( ctx.Height, fp ); /* * Write out whether or not the image is interlaced */ if( ctx.Interlace ) gdPutC( 0x40, fp ); else gdPutC( 0x00, fp ); /* * Write out the initial code size */ gdPutC( InitCodeSize, fp ); /* * Go and actually compress the data */ compress( InitCodeSize+1, fp, im, &ctx ); /* * Write out a Zero-length packet (to end the series) */ gdPutC( 0, fp ); /* * Write the GIF file terminator */ gdPutC( ';', fp ); } /*************************************************************************** * * GIFCOMPR.C - GIF Image compression routines * * Lempel-Ziv compression based on 'compress'. GIF modifications by * David Rowley (mgardi@watdcsu.waterloo.edu) * ***************************************************************************/ /* * General DEFINEs */ #define GIFBITS 12 #ifdef NO_UCHAR typedef char char_type; #else /*NO_UCHAR*/ typedef unsigned char char_type; #endif /*NO_UCHAR*/ /* * * GIF Image compression - modified 'compress' * * Based on: compress.c - File compression ala IEEE Computer, June 1984. * * By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) * Jim McKie (decvax!mcvax!jim) * Steve Davies (decvax!vax135!petsd!peora!srd) * Ken Turkowski (decvax!decwrl!turtlevax!ken) * James A. Woods (decvax!ihnp4!ames!jaw) * Joe Orost (decvax!vax135!petsd!joe) * */ #include <ctype.h> #define ARGVAL() (*++(*argv) || (--argc && *++argv)) #ifdef COMPATIBLE /* But wrong! */ # define MAXCODE(n_bits) ((code_int) 1 << (n_bits) - 1) #else /*COMPATIBLE*/ # define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1) #endif /*COMPATIBLE*/ #define HashTabOf(i) ctx->htab[i] #define CodeTabOf(i) ctx->codetab[i] /* * To save much memory, we overlay the table used by compress() with those * used by decompress(). The tab_prefix table is the same size and type * as the codetab. The tab_suffix table needs 2**GIFBITS characters. We * get this from the beginning of htab. The output stack uses the rest * of htab, and contains characters. There is plenty of room for any * possible stack (stack used to be 8000 characters). */ #define tab_prefixof(i) CodeTabOf(i) #define tab_suffixof(i) ((char_type*)(htab))[i] #define de_stack ((char_type*)&tab_suffixof((code_int)1<<GIFBITS)) /* * compress stdin to stdout * * Algorithm: use open addressing double hashing (no chaining) on the * prefix code / next character combination. We do a variant of Knuth's * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime * secondary probe. Here, the modular division first probe is gives way * to a faster exclusive-or manipulation. Also do block compression with * an adaptive reset, whereby the code table is cleared when the compression * ratio decreases, but after the table fills. The variable-length output * codes are re-sized at this point, and a special CLEAR code is generated * for the decompressor. Late addition: construct the table according to * file size for noticeable speed improvement on small files. Please direct * questions about this implementation to ames!jaw. */ static void output(code_int code, GifCtx *ctx); static void compress(int init_bits, gdIOCtxPtr outfile, gdImagePtr im, GifCtx *ctx) { register long fcode; register code_int i /* = 0 */; register int c; register code_int ent; register code_int disp; register code_int hsize_reg; register int hshift; /* * Set up the globals: g_init_bits - initial number of bits * g_outfile - pointer to output file */ ctx->g_init_bits = init_bits; ctx->g_outfile = outfile; /* * Set up the necessary values */ ctx->offset = 0; ctx->out_count = 0; ctx->clear_flg = 0; ctx->in_count = 1; ctx->maxcode = MAXCODE(ctx->n_bits = ctx->g_init_bits); ctx->ClearCode = (1 << (init_bits - 1)); ctx->EOFCode = ctx->ClearCode + 1; ctx->free_ent = ctx->ClearCode + 2; char_init(ctx); ent = GIFNextPixel( im, ctx ); hshift = 0; for ( fcode = (long) hsize; fcode < 65536L; fcode *= 2L ) ++hshift; hshift = 8 - hshift; /* set hash code range bound */ hsize_reg = hsize; cl_hash( (count_int) hsize_reg, ctx ); /* clear hash table */ output( (code_int)ctx->ClearCode, ctx ); #ifdef SIGNED_COMPARE_SLOW while ( (c = GIFNextPixel( im )) != (unsigned) EOF ) { #else /*SIGNED_COMPARE_SLOW*/ while ( (c = GIFNextPixel( im, ctx )) != EOF ) { /* } */ #endif /*SIGNED_COMPARE_SLOW*/ ++(ctx->in_count); fcode = (long) (((long) c << maxbits) + ent); i = (((code_int)c << hshift) ^ ent); /* xor hashing */ if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; } else if ( (long)HashTabOf (i) < 0 ) /* empty slot */ goto nomatch; disp = hsize_reg - i; /* secondary hash (after G. Knott) */ if ( i == 0 ) disp = 1; probe: if ( (i -= disp) < 0 ) i += hsize_reg; if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; } if ( (long)HashTabOf (i) > 0 ) goto probe; nomatch: output ( (code_int) ent, ctx ); ++(ctx->out_count); ent = c; #ifdef SIGNED_COMPARE_SLOW if ( (unsigned) ctx->free_ent < (unsigned) maxmaxcode) { #else /*SIGNED_COMPARE_SLOW*/ if ( ctx->free_ent < maxmaxcode ) { /* } */ #endif /*SIGNED_COMPARE_SLOW*/ CodeTabOf (i) = ctx->free_ent++; /* code -> hashtable */ HashTabOf (i) = fcode; } else cl_block(ctx); } /* * Put out the final code. */ output( (code_int)ent, ctx ); ++(ctx->out_count); output( (code_int) ctx->EOFCode, ctx ); } /***************************************************************** * TAG( output ) * * Output the given code. * Inputs: * code: A n_bits-bit integer. If == -1, then EOF. This assumes * that n_bits =< (long)wordsize - 1. * Outputs: * Outputs code to the file. * Assumptions: * Chars are 8 bits long. * Algorithm: * Maintain a GIFBITS character long buffer (so that 8 codes will * fit in it exactly). Use the VAX insv instruction to insert each * code in turn. When the buffer fills up empty it and start over. */ static const unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; /* Arbitrary value to mark output is done. When we see EOFCode, then we don't * expect to see any more data. If we do (e.g. corrupt image inputs), cur_bits * might be negative, so flag it to return early. */ #define CUR_BITS_FINISHED -1000 static void output(code_int code, GifCtx *ctx) { if (ctx->cur_bits == CUR_BITS_FINISHED) { return; } ctx->cur_accum &= masks[ ctx->cur_bits ]; if( ctx->cur_bits > 0 ) ctx->cur_accum |= ((long)code << ctx->cur_bits); else ctx->cur_accum = code; ctx->cur_bits += ctx->n_bits; while( ctx->cur_bits >= 8 ) { char_out( (unsigned int)(ctx->cur_accum & 0xff), ctx ); ctx->cur_accum >>= 8; ctx->cur_bits -= 8; } /* * If the next entry is going to be too big for the code size, * then increase it, if possible. */ if ( ctx->free_ent > ctx->maxcode || ctx->clear_flg ) { if( ctx->clear_flg ) { ctx->maxcode = MAXCODE (ctx->n_bits = ctx->g_init_bits); ctx->clear_flg = 0; } else { ++(ctx->n_bits); if ( ctx->n_bits == maxbits ) ctx->maxcode = maxmaxcode; else ctx->maxcode = MAXCODE(ctx->n_bits); } } if( code == ctx->EOFCode ) { /* * At EOF, write the rest of the buffer. */ while( ctx->cur_bits > 0 ) { char_out( (unsigned int)(ctx->cur_accum & 0xff), ctx); ctx->cur_accum >>= 8; ctx->cur_bits -= 8; } /* Flag that it's done to prevent re-entry. */ ctx->cur_bits = CUR_BITS_FINISHED; flush_char(ctx); } } /* * Clear out the hash table */ static void cl_block (GifCtx *ctx) /* table clear for block compress */ { cl_hash ( (count_int) hsize, ctx ); ctx->free_ent = ctx->ClearCode + 2; ctx->clear_flg = 1; output( (code_int)ctx->ClearCode, ctx); } static void cl_hash(register count_int chsize, GifCtx *ctx) /* reset code table */ { register count_int *htab_p = ctx->htab+chsize; register long i; register long m1 = -1; i = chsize - 16; do { /* might use Sys V memset(3) here */ *(htab_p-16) = m1; *(htab_p-15) = m1; *(htab_p-14) = m1; *(htab_p-13) = m1; *(htab_p-12) = m1; *(htab_p-11) = m1; *(htab_p-10) = m1; *(htab_p-9) = m1; *(htab_p-8) = m1; *(htab_p-7) = m1; *(htab_p-6) = m1; *(htab_p-5) = m1; *(htab_p-4) = m1; *(htab_p-3) = m1; *(htab_p-2) = m1; *(htab_p-1) = m1; htab_p -= 16; } while ((i -= 16) >= 0); for ( i += 16; i > 0; --i ) *--htab_p = m1; } /****************************************************************************** * * GIF Specific routines * ******************************************************************************/ /* * Set up the 'byte output' routine */ static void char_init(GifCtx *ctx) { ctx->a_count = 0; } /* * Add a character to the end of the current packet, and if it is 254 * characters, flush the packet to disk. */ static void char_out(int c, GifCtx *ctx) { ctx->accum[ ctx->a_count++ ] = c; if( ctx->a_count >= 254 ) flush_char(ctx); } /* * Flush the packet to disk, and reset the accumulator */ static void flush_char(GifCtx *ctx) { if( ctx->a_count > 0 ) { gdPutC( ctx->a_count, ctx->g_outfile ); gdPutBuf( ctx->accum, ctx->a_count, ctx->g_outfile ); ctx->a_count = 0; } } static int gifPutWord(int w, gdIOCtx *out) { /* Byte order is little-endian */ gdPutC(w & 0xFF, out); gdPutC((w >> 8) & 0xFF, out); return 0; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_1407_0
crossvul-cpp_data_bad_59_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2011 Andres Mejia * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "archive_platform.h" #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include <time.h> #include <limits.h> #ifdef HAVE_ZLIB_H #include <zlib.h> /* crc32 */ #endif #include "archive.h" #ifndef HAVE_ZLIB_H #include "archive_crc32.h" #endif #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_ppmd7_private.h" #include "archive_private.h" #include "archive_read_private.h" /* RAR signature, also known as the mark header */ #define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00" /* Header types */ #define MARK_HEAD 0x72 #define MAIN_HEAD 0x73 #define FILE_HEAD 0x74 #define COMM_HEAD 0x75 #define AV_HEAD 0x76 #define SUB_HEAD 0x77 #define PROTECT_HEAD 0x78 #define SIGN_HEAD 0x79 #define NEWSUB_HEAD 0x7a #define ENDARC_HEAD 0x7b /* Main Header Flags */ #define MHD_VOLUME 0x0001 #define MHD_COMMENT 0x0002 #define MHD_LOCK 0x0004 #define MHD_SOLID 0x0008 #define MHD_NEWNUMBERING 0x0010 #define MHD_AV 0x0020 #define MHD_PROTECT 0x0040 #define MHD_PASSWORD 0x0080 #define MHD_FIRSTVOLUME 0x0100 #define MHD_ENCRYPTVER 0x0200 /* Flags common to all headers */ #define HD_MARKDELETION 0x4000 #define HD_ADD_SIZE_PRESENT 0x8000 /* File Header Flags */ #define FHD_SPLIT_BEFORE 0x0001 #define FHD_SPLIT_AFTER 0x0002 #define FHD_PASSWORD 0x0004 #define FHD_COMMENT 0x0008 #define FHD_SOLID 0x0010 #define FHD_LARGE 0x0100 #define FHD_UNICODE 0x0200 #define FHD_SALT 0x0400 #define FHD_VERSION 0x0800 #define FHD_EXTTIME 0x1000 #define FHD_EXTFLAGS 0x2000 /* File dictionary sizes */ #define DICTIONARY_SIZE_64 0x00 #define DICTIONARY_SIZE_128 0x20 #define DICTIONARY_SIZE_256 0x40 #define DICTIONARY_SIZE_512 0x60 #define DICTIONARY_SIZE_1024 0x80 #define DICTIONARY_SIZE_2048 0xA0 #define DICTIONARY_SIZE_4096 0xC0 #define FILE_IS_DIRECTORY 0xE0 #define DICTIONARY_MASK FILE_IS_DIRECTORY /* OS Flags */ #define OS_MSDOS 0 #define OS_OS2 1 #define OS_WIN32 2 #define OS_UNIX 3 #define OS_MAC_OS 4 #define OS_BEOS 5 /* Compression Methods */ #define COMPRESS_METHOD_STORE 0x30 /* LZSS */ #define COMPRESS_METHOD_FASTEST 0x31 #define COMPRESS_METHOD_FAST 0x32 #define COMPRESS_METHOD_NORMAL 0x33 /* PPMd Variant H */ #define COMPRESS_METHOD_GOOD 0x34 #define COMPRESS_METHOD_BEST 0x35 #define CRC_POLYNOMIAL 0xEDB88320 #define NS_UNIT 10000000 #define DICTIONARY_MAX_SIZE 0x400000 #define MAINCODE_SIZE 299 #define OFFSETCODE_SIZE 60 #define LOWOFFSETCODE_SIZE 17 #define LENGTHCODE_SIZE 28 #define HUFFMAN_TABLE_SIZE \ MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE #define MAX_SYMBOL_LENGTH 0xF #define MAX_SYMBOLS 20 /* * Considering L1,L2 cache miss and a calling of write system-call, * the best size of the output buffer(uncompressed buffer) is 128K. * If the structure of extracting process is changed, this value * might be researched again. */ #define UNP_BUFFER_SIZE (128 * 1024) /* Define this here for non-Windows platforms */ #if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__)) #define FILE_ATTRIBUTE_DIRECTORY 0x10 #endif /* Fields common to all headers */ struct rar_header { char crc[2]; char type; char flags[2]; char size[2]; }; /* Fields common to all file headers */ struct rar_file_header { char pack_size[4]; char unp_size[4]; char host_os; char file_crc[4]; char file_time[4]; char unp_ver; char method; char name_size[2]; char file_attr[4]; }; struct huffman_tree_node { int branches[2]; }; struct huffman_table_entry { unsigned int length; int value; }; struct huffman_code { struct huffman_tree_node *tree; int numentries; int numallocatedentries; int minlength; int maxlength; int tablesize; struct huffman_table_entry *table; }; struct lzss { unsigned char *window; int mask; int64_t position; }; struct data_block_offsets { int64_t header_size; int64_t start_offset; int64_t end_offset; }; struct rar { /* Entries from main RAR header */ unsigned main_flags; unsigned long file_crc; char reserved1[2]; char reserved2[4]; char encryptver; /* File header entries */ char compression_method; unsigned file_flags; int64_t packed_size; int64_t unp_size; time_t mtime; long mnsec; mode_t mode; char *filename; char *filename_save; size_t filename_save_size; size_t filename_allocated; /* File header optional entries */ char salt[8]; time_t atime; long ansec; time_t ctime; long cnsec; time_t arctime; long arcnsec; /* Fields to help with tracking decompression of files. */ int64_t bytes_unconsumed; int64_t bytes_remaining; int64_t bytes_uncopied; int64_t offset; int64_t offset_outgoing; int64_t offset_seek; char valid; unsigned int unp_offset; unsigned int unp_buffer_size; unsigned char *unp_buffer; unsigned int dictionary_size; char start_new_block; char entry_eof; unsigned long crc_calculated; int found_first_header; char has_endarc_header; struct data_block_offsets *dbo; unsigned int cursor; unsigned int nodes; /* LZSS members */ struct huffman_code maincode; struct huffman_code offsetcode; struct huffman_code lowoffsetcode; struct huffman_code lengthcode; unsigned char lengthtable[HUFFMAN_TABLE_SIZE]; struct lzss lzss; char output_last_match; unsigned int lastlength; unsigned int lastoffset; unsigned int oldoffset[4]; unsigned int lastlowoffset; unsigned int numlowoffsetrepeats; int64_t filterstart; char start_new_table; /* PPMd Variant H members */ char ppmd_valid; char ppmd_eod; char is_ppmd_block; int ppmd_escape; CPpmd7 ppmd7_context; CPpmd7z_RangeDec range_dec; IByteIn bytein; /* * String conversion object. */ int init_default_conversion; struct archive_string_conv *sconv_default; struct archive_string_conv *opt_sconv; struct archive_string_conv *sconv_utf8; struct archive_string_conv *sconv_utf16be; /* * Bit stream reader. */ struct rar_br { #define CACHE_TYPE uint64_t #define CACHE_BITS (8 * sizeof(CACHE_TYPE)) /* Cache buffer. */ CACHE_TYPE cache_buffer; /* Indicates how many bits avail in cache_buffer. */ int cache_avail; ssize_t avail_in; const unsigned char *next_in; } br; /* * Custom field to denote that this archive contains encrypted entries */ int has_encrypted_entries; }; static int archive_read_support_format_rar_capabilities(struct archive_read *); static int archive_read_format_rar_has_encrypted_entries(struct archive_read *); static int archive_read_format_rar_bid(struct archive_read *, int); static int archive_read_format_rar_options(struct archive_read *, const char *, const char *); static int archive_read_format_rar_read_header(struct archive_read *, struct archive_entry *); static int archive_read_format_rar_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_rar_read_data_skip(struct archive_read *a); static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t, int); static int archive_read_format_rar_cleanup(struct archive_read *); /* Support functions */ static int read_header(struct archive_read *, struct archive_entry *, char); static time_t get_time(int); static int read_exttime(const char *, struct rar *, const char *); static int read_symlink_stored(struct archive_read *, struct archive_entry *, struct archive_string_conv *); static int read_data_stored(struct archive_read *, const void **, size_t *, int64_t *); static int read_data_compressed(struct archive_read *, const void **, size_t *, int64_t *); static int rar_br_preparation(struct archive_read *, struct rar_br *); static int parse_codes(struct archive_read *); static void free_codes(struct archive_read *); static int read_next_symbol(struct archive_read *, struct huffman_code *); static int create_code(struct archive_read *, struct huffman_code *, unsigned char *, int, char); static int add_value(struct archive_read *, struct huffman_code *, int, int, int); static int new_node(struct huffman_code *); static int make_table(struct archive_read *, struct huffman_code *); static int make_table_recurse(struct archive_read *, struct huffman_code *, int, struct huffman_table_entry *, int, int); static int64_t expand(struct archive_read *, int64_t); static int copy_from_lzss_window(struct archive_read *, const void **, int64_t, int); static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *); /* * Bit stream reader. */ /* Check that the cache buffer has enough bits. */ #define rar_br_has(br, n) ((br)->cache_avail >= n) /* Get compressed data by bit. */ #define rar_br_bits(br, n) \ (((uint32_t)((br)->cache_buffer >> \ ((br)->cache_avail - (n)))) & cache_masks[n]) #define rar_br_bits_forced(br, n) \ (((uint32_t)((br)->cache_buffer << \ ((n) - (br)->cache_avail))) & cache_masks[n]) /* Read ahead to make sure the cache buffer has enough compressed data we * will use. * True : completed, there is enough data in the cache buffer. * False : there is no data in the stream. */ #define rar_br_read_ahead(a, br, n) \ ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n))) /* Notify how many bits we consumed. */ #define rar_br_consume(br, n) ((br)->cache_avail -= (n)) #define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7) static const uint32_t cache_masks[] = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; /* * Shift away used bits in the cache data and fill it up with following bits. * Call this when cache buffer does not have enough bits you need. * * Returns 1 if the cache buffer is full. * Returns 0 if the cache buffer is not full; input buffer is empty. */ static int rar_br_fillup(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); int n = CACHE_BITS - br->cache_avail; for (;;) { switch (n >> 3) { case 8: if (br->avail_in >= 8) { br->cache_buffer = ((uint64_t)br->next_in[0]) << 56 | ((uint64_t)br->next_in[1]) << 48 | ((uint64_t)br->next_in[2]) << 40 | ((uint64_t)br->next_in[3]) << 32 | ((uint32_t)br->next_in[4]) << 24 | ((uint32_t)br->next_in[5]) << 16 | ((uint32_t)br->next_in[6]) << 8 | (uint32_t)br->next_in[7]; br->next_in += 8; br->avail_in -= 8; br->cache_avail += 8 * 8; rar->bytes_unconsumed += 8; rar->bytes_remaining -= 8; return (1); } break; case 7: if (br->avail_in >= 7) { br->cache_buffer = (br->cache_buffer << 56) | ((uint64_t)br->next_in[0]) << 48 | ((uint64_t)br->next_in[1]) << 40 | ((uint64_t)br->next_in[2]) << 32 | ((uint32_t)br->next_in[3]) << 24 | ((uint32_t)br->next_in[4]) << 16 | ((uint32_t)br->next_in[5]) << 8 | (uint32_t)br->next_in[6]; br->next_in += 7; br->avail_in -= 7; br->cache_avail += 7 * 8; rar->bytes_unconsumed += 7; rar->bytes_remaining -= 7; return (1); } break; case 6: if (br->avail_in >= 6) { br->cache_buffer = (br->cache_buffer << 48) | ((uint64_t)br->next_in[0]) << 40 | ((uint64_t)br->next_in[1]) << 32 | ((uint32_t)br->next_in[2]) << 24 | ((uint32_t)br->next_in[3]) << 16 | ((uint32_t)br->next_in[4]) << 8 | (uint32_t)br->next_in[5]; br->next_in += 6; br->avail_in -= 6; br->cache_avail += 6 * 8; rar->bytes_unconsumed += 6; rar->bytes_remaining -= 6; return (1); } break; case 0: /* We have enough compressed data in * the cache buffer.*/ return (1); default: break; } if (br->avail_in <= 0) { if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor * actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) return (0); if (br->avail_in == 0) return (0); } br->cache_buffer = (br->cache_buffer << 8) | *br->next_in++; br->avail_in--; br->cache_avail += 8; n -= 8; rar->bytes_unconsumed++; rar->bytes_remaining--; } } static int rar_br_preparation(struct archive_read *a, struct rar_br *br) { struct rar *rar = (struct rar *)(a->format->data); if (rar->bytes_remaining > 0) { br->next_in = rar_read_ahead(a, 1, &(br->avail_in)); if (br->next_in == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } if (br->cache_avail == 0) (void)rar_br_fillup(a, br); } return (ARCHIVE_OK); } /* Find last bit set */ static inline int rar_fls(unsigned int word) { word |= (word >> 1); word |= (word >> 2); word |= (word >> 4); word |= (word >> 8); word |= (word >> 16); return word - (word >> 1); } /* LZSS functions */ static inline int64_t lzss_position(struct lzss *lzss) { return lzss->position; } static inline int lzss_mask(struct lzss *lzss) { return lzss->mask; } static inline int lzss_size(struct lzss *lzss) { return lzss->mask + 1; } static inline int lzss_offset_for_position(struct lzss *lzss, int64_t pos) { return (int)(pos & lzss->mask); } static inline unsigned char * lzss_pointer_for_position(struct lzss *lzss, int64_t pos) { return &lzss->window[lzss_offset_for_position(lzss, pos)]; } static inline int lzss_current_offset(struct lzss *lzss) { return lzss_offset_for_position(lzss, lzss->position); } static inline uint8_t * lzss_current_pointer(struct lzss *lzss) { return lzss_pointer_for_position(lzss, lzss->position); } static inline void lzss_emit_literal(struct rar *rar, uint8_t literal) { *lzss_current_pointer(&rar->lzss) = literal; rar->lzss.position++; } static inline void lzss_emit_match(struct rar *rar, int offset, int length) { int dstoffs = lzss_current_offset(&rar->lzss); int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss); int l, li, remaining; unsigned char *d, *s; remaining = length; while (remaining > 0) { l = remaining; if (dstoffs > srcoffs) { if (l > lzss_size(&rar->lzss) - dstoffs) l = lzss_size(&rar->lzss) - dstoffs; } else { if (l > lzss_size(&rar->lzss) - srcoffs) l = lzss_size(&rar->lzss) - srcoffs; } d = &(rar->lzss.window[dstoffs]); s = &(rar->lzss.window[srcoffs]); if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs)) memcpy(d, s, l); else { for (li = 0; li < l; li++) d[li] = s[li]; } remaining -= l; dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss)); srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss)); } rar->lzss.position += length; } static Byte ppmd_read(void *p) { struct archive_read *a = ((IByteIn*)p)->a; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); Byte b; if (!rar_br_read_ahead(a, br, 8)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return 0; } b = rar_br_bits(br, 8); rar_br_consume(br, 8); return b; } int archive_read_support_format_rar(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct rar *rar; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_rar"); rar = (struct rar *)calloc(sizeof(*rar), 1); if (rar == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data"); return (ARCHIVE_FATAL); } /* * Until enough data has been read, we cannot tell about * any encrypted entries yet. */ rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; r = __archive_read_register_format(a, rar, "rar", archive_read_format_rar_bid, archive_read_format_rar_options, archive_read_format_rar_read_header, archive_read_format_rar_read_data, archive_read_format_rar_read_data_skip, archive_read_format_rar_seek_data, archive_read_format_rar_cleanup, archive_read_support_format_rar_capabilities, archive_read_format_rar_has_encrypted_entries); if (r != ARCHIVE_OK) free(rar); return (r); } static int archive_read_support_format_rar_capabilities(struct archive_read * a) { (void)a; /* UNUSED */ return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA); } static int archive_read_format_rar_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct rar * rar = (struct rar *)_a->format->data; if (rar) { return rar->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } static int archive_read_format_rar_bid(struct archive_read *a, int best_bid) { const char *p; /* If there's already a bid > 30, we'll never win. */ if (best_bid > 30) return (-1); if ((p = __archive_read_ahead(a, 7, NULL)) == NULL) return (-1); if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) { /* This is a PE file */ ssize_t offset = 0x10000; ssize_t window = 4096; ssize_t bytes_avail; while (offset + window <= (1024 * 128)) { const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail); if (buff == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) return (0); continue; } p = buff + offset; while (p + 7 < buff + bytes_avail) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) return (30); p += 0x10; } offset = p - buff; } } return (0); } static int skip_sfx(struct archive_read *a) { const void *h; const char *p, *q; size_t skip, total; ssize_t bytes, window; total = 0; window = 4096; while (total + window <= (1024 * 128)) { h = __archive_read_ahead(a, window, &bytes); if (h == NULL) { /* Remaining bytes are less than window. */ window >>= 1; if (window < 0x40) goto fatal; continue; } if (bytes < 0x40) goto fatal; p = h; q = p + bytes; /* * Scan ahead until we find something that looks * like the RAR header. */ while (p + 7 < q) { if (memcmp(p, RAR_SIGNATURE, 7) == 0) { skip = p - (const char *)h; __archive_read_consume(a, skip); return (ARCHIVE_OK); } p += 0x10; } skip = p - (const char *)h; __archive_read_consume(a, skip); total += skip; } fatal: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Couldn't find out RAR header"); return (ARCHIVE_FATAL); } static int archive_read_format_rar_options(struct archive_read *a, const char *key, const char *val) { struct rar *rar; int ret = ARCHIVE_FAILED; rar = (struct rar *)(a->format->data); if (strcmp(key, "hdrcharset") == 0) { if (val == NULL || val[0] == 0) archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "rar: hdrcharset option needs a character-set name"); else { rar->opt_sconv = archive_string_conversion_from_charset( &a->archive, val, 0); if (rar->opt_sconv != NULL) ret = ARCHIVE_OK; else ret = ARCHIVE_FATAL; } return (ret); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int archive_read_format_rar_read_header(struct archive_read *a, struct archive_entry *entry) { const void *h; const char *p; struct rar *rar; size_t skip; char head_type; int ret; unsigned flags; unsigned long crc32_expected; a->archive.archive_format = ARCHIVE_FORMAT_RAR; if (a->archive.archive_format_name == NULL) a->archive.archive_format_name = "RAR"; rar = (struct rar *)(a->format->data); /* * It should be sufficient to call archive_read_next_header() for * a reader to determine if an entry is encrypted or not. If the * encryption of an entry is only detectable when calling * archive_read_data(), so be it. We'll do the same check there * as well. */ if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if * this fails. */ if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_EOF); p = h; if (rar->found_first_header == 0 && ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) { /* This is an executable ? Must be self-extracting... */ ret = skip_sfx(a); if (ret < ARCHIVE_WARN) return (ret); } rar->found_first_header = 1; while (1) { unsigned long crc32_val; if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; head_type = p[2]; switch(head_type) { case MARK_HEAD: if (memcmp(p, RAR_SIGNATURE, 7) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid marker header"); return (ARCHIVE_FATAL); } __archive_read_consume(a, 7); break; case MAIN_HEAD: rar->main_flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1)); memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1), sizeof(rar->reserved2)); if (rar->main_flags & MHD_ENCRYPTVER) { if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } rar->encryptver = *(p + 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)); } /* Main header is password encrypted, so we cannot read any file names or any other info about files from the header. */ if (rar->main_flags & MHD_PASSWORD) { archive_entry_set_is_metadata_encrypted(entry, 1); archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2); if ((crc32_val & 0xffff) != archive_le16dec(p)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } __archive_read_consume(a, skip); break; case FILE_HEAD: return read_header(a, entry, head_type); case COMM_HEAD: case AV_HEAD: case SUB_HEAD: case PROTECT_HEAD: case SIGN_HEAD: case ENDARC_HEAD: flags = archive_le16dec(p + 3); skip = archive_le16dec(p + 5); if (skip < 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if (flags & HD_ADD_SIZE_PRESENT) { if (skip < 7 + 4) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size too small"); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, skip, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; skip += archive_le32dec(p + 7); } /* Skip over the 2-byte CRC at the beginning of the header. */ crc32_expected = archive_le16dec(p); __archive_read_consume(a, 2); skip -= 2; /* Skim the entire header and compute the CRC. */ crc32_val = 0; while (skip > 0) { size_t to_read = skip; ssize_t did_read; if (to_read > 32 * 1024) { to_read = 32 * 1024; } if ((h = __archive_read_ahead(a, to_read, &did_read)) == NULL) { return (ARCHIVE_FATAL); } p = h; crc32_val = crc32(crc32_val, (const unsigned char *)p, (unsigned)did_read); __archive_read_consume(a, did_read); skip -= did_read; } if ((crc32_val & 0xffff) != crc32_expected) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } if (head_type == ENDARC_HEAD) return (ARCHIVE_EOF); break; case NEWSUB_HEAD: if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN) return ret; break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file"); return (ARCHIVE_FATAL); } } } static int archive_read_format_rar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar = (struct rar *)(a->format->data); int ret; if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } *buff = NULL; if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { *size = 0; *offset = rar->offset; if (*offset < rar->unp_size) *offset = rar->unp_size; return (ARCHIVE_EOF); } switch (rar->compression_method) { case COMPRESS_METHOD_STORE: ret = read_data_stored(a, buff, size, offset); break; case COMPRESS_METHOD_FASTEST: case COMPRESS_METHOD_FAST: case COMPRESS_METHOD_NORMAL: case COMPRESS_METHOD_GOOD: case COMPRESS_METHOD_BEST: ret = read_data_compressed(a, buff, size, offset); if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported compression method for RAR file."); ret = ARCHIVE_FATAL; break; } return (ret); } static int archive_read_format_rar_read_data_skip(struct archive_read *a) { struct rar *rar; int64_t bytes_skipped; int ret; rar = (struct rar *)(a->format->data); if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } if (rar->bytes_remaining > 0) { bytes_skipped = __archive_read_consume(a, rar->bytes_remaining); if (bytes_skipped < 0) return (ARCHIVE_FATAL); } /* Compressed data to skip must be read from each header in a multivolume * archive. */ if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) return ret; return archive_read_format_rar_read_data_skip(a); } return (ARCHIVE_OK); } static int64_t archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset, int whence) { int64_t client_offset, ret; unsigned int i; struct rar *rar = (struct rar *)(a->format->data); if (rar->compression_method == COMPRESS_METHOD_STORE) { /* Modify the offset for use with SEEK_SET */ switch (whence) { case SEEK_CUR: client_offset = rar->offset_seek; break; case SEEK_END: client_offset = rar->unp_size; break; case SEEK_SET: default: client_offset = 0; } client_offset += offset; if (client_offset < 0) { /* Can't seek past beginning of data block */ return -1; } else if (client_offset > rar->unp_size) { /* * Set the returned offset but only seek to the end of * the data block. */ rar->offset_seek = client_offset; client_offset = rar->unp_size; } client_offset += rar->dbo[0].start_offset; i = 0; while (i < rar->cursor) { i++; client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset; } if (rar->main_flags & MHD_VOLUME) { /* Find the appropriate offset among the multivolume archive */ while (1) { if (client_offset < rar->dbo[rar->cursor].start_offset && rar->file_flags & FHD_SPLIT_BEFORE) { /* Search backwards for the correct data block */ if (rar->cursor == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Attempt to seek past beginning of RAR data block"); return (ARCHIVE_FAILED); } rar->cursor--; client_offset -= rar->dbo[rar->cursor+1].start_offset - rar->dbo[rar->cursor].end_offset; if (client_offset < rar->dbo[rar->cursor].start_offset) continue; ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor].header_size, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } rar->cursor--; break; } else if (client_offset > rar->dbo[rar->cursor].end_offset && rar->file_flags & FHD_SPLIT_AFTER) { /* Search forward for the correct data block */ rar->cursor++; if (rar->cursor < rar->nodes && client_offset > rar->dbo[rar->cursor].end_offset) { client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } rar->cursor--; ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Error during seek of RAR file"); return (ARCHIVE_FAILED); } client_offset += rar->dbo[rar->cursor].start_offset - rar->dbo[rar->cursor-1].end_offset; continue; } break; } } ret = __archive_read_seek(a, client_offset, SEEK_SET); if (ret < (ARCHIVE_OK)) return ret; rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret; i = rar->cursor; while (i > 0) { i--; ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset; } ret -= rar->dbo[0].start_offset; /* Always restart reading the file after a seek */ __archive_reset_read_data(&a->archive); rar->bytes_unconsumed = 0; rar->offset = 0; /* * If a seek past the end of file was requested, return the requested * offset. */ if (ret == rar->unp_size && rar->offset_seek > rar->unp_size) return rar->offset_seek; /* Return the new offset */ rar->offset_seek = ret; return rar->offset_seek; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Seeking of compressed RAR files is unsupported"); } return (ARCHIVE_FAILED); } static int archive_read_format_rar_cleanup(struct archive_read *a) { struct rar *rar; rar = (struct rar *)(a->format->data); free_codes(a); free(rar->filename); free(rar->filename_save); free(rar->dbo); free(rar->unp_buffer); free(rar->lzss.window); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); free(rar); (a->format->data) = NULL; return (ARCHIVE_OK); } static int read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; /* * Do not increment filename_size here as the computations below * add the space for the terminating NUL explicitly. */ filename[filename_size] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; } static time_t get_time(int ttime) { struct tm tm; tm.tm_sec = 2 * (ttime & 0x1f); tm.tm_min = (ttime >> 5) & 0x3f; tm.tm_hour = (ttime >> 11) & 0x1f; tm.tm_mday = (ttime >> 16) & 0x1f; tm.tm_mon = ((ttime >> 21) & 0x0f) - 1; tm.tm_year = ((ttime >> 25) & 0x7f) + 80; tm.tm_isdst = -1; return mktime(&tm); } static int read_exttime(const char *p, struct rar *rar, const char *endp) { unsigned rmode, flags, rem, j, count; int ttime, i; struct tm *tm; time_t t; long nsec; if (p + 2 > endp) return (-1); flags = archive_le16dec(p); p += 2; for (i = 3; i >= 0; i--) { t = 0; if (i == 3) t = rar->mtime; rmode = flags >> i * 4; if (rmode & 8) { if (!t) { if (p + 4 > endp) return (-1); ttime = archive_le32dec(p); t = get_time(ttime); p += 4; } rem = 0; count = rmode & 3; if (p + count > endp) return (-1); for (j = 0; j < count; j++) { rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8); p++; } tm = localtime(&t); nsec = tm->tm_sec + rem / NS_UNIT; if (rmode & 4) { tm->tm_sec++; t = mktime(tm); } if (i == 3) { rar->mtime = t; rar->mnsec = nsec; } else if (i == 2) { rar->ctime = t; rar->cnsec = nsec; } else if (i == 1) { rar->atime = t; rar->ansec = nsec; } else { rar->arctime = t; rar->arcnsec = nsec; } } } return (0); } static int read_symlink_stored(struct archive_read *a, struct archive_entry *entry, struct archive_string_conv *sconv) { const void *h; const char *p; struct rar *rar; int ret = (ARCHIVE_OK); rar = (struct rar *)(a->format->data); if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; if (archive_entry_copy_symlink_l(entry, p, (size_t)rar->packed_size, sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for link"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "link cannot be converted from %s to current locale.", archive_string_conversion_charset_name(sconv)); ret = (ARCHIVE_WARN); } __archive_read_consume(a, rar->packed_size); return ret; } static int read_data_stored(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; ssize_t bytes_avail; rar = (struct rar *)(a->format->data); if (rar->bytes_remaining == 0 && !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)) { *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } *buff = rar_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } *size = bytes_avail; *offset = rar->offset; rar->offset += bytes_avail; rar->offset_seek += bytes_avail; rar->bytes_remaining -= bytes_avail; rar->bytes_unconsumed = bytes_avail; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)bytes_avail); return (ARCHIVE_OK); } static int read_data_compressed(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar; int64_t start, end, actualend; size_t bs; int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i; rar = (struct rar *)(a->format->data); do { if (!rar->valid) return (ARCHIVE_FATAL); if (rar->ppmd_eod || (rar->dictionary_size && rar->offset >= rar->unp_size)) { if (rar->unp_offset > 0) { /* * We have unprocessed extracted data. write it out. */ *buff = rar->unp_buffer; *size = rar->unp_offset; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); rar->unp_offset = 0; return (ARCHIVE_OK); } *buff = NULL; *size = 0; *offset = rar->offset; if (rar->file_crc != rar->crc_calculated) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "File CRC error"); return (ARCHIVE_FATAL); } rar->entry_eof = 1; return (ARCHIVE_EOF); } if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0) { if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; if (*buff != NULL) { rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return (ret); } continue; } if (!rar->br.next_in && (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN) return (ret); if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN))) return (ret); if (rar->is_ppmd_block) { if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } if(sym != rar->ppmd_escape) { lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } else { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } switch(code) { case 0: rar->start_new_table = 1; return read_data_compressed(a, buff, size, offset); case 2: rar->ppmd_eod = 1;/* End Of ppmd Data. */ continue; case 3: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); case 4: lzss_offset = 0; for (i = 2; i >= 0; i--) { if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_offset |= code << (i * 8); } if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, lzss_offset + 2, length + 32); rar->bytes_uncopied += length + 32; break; case 5: if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol( &rar->ppmd7_context, &rar->range_dec.p)) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid symbol"); return (ARCHIVE_FATAL); } lzss_emit_match(rar, 1, length + 4); rar->bytes_uncopied += length + 4; break; default: lzss_emit_literal(rar, sym); rar->bytes_uncopied++; } } } else { start = rar->offset; end = start + rar->dictionary_size; rar->filterstart = INT64_MAX; if ((actualend = expand(a, end)) < 0) return ((int)actualend); rar->bytes_uncopied = actualend - start; if (rar->bytes_uncopied == 0) { /* Broken RAR files cause this case. * NOTE: If this case were possible on a normal RAR file * we would find out where it was actually bad and * what we would do to solve it. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file"); return (ARCHIVE_FATAL); } } if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset)) bs = rar->unp_buffer_size - rar->unp_offset; else bs = (size_t)rar->bytes_uncopied; ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs); if (ret != ARCHIVE_OK) return (ret); rar->offset += bs; rar->bytes_uncopied -= bs; /* * If *buff is NULL, it means unp_buffer is not full. * So we have to continue extracting a RAR file. */ } while (*buff == NULL); rar->unp_offset = 0; *size = rar->unp_buffer_size; *offset = rar->offset_outgoing; rar->offset_outgoing += *size; /* Calculate File CRC. */ rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size); return ret; } static int parse_codes(struct archive_read *a) { int i, j, val, n, r; unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; unsigned int maxorder; struct huffman_code precode; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); free_codes(a); /* Skip to the next byte */ rar_br_consume_unalined_bits(br); /* PPMd block flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) { rar_br_consume(br, 1); if (!rar_br_read_ahead(a, br, 7)) goto truncated_data; ppmd_flags = rar_br_bits(br, 7); rar_br_consume(br, 7); /* Memory is allocated in MB */ if (ppmd_flags & 0x20) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; rar_br_consume(br, 8); } if (ppmd_flags & 0x40) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); rar_br_consume(br, 8); } else rar->ppmd_escape = 2; if (ppmd_flags & 0x20) { maxorder = (ppmd_flags & 0x1F) + 1; if(maxorder > 16) maxorder = 16 + (maxorder - 16) * 3; if (maxorder == 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } /* Make sure ppmd7_contest is freed before Ppmd7_Construct * because reading a broken file cause this abnormal sequence. */ __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); rar->bytein.a = a; rar->bytein.Read = &ppmd_read; __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); rar->range_dec.Stream = &rar->bytein; __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); if (rar->dictionary_size == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid zero dictionary size"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, rar->dictionary_size)) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); rar->ppmd_valid = 1; } else { if (!rar->ppmd_valid) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid PPMd sequence"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } } } else { rar_br_consume(br, 1); /* Keep existing table flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if (!rar_br_bits(br, 1)) memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); rar_br_consume(br, 1); memset(&bitlengths, 0, sizeof(bitlengths)); for (i = 0; i < MAX_SYMBOLS;) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; bitlengths[i++] = rar_br_bits(br, 4); rar_br_consume(br, 4); if (bitlengths[i-1] == 0xF) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; zerocount = rar_br_bits(br, 4); rar_br_consume(br, 4); if (zerocount) { i--; for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) bitlengths[i++] = 0; } } } memset(&precode, 0, sizeof(precode)); r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) { free(precode.tree); free(precode.table); return (r); } for (i = 0; i < HUFFMAN_TABLE_SIZE;) { if ((val = read_next_symbol(a, &precode)) < 0) { free(precode.tree); free(precode.table); return (ARCHIVE_FATAL); } if (val < 16) { rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; i++; } else if (val < 18) { if (i == 0) { free(precode.tree); free(precode.table); archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file."); return (ARCHIVE_FATAL); } if(val == 16) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) { rar->lengthtable[i] = rar->lengthtable[i-1]; i++; } } else { if(val == 18) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) rar->lengthtable[i++] = 0; } } free(precode.tree); free(precode.table); r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lowoffsetcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lengthcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); } if (!rar->dictionary_size || !rar->lzss.window) { /* Seems as though dictionary sizes are not used. Even so, minimize * memory usage as much as possible. */ void *new_window; unsigned int new_size; if (rar->unp_size >= DICTIONARY_MAX_SIZE) new_size = DICTIONARY_MAX_SIZE; else new_size = rar_fls((unsigned int)rar->unp_size) << 1; new_window = realloc(rar->lzss.window, new_size); if (new_window == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } rar->lzss.window = (unsigned char *)new_window; rar->dictionary_size = new_size; memset(rar->lzss.window, 0, rar->dictionary_size); rar->lzss.mask = rar->dictionary_size - 1; } rar->start_new_table = 0; return (ARCHIVE_OK); truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); } static void free_codes(struct archive_read *a) { struct rar *rar = (struct rar *)(a->format->data); free(rar->maincode.tree); free(rar->offsetcode.tree); free(rar->lowoffsetcode.tree); free(rar->lengthcode.tree); free(rar->maincode.table); free(rar->offsetcode.table); free(rar->lowoffsetcode.table); free(rar->lengthcode.table); memset(&rar->maincode, 0, sizeof(rar->maincode)); memset(&rar->offsetcode, 0, sizeof(rar->offsetcode)); memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode)); memset(&rar->lengthcode, 0, sizeof(rar->lengthcode)); } static int read_next_symbol(struct archive_read *a, struct huffman_code *code) { unsigned char bit; unsigned int bits; int length, value, node; struct rar *rar; struct rar_br *br; if (!code->table) { if (make_table(a, code) != (ARCHIVE_OK)) return -1; } rar = (struct rar *)(a->format->data); br = &(rar->br); /* Look ahead (peek) at bits */ if (!rar_br_read_ahead(a, br, code->tablesize)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bits = rar_br_bits(br, code->tablesize); length = code->table[bits].length; value = code->table[bits].value; if (length < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } if (length <= code->tablesize) { /* Skip length bits */ rar_br_consume(br, length); return value; } /* Skip tablesize bits */ rar_br_consume(br, code->tablesize); node = value; while (!(code->tree[node].branches[0] == code->tree[node].branches[1])) { if (!rar_br_read_ahead(a, br, 1)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return -1; } bit = rar_br_bits(br, 1); rar_br_consume(br, 1); if (code->tree[node].branches[bit] < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid prefix code in bitstream"); return -1; } node = code->tree[node].branches[bit]; } return code->tree[node].branches[0]; } static int create_code(struct archive_read *a, struct huffman_code *code, unsigned char *lengths, int numsymbols, char maxlength) { int i, j, codebits = 0, symbolsleft = numsymbols; code->numentries = 0; code->numallocatedentries = 0; if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->numentries = 1; code->minlength = INT_MAX; code->maxlength = INT_MIN; codebits = 0; for(i = 1; i <= maxlength; i++) { for(j = 0; j < numsymbols; j++) { if (lengths[j] != i) continue; if (add_value(a, code, j, codebits, i) != ARCHIVE_OK) return (ARCHIVE_FATAL); codebits++; if (--symbolsleft <= 0) { break; break; } } codebits <<= 1; } return (ARCHIVE_OK); } static int add_value(struct archive_read *a, struct huffman_code *code, int value, int codebits, int length) { int repeatpos, lastnode, bitpos, bit, repeatnode, nextnode; free(code->table); code->table = NULL; if(length > code->maxlength) code->maxlength = length; if(length < code->minlength) code->minlength = length; repeatpos = -1; if (repeatpos == 0 || (repeatpos >= 0 && (((codebits >> (repeatpos - 1)) & 3) == 0 || ((codebits >> (repeatpos - 1)) & 3) == 3))) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeat position"); return (ARCHIVE_FATAL); } lastnode = 0; for (bitpos = length - 1; bitpos >= 0; bitpos--) { bit = (codebits >> bitpos) & 1; /* Leaf node check */ if (code->tree[lastnode].branches[0] == code->tree[lastnode].branches[1]) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } if (bitpos == repeatpos) { /* Open branch check */ if (!(code->tree[lastnode].branches[bit] < 0)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid repeating code"); return (ARCHIVE_FATAL); } if ((repeatnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } if ((nextnode = new_node(code)) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } /* Set branches */ code->tree[lastnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit] = repeatnode; code->tree[repeatnode].branches[bit^1] = nextnode; lastnode = nextnode; bitpos++; /* terminating bit already handled, skip it */ } else { /* Open branch check */ if (code->tree[lastnode].branches[bit] < 0) { if (new_node(code) < 0) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for node data."); return (ARCHIVE_FATAL); } code->tree[lastnode].branches[bit] = code->numentries++; } /* set to branch */ lastnode = code->tree[lastnode].branches[bit]; } } if (!(code->tree[lastnode].branches[0] == -1 && code->tree[lastnode].branches[1] == -2)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Prefix found"); return (ARCHIVE_FATAL); } /* Set leaf value */ code->tree[lastnode].branches[0] = value; code->tree[lastnode].branches[1] = value; return (ARCHIVE_OK); } static int new_node(struct huffman_code *code) { void *new_tree; if (code->numallocatedentries == code->numentries) { int new_num_entries = 256; if (code->numentries > 0) { new_num_entries = code->numentries * 2; } new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree)); if (new_tree == NULL) return (-1); code->tree = (struct huffman_tree_node *)new_tree; code->numallocatedentries = new_num_entries; } code->tree[code->numentries].branches[0] = -1; code->tree[code->numentries].branches[1] = -2; return 1; } static int make_table(struct archive_read *a, struct huffman_code *code) { if (code->maxlength < code->minlength || code->maxlength > 10) code->tablesize = 10; else code->tablesize = code->maxlength; code->table = (struct huffman_table_entry *)calloc(1, sizeof(*code->table) * ((size_t)1 << code->tablesize)); return make_table_recurse(a, code, 0, code->table, 0, code->tablesize); } static int make_table_recurse(struct archive_read *a, struct huffman_code *code, int node, struct huffman_table_entry *table, int depth, int maxdepth) { int currtablesize, i, ret = (ARCHIVE_OK); if (!code->tree) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Huffman tree was not created."); return (ARCHIVE_FATAL); } if (node < 0 || node >= code->numentries) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid location to Huffman tree specified."); return (ARCHIVE_FATAL); } currtablesize = 1 << (maxdepth - depth); if (code->tree[node].branches[0] == code->tree[node].branches[1]) { for(i = 0; i < currtablesize; i++) { table[i].length = depth; table[i].value = code->tree[node].branches[0]; } } else if (node < 0) { for(i = 0; i < currtablesize; i++) table[i].length = -1; } else { if(depth == maxdepth) { table[0].length = maxdepth + 1; table[0].value = node; } else { ret |= make_table_recurse(a, code, code->tree[node].branches[0], table, depth + 1, maxdepth); ret |= make_table_recurse(a, code, code->tree[node].branches[1], table + currtablesize / 2, depth + 1, maxdepth); } } return ret; } static int64_t expand(struct archive_read *a, int64_t end) { static const unsigned char lengthbases[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224 }; static const unsigned char lengthbits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; static const unsigned int offsetbases[] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 655360, 720896, 786432, 851968, 917504, 983040, 1048576, 1310720, 1572864, 1835008, 2097152, 2359296, 2621440, 2883584, 3145728, 3407872, 3670016, 3932160 }; static const unsigned char offsetbits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 }; static const unsigned char shortbases[] = { 0, 4, 8, 16, 32, 64, 128, 192 }; static const unsigned char shortbits[] = { 2, 2, 3, 4, 5, 6, 6, 6 }; int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol; unsigned char newfile; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); if (rar->filterstart < end) end = rar->filterstart; while (1) { if (rar->output_last_match && lzss_position(&rar->lzss) + rar->lastlength <= end) { lzss_emit_match(rar, rar->lastoffset, rar->lastlength); rar->output_last_match = 0; } if(rar->is_ppmd_block || rar->output_last_match || lzss_position(&rar->lzss) >= end) return lzss_position(&rar->lzss); if ((symbol = read_next_symbol(a, &rar->maincode)) < 0) return (ARCHIVE_FATAL); rar->output_last_match = 0; if (symbol < 256) { lzss_emit_literal(rar, symbol); continue; } else if (symbol == 256) { if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; newfile = !rar_br_bits(br, 1); rar_br_consume(br, 1); if(newfile) { rar->start_new_block = 1; if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; rar->start_new_table = rar_br_bits(br, 1); rar_br_consume(br, 1); return lzss_position(&rar->lzss); } else { if (parse_codes(a) != ARCHIVE_OK) return (ARCHIVE_FATAL); continue; } } else if(symbol==257) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Parsing filters is unsupported."); return (ARCHIVE_FAILED); } else if(symbol==258) { if(rar->lastlength == 0) continue; offs = rar->lastoffset; len = rar->lastlength; } else if (symbol <= 262) { offsindex = symbol - 259; offs = rar->oldoffset[offsindex]; if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0) goto bad_data; if (lensymbol > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (lensymbol > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[lensymbol] + 2; if (lengthbits[lensymbol] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[lensymbol])) goto truncated_data; len += rar_br_bits(br, lengthbits[lensymbol]); rar_br_consume(br, lengthbits[lensymbol]); } for (i = offsindex; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else if(symbol<=270) { offs = shortbases[symbol-263] + 1; if(shortbits[symbol-263] > 0) { if (!rar_br_read_ahead(a, br, shortbits[symbol-263])) goto truncated_data; offs += rar_br_bits(br, shortbits[symbol-263]); rar_br_consume(br, shortbits[symbol-263]); } len = 2; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } else { if (symbol-271 > (int)(sizeof(lengthbases)/sizeof(lengthbases[0]))) goto bad_data; if (symbol-271 > (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))) goto bad_data; len = lengthbases[symbol-271]+3; if(lengthbits[symbol-271] > 0) { if (!rar_br_read_ahead(a, br, lengthbits[symbol-271])) goto truncated_data; len += rar_br_bits(br, lengthbits[symbol-271]); rar_br_consume(br, lengthbits[symbol-271]); } if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0) goto bad_data; if (offssymbol > (int)(sizeof(offsetbases)/sizeof(offsetbases[0]))) goto bad_data; if (offssymbol > (int)(sizeof(offsetbits)/sizeof(offsetbits[0]))) goto bad_data; offs = offsetbases[offssymbol]+1; if(offsetbits[offssymbol] > 0) { if(offssymbol > 9) { if(offsetbits[offssymbol] > 4) { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4)) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4; rar_br_consume(br, offsetbits[offssymbol] - 4); } if(rar->numlowoffsetrepeats > 0) { rar->numlowoffsetrepeats--; offs += rar->lastlowoffset; } else { if ((lowoffsetsymbol = read_next_symbol(a, &rar->lowoffsetcode)) < 0) return (ARCHIVE_FATAL); if(lowoffsetsymbol == 16) { rar->numlowoffsetrepeats = 15; offs += rar->lastlowoffset; } else { offs += lowoffsetsymbol; rar->lastlowoffset = lowoffsetsymbol; } } } else { if (!rar_br_read_ahead(a, br, offsetbits[offssymbol])) goto truncated_data; offs += rar_br_bits(br, offsetbits[offssymbol]); rar_br_consume(br, offsetbits[offssymbol]); } } if (offs >= 0x40000) len++; if (offs >= 0x2000) len++; for(i = 3; i > 0; i--) rar->oldoffset[i] = rar->oldoffset[i-1]; rar->oldoffset[0] = offs; } rar->lastoffset = offs; rar->lastlength = len; rar->output_last_match = 1; } truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); bad_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } static int copy_from_lzss_window(struct archive_read *a, const void **buffer, int64_t startpos, int length) { int windowoffs, firstpart; struct rar *rar = (struct rar *)(a->format->data); if (!rar->unp_buffer) { if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } } windowoffs = lzss_offset_for_position(&rar->lzss, startpos); if(windowoffs + length <= lzss_size(&rar->lzss)) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } else if (length <= lzss_size(&rar->lzss)) { firstpart = lzss_size(&rar->lzss) - windowoffs; if (firstpart < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } if (firstpart < length) { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], firstpart); memcpy(&rar->unp_buffer[rar->unp_offset + firstpart], &rar->lzss.window[0], length - firstpart); } else { memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs], length); } } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data"); return (ARCHIVE_FATAL); } rar->unp_offset += length; if (rar->unp_offset >= rar->unp_buffer_size) *buffer = rar->unp_buffer; else *buffer = NULL; return (ARCHIVE_OK); } static const void * rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { struct rar *rar = (struct rar *)(a->format->data); const void *h = __archive_read_ahead(a, min, avail); int ret; if (avail) { if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) *avail = a->archive.read_data_requested; if (*avail > rar->bytes_remaining) *avail = (ssize_t)rar->bytes_remaining; if (*avail < 0) return NULL; else if (*avail == 0 && rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) return NULL; return rar_read_ahead(a, min, avail); } } return h; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_59_0
crossvul-cpp_data_bad_348_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_7
crossvul-cpp_data_bad_633_0
/* * Common Block IO controller cgroup interface * * Based on ideas and code from CFQ, CFS and BFQ: * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk> * * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it> * Paolo Valente <paolo.valente@unimore.it> * * Copyright (C) 2009 Vivek Goyal <vgoyal@redhat.com> * Nauman Rafique <nauman@google.com> * * For policy-specific per-blkcg data: * Copyright (C) 2015 Paolo Valente <paolo.valente@unimore.it> * Arianna Avanzini <avanzini.arianna@gmail.com> */ #include <linux/ioprio.h> #include <linux/kdev_t.h> #include <linux/module.h> #include <linux/err.h> #include <linux/blkdev.h> #include <linux/backing-dev.h> #include <linux/slab.h> #include <linux/genhd.h> #include <linux/delay.h> #include <linux/atomic.h> #include <linux/ctype.h> #include <linux/blk-cgroup.h> #include "blk.h" #define MAX_KEY_LEN 100 /* * blkcg_pol_mutex protects blkcg_policy[] and policy [de]activation. * blkcg_pol_register_mutex nests outside of it and synchronizes entire * policy [un]register operations including cgroup file additions / * removals. Putting cgroup file registration outside blkcg_pol_mutex * allows grabbing it from cgroup callbacks. */ static DEFINE_MUTEX(blkcg_pol_register_mutex); static DEFINE_MUTEX(blkcg_pol_mutex); struct blkcg blkcg_root; EXPORT_SYMBOL_GPL(blkcg_root); struct cgroup_subsys_state * const blkcg_root_css = &blkcg_root.css; static struct blkcg_policy *blkcg_policy[BLKCG_MAX_POLS]; static LIST_HEAD(all_blkcgs); /* protected by blkcg_pol_mutex */ static bool blkcg_policy_enabled(struct request_queue *q, const struct blkcg_policy *pol) { return pol && test_bit(pol->plid, q->blkcg_pols); } /** * blkg_free - free a blkg * @blkg: blkg to free * * Free @blkg which may be partially allocated. */ static void blkg_free(struct blkcg_gq *blkg) { int i; if (!blkg) return; for (i = 0; i < BLKCG_MAX_POLS; i++) if (blkg->pd[i]) blkcg_policy[i]->pd_free_fn(blkg->pd[i]); if (blkg->blkcg != &blkcg_root) blk_exit_rl(&blkg->rl); blkg_rwstat_exit(&blkg->stat_ios); blkg_rwstat_exit(&blkg->stat_bytes); kfree(blkg); } /** * blkg_alloc - allocate a blkg * @blkcg: block cgroup the new blkg is associated with * @q: request_queue the new blkg is associated with * @gfp_mask: allocation mask to use * * Allocate a new blkg assocating @blkcg and @q. */ static struct blkcg_gq *blkg_alloc(struct blkcg *blkcg, struct request_queue *q, gfp_t gfp_mask) { struct blkcg_gq *blkg; int i; /* alloc and init base part */ blkg = kzalloc_node(sizeof(*blkg), gfp_mask, q->node); if (!blkg) return NULL; if (blkg_rwstat_init(&blkg->stat_bytes, gfp_mask) || blkg_rwstat_init(&blkg->stat_ios, gfp_mask)) goto err_free; blkg->q = q; INIT_LIST_HEAD(&blkg->q_node); blkg->blkcg = blkcg; atomic_set(&blkg->refcnt, 1); /* root blkg uses @q->root_rl, init rl only for !root blkgs */ if (blkcg != &blkcg_root) { if (blk_init_rl(&blkg->rl, q, gfp_mask)) goto err_free; blkg->rl.blkg = blkg; } for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; struct blkg_policy_data *pd; if (!blkcg_policy_enabled(q, pol)) continue; /* alloc per-policy data and attach it to blkg */ pd = pol->pd_alloc_fn(gfp_mask, q->node); if (!pd) goto err_free; blkg->pd[i] = pd; pd->blkg = blkg; pd->plid = i; } return blkg; err_free: blkg_free(blkg); return NULL; } struct blkcg_gq *blkg_lookup_slowpath(struct blkcg *blkcg, struct request_queue *q, bool update_hint) { struct blkcg_gq *blkg; /* * Hint didn't match. Look up from the radix tree. Note that the * hint can only be updated under queue_lock as otherwise @blkg * could have already been removed from blkg_tree. The caller is * responsible for grabbing queue_lock if @update_hint. */ blkg = radix_tree_lookup(&blkcg->blkg_tree, q->id); if (blkg && blkg->q == q) { if (update_hint) { lockdep_assert_held(q->queue_lock); rcu_assign_pointer(blkcg->blkg_hint, blkg); } return blkg; } return NULL; } EXPORT_SYMBOL_GPL(blkg_lookup_slowpath); /* * If @new_blkg is %NULL, this function tries to allocate a new one as * necessary using %GFP_NOWAIT. @new_blkg is always consumed on return. */ static struct blkcg_gq *blkg_create(struct blkcg *blkcg, struct request_queue *q, struct blkcg_gq *new_blkg) { struct blkcg_gq *blkg; struct bdi_writeback_congested *wb_congested; int i, ret; WARN_ON_ONCE(!rcu_read_lock_held()); lockdep_assert_held(q->queue_lock); /* blkg holds a reference to blkcg */ if (!css_tryget_online(&blkcg->css)) { ret = -ENODEV; goto err_free_blkg; } wb_congested = wb_congested_get_create(q->backing_dev_info, blkcg->css.id, GFP_NOWAIT | __GFP_NOWARN); if (!wb_congested) { ret = -ENOMEM; goto err_put_css; } /* allocate */ if (!new_blkg) { new_blkg = blkg_alloc(blkcg, q, GFP_NOWAIT | __GFP_NOWARN); if (unlikely(!new_blkg)) { ret = -ENOMEM; goto err_put_congested; } } blkg = new_blkg; blkg->wb_congested = wb_congested; /* link parent */ if (blkcg_parent(blkcg)) { blkg->parent = __blkg_lookup(blkcg_parent(blkcg), q, false); if (WARN_ON_ONCE(!blkg->parent)) { ret = -ENODEV; goto err_put_congested; } blkg_get(blkg->parent); } /* invoke per-policy init */ for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_init_fn) pol->pd_init_fn(blkg->pd[i]); } /* insert */ spin_lock(&blkcg->lock); ret = radix_tree_insert(&blkcg->blkg_tree, q->id, blkg); if (likely(!ret)) { hlist_add_head_rcu(&blkg->blkcg_node, &blkcg->blkg_list); list_add(&blkg->q_node, &q->blkg_list); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_online_fn) pol->pd_online_fn(blkg->pd[i]); } } blkg->online = true; spin_unlock(&blkcg->lock); if (!ret) return blkg; /* @blkg failed fully initialized, use the usual release path */ blkg_put(blkg); return ERR_PTR(ret); err_put_congested: wb_congested_put(wb_congested); err_put_css: css_put(&blkcg->css); err_free_blkg: blkg_free(new_blkg); return ERR_PTR(ret); } /** * blkg_lookup_create - lookup blkg, try to create one if not there * @blkcg: blkcg of interest * @q: request_queue of interest * * Lookup blkg for the @blkcg - @q pair. If it doesn't exist, try to * create one. blkg creation is performed recursively from blkcg_root such * that all non-root blkg's have access to the parent blkg. This function * should be called under RCU read lock and @q->queue_lock. * * Returns pointer to the looked up or created blkg on success, ERR_PTR() * value on error. If @q is dead, returns ERR_PTR(-EINVAL). If @q is not * dead and bypassing, returns ERR_PTR(-EBUSY). */ struct blkcg_gq *blkg_lookup_create(struct blkcg *blkcg, struct request_queue *q) { struct blkcg_gq *blkg; WARN_ON_ONCE(!rcu_read_lock_held()); lockdep_assert_held(q->queue_lock); /* * This could be the first entry point of blkcg implementation and * we shouldn't allow anything to go through for a bypassing queue. */ if (unlikely(blk_queue_bypass(q))) return ERR_PTR(blk_queue_dying(q) ? -ENODEV : -EBUSY); blkg = __blkg_lookup(blkcg, q, true); if (blkg) return blkg; /* * Create blkgs walking down from blkcg_root to @blkcg, so that all * non-root blkgs have access to their parents. */ while (true) { struct blkcg *pos = blkcg; struct blkcg *parent = blkcg_parent(blkcg); while (parent && !__blkg_lookup(parent, q, false)) { pos = parent; parent = blkcg_parent(parent); } blkg = blkg_create(pos, q, NULL); if (pos == blkcg || IS_ERR(blkg)) return blkg; } } static void blkg_destroy(struct blkcg_gq *blkg) { struct blkcg *blkcg = blkg->blkcg; struct blkcg_gq *parent = blkg->parent; int i; lockdep_assert_held(blkg->q->queue_lock); lockdep_assert_held(&blkcg->lock); /* Something wrong if we are trying to remove same group twice */ WARN_ON_ONCE(list_empty(&blkg->q_node)); WARN_ON_ONCE(hlist_unhashed(&blkg->blkcg_node)); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_offline_fn) pol->pd_offline_fn(blkg->pd[i]); } if (parent) { blkg_rwstat_add_aux(&parent->stat_bytes, &blkg->stat_bytes); blkg_rwstat_add_aux(&parent->stat_ios, &blkg->stat_ios); } blkg->online = false; radix_tree_delete(&blkcg->blkg_tree, blkg->q->id); list_del_init(&blkg->q_node); hlist_del_init_rcu(&blkg->blkcg_node); /* * Both setting lookup hint to and clearing it from @blkg are done * under queue_lock. If it's not pointing to @blkg now, it never * will. Hint assignment itself can race safely. */ if (rcu_access_pointer(blkcg->blkg_hint) == blkg) rcu_assign_pointer(blkcg->blkg_hint, NULL); /* * Put the reference taken at the time of creation so that when all * queues are gone, group can be destroyed. */ blkg_put(blkg); } /** * blkg_destroy_all - destroy all blkgs associated with a request_queue * @q: request_queue of interest * * Destroy all blkgs associated with @q. */ static void blkg_destroy_all(struct request_queue *q) { struct blkcg_gq *blkg, *n; lockdep_assert_held(q->queue_lock); list_for_each_entry_safe(blkg, n, &q->blkg_list, q_node) { struct blkcg *blkcg = blkg->blkcg; spin_lock(&blkcg->lock); blkg_destroy(blkg); spin_unlock(&blkcg->lock); } q->root_blkg = NULL; q->root_rl.blkg = NULL; } /* * A group is RCU protected, but having an rcu lock does not mean that one * can access all the fields of blkg and assume these are valid. For * example, don't try to follow throtl_data and request queue links. * * Having a reference to blkg under an rcu allows accesses to only values * local to groups like group stats and group rate limits. */ void __blkg_release_rcu(struct rcu_head *rcu_head) { struct blkcg_gq *blkg = container_of(rcu_head, struct blkcg_gq, rcu_head); /* release the blkcg and parent blkg refs this blkg has been holding */ css_put(&blkg->blkcg->css); if (blkg->parent) blkg_put(blkg->parent); wb_congested_put(blkg->wb_congested); blkg_free(blkg); } EXPORT_SYMBOL_GPL(__blkg_release_rcu); /* * The next function used by blk_queue_for_each_rl(). It's a bit tricky * because the root blkg uses @q->root_rl instead of its own rl. */ struct request_list *__blk_queue_next_rl(struct request_list *rl, struct request_queue *q) { struct list_head *ent; struct blkcg_gq *blkg; /* * Determine the current blkg list_head. The first entry is * root_rl which is off @q->blkg_list and mapped to the head. */ if (rl == &q->root_rl) { ent = &q->blkg_list; /* There are no more block groups, hence no request lists */ if (list_empty(ent)) return NULL; } else { blkg = container_of(rl, struct blkcg_gq, rl); ent = &blkg->q_node; } /* walk to the next list_head, skip root blkcg */ ent = ent->next; if (ent == &q->root_blkg->q_node) ent = ent->next; if (ent == &q->blkg_list) return NULL; blkg = container_of(ent, struct blkcg_gq, q_node); return &blkg->rl; } static int blkcg_reset_stats(struct cgroup_subsys_state *css, struct cftype *cftype, u64 val) { struct blkcg *blkcg = css_to_blkcg(css); struct blkcg_gq *blkg; int i; mutex_lock(&blkcg_pol_mutex); spin_lock_irq(&blkcg->lock); /* * Note that stat reset is racy - it doesn't synchronize against * stat updates. This is a debug feature which shouldn't exist * anyway. If you get hit by a race, retry. */ hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) { blkg_rwstat_reset(&blkg->stat_bytes); blkg_rwstat_reset(&blkg->stat_ios); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_reset_stats_fn) pol->pd_reset_stats_fn(blkg->pd[i]); } } spin_unlock_irq(&blkcg->lock); mutex_unlock(&blkcg_pol_mutex); return 0; } const char *blkg_dev_name(struct blkcg_gq *blkg) { /* some drivers (floppy) instantiate a queue w/o disk registered */ if (blkg->q->backing_dev_info->dev) return dev_name(blkg->q->backing_dev_info->dev); return NULL; } EXPORT_SYMBOL_GPL(blkg_dev_name); /** * blkcg_print_blkgs - helper for printing per-blkg data * @sf: seq_file to print to * @blkcg: blkcg of interest * @prfill: fill function to print out a blkg * @pol: policy in question * @data: data to be passed to @prfill * @show_total: to print out sum of prfill return values or not * * This function invokes @prfill on each blkg of @blkcg if pd for the * policy specified by @pol exists. @prfill is invoked with @sf, the * policy data and @data and the matching queue lock held. If @show_total * is %true, the sum of the return values from @prfill is printed with * "Total" label at the end. * * This is to be used to construct print functions for * cftype->read_seq_string method. */ void blkcg_print_blkgs(struct seq_file *sf, struct blkcg *blkcg, u64 (*prfill)(struct seq_file *, struct blkg_policy_data *, int), const struct blkcg_policy *pol, int data, bool show_total) { struct blkcg_gq *blkg; u64 total = 0; rcu_read_lock(); hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) { spin_lock_irq(blkg->q->queue_lock); if (blkcg_policy_enabled(blkg->q, pol)) total += prfill(sf, blkg->pd[pol->plid], data); spin_unlock_irq(blkg->q->queue_lock); } rcu_read_unlock(); if (show_total) seq_printf(sf, "Total %llu\n", (unsigned long long)total); } EXPORT_SYMBOL_GPL(blkcg_print_blkgs); /** * __blkg_prfill_u64 - prfill helper for a single u64 value * @sf: seq_file to print to * @pd: policy private data of interest * @v: value to print * * Print @v to @sf for the device assocaited with @pd. */ u64 __blkg_prfill_u64(struct seq_file *sf, struct blkg_policy_data *pd, u64 v) { const char *dname = blkg_dev_name(pd->blkg); if (!dname) return 0; seq_printf(sf, "%s %llu\n", dname, (unsigned long long)v); return v; } EXPORT_SYMBOL_GPL(__blkg_prfill_u64); /** * __blkg_prfill_rwstat - prfill helper for a blkg_rwstat * @sf: seq_file to print to * @pd: policy private data of interest * @rwstat: rwstat to print * * Print @rwstat to @sf for the device assocaited with @pd. */ u64 __blkg_prfill_rwstat(struct seq_file *sf, struct blkg_policy_data *pd, const struct blkg_rwstat *rwstat) { static const char *rwstr[] = { [BLKG_RWSTAT_READ] = "Read", [BLKG_RWSTAT_WRITE] = "Write", [BLKG_RWSTAT_SYNC] = "Sync", [BLKG_RWSTAT_ASYNC] = "Async", }; const char *dname = blkg_dev_name(pd->blkg); u64 v; int i; if (!dname) return 0; for (i = 0; i < BLKG_RWSTAT_NR; i++) seq_printf(sf, "%s %s %llu\n", dname, rwstr[i], (unsigned long long)atomic64_read(&rwstat->aux_cnt[i])); v = atomic64_read(&rwstat->aux_cnt[BLKG_RWSTAT_READ]) + atomic64_read(&rwstat->aux_cnt[BLKG_RWSTAT_WRITE]); seq_printf(sf, "%s Total %llu\n", dname, (unsigned long long)v); return v; } EXPORT_SYMBOL_GPL(__blkg_prfill_rwstat); /** * blkg_prfill_stat - prfill callback for blkg_stat * @sf: seq_file to print to * @pd: policy private data of interest * @off: offset to the blkg_stat in @pd * * prfill callback for printing a blkg_stat. */ u64 blkg_prfill_stat(struct seq_file *sf, struct blkg_policy_data *pd, int off) { return __blkg_prfill_u64(sf, pd, blkg_stat_read((void *)pd + off)); } EXPORT_SYMBOL_GPL(blkg_prfill_stat); /** * blkg_prfill_rwstat - prfill callback for blkg_rwstat * @sf: seq_file to print to * @pd: policy private data of interest * @off: offset to the blkg_rwstat in @pd * * prfill callback for printing a blkg_rwstat. */ u64 blkg_prfill_rwstat(struct seq_file *sf, struct blkg_policy_data *pd, int off) { struct blkg_rwstat rwstat = blkg_rwstat_read((void *)pd + off); return __blkg_prfill_rwstat(sf, pd, &rwstat); } EXPORT_SYMBOL_GPL(blkg_prfill_rwstat); static u64 blkg_prfill_rwstat_field(struct seq_file *sf, struct blkg_policy_data *pd, int off) { struct blkg_rwstat rwstat = blkg_rwstat_read((void *)pd->blkg + off); return __blkg_prfill_rwstat(sf, pd, &rwstat); } /** * blkg_print_stat_bytes - seq_show callback for blkg->stat_bytes * @sf: seq_file to print to * @v: unused * * To be used as cftype->seq_show to print blkg->stat_bytes. * cftype->private must be set to the blkcg_policy. */ int blkg_print_stat_bytes(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_bytes), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_bytes); /** * blkg_print_stat_bytes - seq_show callback for blkg->stat_ios * @sf: seq_file to print to * @v: unused * * To be used as cftype->seq_show to print blkg->stat_ios. cftype->private * must be set to the blkcg_policy. */ int blkg_print_stat_ios(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_ios), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_ios); static u64 blkg_prfill_rwstat_field_recursive(struct seq_file *sf, struct blkg_policy_data *pd, int off) { struct blkg_rwstat rwstat = blkg_rwstat_recursive_sum(pd->blkg, NULL, off); return __blkg_prfill_rwstat(sf, pd, &rwstat); } /** * blkg_print_stat_bytes_recursive - recursive version of blkg_print_stat_bytes * @sf: seq_file to print to * @v: unused */ int blkg_print_stat_bytes_recursive(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field_recursive, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_bytes), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_bytes_recursive); /** * blkg_print_stat_ios_recursive - recursive version of blkg_print_stat_ios * @sf: seq_file to print to * @v: unused */ int blkg_print_stat_ios_recursive(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field_recursive, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_ios), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_ios_recursive); /** * blkg_stat_recursive_sum - collect hierarchical blkg_stat * @blkg: blkg of interest * @pol: blkcg_policy which contains the blkg_stat * @off: offset to the blkg_stat in blkg_policy_data or @blkg * * Collect the blkg_stat specified by @blkg, @pol and @off and all its * online descendants and their aux counts. The caller must be holding the * queue lock for online tests. * * If @pol is NULL, blkg_stat is at @off bytes into @blkg; otherwise, it is * at @off bytes into @blkg's blkg_policy_data of the policy. */ u64 blkg_stat_recursive_sum(struct blkcg_gq *blkg, struct blkcg_policy *pol, int off) { struct blkcg_gq *pos_blkg; struct cgroup_subsys_state *pos_css; u64 sum = 0; lockdep_assert_held(blkg->q->queue_lock); rcu_read_lock(); blkg_for_each_descendant_pre(pos_blkg, pos_css, blkg) { struct blkg_stat *stat; if (!pos_blkg->online) continue; if (pol) stat = (void *)blkg_to_pd(pos_blkg, pol) + off; else stat = (void *)blkg + off; sum += blkg_stat_read(stat) + atomic64_read(&stat->aux_cnt); } rcu_read_unlock(); return sum; } EXPORT_SYMBOL_GPL(blkg_stat_recursive_sum); /** * blkg_rwstat_recursive_sum - collect hierarchical blkg_rwstat * @blkg: blkg of interest * @pol: blkcg_policy which contains the blkg_rwstat * @off: offset to the blkg_rwstat in blkg_policy_data or @blkg * * Collect the blkg_rwstat specified by @blkg, @pol and @off and all its * online descendants and their aux counts. The caller must be holding the * queue lock for online tests. * * If @pol is NULL, blkg_rwstat is at @off bytes into @blkg; otherwise, it * is at @off bytes into @blkg's blkg_policy_data of the policy. */ struct blkg_rwstat blkg_rwstat_recursive_sum(struct blkcg_gq *blkg, struct blkcg_policy *pol, int off) { struct blkcg_gq *pos_blkg; struct cgroup_subsys_state *pos_css; struct blkg_rwstat sum = { }; int i; lockdep_assert_held(blkg->q->queue_lock); rcu_read_lock(); blkg_for_each_descendant_pre(pos_blkg, pos_css, blkg) { struct blkg_rwstat *rwstat; if (!pos_blkg->online) continue; if (pol) rwstat = (void *)blkg_to_pd(pos_blkg, pol) + off; else rwstat = (void *)pos_blkg + off; for (i = 0; i < BLKG_RWSTAT_NR; i++) atomic64_add(atomic64_read(&rwstat->aux_cnt[i]) + percpu_counter_sum_positive(&rwstat->cpu_cnt[i]), &sum.aux_cnt[i]); } rcu_read_unlock(); return sum; } EXPORT_SYMBOL_GPL(blkg_rwstat_recursive_sum); /** * blkg_conf_prep - parse and prepare for per-blkg config update * @blkcg: target block cgroup * @pol: target policy * @input: input string * @ctx: blkg_conf_ctx to be filled * * Parse per-blkg config update from @input and initialize @ctx with the * result. @ctx->blkg points to the blkg to be updated and @ctx->body the * part of @input following MAJ:MIN. This function returns with RCU read * lock and queue lock held and must be paired with blkg_conf_finish(). */ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol, char *input, struct blkg_conf_ctx *ctx) __acquires(rcu) __acquires(disk->queue->queue_lock) { struct gendisk *disk; struct blkcg_gq *blkg; struct module *owner; unsigned int major, minor; int key_len, part, ret; char *body; if (sscanf(input, "%u:%u%n", &major, &minor, &key_len) != 2) return -EINVAL; body = input + key_len; if (!isspace(*body)) return -EINVAL; body = skip_spaces(body); disk = get_gendisk(MKDEV(major, minor), &part); if (!disk) return -ENODEV; if (part) { owner = disk->fops->owner; put_disk(disk); module_put(owner); return -ENODEV; } rcu_read_lock(); spin_lock_irq(disk->queue->queue_lock); if (blkcg_policy_enabled(disk->queue, pol)) blkg = blkg_lookup_create(blkcg, disk->queue); else blkg = ERR_PTR(-EOPNOTSUPP); if (IS_ERR(blkg)) { ret = PTR_ERR(blkg); rcu_read_unlock(); spin_unlock_irq(disk->queue->queue_lock); owner = disk->fops->owner; put_disk(disk); module_put(owner); /* * If queue was bypassing, we should retry. Do so after a * short msleep(). It isn't strictly necessary but queue * can be bypassing for some time and it's always nice to * avoid busy looping. */ if (ret == -EBUSY) { msleep(10); ret = restart_syscall(); } return ret; } ctx->disk = disk; ctx->blkg = blkg; ctx->body = body; return 0; } EXPORT_SYMBOL_GPL(blkg_conf_prep); /** * blkg_conf_finish - finish up per-blkg config update * @ctx: blkg_conf_ctx intiailized by blkg_conf_prep() * * Finish up after per-blkg config update. This function must be paired * with blkg_conf_prep(). */ void blkg_conf_finish(struct blkg_conf_ctx *ctx) __releases(ctx->disk->queue->queue_lock) __releases(rcu) { struct module *owner; spin_unlock_irq(ctx->disk->queue->queue_lock); rcu_read_unlock(); owner = ctx->disk->fops->owner; put_disk(ctx->disk); module_put(owner); } EXPORT_SYMBOL_GPL(blkg_conf_finish); static int blkcg_print_stat(struct seq_file *sf, void *v) { struct blkcg *blkcg = css_to_blkcg(seq_css(sf)); struct blkcg_gq *blkg; rcu_read_lock(); hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) { const char *dname; struct blkg_rwstat rwstat; u64 rbytes, wbytes, rios, wios; dname = blkg_dev_name(blkg); if (!dname) continue; spin_lock_irq(blkg->q->queue_lock); rwstat = blkg_rwstat_recursive_sum(blkg, NULL, offsetof(struct blkcg_gq, stat_bytes)); rbytes = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_READ]); wbytes = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_WRITE]); rwstat = blkg_rwstat_recursive_sum(blkg, NULL, offsetof(struct blkcg_gq, stat_ios)); rios = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_READ]); wios = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_WRITE]); spin_unlock_irq(blkg->q->queue_lock); if (rbytes || wbytes || rios || wios) seq_printf(sf, "%s rbytes=%llu wbytes=%llu rios=%llu wios=%llu\n", dname, rbytes, wbytes, rios, wios); } rcu_read_unlock(); return 0; } static struct cftype blkcg_files[] = { { .name = "stat", .flags = CFTYPE_NOT_ON_ROOT, .seq_show = blkcg_print_stat, }, { } /* terminate */ }; static struct cftype blkcg_legacy_files[] = { { .name = "reset_stats", .write_u64 = blkcg_reset_stats, }, { } /* terminate */ }; /** * blkcg_css_offline - cgroup css_offline callback * @css: css of interest * * This function is called when @css is about to go away and responsible * for shooting down all blkgs associated with @css. blkgs should be * removed while holding both q and blkcg locks. As blkcg lock is nested * inside q lock, this function performs reverse double lock dancing. * * This is the blkcg counterpart of ioc_release_fn(). */ static void blkcg_css_offline(struct cgroup_subsys_state *css) { struct blkcg *blkcg = css_to_blkcg(css); spin_lock_irq(&blkcg->lock); while (!hlist_empty(&blkcg->blkg_list)) { struct blkcg_gq *blkg = hlist_entry(blkcg->blkg_list.first, struct blkcg_gq, blkcg_node); struct request_queue *q = blkg->q; if (spin_trylock(q->queue_lock)) { blkg_destroy(blkg); spin_unlock(q->queue_lock); } else { spin_unlock_irq(&blkcg->lock); cpu_relax(); spin_lock_irq(&blkcg->lock); } } spin_unlock_irq(&blkcg->lock); wb_blkcg_offline(blkcg); } static void blkcg_css_free(struct cgroup_subsys_state *css) { struct blkcg *blkcg = css_to_blkcg(css); int i; mutex_lock(&blkcg_pol_mutex); list_del(&blkcg->all_blkcgs_node); for (i = 0; i < BLKCG_MAX_POLS; i++) if (blkcg->cpd[i]) blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]); mutex_unlock(&blkcg_pol_mutex); kfree(blkcg); } static struct cgroup_subsys_state * blkcg_css_alloc(struct cgroup_subsys_state *parent_css) { struct blkcg *blkcg; struct cgroup_subsys_state *ret; int i; mutex_lock(&blkcg_pol_mutex); if (!parent_css) { blkcg = &blkcg_root; } else { blkcg = kzalloc(sizeof(*blkcg), GFP_KERNEL); if (!blkcg) { ret = ERR_PTR(-ENOMEM); goto free_blkcg; } } for (i = 0; i < BLKCG_MAX_POLS ; i++) { struct blkcg_policy *pol = blkcg_policy[i]; struct blkcg_policy_data *cpd; /* * If the policy hasn't been attached yet, wait for it * to be attached before doing anything else. Otherwise, * check if the policy requires any specific per-cgroup * data: if it does, allocate and initialize it. */ if (!pol || !pol->cpd_alloc_fn) continue; cpd = pol->cpd_alloc_fn(GFP_KERNEL); if (!cpd) { ret = ERR_PTR(-ENOMEM); goto free_pd_blkcg; } blkcg->cpd[i] = cpd; cpd->blkcg = blkcg; cpd->plid = i; if (pol->cpd_init_fn) pol->cpd_init_fn(cpd); } spin_lock_init(&blkcg->lock); INIT_RADIX_TREE(&blkcg->blkg_tree, GFP_NOWAIT | __GFP_NOWARN); INIT_HLIST_HEAD(&blkcg->blkg_list); #ifdef CONFIG_CGROUP_WRITEBACK INIT_LIST_HEAD(&blkcg->cgwb_list); #endif list_add_tail(&blkcg->all_blkcgs_node, &all_blkcgs); mutex_unlock(&blkcg_pol_mutex); return &blkcg->css; free_pd_blkcg: for (i--; i >= 0; i--) if (blkcg->cpd[i]) blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]); free_blkcg: kfree(blkcg); mutex_unlock(&blkcg_pol_mutex); return ret; } /** * blkcg_init_queue - initialize blkcg part of request queue * @q: request_queue to initialize * * Called from blk_alloc_queue_node(). Responsible for initializing blkcg * part of new request_queue @q. * * RETURNS: * 0 on success, -errno on failure. */ int blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) { blkg_free(new_blkg); return PTR_ERR(blkg); } q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; } /** * blkcg_drain_queue - drain blkcg part of request_queue * @q: request_queue to drain * * Called from blk_drain_queue(). Responsible for draining blkcg part. */ void blkcg_drain_queue(struct request_queue *q) { lockdep_assert_held(q->queue_lock); /* * @q could be exiting and already have destroyed all blkgs as * indicated by NULL root_blkg. If so, don't confuse policies. */ if (!q->root_blkg) return; blk_throtl_drain(q); } /** * blkcg_exit_queue - exit and release blkcg part of request_queue * @q: request_queue being released * * Called from blk_release_queue(). Responsible for exiting blkcg part. */ void blkcg_exit_queue(struct request_queue *q) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); blk_throtl_exit(q); } /* * We cannot support shared io contexts, as we have no mean to support * two tasks with the same ioc in two different groups without major rework * of the main cic data structures. For now we allow a task to change * its cgroup only if it's the only owner of its ioc. */ static int blkcg_can_attach(struct cgroup_taskset *tset) { struct task_struct *task; struct cgroup_subsys_state *dst_css; struct io_context *ioc; int ret = 0; /* task_lock() is needed to avoid races with exit_io_context() */ cgroup_taskset_for_each(task, dst_css, tset) { task_lock(task); ioc = task->io_context; if (ioc && atomic_read(&ioc->nr_tasks) > 1) ret = -EINVAL; task_unlock(task); if (ret) break; } return ret; } static void blkcg_bind(struct cgroup_subsys_state *root_css) { int i; mutex_lock(&blkcg_pol_mutex); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; struct blkcg *blkcg; if (!pol || !pol->cpd_bind_fn) continue; list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) if (blkcg->cpd[pol->plid]) pol->cpd_bind_fn(blkcg->cpd[pol->plid]); } mutex_unlock(&blkcg_pol_mutex); } struct cgroup_subsys io_cgrp_subsys = { .css_alloc = blkcg_css_alloc, .css_offline = blkcg_css_offline, .css_free = blkcg_css_free, .can_attach = blkcg_can_attach, .bind = blkcg_bind, .dfl_cftypes = blkcg_files, .legacy_cftypes = blkcg_legacy_files, .legacy_name = "blkio", #ifdef CONFIG_MEMCG /* * This ensures that, if available, memcg is automatically enabled * together on the default hierarchy so that the owner cgroup can * be retrieved from writeback pages. */ .depends_on = 1 << memory_cgrp_id, #endif }; EXPORT_SYMBOL_GPL(io_cgrp_subsys); /** * blkcg_activate_policy - activate a blkcg policy on a request_queue * @q: request_queue of interest * @pol: blkcg policy to activate * * Activate @pol on @q. Requires %GFP_KERNEL context. @q goes through * bypass mode to populate its blkgs with policy_data for @pol. * * Activation happens with @q bypassed, so nobody would be accessing blkgs * from IO path. Update of each blkg is protected by both queue and blkcg * locks so that holding either lock and testing blkcg_policy_enabled() is * always enough for dereferencing policy data. * * The caller is responsible for synchronizing [de]activations and policy * [un]registerations. Returns 0 on success, -errno on failure. */ int blkcg_activate_policy(struct request_queue *q, const struct blkcg_policy *pol) { struct blkg_policy_data *pd_prealloc = NULL; struct blkcg_gq *blkg; int ret; if (blkcg_policy_enabled(q, pol)) return 0; if (q->mq_ops) blk_mq_freeze_queue(q); else blk_queue_bypass_start(q); pd_prealloc: if (!pd_prealloc) { pd_prealloc = pol->pd_alloc_fn(GFP_KERNEL, q->node); if (!pd_prealloc) { ret = -ENOMEM; goto out_bypass_end; } } spin_lock_irq(q->queue_lock); list_for_each_entry(blkg, &q->blkg_list, q_node) { struct blkg_policy_data *pd; if (blkg->pd[pol->plid]) continue; pd = pol->pd_alloc_fn(GFP_NOWAIT | __GFP_NOWARN, q->node); if (!pd) swap(pd, pd_prealloc); if (!pd) { spin_unlock_irq(q->queue_lock); goto pd_prealloc; } blkg->pd[pol->plid] = pd; pd->blkg = blkg; pd->plid = pol->plid; if (pol->pd_init_fn) pol->pd_init_fn(pd); } __set_bit(pol->plid, q->blkcg_pols); ret = 0; spin_unlock_irq(q->queue_lock); out_bypass_end: if (q->mq_ops) blk_mq_unfreeze_queue(q); else blk_queue_bypass_end(q); if (pd_prealloc) pol->pd_free_fn(pd_prealloc); return ret; } EXPORT_SYMBOL_GPL(blkcg_activate_policy); /** * blkcg_deactivate_policy - deactivate a blkcg policy on a request_queue * @q: request_queue of interest * @pol: blkcg policy to deactivate * * Deactivate @pol on @q. Follows the same synchronization rules as * blkcg_activate_policy(). */ void blkcg_deactivate_policy(struct request_queue *q, const struct blkcg_policy *pol) { struct blkcg_gq *blkg; if (!blkcg_policy_enabled(q, pol)) return; if (q->mq_ops) blk_mq_freeze_queue(q); else blk_queue_bypass_start(q); spin_lock_irq(q->queue_lock); __clear_bit(pol->plid, q->blkcg_pols); list_for_each_entry(blkg, &q->blkg_list, q_node) { /* grab blkcg lock too while removing @pd from @blkg */ spin_lock(&blkg->blkcg->lock); if (blkg->pd[pol->plid]) { if (pol->pd_offline_fn) pol->pd_offline_fn(blkg->pd[pol->plid]); pol->pd_free_fn(blkg->pd[pol->plid]); blkg->pd[pol->plid] = NULL; } spin_unlock(&blkg->blkcg->lock); } spin_unlock_irq(q->queue_lock); if (q->mq_ops) blk_mq_unfreeze_queue(q); else blk_queue_bypass_end(q); } EXPORT_SYMBOL_GPL(blkcg_deactivate_policy); /** * blkcg_policy_register - register a blkcg policy * @pol: blkcg policy to register * * Register @pol with blkcg core. Might sleep and @pol may be modified on * successful registration. Returns 0 on success and -errno on failure. */ int blkcg_policy_register(struct blkcg_policy *pol) { struct blkcg *blkcg; int i, ret; mutex_lock(&blkcg_pol_register_mutex); mutex_lock(&blkcg_pol_mutex); /* find an empty slot */ ret = -ENOSPC; for (i = 0; i < BLKCG_MAX_POLS; i++) if (!blkcg_policy[i]) break; if (i >= BLKCG_MAX_POLS) goto err_unlock; /* register @pol */ pol->plid = i; blkcg_policy[pol->plid] = pol; /* allocate and install cpd's */ if (pol->cpd_alloc_fn) { list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) { struct blkcg_policy_data *cpd; cpd = pol->cpd_alloc_fn(GFP_KERNEL); if (!cpd) goto err_free_cpds; blkcg->cpd[pol->plid] = cpd; cpd->blkcg = blkcg; cpd->plid = pol->plid; pol->cpd_init_fn(cpd); } } mutex_unlock(&blkcg_pol_mutex); /* everything is in place, add intf files for the new policy */ if (pol->dfl_cftypes) WARN_ON(cgroup_add_dfl_cftypes(&io_cgrp_subsys, pol->dfl_cftypes)); if (pol->legacy_cftypes) WARN_ON(cgroup_add_legacy_cftypes(&io_cgrp_subsys, pol->legacy_cftypes)); mutex_unlock(&blkcg_pol_register_mutex); return 0; err_free_cpds: if (pol->cpd_alloc_fn) { list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) { if (blkcg->cpd[pol->plid]) { pol->cpd_free_fn(blkcg->cpd[pol->plid]); blkcg->cpd[pol->plid] = NULL; } } } blkcg_policy[pol->plid] = NULL; err_unlock: mutex_unlock(&blkcg_pol_mutex); mutex_unlock(&blkcg_pol_register_mutex); return ret; } EXPORT_SYMBOL_GPL(blkcg_policy_register); /** * blkcg_policy_unregister - unregister a blkcg policy * @pol: blkcg policy to unregister * * Undo blkcg_policy_register(@pol). Might sleep. */ void blkcg_policy_unregister(struct blkcg_policy *pol) { struct blkcg *blkcg; mutex_lock(&blkcg_pol_register_mutex); if (WARN_ON(blkcg_policy[pol->plid] != pol)) goto out_unlock; /* kill the intf files first */ if (pol->dfl_cftypes) cgroup_rm_cftypes(pol->dfl_cftypes); if (pol->legacy_cftypes) cgroup_rm_cftypes(pol->legacy_cftypes); /* remove cpds and unregister */ mutex_lock(&blkcg_pol_mutex); if (pol->cpd_alloc_fn) { list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) { if (blkcg->cpd[pol->plid]) { pol->cpd_free_fn(blkcg->cpd[pol->plid]); blkcg->cpd[pol->plid] = NULL; } } } blkcg_policy[pol->plid] = NULL; mutex_unlock(&blkcg_pol_mutex); out_unlock: mutex_unlock(&blkcg_pol_register_mutex); } EXPORT_SYMBOL_GPL(blkcg_policy_unregister);
./CrossVul/dataset_final_sorted/CWE-415/c/bad_633_0
crossvul-cpp_data_good_1407_1
/* * gd_jpeg.c: Read and write JPEG (JFIF) format image files using the * gd graphics library (http://www.boutell.com/gd/). * * This software is based in part on the work of the Independent JPEG * Group. For more information on the IJG JPEG software (and JPEG * documentation, etc.), see ftp://ftp.uu.net/graphics/jpeg/. * * NOTE: IJG 12-bit JSAMPLE (BITS_IN_JSAMPLE == 12) mode is not * supported at all on read in gd 2.0, and is not supported on write * except for palette images, which is sort of pointless (TBB). Even that * has never been tested according to DB. * * Copyright 2000 Doug Becker, mailto:thebeckers@home.com * * Modification 4/18/00 TBB: JPEG_DEBUG rather than just DEBUG, * so VC++ builds don't spew to standard output, causing * major CGI brain damage * * 2.0.10: more efficient gdImageCreateFromJpegCtx, thanks to * Christian Aberger */ #include <stdio.h> #include <stdlib.h> #include <setjmp.h> #include <limits.h> #include <string.h> #include "gd.h" #include "gd_errors.h" /* TBB: move this up so include files are not brought in */ /* JCE: arrange HAVE_LIBJPEG so that it can be set in gd.h */ #ifdef HAVE_LIBJPEG #include "gdhelpers.h" #undef HAVE_STDLIB_H /* 1.8.1: remove dependency on jinclude.h */ #include "jpeglib.h" #include "jerror.h" static const char *const GD_JPEG_VERSION = "1.0"; typedef struct _jmpbuf_wrapper { jmp_buf jmpbuf; int ignore_warning; } jmpbuf_wrapper; static long php_jpeg_emit_message(j_common_ptr jpeg_info, int level) { char message[JMSG_LENGTH_MAX]; jmpbuf_wrapper *jmpbufw; int ignore_warning = 0; jmpbufw = (jmpbuf_wrapper *) jpeg_info->client_data; if (jmpbufw != 0) { ignore_warning = jmpbufw->ignore_warning; } (jpeg_info->err->format_message)(jpeg_info,message); /* It is a warning message */ if (level < 0) { /* display only the 1st warning, as would do a default libjpeg * unless strace_level >= 3 */ if ((jpeg_info->err->num_warnings == 0) || (jpeg_info->err->trace_level >= 3)) { if (!ignore_warning) { gd_error("gd-jpeg, libjpeg: recoverable error: %s\n", message); } } jpeg_info->err->num_warnings++; } else { /* strace msg, Show it if trace_level >= level. */ if (jpeg_info->err->trace_level >= level) { if (!ignore_warning) { gd_error("gd-jpeg, libjpeg: strace message: %s\n", message); } } } return 1; } /* Called by the IJG JPEG library upon encountering a fatal error */ static void fatal_jpeg_error (j_common_ptr cinfo) { jmpbuf_wrapper *jmpbufw; char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message)(cinfo, buffer); gd_error_ex(GD_WARNING, "gd-jpeg: JPEG library reports unrecoverable error: %s", buffer); jmpbufw = (jmpbuf_wrapper *) cinfo->client_data; jpeg_destroy (cinfo); if (jmpbufw != 0) { longjmp (jmpbufw->jmpbuf, 1); gd_error_ex(GD_ERROR, "gd-jpeg: EXTREMELY fatal error: longjmp returned control; terminating"); } else { gd_error_ex(GD_ERROR, "gd-jpeg: EXTREMELY fatal error: jmpbuf unrecoverable; terminating"); } exit (99); } const char * gdJpegGetVersionString() { switch(JPEG_LIB_VERSION) { case 62: return "6b"; break; case 70: return "7"; break; case 80: return "8"; break; case 90: return "9 compatible"; break; default: return "unknown"; } } static int _gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality); /* * Write IM to OUTFILE as a JFIF-formatted JPEG image, using quality * QUALITY. If QUALITY is in the range 0-100, increasing values * represent higher quality but also larger image size. If QUALITY is * negative, the IJG JPEG library's default quality is used (which * should be near optimal for many applications). See the IJG JPEG * library documentation for more details. */ void gdImageJpeg (gdImagePtr im, FILE * outFile, int quality) { gdIOCtx *out = gdNewFileCtx (outFile); gdImageJpegCtx (im, out, quality); out->gd_free (out); } void *gdImageJpegPtr (gdImagePtr im, int *size, int quality) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); if (!_gdImageJpegCtx(im, out, quality)) { rv = gdDPExtractData(out, size); } else { rv = NULL; } out->gd_free (out); return rv; } void jpeg_gdIOCtx_dest (j_compress_ptr cinfo, gdIOCtx * outfile); void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { _gdImageJpegCtx(im, outfile, quality); } /* returns 0 on success, 1 on failure */ static int _gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int i, j, jidx; /* volatile so we can gdFree it on return from longjmp */ volatile JSAMPROW row = 0; JSAMPROW rowptr[1]; jmpbuf_wrapper jmpbufw; JDIMENSION nlines; char comment[255]; memset (&cinfo, 0, sizeof (cinfo)); memset (&jerr, 0, sizeof (jerr)); cinfo.err = jpeg_std_error (&jerr); cinfo.client_data = &jmpbufw; if (setjmp (jmpbufw.jmpbuf) != 0) { /* we're here courtesy of longjmp */ if (row) { gdFree (row); } return 1; } cinfo.err->error_exit = fatal_jpeg_error; jpeg_create_compress (&cinfo); cinfo.image_width = im->sx; cinfo.image_height = im->sy; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults (&cinfo); cinfo.density_unit = 1; cinfo.X_density = im->res_x; cinfo.Y_density = im->res_y; if (quality >= 0) { jpeg_set_quality (&cinfo, quality, TRUE); } /* If user requests interlace, translate that to progressive JPEG */ if (gdImageGetInterlaced (im)) { jpeg_simple_progression (&cinfo); } jpeg_gdIOCtx_dest (&cinfo, outfile); row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0); memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE)); rowptr[0] = row; jpeg_start_compress (&cinfo, TRUE); if (quality >= 0) { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality); } else { snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION); } jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment)); if (im->trueColor) { #if BITS_IN_JSAMPLE == 12 gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry"); goto error; #endif /* BITS_IN_JSAMPLE == 12 */ for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int val = im->tpixels[i][j]; row[jidx++] = gdTrueColorGetRed (val); row[jidx++] = gdTrueColorGetGreen (val); row[jidx++] = gdTrueColorGetBlue (val); } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } else { for (i = 0; i < im->sy; i++) { for (jidx = 0, j = 0; j < im->sx; j++) { int idx = im->pixels[i][j]; /* NB: Although gd RGB values are ints, their max value is * 255 (see the documentation for gdImageColorAllocate()) * -- perfect for 8-bit JPEG encoding (which is the norm) */ #if BITS_IN_JSAMPLE == 8 row[jidx++] = im->red[idx]; row[jidx++] = im->green[idx]; row[jidx++] = im->blue[idx]; #elif BITS_IN_JSAMPLE == 12 row[jidx++] = im->red[idx] << 4; row[jidx++] = im->green[idx] << 4; row[jidx++] = im->blue[idx] << 4; #else #error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12 #endif } nlines = jpeg_write_scanlines (&cinfo, rowptr, 1); if (nlines != 1) { gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines); } } } jpeg_finish_compress (&cinfo); jpeg_destroy_compress (&cinfo); gdFree (row); return 0; } gdImagePtr gdImageCreateFromJpeg (FILE * inFile) { return gdImageCreateFromJpegEx(inFile, 1); } gdImagePtr gdImageCreateFromJpegEx (FILE * inFile, int ignore_warning) { gdImagePtr im; gdIOCtx *in = gdNewFileCtx(inFile); im = gdImageCreateFromJpegCtxEx(in, ignore_warning); in->gd_free (in); return im; } gdImagePtr gdImageCreateFromJpegPtr (int size, void *data) { return gdImageCreateFromJpegPtrEx(size, data, 1); } gdImagePtr gdImageCreateFromJpegPtrEx (int size, void *data, int ignore_warning) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0); im = gdImageCreateFromJpegCtxEx(in, ignore_warning); in->gd_free(in); return im; } void jpeg_gdIOCtx_src (j_decompress_ptr cinfo, gdIOCtx * infile); static int CMYKToRGB(int c, int m, int y, int k, int inverted); /* * Create a gd-format image from the JPEG-format INFILE. Returns the * image, or NULL upon error. */ gdImagePtr gdImageCreateFromJpegCtx (gdIOCtx * infile) { return gdImageCreateFromJpegCtxEx(infile, 1); } gdImagePtr gdImageCreateFromJpegCtxEx (gdIOCtx * infile, int ignore_warning) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; jmpbuf_wrapper jmpbufw; /* volatile so we can gdFree them after longjmp */ volatile JSAMPROW row = 0; volatile gdImagePtr im = 0; JSAMPROW rowptr[1]; unsigned int i, j; int retval; JDIMENSION nrows; int channels = 3; int inverted = 0; memset (&cinfo, 0, sizeof (cinfo)); memset (&jerr, 0, sizeof (jerr)); jmpbufw.ignore_warning = ignore_warning; cinfo.err = jpeg_std_error (&jerr); cinfo.client_data = &jmpbufw; cinfo.err->emit_message = (void (*)(j_common_ptr,int)) php_jpeg_emit_message; if (setjmp (jmpbufw.jmpbuf) != 0) { /* we're here courtesy of longjmp */ if (row) { gdFree (row); } if (im) { gdImageDestroy (im); } return 0; } cinfo.err->error_exit = fatal_jpeg_error; jpeg_create_decompress (&cinfo); jpeg_gdIOCtx_src (&cinfo, infile); /* 2.0.22: save the APP14 marker to check for Adobe Photoshop CMYK files with inverted components. */ jpeg_save_markers(&cinfo, JPEG_APP0 + 14, 256); retval = jpeg_read_header (&cinfo, TRUE); if (retval != JPEG_HEADER_OK) { gd_error_ex(GD_WARNING, "gd-jpeg: warning: jpeg_read_header returned %d, expected %d", retval, JPEG_HEADER_OK); } if (cinfo.image_height > INT_MAX) { gd_error_ex(GD_WARNING, "gd-jpeg: warning: JPEG image height (%u) is greater than INT_MAX (%d) (and thus greater than gd can handle)", cinfo.image_height, INT_MAX); } if (cinfo.image_width > INT_MAX) { gd_error_ex(GD_WARNING, "gd-jpeg: warning: JPEG image width (%u) is greater than INT_MAX (%d) (and thus greater than gd can handle)", cinfo.image_width, INT_MAX); } im = gdImageCreateTrueColor ((int) cinfo.image_width, (int) cinfo.image_height); if (im == 0) { gd_error("gd-jpeg error: cannot allocate gdImage struct"); goto error; } /* check if the resolution is specified */ switch (cinfo.density_unit) { case 1: im->res_x = cinfo.X_density; im->res_y = cinfo.Y_density; break; case 2: im->res_x = DPCM2DPI(cinfo.X_density); im->res_y = DPCM2DPI(cinfo.Y_density); break; } /* 2.0.22: very basic support for reading CMYK colorspace files. Nice for * thumbnails but there's no support for fussy adjustment of the * assumed properties of inks and paper. */ if ((cinfo.jpeg_color_space == JCS_CMYK) || (cinfo.jpeg_color_space == JCS_YCCK)) { cinfo.out_color_space = JCS_CMYK; } else { cinfo.out_color_space = JCS_RGB; } if (jpeg_start_decompress (&cinfo) != TRUE) { gd_error("gd-jpeg: warning: jpeg_start_decompress reports suspended data source"); } /* REMOVED by TBB 2/12/01. This field of the structure is * documented as private, and sure enough it's gone in the * latest libjpeg, replaced by something else. Unfortunately * there is still no right way to find out if the file was * progressive or not; just declare your intent before you * write one by calling gdImageInterlace(im, 1) yourself. * After all, we're not really supposed to rework JPEGs and * write them out again anyway. Lossy compression, remember? */ #if 0 gdImageInterlace (im, cinfo.progressive_mode != 0); #endif if (cinfo.out_color_space == JCS_RGB) { if (cinfo.output_components != 3) { gd_error_ex(GD_WARNING, "gd-jpeg: error: JPEG color quantization request resulted in output_components == %d (expected 3 for RGB)", cinfo.output_components); goto error; } channels = 3; } else if (cinfo.out_color_space == JCS_CMYK) { jpeg_saved_marker_ptr marker; if (cinfo.output_components != 4) { gd_error_ex(GD_WARNING, "gd-jpeg: error: JPEG color quantization request resulted in output_components == %d (expected 4 for CMYK)", cinfo.output_components); goto error; } channels = 4; marker = cinfo.marker_list; while (marker) { if ((marker->marker == (JPEG_APP0 + 14)) && (marker->data_length >= 12) && (!strncmp((const char *) marker->data, "Adobe", 5))) { inverted = 1; break; } marker = marker->next; } } else { gd_error_ex(GD_WARNING, "gd-jpeg: error: unexpected colorspace."); goto error; } #if BITS_IN_JSAMPLE == 12 gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry."); goto error; #endif /* BITS_IN_JSAMPLE == 12 */ row = safe_emalloc(cinfo.output_width * channels, sizeof(JSAMPLE), 0); memset(row, 0, cinfo.output_width * channels * sizeof(JSAMPLE)); rowptr[0] = row; if (cinfo.out_color_space == JCS_CMYK) { for (i = 0; i < cinfo.output_height; i++) { register JSAMPROW currow = row; register int *tpix = im->tpixels[i]; nrows = jpeg_read_scanlines (&cinfo, rowptr, 1); if (nrows != 1) { gd_error_ex(GD_WARNING, "gd-jpeg: error: jpeg_read_scanlines returns %u, expected 1", nrows); goto error; } for (j = 0; j < cinfo.output_width; j++, currow += 4, tpix++) { *tpix = CMYKToRGB (currow[0], currow[1], currow[2], currow[3], inverted); } } } else { for (i = 0; i < cinfo.output_height; i++) { register JSAMPROW currow = row; register int *tpix = im->tpixels[i]; nrows = jpeg_read_scanlines (&cinfo, rowptr, 1); if (nrows != 1) { gd_error_ex(GD_WARNING, "gd-jpeg: error: jpeg_read_scanlines returns %u, expected 1", nrows); goto error; } for (j = 0; j < cinfo.output_width; j++, currow += 3, tpix++) { *tpix = gdTrueColor (currow[0], currow[1], currow[2]); } } } if (jpeg_finish_decompress (&cinfo) != TRUE) { gd_error("gd-jpeg: warning: jpeg_finish_decompress reports suspended data source"); } if (!ignore_warning) { if (cinfo.err->num_warnings > 0) { goto error; } } jpeg_destroy_decompress (&cinfo); gdFree (row); return im; error: jpeg_destroy_decompress (&cinfo); if (row) { gdFree (row); } if (im) { gdImageDestroy (im); } return 0; } /* A very basic conversion approach, TBB */ static int CMYKToRGB(int c, int m, int y, int k, int inverted) { if (inverted) { c = 255 - c; m = 255 - m; y = 255 - y; k = 255 - k; } return gdTrueColor((255 - c) * (255 - k) / 255, (255 - m) * (255 - k) / 255, (255 - y) * (255 - k) / 255); } /* * gdIOCtx JPEG data sources and sinks, T. Boutell * almost a simple global replace from T. Lane's stdio versions. * */ /* Different versions of libjpeg use either 'jboolean' or 'boolean', and some platforms define 'boolean', and so forth. Deal with this madness by typedeffing 'safeboolean' to 'boolean' if HAVE_BOOLEAN is already set, because this is the test that libjpeg uses. Otherwise, typedef it to int, because that's what libjpeg does if HAVE_BOOLEAN is not defined. -TBB */ #ifdef HAVE_BOOLEAN typedef boolean safeboolean; #else typedef int safeboolean; #endif /* HAVE_BOOLEAN */ /* Expanded data source object for gdIOCtx input */ typedef struct { struct jpeg_source_mgr pub; /* public fields */ gdIOCtx *infile; /* source stream */ unsigned char *buffer; /* start of buffer */ safeboolean start_of_file; /* have we gotten any data yet? */ } my_source_mgr; typedef my_source_mgr *my_src_ptr; #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ /* * Initialize source --- called by jpeg_read_header * before any data is actually read. */ void init_source (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; /* We reset the empty-input-file flag for each image, * but we don't clear the input buffer. * This is correct behavior for reading a series of images from one source. */ src->start_of_file = TRUE; } /* * Fill the input buffer --- called whenever buffer is emptied. * * In typical applications, this should read fresh data into the buffer * (ignoring the current state of next_input_byte & bytes_in_buffer), * reset the pointer & count to the start of the buffer, and return TRUE * indicating that the buffer has been reloaded. It is not necessary to * fill the buffer entirely, only to obtain at least one more byte. * * There is no such thing as an EOF return. If the end of the file has been * reached, the routine has a choice of ERREXIT() or inserting fake data into * the buffer. In most cases, generating a warning message and inserting a * fake EOI marker is the best course of action --- this will allow the * decompressor to output however much of the image is there. However, * the resulting error message is misleading if the real problem is an empty * input file, so we handle that case specially. * * In applications that need to be able to suspend compression due to input * not being available yet, a FALSE return indicates that no more data can be * obtained right now, but more may be forthcoming later. In this situation, * the decompressor will return to its caller (with an indication of the * number of scanlines it has read, if any). The application should resume * decompression after it has loaded more data into the input buffer. Note * that there are substantial restrictions on the use of suspension --- see * the documentation. * * When suspending, the decompressor will back up to a convenient restart point * (typically the start of the current MCU). next_input_byte & bytes_in_buffer * indicate where the restart point will be if the current call returns FALSE. * Data beyond this point must be rescanned after resumption, so move it to * the front of the buffer rather than discarding it. */ #define END_JPEG_SEQUENCE "\r\n[*]--:END JPEG:--[*]\r\n" safeboolean fill_input_buffer (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; /* 2.0.12: signed size. Thanks to Geert Jansen */ ssize_t nbytes = 0; /* ssize_t got; */ /* char *s; */ memset(src->buffer, 0, INPUT_BUF_SIZE); while (nbytes < INPUT_BUF_SIZE) { int got = gdGetBuf(src->buffer + nbytes, INPUT_BUF_SIZE - nbytes, src->infile); if (got == EOF || got == 0) { /* EOF or error. If we got any data, don't worry about it. If we didn't, then this is unexpected. */ if (!nbytes) { nbytes = -1; } break; } nbytes += got; } if (nbytes <= 0) { if (src->start_of_file) { /* Treat empty input file as fatal error */ ERREXIT (cinfo, JERR_INPUT_EMPTY); } WARNMS (cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ src->buffer[0] = (unsigned char) 0xFF; src->buffer[1] = (unsigned char) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; src->start_of_file = FALSE; return TRUE; } /* * Skip data --- used to skip over a potentially large amount of * uninteresting data (such as an APPn marker). * * Writers of suspendable-input applications must note that skip_input_data * is not granted the right to give a suspension return. If the skip extends * beyond the data currently in the buffer, the buffer can be marked empty so * that the next read will cause a fill_input_buffer call that can suspend. * Arranging for additional bytes to be discarded before reloading the input * buffer is the application writer's problem. */ void skip_input_data (j_decompress_ptr cinfo, long num_bytes) { my_src_ptr src = (my_src_ptr) cinfo->src; /* Just a dumb implementation for now. Not clear that being smart is worth * any trouble anyway --- large skips are infrequent. */ if (num_bytes > 0) { while (num_bytes > (long) src->pub.bytes_in_buffer) { num_bytes -= (long) src->pub.bytes_in_buffer; (void) fill_input_buffer (cinfo); /* note we assume that fill_input_buffer will never return FALSE, * so suspension need not be handled. */ } src->pub.next_input_byte += (size_t) num_bytes; src->pub.bytes_in_buffer -= (size_t) num_bytes; } } /* * An additional method that can be provided by data source modules is the * resync_to_restart method for error recovery in the presence of RST markers. * For the moment, this source module just uses the default resync method * provided by the JPEG library. That method assumes that no backtracking * is possible. */ /* * Terminate source --- called by jpeg_finish_decompress * after all data has been read. Often a no-op. * * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding * application must deal with any cleanup that should happen even * for error exit. */ void term_source (j_decompress_ptr cinfo) { #if 0 * never used */ my_src_ptr src = (my_src_ptr) cinfo->src; #endif } /* * Prepare for input from a gdIOCtx stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing decompression. */ void jpeg_gdIOCtx_src (j_decompress_ptr cinfo, gdIOCtx * infile) { my_src_ptr src; /* The source object and input buffer are made permanent so that a series * of JPEG images can be read from the same file by calling jpeg_gdIOCtx_src * only before the first one. (If we discarded the buffer at the end of * one image, we'd likely lose the start of the next one.) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (my_source_mgr)); src = (my_src_ptr) cinfo->src; src->buffer = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * sizeof (unsigned char)); } src = (my_src_ptr) cinfo->src; src->pub.init_source = init_source; src->pub.fill_input_buffer = fill_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->infile = infile; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } /* Expanded data destination object for stdio output */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ gdIOCtx *outfile; /* target stream */ unsigned char *buffer; /* start of buffer */ } my_destination_mgr; typedef my_destination_mgr *my_dest_ptr; #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ /* * Initialize destination --- called by jpeg_start_compress * before any data is actually written. */ void init_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; /* Allocate the output buffer --- it will be released when done with image */ dest->buffer = (unsigned char *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * sizeof (unsigned char)); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } /* * Empty the output buffer --- called whenever buffer fills up. * * In typical applications, this should write the entire output buffer * (ignoring the current state of next_output_byte & free_in_buffer), * reset the pointer & count to the start of the buffer, and return TRUE * indicating that the buffer has been dumped. * * In applications that need to be able to suspend compression due to output * overrun, a FALSE return indicates that the buffer cannot be emptied now. * In this situation, the compressor will return to its caller (possibly with * an indication that it has not accepted all the supplied scanlines). The * application should resume compression after it has made more room in the * output buffer. Note that there are substantial restrictions on the use of * suspension --- see the documentation. * * When suspending, the compressor will back up to a convenient restart point * (typically the start of the current MCU). next_output_byte & free_in_buffer * indicate where the restart point will be if the current call returns FALSE. * Data beyond this point will be regenerated after resumption, so do not * write it out when emptying the buffer externally. */ safeboolean empty_output_buffer (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; if (gdPutBuf (dest->buffer, OUTPUT_BUF_SIZE, dest->outfile) != (size_t) OUTPUT_BUF_SIZE) { ERREXIT (cinfo, JERR_FILE_WRITE); } dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; } /* * Terminate destination --- called by jpeg_finish_compress * after all data has been written. Usually needs to flush buffer. * * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding * application must deal with any cleanup that should happen even * for error exit. */ void term_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; /* Write any data remaining in the buffer */ if (datacount > 0 && ((size_t)gdPutBuf (dest->buffer, datacount, dest->outfile) != datacount)) { ERREXIT (cinfo, JERR_FILE_WRITE); } } /* * Prepare for output to a stdio stream. * The caller must have already opened the stream, and is responsible * for closing it after finishing compression. */ void jpeg_gdIOCtx_dest (j_compress_ptr cinfo, gdIOCtx * outfile) { my_dest_ptr dest; /* The destination object is made permanent so that multiple JPEG images * can be written to the same file without re-executing jpeg_stdio_dest. * This makes it dangerous to use this manager and a different destination * manager serially with the same JPEG object, because their private object * sizes may be different. Caveat programmer. */ if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof (my_destination_mgr)); } dest = (my_dest_ptr) cinfo->dest; dest->pub.init_destination = init_destination; dest->pub.empty_output_buffer = empty_output_buffer; dest->pub.term_destination = term_destination; dest->outfile = outfile; } #endif /* HAVE_JPEG */
./CrossVul/dataset_final_sorted/CWE-415/c/good_1407_1
crossvul-cpp_data_good_666_0
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "index.h" #include <stddef.h> #include "repository.h" #include "tree.h" #include "tree-cache.h" #include "hash.h" #include "iterator.h" #include "pathspec.h" #include "ignore.h" #include "blob.h" #include "idxmap.h" #include "diff.h" #include "varint.h" #include "git2/odb.h" #include "git2/oid.h" #include "git2/blob.h" #include "git2/config.h" #include "git2/sys/index.h" #define INSERT_IN_MAP_EX(idx, map, e, err) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_insert((khash_t(idxicase) *) (map), (e), (e), (err)); \ else \ git_idxmap_insert((map), (e), (e), (err)); \ } while (0) #define INSERT_IN_MAP(idx, e, err) INSERT_IN_MAP_EX(idx, (idx)->entries_map, e, err) #define LOOKUP_IN_MAP(p, idx, k) do { \ if ((idx)->ignore_case) \ (p) = git_idxmap_icase_lookup_index((khash_t(idxicase) *) index->entries_map, (k)); \ else \ (p) = git_idxmap_lookup_index(index->entries_map, (k)); \ } while (0) #define DELETE_IN_MAP(idx, e) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_delete((khash_t(idxicase) *) (idx)->entries_map, (e)); \ else \ git_idxmap_delete((idx)->entries_map, (e)); \ } while (0) static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload); #define minimal_entry_size (offsetof(struct entry_short, path)) static const size_t INDEX_FOOTER_SIZE = GIT_OID_RAWSZ; static const size_t INDEX_HEADER_SIZE = 12; static const unsigned int INDEX_VERSION_NUMBER_DEFAULT = 2; static const unsigned int INDEX_VERSION_NUMBER_LB = 2; static const unsigned int INDEX_VERSION_NUMBER_EXT = 3; static const unsigned int INDEX_VERSION_NUMBER_COMP = 4; static const unsigned int INDEX_VERSION_NUMBER_UB = 4; static const unsigned int INDEX_HEADER_SIG = 0x44495243; static const char INDEX_EXT_TREECACHE_SIG[] = {'T', 'R', 'E', 'E'}; static const char INDEX_EXT_UNMERGED_SIG[] = {'R', 'E', 'U', 'C'}; static const char INDEX_EXT_CONFLICT_NAME_SIG[] = {'N', 'A', 'M', 'E'}; #define INDEX_OWNER(idx) ((git_repository *)(GIT_REFCOUNT_OWNER(idx))) struct index_header { uint32_t signature; uint32_t version; uint32_t entry_count; }; struct index_extension { char signature[4]; uint32_t extension_size; }; struct entry_time { uint32_t seconds; uint32_t nanoseconds; }; struct entry_short { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; char path[1]; /* arbitrary length */ }; struct entry_long { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; uint16_t flags_extended; char path[1]; /* arbitrary length */ }; struct entry_srch_key { const char *path; size_t pathlen; int stage; }; struct entry_internal { git_index_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; struct reuc_entry_internal { git_index_reuc_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; /* local declarations */ static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size); static int read_header(struct index_header *dest, const void *buffer); static int parse_index(git_index *index, const char *buffer, size_t buffer_size); static bool is_index_extended(git_index *index); static int write_index(git_oid *checksum, git_index *index, git_filebuf *file); static void index_entry_free(git_index_entry *entry); static void index_entry_reuc_free(git_index_reuc_entry *reuc); int git_index_entry_srch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = memcmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } int git_index_entry_isrch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = strncasecmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } static int index_entry_srch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcmp((const char *)path, entry->path); } static int index_entry_isrch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcasecmp((const char *)path, entry->path); } int git_index_entry_cmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } int git_index_entry_icmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcasecmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } static int conflict_name_cmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcmp(name_a->ours, name_b->ours); } /** * TODO: enable this when resolving case insensitive conflicts */ #if 0 static int conflict_name_icmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcasecmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcasecmp(name_a->ours, name_b->ours); } #endif static int reuc_srch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcmp(key, reuc->path); } static int reuc_isrch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcasecmp(key, reuc->path); } static int reuc_cmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcmp(info_a->path, info_b->path); } static int reuc_icmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcasecmp(info_a->path, info_b->path); } static void index_entry_reuc_free(git_index_reuc_entry *reuc) { git__free(reuc); } static void index_entry_free(git_index_entry *entry) { if (!entry) return; memset(&entry->id, 0, sizeof(entry->id)); git__free(entry); } unsigned int git_index__create_mode(unsigned int mode) { if (S_ISLNK(mode)) return S_IFLNK; if (S_ISDIR(mode) || (mode & S_IFMT) == (S_IFLNK | S_IFDIR)) return (S_IFLNK | S_IFDIR); return S_IFREG | GIT_PERMS_CANONICAL(mode); } static unsigned int index_merge_mode( git_index *index, git_index_entry *existing, unsigned int mode) { if (index->no_symlinks && S_ISREG(mode) && existing && S_ISLNK(existing->mode)) return existing->mode; if (index->distrust_filemode && S_ISREG(mode)) return (existing && S_ISREG(existing->mode)) ? existing->mode : git_index__create_mode(0666); return git_index__create_mode(mode); } GIT_INLINE(int) index_find_in_entries( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { struct entry_srch_key srch_key; srch_key.path = path; srch_key.pathlen = !path_len ? strlen(path) : path_len; srch_key.stage = stage; return git_vector_bsearch2(out, entries, entry_srch, &srch_key); } GIT_INLINE(int) index_find( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { git_vector_sort(&index->entries); return index_find_in_entries( out, &index->entries, index->entries_search, path, path_len, stage); } void git_index__set_ignore_case(git_index *index, bool ignore_case) { index->ignore_case = ignore_case; if (ignore_case) { index->entries_cmp_path = git__strcasecmp_cb; index->entries_search = git_index_entry_isrch; index->entries_search_path = index_entry_isrch_path; index->reuc_search = reuc_isrch; } else { index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; } git_vector_set_cmp(&index->entries, ignore_case ? git_index_entry_icmp : git_index_entry_cmp); git_vector_sort(&index->entries); git_vector_set_cmp(&index->reuc, ignore_case ? reuc_icmp : reuc_cmp); git_vector_sort(&index->reuc); } int git_index_open(git_index **index_out, const char *index_path) { git_index *index; int error = -1; assert(index_out); index = git__calloc(1, sizeof(git_index)); GITERR_CHECK_ALLOC(index); git_pool_init(&index->tree_pool, 1); if (index_path != NULL) { index->index_file_path = git__strdup(index_path); if (!index->index_file_path) goto fail; /* Check if index file is stored on disk already */ if (git_path_exists(index->index_file_path) == true) index->on_disk = 1; } if (git_vector_init(&index->entries, 32, git_index_entry_cmp) < 0 || git_idxmap_alloc(&index->entries_map) < 0 || git_vector_init(&index->names, 8, conflict_name_cmp) < 0 || git_vector_init(&index->reuc, 8, reuc_cmp) < 0 || git_vector_init(&index->deleted, 8, git_index_entry_cmp) < 0) goto fail; index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; index->version = INDEX_VERSION_NUMBER_DEFAULT; if (index_path != NULL && (error = git_index_read(index, true)) < 0) goto fail; *index_out = index; GIT_REFCOUNT_INC(index); return 0; fail: git_pool_clear(&index->tree_pool); git_index_free(index); return error; } int git_index_new(git_index **out) { return git_index_open(out, NULL); } static void index_free(git_index *index) { /* index iterators increment the refcount of the index, so if we * get here then there should be no outstanding iterators. */ assert(!git_atomic_get(&index->readers)); git_index_clear(index); git_idxmap_free(index->entries_map); git_vector_free(&index->entries); git_vector_free(&index->names); git_vector_free(&index->reuc); git_vector_free(&index->deleted); git__free(index->index_file_path); git__memzero(index, sizeof(*index)); git__free(index); } void git_index_free(git_index *index) { if (index == NULL) return; GIT_REFCOUNT_DEC(index, index_free); } /* call with locked index */ static void index_free_deleted(git_index *index) { int readers = (int)git_atomic_get(&index->readers); size_t i; if (readers > 0 || !index->deleted.length) return; for (i = 0; i < index->deleted.length; ++i) { git_index_entry *ie = git__swap(index->deleted.contents[i], NULL); index_entry_free(ie); } git_vector_clear(&index->deleted); } /* call with locked index */ static int index_remove_entry(git_index *index, size_t pos) { int error = 0; git_index_entry *entry = git_vector_get(&index->entries, pos); if (entry != NULL) { git_tree_cache_invalidate_path(index->tree, entry->path); DELETE_IN_MAP(index, entry); } error = git_vector_remove(&index->entries, pos); if (!error) { if (git_atomic_get(&index->readers) > 0) { error = git_vector_insert(&index->deleted, entry); } else { index_entry_free(entry); } } return error; } int git_index_clear(git_index *index) { int error = 0; assert(index); index->tree = NULL; git_pool_clear(&index->tree_pool); git_idxmap_clear(index->entries_map); while (!error && index->entries.length > 0) error = index_remove_entry(index, index->entries.length - 1); index_free_deleted(index); git_index_reuc_clear(index); git_index_name_clear(index); git_futils_filestamp_set(&index->stamp, NULL); return error; } static int create_index_error(int error, const char *msg) { giterr_set_str(GITERR_INDEX, msg); return error; } int git_index_set_caps(git_index *index, int caps) { unsigned int old_ignore_case; assert(index); old_ignore_case = index->ignore_case; if (caps == GIT_INDEXCAP_FROM_OWNER) { git_repository *repo = INDEX_OWNER(index); int val; if (!repo) return create_index_error( -1, "cannot access repository to set index caps"); if (!git_repository__cvar(&val, repo, GIT_CVAR_IGNORECASE)) index->ignore_case = (val != 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_FILEMODE)) index->distrust_filemode = (val == 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_SYMLINKS)) index->no_symlinks = (val == 0); } else { index->ignore_case = ((caps & GIT_INDEXCAP_IGNORE_CASE) != 0); index->distrust_filemode = ((caps & GIT_INDEXCAP_NO_FILEMODE) != 0); index->no_symlinks = ((caps & GIT_INDEXCAP_NO_SYMLINKS) != 0); } if (old_ignore_case != index->ignore_case) { git_index__set_ignore_case(index, (bool)index->ignore_case); } return 0; } int git_index_caps(const git_index *index) { return ((index->ignore_case ? GIT_INDEXCAP_IGNORE_CASE : 0) | (index->distrust_filemode ? GIT_INDEXCAP_NO_FILEMODE : 0) | (index->no_symlinks ? GIT_INDEXCAP_NO_SYMLINKS : 0)); } const git_oid *git_index_checksum(git_index *index) { return &index->checksum; } /** * Returns 1 for changed, 0 for not changed and <0 for errors */ static int compare_checksum(git_index *index) { int fd; ssize_t bytes_read; git_oid checksum = {{ 0 }}; if ((fd = p_open(index->index_file_path, O_RDONLY)) < 0) return fd; if (p_lseek(fd, -20, SEEK_END) < 0) { p_close(fd); giterr_set(GITERR_OS, "failed to seek to end of file"); return -1; } bytes_read = p_read(fd, &checksum, GIT_OID_RAWSZ); p_close(fd); if (bytes_read < 0) return -1; return !!git_oid_cmp(&checksum, &index->checksum); } int git_index_read(git_index *index, int force) { int error = 0, updated; git_buf buffer = GIT_BUF_INIT; git_futils_filestamp stamp = index->stamp; if (!index->index_file_path) return create_index_error(-1, "failed to read index: The index is in-memory only"); index->on_disk = git_path_exists(index->index_file_path); if (!index->on_disk) { if (force) return git_index_clear(index); return 0; } if ((updated = git_futils_filestamp_check(&stamp, index->index_file_path) < 0) || ((updated = compare_checksum(index)) < 0)) { giterr_set( GITERR_INDEX, "failed to read index: '%s' no longer exists", index->index_file_path); return updated; } if (!updated && !force) return 0; error = git_futils_readbuffer(&buffer, index->index_file_path); if (error < 0) return error; index->tree = NULL; git_pool_clear(&index->tree_pool); error = git_index_clear(index); if (!error) error = parse_index(index, buffer.ptr, buffer.size); if (!error) git_futils_filestamp_set(&index->stamp, &stamp); git_buf_free(&buffer); return error; } int git_index__changed_relative_to( git_index *index, const git_oid *checksum) { /* attempt to update index (ignoring errors) */ if (git_index_read(index, false) < 0) giterr_clear(); return !!git_oid_cmp(&index->checksum, checksum); } static bool is_racy_entry(git_index *index, const git_index_entry *entry) { /* Git special-cases submodules in the check */ if (S_ISGITLINK(entry->mode)) return false; return git_index_entry_newer_than_index(entry, index); } /* * Force the next diff to take a look at those entries which have the * same timestamp as the current index. */ static int truncate_racily_clean(git_index *index) { size_t i; int error; git_index_entry *entry; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; git_diff *diff = NULL; git_vector paths = GIT_VECTOR_INIT; git_diff_delta *delta; /* Nothing to do if there's no repo to talk about */ if (!INDEX_OWNER(index)) return 0; /* If there's no workdir, we can't know where to even check */ if (!git_repository_workdir(INDEX_OWNER(index))) return 0; diff_opts.flags |= GIT_DIFF_INCLUDE_TYPECHANGE | GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_DISABLE_PATHSPEC_MATCH; git_vector_foreach(&index->entries, i, entry) { if ((entry->flags_extended & GIT_IDXENTRY_UPTODATE) == 0 && is_racy_entry(index, entry)) git_vector_insert(&paths, (char *)entry->path); } if (paths.length == 0) goto done; diff_opts.pathspec.count = paths.length; diff_opts.pathspec.strings = (char **)paths.contents; if ((error = git_diff_index_to_workdir(&diff, INDEX_OWNER(index), index, &diff_opts)) < 0) return error; git_vector_foreach(&diff->deltas, i, delta) { entry = (git_index_entry *)git_index_get_bypath(index, delta->old_file.path, 0); /* Ensure that we have a stage 0 for this file (ie, it's not a * conflict), otherwise smudging it is quite pointless. */ if (entry) entry->file_size = 0; } done: git_diff_free(diff); git_vector_free(&paths); return 0; } unsigned git_index_version(git_index *index) { assert(index); return index->version; } int git_index_set_version(git_index *index, unsigned int version) { assert(index); if (version < INDEX_VERSION_NUMBER_LB || version > INDEX_VERSION_NUMBER_UB) { giterr_set(GITERR_INDEX, "invalid version number"); return -1; } index->version = version; return 0; } int git_index_write(git_index *index) { git_indexwriter writer = GIT_INDEXWRITER_INIT; int error; truncate_racily_clean(index); if ((error = git_indexwriter_init(&writer, index)) == 0) error = git_indexwriter_commit(&writer); git_indexwriter_cleanup(&writer); return error; } const char * git_index_path(const git_index *index) { assert(index); return index->index_file_path; } int git_index_write_tree(git_oid *oid, git_index *index) { git_repository *repo; assert(oid && index); repo = INDEX_OWNER(index); if (repo == NULL) return create_index_error(-1, "Failed to write tree. " "the index file is not backed up by an existing repository"); return git_tree__write_index(oid, index, repo); } int git_index_write_tree_to( git_oid *oid, git_index *index, git_repository *repo) { assert(oid && index && repo); return git_tree__write_index(oid, index, repo); } size_t git_index_entrycount(const git_index *index) { assert(index); return index->entries.length; } const git_index_entry *git_index_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->entries); return git_vector_get(&index->entries, n); } const git_index_entry *git_index_get_bypath( git_index *index, const char *path, int stage) { khiter_t pos; git_index_entry key = {{ 0 }}; assert(index); key.path = path; GIT_IDXENTRY_STAGE_SET(&key, stage); LOOKUP_IN_MAP(pos, index, &key); if (git_idxmap_valid_index(index->entries_map, pos)) return git_idxmap_value_at(index->entries_map, pos); giterr_set(GITERR_INDEX, "index does not contain '%s'", path); return NULL; } void git_index_entry__init_from_stat( git_index_entry *entry, struct stat *st, bool trust_mode) { entry->ctime.seconds = (int32_t)st->st_ctime; entry->mtime.seconds = (int32_t)st->st_mtime; #if defined(GIT_USE_NSEC) entry->mtime.nanoseconds = st->st_mtime_nsec; entry->ctime.nanoseconds = st->st_ctime_nsec; #endif entry->dev = st->st_rdev; entry->ino = st->st_ino; entry->mode = (!trust_mode && S_ISREG(st->st_mode)) ? git_index__create_mode(0666) : git_index__create_mode(st->st_mode); entry->uid = st->st_uid; entry->gid = st->st_gid; entry->file_size = (uint32_t)st->st_size; } static void index_entry_adjust_namemask( git_index_entry *entry, size_t path_length) { entry->flags &= ~GIT_IDXENTRY_NAMEMASK; if (path_length < GIT_IDXENTRY_NAMEMASK) entry->flags |= path_length & GIT_IDXENTRY_NAMEMASK; else entry->flags |= GIT_IDXENTRY_NAMEMASK; } /* When `from_workdir` is true, we will validate the paths to avoid placing * paths that are invalid for the working directory on the current filesystem * (eg, on Windows, we will disallow `GIT~1`, `AUX`, `COM1`, etc). This * function will *always* prevent `.git` and directory traversal `../` from * being added to the index. */ static int index_entry_create( git_index_entry **out, git_repository *repo, const char *path, bool from_workdir) { size_t pathlen = strlen(path), alloclen; struct entry_internal *entry; unsigned int path_valid_flags = GIT_PATH_REJECT_INDEX_DEFAULTS; /* always reject placing `.git` in the index and directory traversal. * when requested, disallow platform-specific filenames and upgrade to * the platform-specific `.git` tests (eg, `git~1`, etc). */ if (from_workdir) path_valid_flags |= GIT_PATH_REJECT_WORKDIR_DEFAULTS; if (!git_path_isvalid(repo, path, path_valid_flags)) { giterr_set(GITERR_INDEX, "invalid path: '%s'", path); return -1; } GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(struct entry_internal), pathlen); GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); entry = git__calloc(1, alloclen); GITERR_CHECK_ALLOC(entry); entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; *out = (git_index_entry *)entry; return 0; } static int index_entry_init( git_index_entry **entry_out, git_index *index, const char *rel_path) { int error = 0; git_index_entry *entry = NULL; struct stat st; git_oid oid; if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (index_entry_create(&entry, INDEX_OWNER(index), rel_path, true) < 0) return -1; /* write the blob to disk and get the oid and stat info */ error = git_blob__create_from_paths( &oid, &st, INDEX_OWNER(index), NULL, rel_path, 0, true); if (error < 0) { index_entry_free(entry); return error; } entry->id = oid; git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); *entry_out = (git_index_entry *)entry; return 0; } static git_index_reuc_entry *reuc_entry_alloc(const char *path) { size_t pathlen = strlen(path), structlen = sizeof(struct reuc_entry_internal), alloclen; struct reuc_entry_internal *entry; if (GIT_ADD_SIZET_OVERFLOW(&alloclen, structlen, pathlen) || GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1)) return NULL; entry = git__calloc(1, alloclen); if (!entry) return NULL; entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; return (git_index_reuc_entry *)entry; } static int index_entry_reuc_init(git_index_reuc_entry **reuc_out, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; assert(reuc_out && path); *reuc_out = reuc = reuc_entry_alloc(path); GITERR_CHECK_ALLOC(reuc); if ((reuc->mode[0] = ancestor_mode) > 0) { assert(ancestor_oid); git_oid_cpy(&reuc->oid[0], ancestor_oid); } if ((reuc->mode[1] = our_mode) > 0) { assert(our_oid); git_oid_cpy(&reuc->oid[1], our_oid); } if ((reuc->mode[2] = their_mode) > 0) { assert(their_oid); git_oid_cpy(&reuc->oid[2], their_oid); } return 0; } static void index_entry_cpy( git_index_entry *tgt, const git_index_entry *src) { const char *tgt_path = tgt->path; memcpy(tgt, src, sizeof(*tgt)); tgt->path = tgt_path; } static int index_entry_dup( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy(*out, src); return 0; } static void index_entry_cpy_nocache( git_index_entry *tgt, const git_index_entry *src) { git_oid_cpy(&tgt->id, &src->id); tgt->mode = src->mode; tgt->flags = src->flags; tgt->flags_extended = (src->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); } static int index_entry_dup_nocache( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy_nocache(*out, src); return 0; } static int has_file_name(git_index *index, const git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = 0; size_t len = strlen(entry->path); int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; while (pos < index->entries.length) { struct entry_internal *p = index->entries.contents[pos++]; if (len >= p->pathlen) break; if (memcmp(name, p->path, len)) break; if (GIT_IDXENTRY_STAGE(&p->entry) != stage) continue; if (p->path[len] != '/') continue; retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, --pos) < 0) break; } return retval; } /* * Do we have another file with a pathname that is a proper * subset of the name we're trying to add? */ static int has_dir_name(git_index *index, const git_index_entry *entry, int ok_to_replace) { int retval = 0; int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; const char *slash = name + strlen(name); for (;;) { size_t len, pos; for (;;) { if (*--slash == '/') break; if (slash <= entry->path) return retval; } len = slash - name; if (!index_find(&pos, index, name, len, stage)) { retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, pos) < 0) break; continue; } /* * Trivial optimization: if we find an entry that * already matches the sub-directory, then we know * we're ok, and we can exit. */ for (; pos < index->entries.length; ++pos) { struct entry_internal *p = index->entries.contents[pos]; if (p->pathlen <= len || p->path[len] != '/' || memcmp(p->path, name, len)) break; /* not our subdirectory */ if (GIT_IDXENTRY_STAGE(&p->entry) == stage) return retval; } } return retval; } static int check_file_directory_collision(git_index *index, git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = has_file_name(index, entry, pos, ok_to_replace); retval = retval + has_dir_name(index, entry, ok_to_replace); if (retval) { giterr_set(GITERR_INDEX, "'%s' appears as both a file and a directory", entry->path); return -1; } return 0; } static int canonicalize_directory_path( git_index *index, git_index_entry *entry, git_index_entry *existing) { const git_index_entry *match, *best = NULL; char *search, *sep; size_t pos, search_len, best_len; if (!index->ignore_case) return 0; /* item already exists in the index, simply re-use the existing case */ if (existing) { memcpy((char *)entry->path, existing->path, strlen(existing->path)); return 0; } /* nothing to do */ if (strchr(entry->path, '/') == NULL) return 0; if ((search = git__strdup(entry->path)) == NULL) return -1; /* starting at the parent directory and descending to the root, find the * common parent directory. */ while (!best && (sep = strrchr(search, '/'))) { sep[1] = '\0'; search_len = strlen(search); git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, search); while ((match = git_vector_get(&index->entries, pos))) { if (GIT_IDXENTRY_STAGE(match) != 0) { /* conflicts do not contribute to canonical paths */ } else if (strncmp(search, match->path, search_len) == 0) { /* prefer an exact match to the input filename */ best = match; best_len = search_len; break; } else if (strncasecmp(search, match->path, search_len) == 0) { /* continue walking, there may be a path with an exact * (case sensitive) match later in the index, but use this * as the best match until that happens. */ if (!best) { best = match; best_len = search_len; } } else { break; } pos++; } sep[0] = '\0'; } if (best) memcpy((char *)entry->path, best->path, best_len); git__free(search); return 0; } static int index_no_dups(void **old, void *new) { const git_index_entry *entry = new; GIT_UNUSED(old); giterr_set(GITERR_INDEX, "'%s' appears multiple times at stage %d", entry->path, GIT_IDXENTRY_STAGE(entry)); return GIT_EEXISTS; } static void index_existing_and_best( git_index_entry **existing, size_t *existing_position, git_index_entry **best, git_index *index, const git_index_entry *entry) { git_index_entry *e; size_t pos; int error; error = index_find(&pos, index, entry->path, 0, GIT_IDXENTRY_STAGE(entry)); if (error == 0) { *existing = index->entries.contents[pos]; *existing_position = pos; *best = index->entries.contents[pos]; return; } *existing = NULL; *existing_position = 0; *best = NULL; if (GIT_IDXENTRY_STAGE(entry) == 0) { for (; pos < index->entries.length; pos++) { int (*strcomp)(const char *a, const char *b) = index->ignore_case ? git__strcasecmp : git__strcmp; e = index->entries.contents[pos]; if (strcomp(entry->path, e->path) != 0) break; if (GIT_IDXENTRY_STAGE(e) == GIT_INDEX_STAGE_ANCESTOR) { *best = e; continue; } else { *best = e; break; } } } } /* index_insert takes ownership of the new entry - if it can't insert * it, then it will return an error **and also free the entry**. When * it replaces an existing entry, it will update the entry_ptr with the * actual entry in the index (and free the passed in one). * * trust_path is whether we use the given path, or whether (on case * insensitive systems only) we try to canonicalize the given path to * be within an existing directory. * * trust_mode is whether we trust the mode in entry_ptr. * * trust_id is whether we trust the id or it should be validated. */ static int index_insert( git_index *index, git_index_entry **entry_ptr, int replace, bool trust_path, bool trust_mode, bool trust_id) { int error = 0; size_t path_length, position; git_index_entry *existing, *best, *entry; assert(index && entry_ptr); entry = *entry_ptr; /* make sure that the path length flag is correct */ path_length = ((struct entry_internal *)entry)->pathlen; index_entry_adjust_namemask(entry, path_length); /* this entry is now up-to-date and should not be checked for raciness */ entry->flags_extended |= GIT_IDXENTRY_UPTODATE; git_vector_sort(&index->entries); /* look if an entry with this path already exists, either staged, or (if * this entry is a regular staged item) as the "ours" side of a conflict. */ index_existing_and_best(&existing, &position, &best, index, entry); /* update the file mode */ entry->mode = trust_mode ? git_index__create_mode(entry->mode) : index_merge_mode(index, best, entry->mode); /* canonicalize the directory name */ if (!trust_path) error = canonicalize_directory_path(index, entry, best); /* ensure that the given id exists (unless it's a submodule) */ if (!error && !trust_id && INDEX_OWNER(index) && (entry->mode & GIT_FILEMODE_COMMIT) != GIT_FILEMODE_COMMIT) { if (!git_object__is_valid(INDEX_OWNER(index), &entry->id, git_object__type_from_filemode(entry->mode))) error = -1; } /* look for tree / blob name collisions, removing conflicts if requested */ if (!error) error = check_file_directory_collision(index, entry, position, replace); if (error < 0) /* skip changes */; /* if we are replacing an existing item, overwrite the existing entry * and return it in place of the passed in one. */ else if (existing) { if (replace) { index_entry_cpy(existing, entry); if (trust_path) memcpy((char *)existing->path, entry->path, strlen(entry->path)); } index_entry_free(entry); *entry_ptr = entry = existing; } else { /* if replace is not requested or no existing entry exists, insert * at the sorted position. (Since we re-sort after each insert to * check for dups, this is actually cheaper in the long run.) */ error = git_vector_insert_sorted(&index->entries, entry, index_no_dups); if (error == 0) { INSERT_IN_MAP(index, entry, &error); } } if (error < 0) { index_entry_free(*entry_ptr); *entry_ptr = NULL; } return error; } static int index_conflict_to_reuc(git_index *index, const char *path) { const git_index_entry *conflict_entries[3]; int ancestor_mode, our_mode, their_mode; git_oid const *ancestor_oid, *our_oid, *their_oid; int ret; if ((ret = git_index_conflict_get(&conflict_entries[0], &conflict_entries[1], &conflict_entries[2], index, path)) < 0) return ret; ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode; our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode; their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode; ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id; our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id; their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id; if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) >= 0) ret = git_index_conflict_remove(index, path); return ret; } GIT_INLINE(bool) is_file_or_link(const int filemode) { return (filemode == GIT_FILEMODE_BLOB || filemode == GIT_FILEMODE_BLOB_EXECUTABLE || filemode == GIT_FILEMODE_LINK); } GIT_INLINE(bool) valid_filemode(const int filemode) { return (is_file_or_link(filemode) || filemode == GIT_FILEMODE_COMMIT); } int git_index_add_frombuffer( git_index *index, const git_index_entry *source_entry, const void *buffer, size_t len) { git_index_entry *entry = NULL; int error = 0; git_oid id; assert(index && source_entry->path); if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (!is_file_or_link(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid filemode"); return -1; } if (index_entry_dup(&entry, index, source_entry) < 0) return -1; error = git_blob_create_frombuffer(&id, INDEX_OWNER(index), buffer, len); if (error < 0) { index_entry_free(entry); return error; } git_oid_cpy(&entry->id, &id); entry->file_size = len; if ((error = index_insert(index, &entry, 1, true, true, true)) < 0) return error; /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((error = index_conflict_to_reuc(index, entry->path)) < 0 && error != GIT_ENOTFOUND) return error; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } static int add_repo_as_submodule(git_index_entry **out, git_index *index, const char *path) { git_repository *sub; git_buf abspath = GIT_BUF_INIT; git_repository *repo = INDEX_OWNER(index); git_reference *head; git_index_entry *entry; struct stat st; int error; if (index_entry_create(&entry, INDEX_OWNER(index), path, true) < 0) return -1; if ((error = git_buf_joinpath(&abspath, git_repository_workdir(repo), path)) < 0) return error; if ((error = p_stat(abspath.ptr, &st)) < 0) { giterr_set(GITERR_OS, "failed to stat repository dir"); return -1; } git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); if ((error = git_repository_open(&sub, abspath.ptr)) < 0) return error; if ((error = git_repository_head(&head, sub)) < 0) return error; git_oid_cpy(&entry->id, git_reference_target(head)); entry->mode = GIT_FILEMODE_COMMIT; git_reference_free(head); git_repository_free(sub); git_buf_free(&abspath); *out = entry; return 0; } int git_index_add_bypath(git_index *index, const char *path) { git_index_entry *entry = NULL; int ret; assert(index && path); if ((ret = index_entry_init(&entry, index, path)) == 0) ret = index_insert(index, &entry, 1, false, false, true); /* If we were given a directory, let's see if it's a submodule */ if (ret < 0 && ret != GIT_EDIRECTORY) return ret; if (ret == GIT_EDIRECTORY) { git_submodule *sm; git_error_state err; giterr_state_capture(&err, ret); ret = git_submodule_lookup(&sm, INDEX_OWNER(index), path); if (ret == GIT_ENOTFOUND) return giterr_state_restore(&err); giterr_state_free(&err); /* * EEXISTS means that there is a repository at that path, but it's not known * as a submodule. We add its HEAD as an entry and don't register it. */ if (ret == GIT_EEXISTS) { if ((ret = add_repo_as_submodule(&entry, index, path)) < 0) return ret; if ((ret = index_insert(index, &entry, 1, false, false, true)) < 0) return ret; } else if (ret < 0) { return ret; } else { ret = git_submodule_add_to_index(sm, false); git_submodule_free(sm); return ret; } } /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove_bypath(git_index *index, const char *path) { int ret; assert(index && path); if (((ret = git_index_remove(index, path, 0)) < 0 && ret != GIT_ENOTFOUND) || ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND)) return ret; if (ret == GIT_ENOTFOUND) giterr_clear(); return 0; } int git_index__fill(git_index *index, const git_vector *source_entries) { const git_index_entry *source_entry = NULL; size_t i; int ret = 0; assert(index); if (!source_entries->length) return 0; git_vector_size_hint(&index->entries, source_entries->length); git_idxmap_resize(index->entries_map, (khint_t)(source_entries->length * 1.3)); git_vector_foreach(source_entries, i, source_entry) { git_index_entry *entry = NULL; if ((ret = index_entry_dup(&entry, index, source_entry)) < 0) break; index_entry_adjust_namemask(entry, ((struct entry_internal *)entry)->pathlen); entry->flags_extended |= GIT_IDXENTRY_UPTODATE; entry->mode = git_index__create_mode(entry->mode); if ((ret = git_vector_insert(&index->entries, entry)) < 0) break; INSERT_IN_MAP(index, entry, &ret); if (ret < 0) break; } if (!ret) git_vector_sort(&index->entries); return ret; } int git_index_add(git_index *index, const git_index_entry *source_entry) { git_index_entry *entry = NULL; int ret; assert(index && source_entry && source_entry->path); if (!valid_filemode(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid entry mode"); return -1; } if ((ret = index_entry_dup(&entry, index, source_entry)) < 0 || (ret = index_insert(index, &entry, 1, true, true, false)) < 0) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove(git_index *index, const char *path, int stage) { int error; size_t position; git_index_entry remove_key = {{ 0 }}; remove_key.path = path; GIT_IDXENTRY_STAGE_SET(&remove_key, stage); DELETE_IN_MAP(index, &remove_key); if (index_find(&position, index, path, 0, stage) < 0) { giterr_set( GITERR_INDEX, "index does not contain %s at stage %d", path, stage); error = GIT_ENOTFOUND; } else { error = index_remove_entry(index, position); } return error; } int git_index_remove_directory(git_index *index, const char *dir, int stage) { git_buf pfx = GIT_BUF_INIT; int error = 0; size_t pos; git_index_entry *entry; if (!(error = git_buf_sets(&pfx, dir)) && !(error = git_path_to_dir(&pfx))) index_find(&pos, index, pfx.ptr, pfx.size, GIT_INDEX_STAGE_ANY); while (!error) { entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, pfx.ptr) != 0) break; if (GIT_IDXENTRY_STAGE(entry) != stage) { ++pos; continue; } error = index_remove_entry(index, pos); /* removed entry at 'pos' so we don't need to increment */ } git_buf_free(&pfx); return error; } int git_index_find_prefix(size_t *at_pos, git_index *index, const char *prefix) { int error = 0; size_t pos; const git_index_entry *entry; index_find(&pos, index, prefix, strlen(prefix), GIT_INDEX_STAGE_ANY); entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, prefix) != 0) error = GIT_ENOTFOUND; if (!error && at_pos) *at_pos = pos; return error; } int git_index__find_pos( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { assert(index && path); return index_find(out, index, path, path_len, stage); } int git_index_find(size_t *at_pos, git_index *index, const char *path) { size_t pos; assert(index && path); if (git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, path) < 0) { giterr_set(GITERR_INDEX, "index does not contain %s", path); return GIT_ENOTFOUND; } /* Since our binary search only looked at path, we may be in the * middle of a list of stages. */ for (; pos > 0; --pos) { const git_index_entry *prev = git_vector_get(&index->entries, pos - 1); if (index->entries_cmp_path(prev->path, path) != 0) break; } if (at_pos) *at_pos = pos; return 0; } int git_index_conflict_add(git_index *index, const git_index_entry *ancestor_entry, const git_index_entry *our_entry, const git_index_entry *their_entry) { git_index_entry *entries[3] = { 0 }; unsigned short i; int ret = 0; assert (index); if ((ancestor_entry && (ret = index_entry_dup(&entries[0], index, ancestor_entry)) < 0) || (our_entry && (ret = index_entry_dup(&entries[1], index, our_entry)) < 0) || (their_entry && (ret = index_entry_dup(&entries[2], index, their_entry)) < 0)) goto on_error; /* Validate entries */ for (i = 0; i < 3; i++) { if (entries[i] && !valid_filemode(entries[i]->mode)) { giterr_set(GITERR_INDEX, "invalid filemode for stage %d entry", i + 1); return -1; } } /* Remove existing index entries for each path */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; if ((ret = git_index_remove(index, entries[i]->path, 0)) != 0) { if (ret != GIT_ENOTFOUND) goto on_error; giterr_clear(); ret = 0; } } /* Add the conflict entries */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; /* Make sure stage is correct */ GIT_IDXENTRY_STAGE_SET(entries[i], i + 1); if ((ret = index_insert(index, &entries[i], 1, true, true, false)) < 0) goto on_error; entries[i] = NULL; /* don't free if later entry fails */ } return 0; on_error: for (i = 0; i < 3; i++) { if (entries[i] != NULL) index_entry_free(entries[i]); } return ret; } static int index_conflict__get_byindex( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, size_t n) { const git_index_entry *conflict_entry; const char *path = NULL; size_t count; int stage, len = 0; assert(ancestor_out && our_out && their_out && index); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; for (count = git_index_entrycount(index); n < count; ++n) { conflict_entry = git_vector_get(&index->entries, n); if (path && index->entries_cmp_path(conflict_entry->path, path) != 0) break; stage = GIT_IDXENTRY_STAGE(conflict_entry); path = conflict_entry->path; switch (stage) { case 3: *their_out = conflict_entry; len++; break; case 2: *our_out = conflict_entry; len++; break; case 1: *ancestor_out = conflict_entry; len++; break; default: break; }; } return len; } int git_index_conflict_get( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, const char *path) { size_t pos; int len = 0; assert(ancestor_out && our_out && their_out && index && path); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; if (git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, index, pos)) < 0) return len; else if (len == 0) return GIT_ENOTFOUND; return 0; } static int index_conflict_remove(git_index *index, const char *path) { size_t pos = 0; git_index_entry *conflict_entry; int error = 0; if (path != NULL && git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; while ((conflict_entry = git_vector_get(&index->entries, pos)) != NULL) { if (path != NULL && index->entries_cmp_path(conflict_entry->path, path) != 0) break; if (GIT_IDXENTRY_STAGE(conflict_entry) == 0) { pos++; continue; } if ((error = index_remove_entry(index, pos)) < 0) break; } return error; } int git_index_conflict_remove(git_index *index, const char *path) { assert(index && path); return index_conflict_remove(index, path); } int git_index_conflict_cleanup(git_index *index) { assert(index); return index_conflict_remove(index, NULL); } int git_index_has_conflicts(const git_index *index) { size_t i; git_index_entry *entry; assert(index); git_vector_foreach(&index->entries, i, entry) { if (GIT_IDXENTRY_STAGE(entry) > 0) return 1; } return 0; } int git_index_conflict_iterator_new( git_index_conflict_iterator **iterator_out, git_index *index) { git_index_conflict_iterator *it = NULL; assert(iterator_out && index); it = git__calloc(1, sizeof(git_index_conflict_iterator)); GITERR_CHECK_ALLOC(it); it->index = index; *iterator_out = it; return 0; } int git_index_conflict_next( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index_conflict_iterator *iterator) { const git_index_entry *entry; int len; assert(ancestor_out && our_out && their_out && iterator); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; while (iterator->cur < iterator->index->entries.length) { entry = git_index_get_byindex(iterator->index, iterator->cur); if (git_index_entry_is_conflict(entry)) { if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, iterator->index, iterator->cur)) < 0) return len; iterator->cur += len; return 0; } iterator->cur++; } return GIT_ITEROVER; } void git_index_conflict_iterator_free(git_index_conflict_iterator *iterator) { if (iterator == NULL) return; git__free(iterator); } size_t git_index_name_entrycount(git_index *index) { assert(index); return index->names.length; } const git_index_name_entry *git_index_name_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->names); return git_vector_get(&index->names, n); } static void index_name_entry_free(git_index_name_entry *ne) { if (!ne) return; git__free(ne->ancestor); git__free(ne->ours); git__free(ne->theirs); git__free(ne); } int git_index_name_add(git_index *index, const char *ancestor, const char *ours, const char *theirs) { git_index_name_entry *conflict_name; assert((ancestor && ours) || (ancestor && theirs) || (ours && theirs)); conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); if ((ancestor && !(conflict_name->ancestor = git__strdup(ancestor))) || (ours && !(conflict_name->ours = git__strdup(ours))) || (theirs && !(conflict_name->theirs = git__strdup(theirs))) || git_vector_insert(&index->names, conflict_name) < 0) { index_name_entry_free(conflict_name); return -1; } return 0; } void git_index_name_clear(git_index *index) { size_t i; git_index_name_entry *conflict_name; assert(index); git_vector_foreach(&index->names, i, conflict_name) index_name_entry_free(conflict_name); git_vector_clear(&index->names); } size_t git_index_reuc_entrycount(git_index *index) { assert(index); return index->reuc.length; } static int index_reuc_on_dup(void **old, void *new) { index_entry_reuc_free(*old); *old = new; return GIT_EEXISTS; } static int index_reuc_insert( git_index *index, git_index_reuc_entry *reuc) { int res; assert(index && reuc && reuc->path != NULL); assert(git_vector_is_sorted(&index->reuc)); res = git_vector_insert_sorted(&index->reuc, reuc, &index_reuc_on_dup); return res == GIT_EEXISTS ? 0 : res; } int git_index_reuc_add(git_index *index, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; int error = 0; assert(index && path); if ((error = index_entry_reuc_init(&reuc, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) < 0 || (error = index_reuc_insert(index, reuc)) < 0) index_entry_reuc_free(reuc); return error; } int git_index_reuc_find(size_t *at_pos, git_index *index, const char *path) { return git_vector_bsearch2(at_pos, &index->reuc, index->reuc_search, path); } const git_index_reuc_entry *git_index_reuc_get_bypath( git_index *index, const char *path) { size_t pos; assert(index && path); if (!index->reuc.length) return NULL; assert(git_vector_is_sorted(&index->reuc)); if (git_index_reuc_find(&pos, index, path) < 0) return NULL; return git_vector_get(&index->reuc, pos); } const git_index_reuc_entry *git_index_reuc_get_byindex( git_index *index, size_t n) { assert(index); assert(git_vector_is_sorted(&index->reuc)); return git_vector_get(&index->reuc, n); } int git_index_reuc_remove(git_index *index, size_t position) { int error; git_index_reuc_entry *reuc; assert(git_vector_is_sorted(&index->reuc)); reuc = git_vector_get(&index->reuc, position); error = git_vector_remove(&index->reuc, position); if (!error) index_entry_reuc_free(reuc); return error; } void git_index_reuc_clear(git_index *index) { size_t i; assert(index); for (i = 0; i < index->reuc.length; ++i) index_entry_reuc_free(git__swap(index->reuc.contents[i], NULL)); git_vector_clear(&index->reuc); } static int index_error_invalid(const char *message) { giterr_set(GITERR_INDEX, "invalid data in index - %s", message); return -1; } static int read_reuc(git_index *index, const char *buffer, size_t size) { const char *endptr; size_t len; int i; /* If called multiple times, the vector might already be initialized */ if (index->reuc._alloc_size == 0 && git_vector_init(&index->reuc, 16, reuc_cmp) < 0) return -1; while (size) { git_index_reuc_entry *lost; len = p_strnlen(buffer, size) + 1; if (size <= len) return index_error_invalid("reading reuc entries"); lost = reuc_entry_alloc(buffer); GITERR_CHECK_ALLOC(lost); size -= len; buffer += len; /* read 3 ASCII octal numbers for stage entries */ for (i = 0; i < 3; i++) { int64_t tmp; if (git__strtol64(&tmp, buffer, &endptr, 8) < 0 || !endptr || endptr == buffer || *endptr || tmp < 0 || tmp > UINT32_MAX) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } lost->mode[i] = (uint32_t)tmp; len = (endptr + 1) - buffer; if (size <= len) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } size -= len; buffer += len; } /* read up to 3 OIDs for stage entries */ for (i = 0; i < 3; i++) { if (!lost->mode[i]) continue; if (size < 20) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry oid"); } git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer); size -= 20; buffer += 20; } /* entry was read successfully - insert into reuc vector */ if (git_vector_insert(&index->reuc, lost) < 0) return -1; } /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->reuc, true); return 0; } static int read_conflict_names(git_index *index, const char *buffer, size_t size) { size_t len; /* This gets called multiple times, the vector might already be initialized */ if (index->names._alloc_size == 0 && git_vector_init(&index->names, 16, conflict_name_cmp) < 0) return -1; #define read_conflict_name(ptr) \ len = p_strnlen(buffer, size) + 1; \ if (size < len) { \ index_error_invalid("reading conflict name entries"); \ goto out_err; \ } \ if (len == 1) \ ptr = NULL; \ else { \ ptr = git__malloc(len); \ GITERR_CHECK_ALLOC(ptr); \ memcpy(ptr, buffer, len); \ } \ \ buffer += len; \ size -= len; while (size) { git_index_name_entry *conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); read_conflict_name(conflict_name->ancestor); read_conflict_name(conflict_name->ours); read_conflict_name(conflict_name->theirs); if (git_vector_insert(&index->names, conflict_name) < 0) goto out_err; continue; out_err: git__free(conflict_name->ancestor); git__free(conflict_name->ours); git__free(conflict_name->theirs); git__free(conflict_name); return -1; } #undef read_conflict_name /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->names, true); return 0; } static size_t index_entry_size(size_t path_len, size_t varint_len, uint32_t flags) { if (varint_len) { if (flags & GIT_IDXENTRY_EXTENDED) return offsetof(struct entry_long, path) + path_len + 1 + varint_len; else return offsetof(struct entry_short, path) + path_len + 1 + varint_len; } else { #define entry_size(type,len) ((offsetof(type, path) + (len) + 8) & ~7) if (flags & GIT_IDXENTRY_EXTENDED) return entry_size(struct entry_long, path_len); else return entry_size(struct entry_short, path_len); #undef entry_size } } static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } static int read_header(struct index_header *dest, const void *buffer) { const struct index_header *source = buffer; dest->signature = ntohl(source->signature); if (dest->signature != INDEX_HEADER_SIG) return index_error_invalid("incorrect header signature"); dest->version = ntohl(source->version); if (dest->version < INDEX_VERSION_NUMBER_LB || dest->version > INDEX_VERSION_NUMBER_UB) return index_error_invalid("incorrect header version"); dest->entry_count = ntohl(source->entry_count); return 0; } static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size) { struct index_extension dest; size_t total_size; /* buffer is not guaranteed to be aligned */ memcpy(&dest, buffer, sizeof(struct index_extension)); dest.extension_size = ntohl(dest.extension_size); total_size = dest.extension_size + sizeof(struct index_extension); if (dest.extension_size > total_size || buffer_size < total_size || buffer_size - total_size < INDEX_FOOTER_SIZE) return 0; /* optional extension */ if (dest.signature[0] >= 'A' && dest.signature[0] <= 'Z') { /* tree cache */ if (memcmp(dest.signature, INDEX_EXT_TREECACHE_SIG, 4) == 0) { if (git_tree_cache_read(&index->tree, buffer + 8, dest.extension_size, &index->tree_pool) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_UNMERGED_SIG, 4) == 0) { if (read_reuc(index, buffer + 8, dest.extension_size) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4) == 0) { if (read_conflict_names(index, buffer + 8, dest.extension_size) < 0) return 0; } /* else, unsupported extension. We cannot parse this, but we can skip * it by returning `total_size */ } else { /* we cannot handle non-ignorable extensions; * in fact they aren't even defined in the standard */ return 0; } return total_size; } static int parse_index(git_index *index, const char *buffer, size_t buffer_size) { int error = 0; unsigned int i; struct index_header header = { 0 }; git_oid checksum_calculated, checksum_expected; const char *last = NULL; const char *empty = ""; #define seek_forward(_increase) { \ if (_increase >= buffer_size) { \ error = index_error_invalid("ran out of data while parsing"); \ goto done; } \ buffer += _increase; \ buffer_size -= _increase;\ } if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE) return index_error_invalid("insufficient buffer space"); /* Precalculate the SHA1 of the files's contents -- we'll match it to * the provided SHA1 in the footer */ git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE); /* Parse header */ if ((error = read_header(&header, buffer)) < 0) return error; index->version = header.version; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = empty; seek_forward(INDEX_HEADER_SIZE); assert(!index->entries.length); if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count); else git_idxmap_resize(index->entries_map, header.entry_count); /* Parse all the entries */ for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) { git_index_entry *entry = NULL; size_t entry_size; if ((error = read_entry(&entry, &entry_size, index, buffer, buffer_size, last)) < 0) { error = index_error_invalid("invalid entry"); goto done; } if ((error = git_vector_insert(&index->entries, entry)) < 0) { index_entry_free(entry); goto done; } INSERT_IN_MAP(index, entry, &error); if (error < 0) { index_entry_free(entry); goto done; } error = 0; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; seek_forward(entry_size); } if (i != header.entry_count) { error = index_error_invalid("header entries changed while parsing"); goto done; } /* There's still space for some extensions! */ while (buffer_size > INDEX_FOOTER_SIZE) { size_t extension_size; extension_size = read_extension(index, buffer, buffer_size); /* see if we have read any bytes from the extension */ if (extension_size == 0) { error = index_error_invalid("extension is truncated"); goto done; } seek_forward(extension_size); } if (buffer_size != INDEX_FOOTER_SIZE) { error = index_error_invalid( "buffer size does not match index footer size"); goto done; } /* 160-bit SHA-1 over the content of the index file before this checksum. */ git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer); if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) { error = index_error_invalid( "calculated checksum does not match expected"); goto done; } git_oid_cpy(&index->checksum, &checksum_calculated); #undef seek_forward /* Entries are stored case-sensitively on disk, so re-sort now if * in-memory index is supposed to be case-insensitive */ git_vector_set_sorted(&index->entries, !index->ignore_case); git_vector_sort(&index->entries); done: return error; } static bool is_index_extended(git_index *index) { size_t i, extended; git_index_entry *entry; extended = 0; git_vector_foreach(&index->entries, i, entry) { entry->flags &= ~GIT_IDXENTRY_EXTENDED; if (entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS) { extended++; entry->flags |= GIT_IDXENTRY_EXTENDED; } } return (extended > 0); } static int write_disk_entry(git_filebuf *file, git_index_entry *entry, const char *last) { void *mem = NULL; struct entry_short *ondisk; size_t path_len, disk_size; int varint_len = 0; char *path; const char *path_start = entry->path; size_t same_len = 0; path_len = ((struct entry_internal *)entry)->pathlen; if (last) { const char *last_c = last; while (*path_start == *last_c) { if (!*path_start || !*last_c) break; ++path_start; ++last_c; ++same_len; } path_len -= same_len; varint_len = git_encode_varint(NULL, 0, same_len); } disk_size = index_entry_size(path_len, varint_len, entry->flags); if (git_filebuf_reserve(file, &mem, disk_size) < 0) return -1; ondisk = (struct entry_short *)mem; memset(ondisk, 0x0, disk_size); /** * Yes, we have to truncate. * * The on-disk format for Index entries clearly defines * the time and size fields to be 4 bytes each -- so even if * we store these values with 8 bytes on-memory, they must * be truncated to 4 bytes before writing to disk. * * In 2038 I will be either too dead or too rich to care about this */ ondisk->ctime.seconds = htonl((uint32_t)entry->ctime.seconds); ondisk->mtime.seconds = htonl((uint32_t)entry->mtime.seconds); ondisk->ctime.nanoseconds = htonl(entry->ctime.nanoseconds); ondisk->mtime.nanoseconds = htonl(entry->mtime.nanoseconds); ondisk->dev = htonl(entry->dev); ondisk->ino = htonl(entry->ino); ondisk->mode = htonl(entry->mode); ondisk->uid = htonl(entry->uid); ondisk->gid = htonl(entry->gid); ondisk->file_size = htonl((uint32_t)entry->file_size); git_oid_cpy(&ondisk->oid, &entry->id); ondisk->flags = htons(entry->flags); if (entry->flags & GIT_IDXENTRY_EXTENDED) { struct entry_long *ondisk_ext; ondisk_ext = (struct entry_long *)ondisk; ondisk_ext->flags_extended = htons(entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); path = ondisk_ext->path; disk_size -= offsetof(struct entry_long, path); } else { path = ondisk->path; disk_size -= offsetof(struct entry_short, path); } if (last) { varint_len = git_encode_varint((unsigned char *) path, disk_size, same_len); assert(varint_len > 0); path += varint_len; disk_size -= varint_len; /* * If using path compression, we are not allowed * to have additional trailing NULs. */ assert(disk_size == path_len + 1); } else { /* * If no path compression is used, we do have * NULs as padding. As such, simply assert that * we have enough space left to write the path. */ assert(disk_size > path_len); } memcpy(path, path_start, path_len + 1); return 0; } static int write_entries(git_index *index, git_filebuf *file) { int error = 0; size_t i; git_vector case_sorted, *entries; git_index_entry *entry; const char *last = NULL; /* If index->entries is sorted case-insensitively, then we need * to re-sort it case-sensitively before writing */ if (index->ignore_case) { git_vector_dup(&case_sorted, &index->entries, git_index_entry_cmp); git_vector_sort(&case_sorted); entries = &case_sorted; } else { entries = &index->entries; } if (index->version >= INDEX_VERSION_NUMBER_COMP) last = ""; git_vector_foreach(entries, i, entry) { if ((error = write_disk_entry(file, entry, last)) < 0) break; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; } if (index->ignore_case) git_vector_free(&case_sorted); return error; } static int write_extension(git_filebuf *file, struct index_extension *header, git_buf *data) { struct index_extension ondisk; memset(&ondisk, 0x0, sizeof(struct index_extension)); memcpy(&ondisk, header, 4); ondisk.extension_size = htonl(header->extension_size); git_filebuf_write(file, &ondisk, sizeof(struct index_extension)); return git_filebuf_write(file, data->ptr, data->size); } static int create_name_extension_data(git_buf *name_buf, git_index_name_entry *conflict_name) { int error = 0; if (conflict_name->ancestor == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ancestor, strlen(conflict_name->ancestor) + 1); if (error != 0) goto on_error; if (conflict_name->ours == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ours, strlen(conflict_name->ours) + 1); if (error != 0) goto on_error; if (conflict_name->theirs == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->theirs, strlen(conflict_name->theirs) + 1); on_error: return error; } static int write_name_extension(git_index *index, git_filebuf *file) { git_buf name_buf = GIT_BUF_INIT; git_vector *out = &index->names; git_index_name_entry *conflict_name; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, conflict_name) { if ((error = create_name_extension_data(&name_buf, conflict_name)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4); extension.extension_size = (uint32_t)name_buf.size; error = write_extension(file, &extension, &name_buf); git_buf_free(&name_buf); done: return error; } static int create_reuc_extension_data(git_buf *reuc_buf, git_index_reuc_entry *reuc) { int i; int error = 0; if ((error = git_buf_put(reuc_buf, reuc->path, strlen(reuc->path) + 1)) < 0) return error; for (i = 0; i < 3; i++) { if ((error = git_buf_printf(reuc_buf, "%o", reuc->mode[i])) < 0 || (error = git_buf_put(reuc_buf, "\0", 1)) < 0) return error; } for (i = 0; i < 3; i++) { if (reuc->mode[i] && (error = git_buf_put(reuc_buf, (char *)&reuc->oid[i].id, GIT_OID_RAWSZ)) < 0) return error; } return 0; } static int write_reuc_extension(git_index *index, git_filebuf *file) { git_buf reuc_buf = GIT_BUF_INIT; git_vector *out = &index->reuc; git_index_reuc_entry *reuc; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, reuc) { if ((error = create_reuc_extension_data(&reuc_buf, reuc)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_UNMERGED_SIG, 4); extension.extension_size = (uint32_t)reuc_buf.size; error = write_extension(file, &extension, &reuc_buf); git_buf_free(&reuc_buf); done: return error; } static int write_tree_extension(git_index *index, git_filebuf *file) { struct index_extension extension; git_buf buf = GIT_BUF_INIT; int error; if (index->tree == NULL) return 0; if ((error = git_tree_cache_write(&buf, index->tree)) < 0) return error; memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_TREECACHE_SIG, 4); extension.extension_size = (uint32_t)buf.size; error = write_extension(file, &extension, &buf); git_buf_free(&buf); return error; } static void clear_uptodate(git_index *index) { git_index_entry *entry; size_t i; git_vector_foreach(&index->entries, i, entry) entry->flags_extended &= ~GIT_IDXENTRY_UPTODATE; } static int write_index(git_oid *checksum, git_index *index, git_filebuf *file) { git_oid hash_final; struct index_header header; bool is_extended; uint32_t index_version_number; assert(index && file); if (index->version <= INDEX_VERSION_NUMBER_EXT) { is_extended = is_index_extended(index); index_version_number = is_extended ? INDEX_VERSION_NUMBER_EXT : INDEX_VERSION_NUMBER_LB; } else { index_version_number = index->version; } header.signature = htonl(INDEX_HEADER_SIG); header.version = htonl(index_version_number); header.entry_count = htonl((uint32_t)index->entries.length); if (git_filebuf_write(file, &header, sizeof(struct index_header)) < 0) return -1; if (write_entries(index, file) < 0) return -1; /* write the tree cache extension */ if (index->tree != NULL && write_tree_extension(index, file) < 0) return -1; /* write the rename conflict extension */ if (index->names.length > 0 && write_name_extension(index, file) < 0) return -1; /* write the reuc extension */ if (index->reuc.length > 0 && write_reuc_extension(index, file) < 0) return -1; /* get out the hash for all the contents we've appended to the file */ git_filebuf_hash(&hash_final, file); git_oid_cpy(checksum, &hash_final); /* write it at the end of the file */ if (git_filebuf_write(file, hash_final.id, GIT_OID_RAWSZ) < 0) return -1; /* file entries are no longer up to date */ clear_uptodate(index); return 0; } int git_index_entry_stage(const git_index_entry *entry) { return GIT_IDXENTRY_STAGE(entry); } int git_index_entry_is_conflict(const git_index_entry *entry) { return (GIT_IDXENTRY_STAGE(entry) > 0); } typedef struct read_tree_data { git_index *index; git_vector *old_entries; git_vector *new_entries; git_vector_cmp entry_cmp; git_tree_cache *tree; } read_tree_data; static int read_tree_cb( const char *root, const git_tree_entry *tentry, void *payload) { read_tree_data *data = payload; git_index_entry *entry = NULL, *old_entry; git_buf path = GIT_BUF_INIT; size_t pos; if (git_tree_entry__is_tree(tentry)) return 0; if (git_buf_joinpath(&path, root, tentry->filename) < 0) return -1; if (index_entry_create(&entry, INDEX_OWNER(data->index), path.ptr, false) < 0) return -1; entry->mode = tentry->attr; git_oid_cpy(&entry->id, git_tree_entry_id(tentry)); /* look for corresponding old entry and copy data to new entry */ if (data->old_entries != NULL && !index_find_in_entries( &pos, data->old_entries, data->entry_cmp, path.ptr, 0, 0) && (old_entry = git_vector_get(data->old_entries, pos)) != NULL && entry->mode == old_entry->mode && git_oid_equal(&entry->id, &old_entry->id)) { index_entry_cpy(entry, old_entry); entry->flags_extended = 0; } index_entry_adjust_namemask(entry, path.size); git_buf_free(&path); if (git_vector_insert(data->new_entries, entry) < 0) { index_entry_free(entry); return -1; } return 0; } int git_index_read_tree(git_index *index, const git_tree *tree) { int error = 0; git_vector entries = GIT_VECTOR_INIT; git_idxmap *entries_map; read_tree_data data; size_t i; git_index_entry *e; if (git_idxmap_alloc(&entries_map) < 0) return -1; git_vector_set_cmp(&entries, index->entries._cmp); /* match sort */ data.index = index; data.old_entries = &index->entries; data.new_entries = &entries; data.entry_cmp = index->entries_search; index->tree = NULL; git_pool_clear(&index->tree_pool); git_vector_sort(&index->entries); if ((error = git_tree_walk(tree, GIT_TREEWALK_POST, read_tree_cb, &data)) < 0) goto cleanup; if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) entries_map, entries.length); else git_idxmap_resize(entries_map, entries.length); git_vector_foreach(&entries, i, e) { INSERT_IN_MAP_EX(index, entries_map, e, &error); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry into map"); return error; } } error = 0; git_vector_sort(&entries); if ((error = git_index_clear(index)) < 0) { /* well, this isn't good */; } else { git_vector_swap(&entries, &index->entries); entries_map = git__swap(index->entries_map, entries_map); } cleanup: git_vector_free(&entries); git_idxmap_free(entries_map); if (error < 0) return error; error = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool); return error; } static int git_index_read_iterator( git_index *index, git_iterator *new_iterator, size_t new_length_hint) { git_vector new_entries = GIT_VECTOR_INIT, remove_entries = GIT_VECTOR_INIT; git_idxmap *new_entries_map = NULL; git_iterator *index_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; const git_index_entry *old_entry, *new_entry; git_index_entry *entry; size_t i; int error; assert((new_iterator->flags & GIT_ITERATOR_DONT_IGNORE_CASE)); if ((error = git_vector_init(&new_entries, new_length_hint, index->entries._cmp)) < 0 || (error = git_vector_init(&remove_entries, index->entries.length, NULL)) < 0 || (error = git_idxmap_alloc(&new_entries_map)) < 0) goto done; if (index->ignore_case && new_length_hint) git_idxmap_icase_resize((khash_t(idxicase) *) new_entries_map, new_length_hint); else if (new_length_hint) git_idxmap_resize(new_entries_map, new_length_hint); opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&index_iterator, git_index_owner(index), index, &opts)) < 0 || ((error = git_iterator_current(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) || ((error = git_iterator_current(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER)) goto done; while (true) { git_index_entry *dup_entry = NULL, *add_entry = NULL, *remove_entry = NULL; int diff; error = 0; if (old_entry && new_entry) diff = git_index_entry_cmp(old_entry, new_entry); else if (!old_entry && new_entry) diff = 1; else if (old_entry && !new_entry) diff = -1; else break; if (diff < 0) { remove_entry = (git_index_entry *)old_entry; } else if (diff > 0) { dup_entry = (git_index_entry *)new_entry; } else { /* Path and stage are equal, if the OID is equal, keep it to * keep the stat cache data. */ if (git_oid_equal(&old_entry->id, &new_entry->id) && old_entry->mode == new_entry->mode) { add_entry = (git_index_entry *)old_entry; } else { dup_entry = (git_index_entry *)new_entry; remove_entry = (git_index_entry *)old_entry; } } if (dup_entry) { if ((error = index_entry_dup_nocache(&add_entry, index, dup_entry)) < 0) goto done; index_entry_adjust_namemask(add_entry, ((struct entry_internal *)add_entry)->pathlen); } /* invalidate this path in the tree cache if this is new (to * invalidate the parent trees) */ if (dup_entry && !remove_entry && index->tree) git_tree_cache_invalidate_path(index->tree, dup_entry->path); if (add_entry) { if ((error = git_vector_insert(&new_entries, add_entry)) == 0) INSERT_IN_MAP_EX(index, new_entries_map, add_entry, &error); } if (remove_entry && error >= 0) error = git_vector_insert(&remove_entries, remove_entry); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry"); goto done; } if (diff <= 0) { if ((error = git_iterator_advance(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) goto done; } if (diff >= 0) { if ((error = git_iterator_advance(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER) goto done; } } git_index_name_clear(index); git_index_reuc_clear(index); git_vector_swap(&new_entries, &index->entries); new_entries_map = git__swap(index->entries_map, new_entries_map); git_vector_foreach(&remove_entries, i, entry) { if (index->tree) git_tree_cache_invalidate_path(index->tree, entry->path); index_entry_free(entry); } clear_uptodate(index); error = 0; done: git_idxmap_free(new_entries_map); git_vector_free(&new_entries); git_vector_free(&remove_entries); git_iterator_free(index_iterator); return error; } int git_index_read_index( git_index *index, const git_index *new_index) { git_iterator *new_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; int error; opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&new_iterator, git_index_owner(new_index), (git_index *)new_index, &opts)) < 0 || (error = git_index_read_iterator(index, new_iterator, new_index->entries.length)) < 0) goto done; done: git_iterator_free(new_iterator); return error; } git_repository *git_index_owner(const git_index *index) { return INDEX_OWNER(index); } enum { INDEX_ACTION_NONE = 0, INDEX_ACTION_UPDATE = 1, INDEX_ACTION_REMOVE = 2, INDEX_ACTION_ADDALL = 3, }; int git_index_add_all( git_index *index, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_repository *repo; git_iterator *wditer = NULL; git_pathspec ps; bool no_fnmatch = (flags & GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH) != 0; assert(index); repo = INDEX_OWNER(index); if ((error = git_repository__ensure_not_bare(repo, "index add all")) < 0) return error; if ((error = git_pathspec__init(&ps, paths)) < 0) return error; /* optionally check that pathspec doesn't mention any ignored files */ if ((flags & GIT_INDEX_ADD_CHECK_PATHSPEC) != 0 && (flags & GIT_INDEX_ADD_FORCE) == 0 && (error = git_ignore__check_pathspec_for_exact_ignores( repo, &ps.pathspec, no_fnmatch)) < 0) goto cleanup; error = index_apply_to_wd_diff(index, INDEX_ACTION_ADDALL, paths, flags, cb, payload); if (error) giterr_set_after_callback(error); cleanup: git_iterator_free(wditer); git_pathspec__clear(&ps); return error; } struct foreach_diff_data { git_index *index; const git_pathspec *pathspec; unsigned int flags; git_index_matched_path_cb cb; void *payload; }; static int apply_each_file(const git_diff_delta *delta, float progress, void *payload) { struct foreach_diff_data *data = payload; const char *match, *path; int error = 0; GIT_UNUSED(progress); path = delta->old_file.path; /* We only want those which match the pathspecs */ if (!git_pathspec__match( &data->pathspec->pathspec, path, false, (bool)data->index->ignore_case, &match, NULL)) return 0; if (data->cb) error = data->cb(path, match, data->payload); if (error > 0) /* skip this entry */ return 0; if (error < 0) /* actual error */ return error; /* If the workdir item does not exist, remove it from the index. */ if ((delta->new_file.flags & GIT_DIFF_FLAG_EXISTS) == 0) error = git_index_remove_bypath(data->index, path); else error = git_index_add_bypath(data->index, delta->new_file.path); return error; } static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_diff *diff; git_pathspec ps; git_repository *repo; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; struct foreach_diff_data data = { index, NULL, flags, cb, payload, }; assert(index); assert(action == INDEX_ACTION_UPDATE || action == INDEX_ACTION_ADDALL); repo = INDEX_OWNER(index); if (!repo) { return create_index_error(-1, "cannot run update; the index is not backed up by a repository."); } /* * We do the matching ourselves intead of passing the list to * diff because we want to tell the callback which one * matched, which we do not know if we ask diff to filter for us. */ if ((error = git_pathspec__init(&ps, paths)) < 0) return error; opts.flags = GIT_DIFF_INCLUDE_TYPECHANGE; if (action == INDEX_ACTION_ADDALL) { opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_RECURSE_UNTRACKED_DIRS; if (flags == GIT_INDEX_ADD_FORCE) opts.flags |= GIT_DIFF_INCLUDE_IGNORED; } if ((error = git_diff_index_to_workdir(&diff, repo, index, &opts)) < 0) goto cleanup; data.pathspec = &ps; error = git_diff_foreach(diff, apply_each_file, NULL, NULL, NULL, &data); git_diff_free(diff); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); cleanup: git_pathspec__clear(&ps); return error; } static int index_apply_to_all( git_index *index, int action, const git_strarray *paths, git_index_matched_path_cb cb, void *payload) { int error = 0; size_t i; git_pathspec ps; const char *match; git_buf path = GIT_BUF_INIT; assert(index); if ((error = git_pathspec__init(&ps, paths)) < 0) return error; git_vector_sort(&index->entries); for (i = 0; !error && i < index->entries.length; ++i) { git_index_entry *entry = git_vector_get(&index->entries, i); /* check if path actually matches */ if (!git_pathspec__match( &ps.pathspec, entry->path, false, (bool)index->ignore_case, &match, NULL)) continue; /* issue notification callback if requested */ if (cb && (error = cb(entry->path, match, payload)) != 0) { if (error > 0) { /* return > 0 means skip this one */ error = 0; continue; } if (error < 0) /* return < 0 means abort */ break; } /* index manipulation may alter entry, so don't depend on it */ if ((error = git_buf_sets(&path, entry->path)) < 0) break; switch (action) { case INDEX_ACTION_NONE: break; case INDEX_ACTION_UPDATE: error = git_index_add_bypath(index, path.ptr); if (error == GIT_ENOTFOUND) { giterr_clear(); error = git_index_remove_bypath(index, path.ptr); if (!error) /* back up foreach if we removed this */ i--; } break; case INDEX_ACTION_REMOVE: if (!(error = git_index_remove_bypath(index, path.ptr))) i--; /* back up foreach if we removed this */ break; default: giterr_set(GITERR_INVALID, "unknown index action %d", action); error = -1; break; } } git_buf_free(&path); git_pathspec__clear(&ps); return error; } int git_index_remove_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_all( index, INDEX_ACTION_REMOVE, pathspec, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_update_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_wd_diff(index, INDEX_ACTION_UPDATE, pathspec, 0, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_snapshot_new(git_vector *snap, git_index *index) { int error; GIT_REFCOUNT_INC(index); git_atomic_inc(&index->readers); git_vector_sort(&index->entries); error = git_vector_dup(snap, &index->entries, index->entries._cmp); if (error < 0) git_index_free(index); return error; } void git_index_snapshot_release(git_vector *snap, git_index *index) { git_vector_free(snap); git_atomic_dec(&index->readers); git_index_free(index); } int git_index_snapshot_find( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { return index_find_in_entries(out, entries, entry_srch, path, path_len, stage); } int git_indexwriter_init( git_indexwriter *writer, git_index *index) { int error; GIT_REFCOUNT_INC(index); writer->index = index; if (!index->index_file_path) return create_index_error(-1, "failed to write index: The index is in-memory only"); if ((error = git_filebuf_open( &writer->file, index->index_file_path, GIT_FILEBUF_HASH_CONTENTS, GIT_INDEX_FILE_MODE)) < 0) { if (error == GIT_ELOCKED) giterr_set(GITERR_INDEX, "the index is locked; this might be due to a concurrent or crashed process"); return error; } writer->should_write = 1; return 0; } int git_indexwriter_init_for_operation( git_indexwriter *writer, git_repository *repo, unsigned int *checkout_strategy) { git_index *index; int error; if ((error = git_repository_index__weakptr(&index, repo)) < 0 || (error = git_indexwriter_init(writer, index)) < 0) return error; writer->should_write = (*checkout_strategy & GIT_CHECKOUT_DONT_WRITE_INDEX) == 0; *checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX; return 0; } int git_indexwriter_commit(git_indexwriter *writer) { int error; git_oid checksum = {{ 0 }}; if (!writer->should_write) return 0; git_vector_sort(&writer->index->entries); git_vector_sort(&writer->index->reuc); if ((error = write_index(&checksum, writer->index, &writer->file)) < 0) { git_indexwriter_cleanup(writer); return error; } if ((error = git_filebuf_commit(&writer->file)) < 0) return error; if ((error = git_futils_filestamp_check( &writer->index->stamp, writer->index->index_file_path)) < 0) { giterr_set(GITERR_OS, "could not read index timestamp"); return -1; } writer->index->on_disk = 1; git_oid_cpy(&writer->index->checksum, &checksum); git_index_free(writer->index); writer->index = NULL; return 0; } void git_indexwriter_cleanup(git_indexwriter *writer) { git_filebuf_cleanup(&writer->file); git_index_free(writer->index); writer->index = NULL; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_666_0
crossvul-cpp_data_bad_348_3
/* * card-tcos.c: Support for TCOS cards * * Copyright (C) 2011 Peter Koch <pk@opensc-project.org> * Copyright (C) 2002 g10 Code GmbH * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <ctype.h> #include <time.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table tcos_atrs[] = { /* Infineon SLE44 */ { "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66S */ { "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX320P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX322P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Philips P5CT072 */ { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, /* Philips P5CT080 */ { "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_card_operations tcos_ops; static struct sc_card_driver tcos_drv = { "TCOS 3.0", "tcos", &tcos_ops, NULL, 0, NULL }; static const struct sc_card_operations *iso_ops = NULL; typedef struct tcos_data_st { unsigned int pad_flags; unsigned int next_sign; } tcos_data; static int tcos_finish(sc_card_t *card) { free(card->drv_data); return 0; } static int tcos_match_card(sc_card_t *card) { int i; i = _sc_match_atr(card, tcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int tcos_init(sc_card_t *card) { unsigned long flags; tcos_data *data = malloc(sizeof(tcos_data)); if (!data) return SC_ERROR_OUT_OF_MEMORY; card->name = "TCOS"; card->drv_data = (void *)data; card->cla = 0x00; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); if (card->type == SC_CARD_TYPE_TCOS_V3) { card->caps |= SC_CARD_CAP_APDU_EXT; _sc_card_add_rsa_alg(card, 1280, flags, 0); _sc_card_add_rsa_alg(card, 1536, flags, 0); _sc_card_add_rsa_alg(card, 1792, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return 0; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static int tcos_construct_fci(const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; size_t n; /* FIXME: possible buffer overflow */ *p++ = 0x6F; /* FCI */ p++; /* File size */ buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x81, buf, 2, p, 16, &p); /* File descriptor */ n = 0; buf[n] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_WORKING_EF: break; case SC_FILE_TYPE_DF: buf[0] |= 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } buf[n++] |= file->ef_structure & 7; if ( (file->ef_structure & 7) > 1) { /* record structured file */ buf[n++] = 0x41; /* indicate 3rd byte */ buf[n++] = file->record_length; } sc_asn1_put_tag(0x82, buf, n, p, 8, &p); /* File identifier */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, 16, &p); /* Directory name */ if (file->type == SC_FILE_TYPE_DF) { if (file->namelen) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, 16, &p); } else { /* TCOS needs one, so we use a faked one */ snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu", (unsigned long) time (NULL)); sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p); } } /* File descriptor extension */ if (file->prop_attr_len && file->prop_attr) { n = file->prop_attr_len; memcpy(buf, file->prop_attr, n); } else { n = 0; buf[n++] = 0x01; /* not invalidated, permanent */ if (file->type == SC_FILE_TYPE_WORKING_EF) buf[n++] = 0x00; /* generic data file */ } sc_asn1_put_tag(0x85, buf, n, p, 16, &p); /* Security attributes */ if (file->sec_attr_len && file->sec_attr) { memcpy(buf, file->sec_attr, file->sec_attr_len); n = file->sec_attr_len; } else { /* no attributes given - fall back to default one */ memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */ memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */ memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */ memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/ n = 24; } sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p); /* fixup length of FCI */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int tcos_create_file(sc_card_t *card, sc_file_t *file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; len = SC_MAX_APDU_BUFFER_SIZE; r = tcos_construct_fci(file, sbuf, &len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.cla |= 0x80; /* this is an proprietary extension */ apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static unsigned int map_operations (int commandbyte ) { unsigned int op = (unsigned int)-1; switch ( (commandbyte & 0xfe) ) { case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break; case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break; case 0xe0: /* create */ op = SC_AC_OP_CREATE; break; case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break; case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break; case 0x82: /* external auth */ op = SC_AC_OP_READ; break; case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break; case 0x88: /* internal auth */ op = SC_AC_OP_READ; break; case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break; case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break; case 0xb0: /* read binary */ op = SC_AC_OP_READ; break; case 0xb2: /* read record */ op = SC_AC_OP_READ; break; case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break; case 0xa4: /* select */ op = SC_AC_OP_SELECT; break; case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break; case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break; case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break; case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break; case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break; case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break; } return op; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static void parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { unsigned int op; /* list directory is not covered by ACLs - so always add an entry */ sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES, SC_AC_NONE, SC_AC_KEY_REF_NONE); /* FIXME: check for what LOCK is used */ sc_file_add_acl_entry (file, SC_AC_OP_LOCK, SC_AC_NONE, SC_AC_KEY_REF_NONE); for (; len >= 6; len -= 6, buf += 6) { /* FIXME: temporary hacks */ if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */ sc_file_add_acl_entry (file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/ sc_file_add_acl_entry (file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/ sc_file_add_acl_entry (file, SC_AC_OP_UPDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */ sc_file_add_acl_entry (file, SC_AC_OP_WRITE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_CREATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else { /* the first byte tells use the command or the command group. We have to mask bit 0 because this one distinguish between AND/OR combination of PINs*/ op = map_operations (buf[0]); if (op == (unsigned int)-1) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown security command byte %02x\n", buf[0]); continue; } if (!buf[1]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_CHV, buf[1]); if (!buf[2] && !buf[3]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_TERM, (buf[2]<<8)|buf[3]); } } } static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1; int r, count = 0; assert(card != NULL); ctx = card->ctx; for (p1=1; p1<=2; p1++) { sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n", apdu.resplen / 2, p1 == 1 ? "DF" : "EF"); memcpy(buf, apdu.resp, apdu.resplen); buf += apdu.resplen; buflen -= apdu.resplen; count += apdu.resplen; } return count; } static int tcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r; u8 sbuf[2]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } sbuf[0] = path->value[0]; sbuf[1] = path->value[1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_context_t *ctx; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p; int r, default_key, tcos3; tcos_data *data; assert(card != NULL && env != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "No Key-Reference in SecEnvironment\n"); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n", env->key_ref[0], env->key_ref_len); /* Key-Reference 0x80 ?? */ default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n", tcos3, !!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); data->pad_flags = env->algorithm_flags; data->next_sign = default_key; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8); p = sbuf; *p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10; if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { *p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } apdu.data = sbuf; apdu.lc = apdu.datalen = (p - sbuf); r=sc_transmit_apdu(card, &apdu); if (r) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Detected Signature-Only key\n"); if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS; } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_restore_security_env(sc_card_t *card, int se_num) { return 0; } static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { size_t i, dlen=datalen; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int tcos3, r; assert(card != NULL && data != NULL && out != NULL); tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); if(((tcos_data *)card->drv_data)->next_sign){ if(datalen>48){ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A); memcpy(sbuf, data, datalen); dlen=datalen; } else { int keylen= tcos3 ? 256 : 128; sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = tcos3 ? 256 : 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) { int keylen=128; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); } if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len = apdu.resplen>outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){ offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset; offset=(offset<len-1) ? offset+1 : 0; } memcpy(out, apdu.resp+offset, len-offset); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the NullPIN method will be activated, otherwise the permanent operation will be done on the active file. */ static int tcos_setperm(sc_card_t *card, int enable_nullpin) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 0; apdu.datalen = 0; apdu.data = NULL; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; if (!serial) return SC_ERROR_INVALID_ARGUMENTS; /* see if we have cached serial number */ if (card->serialnr.len) { memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } card->serialnr.len = sizeof card->serialnr.value; r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0); if (r < 0) { card->serialnr.len = 0; return r; } /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_TCOS_SETPERM: return tcos_setperm(card, !!ptr); case SC_CARDCTL_GET_SERIALNR: return tcos_get_serialnr(card, (sc_serial_number_t *)ptr); } return SC_ERROR_NOT_SUPPORTED; } struct sc_card_driver * sc_get_tcos_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; tcos_ops = *iso_drv->ops; tcos_ops.match_card = tcos_match_card; tcos_ops.init = tcos_init; tcos_ops.finish = tcos_finish; tcos_ops.create_file = tcos_create_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.select_file = tcos_select_file; tcos_ops.list_files = tcos_list_files; tcos_ops.delete_file = tcos_delete_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.compute_signature = tcos_compute_signature; tcos_ops.decipher = tcos_decipher; tcos_ops.restore_security_env = tcos_restore_security_env; tcos_ops.card_ctl = tcos_card_ctl; return &tcos_drv; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_3
crossvul-cpp_data_good_348_4
/* * PKCS15 emulation layer for EstEID card. * * Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net> * Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "internal.h" #include "opensc.h" #include "pkcs15.h" #include "esteid.h" int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *); static void set_string (char **strp, const char *value) { if (*strp) free (*strp); *strp = value ? strdup (value) : NULL; } int select_esteid_df (sc_card_t * card) { int r; sc_path_t tmppath; sc_format_path ("3F00EEEE", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed"); return r; } static int sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[MIN((size_t) r, (sizeof buff)-1)] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } static int esteid_detect_card(sc_pkcs15_card_t *p15card) { if (is_esteid_card(p15card->card)) return SC_SUCCESS; else return SC_ERROR_WRONG_CARD; } int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_esteid_init(p15card); else { int r = esteid_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_esteid_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_4
crossvul-cpp_data_bad_2579_0
/* #pragma ident "@(#)g_accept_sec_context.c 1.19 04/02/23 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_accept_sec_context */ #include "mglueP.h" #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> #include <errno.h> #include <time.h> #ifndef LEAN_CLIENT static OM_uint32 val_acc_sec_ctx_args( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token_buffer, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *d_cred) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (d_cred != NULL) *d_cred = GSS_C_NO_CREDENTIAL; /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (input_token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (output_token == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); return (GSS_S_COMPLETE); } /* Return true if mech should be accepted with no acceptor credential. */ static int allow_mech_by_default(gss_OID mech) { OM_uint32 status, minor; gss_OID_set attrs; int reject = 0, p; /* Whether we accept an interposer mech depends on whether we accept the * mech it interposes. */ mech = gssint_get_public_oid(mech); if (mech == GSS_C_NO_OID) return 0; status = gss_inquire_attrs_for_mech(&minor, mech, &attrs, NULL); if (status) return 0; /* Check for each attribute which would cause us to exclude this mech from * the default credential. */ if (generic_gss_test_oid_set_member(&minor, GSS_C_MA_DEPRECATED, attrs, &p) != GSS_S_COMPLETE || p) reject = 1; else if (generic_gss_test_oid_set_member(&minor, GSS_C_MA_NOT_DFLT_MECH, attrs, &p) != GSS_S_COMPLETE || p) reject = 1; (void) gss_release_oid_set(&minor, &attrs); return !reject; } OM_uint32 KRB5_CALLCONV gss_accept_sec_context (minor_status, context_handle, verifier_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, d_cred) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_cred_id_t verifier_cred_handle; gss_buffer_t input_token_buffer; gss_channel_bindings_t input_chan_bindings; gss_name_t * src_name; gss_OID * mech_type; gss_buffer_t output_token; OM_uint32 * ret_flags; OM_uint32 * time_rec; gss_cred_id_t * d_cred; { OM_uint32 status, temp_status, temp_minor_status; OM_uint32 temp_ret_flags = 0; gss_union_ctx_id_t union_ctx_id = NULL; gss_cred_id_t input_cred_handle = GSS_C_NO_CREDENTIAL; gss_cred_id_t tmp_d_cred = GSS_C_NO_CREDENTIAL; gss_name_t internal_name = GSS_C_NO_NAME; gss_name_t tmp_src_name = GSS_C_NO_NAME; gss_OID_desc token_mech_type_desc; gss_OID token_mech_type = &token_mech_type_desc; gss_OID actual_mech = GSS_C_NO_OID; gss_OID selected_mech = GSS_C_NO_OID; gss_OID public_mech; gss_mechanism mech = NULL; gss_union_cred_t uc; int i; status = val_acc_sec_ctx_args(minor_status, context_handle, verifier_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, d_cred); if (status != GSS_S_COMPLETE) return (status); /* * if context_handle is GSS_C_NO_CONTEXT, allocate a union context * descriptor to hold the mech type information as well as the * underlying mechanism context handle. Otherwise, cast the * value of *context_handle to the union context variable. */ if(*context_handle == GSS_C_NO_CONTEXT) { if (input_token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); /* Get the token mech type */ status = gssint_get_mech_type(token_mech_type, input_token_buffer); if (status) return status; /* * An interposer calling back into the mechglue can't pass in a special * mech, so we have to recognize it using verifier_cred_handle. Use * the mechanism for which we have matching creds, if available. */ if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) { uc = (gss_union_cred_t)verifier_cred_handle; for (i = 0; i < uc->count; i++) { public_mech = gssint_get_public_oid(&uc->mechs_array[i]); if (public_mech && g_OID_equal(token_mech_type, public_mech)) { selected_mech = &uc->mechs_array[i]; break; } } } if (selected_mech == GSS_C_NO_OID) { status = gssint_select_mech_type(minor_status, token_mech_type, &selected_mech); if (status) return status; } } else { union_ctx_id = (gss_union_ctx_id_t)*context_handle; selected_mech = union_ctx_id->mech_type; } /* Now create a new context if we didn't get one. */ if (*context_handle == GSS_C_NO_CONTEXT) { status = GSS_S_FAILURE; union_ctx_id = (gss_union_ctx_id_t) malloc(sizeof(gss_union_ctx_id_desc)); if (!union_ctx_id) return (GSS_S_FAILURE); union_ctx_id->loopback = union_ctx_id; union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT; status = generic_gss_copy_oid(&temp_minor_status, selected_mech, &union_ctx_id->mech_type); if (status != GSS_S_COMPLETE) { free(union_ctx_id); return (status); } /* set the new context handle to caller's data */ *context_handle = (gss_ctx_id_t)union_ctx_id; } /* * get the appropriate cred handle from the union cred struct. */ if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) { input_cred_handle = gssint_get_mechanism_cred((gss_union_cred_t)verifier_cred_handle, selected_mech); if (input_cred_handle == GSS_C_NO_CREDENTIAL) { /* verifier credential specified but no acceptor credential found */ status = GSS_S_NO_CRED; goto error_out; } } else if (!allow_mech_by_default(selected_mech)) { status = GSS_S_NO_CRED; goto error_out; } /* * now select the approprate underlying mechanism routine and * call it. */ mech = gssint_get_mechanism(selected_mech); if (mech && mech->gss_accept_sec_context) { status = mech->gss_accept_sec_context(minor_status, &union_ctx_id->internal_ctx_id, input_cred_handle, input_token_buffer, input_chan_bindings, src_name ? &internal_name : NULL, &actual_mech, output_token, &temp_ret_flags, time_rec, d_cred ? &tmp_d_cred : NULL); /* If there's more work to do, keep going... */ if (status == GSS_S_CONTINUE_NEEDED) return GSS_S_CONTINUE_NEEDED; /* if the call failed, return with failure */ if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); goto error_out; } /* * if src_name is non-NULL, * convert internal_name into a union name equivalent * First call the mechanism specific display_name() * then call gss_import_name() to create * the union name struct cast to src_name */ if (src_name != NULL) { if (internal_name != GSS_C_NO_NAME) { /* consumes internal_name regardless of success */ temp_status = gssint_convert_name_to_union_name( &temp_minor_status, mech, internal_name, &tmp_src_name); if (temp_status != GSS_S_COMPLETE) { status = temp_status; *minor_status = temp_minor_status; map_error(minor_status, mech); if (output_token->length) (void) gss_release_buffer(&temp_minor_status, output_token); goto error_out; } *src_name = tmp_src_name; } else *src_name = GSS_C_NO_NAME; } #define g_OID_prefix_equal(o1, o2) \ (((o1)->length >= (o2)->length) && \ (memcmp((o1)->elements, (o2)->elements, (o2)->length) == 0)) /* Ensure we're returning correct creds format */ if ((temp_ret_flags & GSS_C_DELEG_FLAG) && tmp_d_cred != GSS_C_NO_CREDENTIAL) { public_mech = gssint_get_public_oid(selected_mech); if (actual_mech != GSS_C_NO_OID && public_mech != GSS_C_NO_OID && !g_OID_prefix_equal(actual_mech, public_mech)) { *d_cred = tmp_d_cred; /* unwrapped pseudo-mech */ } else { gss_union_cred_t d_u_cred = NULL; d_u_cred = malloc(sizeof (gss_union_cred_desc)); if (d_u_cred == NULL) { status = GSS_S_FAILURE; goto error_out; } (void) memset(d_u_cred, 0, sizeof (gss_union_cred_desc)); d_u_cred->count = 1; status = generic_gss_copy_oid(&temp_minor_status, selected_mech, &d_u_cred->mechs_array); if (status != GSS_S_COMPLETE) { free(d_u_cred); goto error_out; } d_u_cred->cred_array = malloc(sizeof(gss_cred_id_t)); if (d_u_cred->cred_array != NULL) { d_u_cred->cred_array[0] = tmp_d_cred; } else { free(d_u_cred); status = GSS_S_FAILURE; goto error_out; } d_u_cred->loopback = d_u_cred; *d_cred = (gss_cred_id_t)d_u_cred; } } if (mech_type != NULL) *mech_type = gssint_get_public_oid(actual_mech); if (ret_flags != NULL) *ret_flags = temp_ret_flags; return (status); } else { status = GSS_S_BAD_MECH; } error_out: if (union_ctx_id) { if (union_ctx_id->mech_type) { if (union_ctx_id->mech_type->elements) free(union_ctx_id->mech_type->elements); free(union_ctx_id->mech_type); } if (union_ctx_id->internal_ctx_id && mech && mech->gss_delete_sec_context) { mech->gss_delete_sec_context(&temp_minor_status, &union_ctx_id->internal_ctx_id, GSS_C_NO_BUFFER); } free(union_ctx_id); *context_handle = GSS_C_NO_CONTEXT; } if (src_name) *src_name = GSS_C_NO_NAME; if (tmp_src_name != GSS_C_NO_NAME) (void) gss_release_buffer(&temp_minor_status, (gss_buffer_t)tmp_src_name); return (status); } #endif /* LEAN_CLIENT */
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_0
crossvul-cpp_data_bad_4406_0
/* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2014 Google Inc. * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <unistd.h> #include <errno.h> #include "src/shared/io.h" #include "src/shared/queue.h" #include "src/shared/util.h" #include "src/shared/timeout.h" #include "lib/bluetooth.h" #include "lib/l2cap.h" #include "lib/uuid.h" #include "src/shared/att.h" #include "src/shared/crypto.h" #define ATT_MIN_PDU_LEN 1 /* At least 1 byte for the opcode. */ #define ATT_OP_CMD_MASK 0x40 #define ATT_OP_SIGNED_MASK 0x80 #define ATT_TIMEOUT_INTERVAL 30000 /* 30000 ms */ /* Length of signature in write signed packet */ #define BT_ATT_SIGNATURE_LEN 12 struct att_send_op; struct bt_att_chan { struct bt_att *att; int fd; struct io *io; uint8_t type; int sec_level; /* Only used for non-L2CAP */ struct queue *queue; /* Channel dedicated queue */ struct att_send_op *pending_req; struct att_send_op *pending_ind; bool writer_active; bool in_req; /* There's a pending incoming request */ uint8_t *buf; uint16_t mtu; }; struct bt_att { int ref_count; bool close_on_unref; struct queue *chans; uint8_t enc_size; uint16_t mtu; /* Biggest possible MTU */ struct queue *notify_list; /* List of registered callbacks */ struct queue *disconn_list; /* List of disconnect handlers */ unsigned int next_send_id; /* IDs for "send" ops */ unsigned int next_reg_id; /* IDs for registered callbacks */ struct queue *req_queue; /* Queued ATT protocol requests */ struct queue *ind_queue; /* Queued ATT protocol indications */ struct queue *write_queue; /* Queue of PDUs ready to send */ bt_att_timeout_func_t timeout_callback; bt_att_destroy_func_t timeout_destroy; void *timeout_data; bt_att_debug_func_t debug_callback; bt_att_destroy_func_t debug_destroy; void *debug_data; struct bt_crypto *crypto; struct sign_info *local_sign; struct sign_info *remote_sign; }; struct sign_info { uint8_t key[16]; bt_att_counter_func_t counter; void *user_data; }; enum att_op_type { ATT_OP_TYPE_REQ, ATT_OP_TYPE_RSP, ATT_OP_TYPE_CMD, ATT_OP_TYPE_IND, ATT_OP_TYPE_NFY, ATT_OP_TYPE_CONF, ATT_OP_TYPE_UNKNOWN, }; static const struct { uint8_t opcode; enum att_op_type type; } att_opcode_type_table[] = { { BT_ATT_OP_ERROR_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_MTU_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_MTU_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_FIND_INFO_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_FIND_INFO_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_FIND_BY_TYPE_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_FIND_BY_TYPE_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_READ_BY_TYPE_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_READ_BY_TYPE_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_READ_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_READ_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_READ_BLOB_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_READ_BLOB_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_READ_MULT_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_READ_MULT_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_READ_BY_GRP_TYPE_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_READ_BY_GRP_TYPE_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_WRITE_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_WRITE_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_WRITE_CMD, ATT_OP_TYPE_CMD }, { BT_ATT_OP_SIGNED_WRITE_CMD, ATT_OP_TYPE_CMD }, { BT_ATT_OP_PREP_WRITE_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_PREP_WRITE_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_EXEC_WRITE_REQ, ATT_OP_TYPE_REQ }, { BT_ATT_OP_EXEC_WRITE_RSP, ATT_OP_TYPE_RSP }, { BT_ATT_OP_HANDLE_NFY, ATT_OP_TYPE_NFY }, { BT_ATT_OP_HANDLE_NFY_MULT, ATT_OP_TYPE_NFY }, { BT_ATT_OP_HANDLE_IND, ATT_OP_TYPE_IND }, { BT_ATT_OP_HANDLE_CONF, ATT_OP_TYPE_CONF }, { } }; static enum att_op_type get_op_type(uint8_t opcode) { int i; for (i = 0; att_opcode_type_table[i].opcode; i++) { if (att_opcode_type_table[i].opcode == opcode) return att_opcode_type_table[i].type; } if (opcode & ATT_OP_CMD_MASK) return ATT_OP_TYPE_CMD; return ATT_OP_TYPE_UNKNOWN; } static const struct { uint8_t req_opcode; uint8_t rsp_opcode; } att_req_rsp_mapping_table[] = { { BT_ATT_OP_MTU_REQ, BT_ATT_OP_MTU_RSP }, { BT_ATT_OP_FIND_INFO_REQ, BT_ATT_OP_FIND_INFO_RSP}, { BT_ATT_OP_FIND_BY_TYPE_REQ, BT_ATT_OP_FIND_BY_TYPE_RSP }, { BT_ATT_OP_READ_BY_TYPE_REQ, BT_ATT_OP_READ_BY_TYPE_RSP }, { BT_ATT_OP_READ_REQ, BT_ATT_OP_READ_RSP }, { BT_ATT_OP_READ_BLOB_REQ, BT_ATT_OP_READ_BLOB_RSP }, { BT_ATT_OP_READ_MULT_REQ, BT_ATT_OP_READ_MULT_RSP }, { BT_ATT_OP_READ_BY_GRP_TYPE_REQ, BT_ATT_OP_READ_BY_GRP_TYPE_RSP }, { BT_ATT_OP_WRITE_REQ, BT_ATT_OP_WRITE_RSP }, { BT_ATT_OP_PREP_WRITE_REQ, BT_ATT_OP_PREP_WRITE_RSP }, { BT_ATT_OP_EXEC_WRITE_REQ, BT_ATT_OP_EXEC_WRITE_RSP }, { } }; static uint8_t get_req_opcode(uint8_t rsp_opcode) { int i; for (i = 0; att_req_rsp_mapping_table[i].rsp_opcode; i++) { if (att_req_rsp_mapping_table[i].rsp_opcode == rsp_opcode) return att_req_rsp_mapping_table[i].req_opcode; } return 0; } struct att_send_op { unsigned int id; unsigned int timeout_id; enum att_op_type type; uint8_t opcode; void *pdu; uint16_t len; bt_att_response_func_t callback; bt_att_destroy_func_t destroy; void *user_data; }; static void destroy_att_send_op(void *data) { struct att_send_op *op = data; if (op->timeout_id) timeout_remove(op->timeout_id); if (op->destroy) op->destroy(op->user_data); free(op->pdu); free(op); } static void cancel_att_send_op(struct att_send_op *op) { if (op->destroy) op->destroy(op->user_data); op->user_data = NULL; op->callback = NULL; op->destroy = NULL; } struct att_notify { unsigned int id; uint16_t opcode; bt_att_notify_func_t callback; bt_att_destroy_func_t destroy; void *user_data; }; static void destroy_att_notify(void *data) { struct att_notify *notify = data; if (notify->destroy) notify->destroy(notify->user_data); free(notify); } static bool match_notify_id(const void *a, const void *b) { const struct att_notify *notify = a; unsigned int id = PTR_TO_UINT(b); return notify->id == id; } struct att_disconn { unsigned int id; bool removed; bt_att_disconnect_func_t callback; bt_att_destroy_func_t destroy; void *user_data; }; static void destroy_att_disconn(void *data) { struct att_disconn *disconn = data; if (disconn->destroy) disconn->destroy(disconn->user_data); free(disconn); } static bool match_disconn_id(const void *a, const void *b) { const struct att_disconn *disconn = a; unsigned int id = PTR_TO_UINT(b); return disconn->id == id; } static bool encode_pdu(struct bt_att *att, struct att_send_op *op, const void *pdu, uint16_t length) { uint16_t pdu_len = 1; struct sign_info *sign = att->local_sign; uint32_t sign_cnt; if (sign && (op->opcode & ATT_OP_SIGNED_MASK)) pdu_len += BT_ATT_SIGNATURE_LEN; if (length && pdu) pdu_len += length; if (pdu_len > att->mtu) return false; op->len = pdu_len; op->pdu = malloc(op->len); if (!op->pdu) return false; ((uint8_t *) op->pdu)[0] = op->opcode; if (pdu_len > 1) memcpy(op->pdu + 1, pdu, length); if (!sign || !(op->opcode & ATT_OP_SIGNED_MASK) || !att->crypto) return true; if (!sign->counter(&sign_cnt, sign->user_data)) goto fail; if ((bt_crypto_sign_att(att->crypto, sign->key, op->pdu, 1 + length, sign_cnt, &((uint8_t *) op->pdu)[1 + length]))) return true; util_debug(att->debug_callback, att->debug_data, "ATT unable to generate signature"); fail: free(op->pdu); return false; } static struct att_send_op *create_att_send_op(struct bt_att *att, uint8_t opcode, const void *pdu, uint16_t length, bt_att_response_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { struct att_send_op *op; enum att_op_type type; if (length && !pdu) return NULL; type = get_op_type(opcode); if (type == ATT_OP_TYPE_UNKNOWN) return NULL; /* If the opcode corresponds to an operation type that does not elicit a * response from the remote end, then no callback should have been * provided, since it will never be called. */ if (callback && type != ATT_OP_TYPE_REQ && type != ATT_OP_TYPE_IND) return NULL; /* Similarly, if the operation does elicit a response then a callback * must be provided. */ if (!callback && (type == ATT_OP_TYPE_REQ || type == ATT_OP_TYPE_IND)) return NULL; op = new0(struct att_send_op, 1); op->type = type; op->opcode = opcode; op->callback = callback; op->destroy = destroy; op->user_data = user_data; if (!encode_pdu(att, op, pdu, length)) { free(op); return NULL; } return op; } static struct att_send_op *pick_next_send_op(struct bt_att_chan *chan) { struct bt_att *att = chan->att; struct att_send_op *op; /* Check if there is anything queued on the channel */ op = queue_pop_head(chan->queue); if (op) return op; /* See if any operations are already in the write queue */ op = queue_peek_head(att->write_queue); if (op && op->len <= chan->mtu) return queue_pop_head(att->write_queue); /* If there is no pending request, pick an operation from the * request queue. */ if (!chan->pending_req) { op = queue_peek_head(att->req_queue); if (op && op->len <= chan->mtu) return queue_pop_head(att->req_queue); } /* There is either a request pending or no requests queued. If there is * no pending indication, pick an operation from the indication queue. */ if (!chan->pending_ind) { op = queue_peek_head(att->ind_queue); if (op && op->len <= chan->mtu) return queue_pop_head(att->ind_queue); } return NULL; } static void disc_att_send_op(void *data) { struct att_send_op *op = data; if (op->callback) op->callback(BT_ATT_OP_ERROR_RSP, NULL, 0, op->user_data); destroy_att_send_op(op); } struct timeout_data { struct bt_att_chan *chan; unsigned int id; }; static bool timeout_cb(void *user_data) { struct timeout_data *timeout = user_data; struct bt_att_chan *chan = timeout->chan; struct bt_att *att = chan->att; struct att_send_op *op = NULL; if (chan->pending_req && chan->pending_req->id == timeout->id) { op = chan->pending_req; chan->pending_req = NULL; } else if (chan->pending_ind && chan->pending_ind->id == timeout->id) { op = chan->pending_ind; chan->pending_ind = NULL; } if (!op) return false; util_debug(att->debug_callback, att->debug_data, "(chan %p) Operation timed out: 0x%02x", chan, op->opcode); if (att->timeout_callback) att->timeout_callback(op->id, op->opcode, att->timeout_data); op->timeout_id = 0; disc_att_send_op(op); /* * Directly terminate the connection as required by the ATT protocol. * This should trigger an io disconnect event which will clean up the * io and notify the upper layer. */ io_shutdown(chan->io); return false; } static void write_watch_destroy(void *user_data) { struct bt_att_chan *chan = user_data; chan->writer_active = false; } static ssize_t bt_att_chan_write(struct bt_att_chan *chan, uint8_t opcode, const void *pdu, uint16_t len) { struct bt_att *att = chan->att; ssize_t ret; struct iovec iov; iov.iov_base = (void *) pdu; iov.iov_len = len; util_debug(att->debug_callback, att->debug_data, "(chan %p) ATT op 0x%02x", chan, opcode); ret = io_send(chan->io, &iov, 1); if (ret < 0) { util_debug(att->debug_callback, att->debug_data, "(chan %p) write failed: %s", chan, strerror(-ret)); return ret; } util_hexdump('<', pdu, ret, att->debug_callback, att->debug_data); return ret; } static bool can_write_data(struct io *io, void *user_data) { struct bt_att_chan *chan = user_data; struct att_send_op *op; struct timeout_data *timeout; op = pick_next_send_op(chan); if (!op) return false; if (!bt_att_chan_write(chan, op->opcode, op->pdu, op->len)) { if (op->callback) op->callback(BT_ATT_OP_ERROR_RSP, NULL, 0, op->user_data); destroy_att_send_op(op); return true; } /* Based on the operation type, set either the pending request or the * pending indication. If it came from the write queue, then there is * no need to keep it around. */ switch (op->type) { case ATT_OP_TYPE_REQ: chan->pending_req = op; break; case ATT_OP_TYPE_IND: chan->pending_ind = op; break; case ATT_OP_TYPE_RSP: /* Set in_req to false to indicate that no request is pending */ chan->in_req = false; /* fall through */ case ATT_OP_TYPE_CMD: case ATT_OP_TYPE_NFY: case ATT_OP_TYPE_CONF: case ATT_OP_TYPE_UNKNOWN: default: destroy_att_send_op(op); return true; } timeout = new0(struct timeout_data, 1); timeout->chan = chan; timeout->id = op->id; op->timeout_id = timeout_add(ATT_TIMEOUT_INTERVAL, timeout_cb, timeout, free); /* Return true as there may be more operations ready to write. */ return true; } static void wakeup_chan_writer(void *data, void *user_data) { struct bt_att_chan *chan = data; struct bt_att *att = chan->att; if (chan->writer_active) return; /* Set the write handler only if there is anything that can be sent * at all. */ if (queue_isempty(chan->queue) && queue_isempty(att->write_queue)) { if ((chan->pending_req || queue_isempty(att->req_queue)) && (chan->pending_ind || queue_isempty(att->ind_queue))) return; } if (!io_set_write_handler(chan->io, can_write_data, chan, write_watch_destroy)) return; chan->writer_active = true; } static void wakeup_writer(struct bt_att *att) { queue_foreach(att->chans, wakeup_chan_writer, NULL); } static void disconn_handler(void *data, void *user_data) { struct att_disconn *disconn = data; int err = PTR_TO_INT(user_data); if (disconn->removed) return; if (disconn->callback) disconn->callback(err, disconn->user_data); } static void bt_att_chan_free(void *data) { struct bt_att_chan *chan = data; if (chan->pending_req) destroy_att_send_op(chan->pending_req); if (chan->pending_ind) destroy_att_send_op(chan->pending_ind); queue_destroy(chan->queue, destroy_att_send_op); io_destroy(chan->io); free(chan->buf); free(chan); } static bool disconnect_cb(struct io *io, void *user_data) { struct bt_att_chan *chan = user_data; struct bt_att *att = chan->att; int err; socklen_t len; len = sizeof(err); if (getsockopt(chan->fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) { util_debug(chan->att->debug_callback, chan->att->debug_data, "(chan %p) Failed to obtain disconnect" " error: %s", chan, strerror(errno)); err = 0; } util_debug(chan->att->debug_callback, chan->att->debug_data, "Channel %p disconnected: %s", chan, strerror(err)); /* Dettach channel */ queue_remove(att->chans, chan); /* Notify request callbacks */ queue_remove_all(att->req_queue, NULL, NULL, disc_att_send_op); queue_remove_all(att->ind_queue, NULL, NULL, disc_att_send_op); queue_remove_all(att->write_queue, NULL, NULL, disc_att_send_op); if (chan->pending_req) { disc_att_send_op(chan->pending_req); chan->pending_req = NULL; } if (chan->pending_ind) { disc_att_send_op(chan->pending_ind); chan->pending_ind = NULL; } bt_att_chan_free(chan); /* Don't run disconnect callback if there are channels left */ if (!queue_isempty(att->chans)) return false; bt_att_ref(att); queue_foreach(att->disconn_list, disconn_handler, INT_TO_PTR(err)); bt_att_unregister_all(att); bt_att_unref(att); return false; } static int bt_att_chan_get_security(struct bt_att_chan *chan) { struct bt_security sec; socklen_t len; if (chan->type == BT_ATT_LOCAL) return chan->sec_level; memset(&sec, 0, sizeof(sec)); len = sizeof(sec); if (getsockopt(chan->fd, SOL_BLUETOOTH, BT_SECURITY, &sec, &len) < 0) return -EIO; return sec.level; } static bool bt_att_chan_set_security(struct bt_att_chan *chan, int level) { struct bt_security sec; if (chan->type == BT_ATT_LOCAL) { chan->sec_level = level; return true; } memset(&sec, 0, sizeof(sec)); sec.level = level; if (setsockopt(chan->fd, SOL_BLUETOOTH, BT_SECURITY, &sec, sizeof(sec)) < 0) return false; return true; } static bool change_security(struct bt_att_chan *chan, uint8_t ecode) { int security; if (chan->sec_level != BT_ATT_SECURITY_AUTO) return false; security = bt_att_chan_get_security(chan); if (ecode == BT_ATT_ERROR_INSUFFICIENT_ENCRYPTION && security < BT_ATT_SECURITY_MEDIUM) { security = BT_ATT_SECURITY_MEDIUM; } else if (ecode == BT_ATT_ERROR_AUTHENTICATION) { if (security < BT_ATT_SECURITY_MEDIUM) security = BT_ATT_SECURITY_MEDIUM; else if (security < BT_ATT_SECURITY_HIGH) security = BT_ATT_SECURITY_HIGH; else if (security < BT_ATT_SECURITY_FIPS) security = BT_ATT_SECURITY_FIPS; else return false; } else { return false; } return bt_att_chan_set_security(chan, security); } static bool handle_error_rsp(struct bt_att_chan *chan, uint8_t *pdu, ssize_t pdu_len, uint8_t *opcode) { struct bt_att *att = chan->att; const struct bt_att_pdu_error_rsp *rsp; struct att_send_op *op = chan->pending_req; if (pdu_len != sizeof(*rsp)) { *opcode = 0; return false; } rsp = (void *) pdu; *opcode = rsp->opcode; /* Attempt to change security */ if (!change_security(chan, rsp->ecode)) return false; /* Remove timeout_id if outstanding */ if (op->timeout_id) { timeout_remove(op->timeout_id); op->timeout_id = 0; } util_debug(att->debug_callback, att->debug_data, "(chan %p) Retrying operation " "%p", chan, op); chan->pending_req = NULL; /* Push operation back to request queue */ return queue_push_head(att->req_queue, op); } static void handle_rsp(struct bt_att_chan *chan, uint8_t opcode, uint8_t *pdu, ssize_t pdu_len) { struct bt_att *att = chan->att; struct att_send_op *op = chan->pending_req; uint8_t req_opcode; uint8_t rsp_opcode; uint8_t *rsp_pdu = NULL; uint16_t rsp_pdu_len = 0; /* * If no request is pending, then the response is unexpected. Disconnect * the bearer. */ if (!op) { util_debug(att->debug_callback, att->debug_data, "(chan %p) Received unexpected ATT " "response", chan); io_shutdown(chan->io); return; } /* * If the received response doesn't match the pending request, or if * the request is malformed, end the current request with failure. */ if (opcode == BT_ATT_OP_ERROR_RSP) { /* Return if error response cause a retry */ if (handle_error_rsp(chan, pdu, pdu_len, &req_opcode)) { wakeup_chan_writer(chan, NULL); return; } } else if (!(req_opcode = get_req_opcode(opcode))) goto fail; if (req_opcode != op->opcode) goto fail; rsp_opcode = opcode; if (pdu_len > 0) { rsp_pdu = pdu; rsp_pdu_len = pdu_len; } goto done; fail: util_debug(att->debug_callback, att->debug_data, "(chan %p) Failed to handle response PDU; opcode: " "0x%02x", chan, opcode); rsp_opcode = BT_ATT_OP_ERROR_RSP; done: if (op->callback) op->callback(rsp_opcode, rsp_pdu, rsp_pdu_len, op->user_data); destroy_att_send_op(op); chan->pending_req = NULL; wakeup_chan_writer(chan, NULL); } static void handle_conf(struct bt_att_chan *chan, uint8_t *pdu, ssize_t pdu_len) { struct bt_att *att = chan->att; struct att_send_op *op = chan->pending_ind; /* * Disconnect the bearer if the confirmation is unexpected or the PDU is * invalid. */ if (!op || pdu_len) { util_debug(att->debug_callback, att->debug_data, "(chan %p) Received unexpected/invalid ATT " "confirmation", chan); io_shutdown(chan->io); return; } if (op->callback) op->callback(BT_ATT_OP_HANDLE_CONF, NULL, 0, op->user_data); destroy_att_send_op(op); chan->pending_ind = NULL; wakeup_chan_writer(chan, NULL); } struct notify_data { uint8_t opcode; uint8_t *pdu; ssize_t pdu_len; bool handler_found; }; static bool opcode_match(uint8_t opcode, uint8_t test_opcode) { enum att_op_type op_type = get_op_type(test_opcode); if (opcode == BT_ATT_ALL_REQUESTS && (op_type == ATT_OP_TYPE_REQ || op_type == ATT_OP_TYPE_CMD)) return true; return opcode == test_opcode; } static void respond_not_supported(struct bt_att *att, uint8_t opcode) { struct bt_att_pdu_error_rsp pdu; pdu.opcode = opcode; pdu.handle = 0x0000; pdu.ecode = BT_ATT_ERROR_REQUEST_NOT_SUPPORTED; bt_att_send(att, BT_ATT_OP_ERROR_RSP, &pdu, sizeof(pdu), NULL, NULL, NULL); } static bool handle_signed(struct bt_att *att, uint8_t *pdu, ssize_t pdu_len) { uint8_t *signature; uint32_t sign_cnt; struct sign_info *sign; uint8_t opcode = pdu[0]; /* Check if there is enough data for a signature */ if (pdu_len < 3 + BT_ATT_SIGNATURE_LEN) goto fail; sign = att->remote_sign; if (!sign) goto fail; signature = pdu + (pdu_len - BT_ATT_SIGNATURE_LEN); sign_cnt = get_le32(signature); /* Validate counter */ if (!sign->counter(&sign_cnt, sign->user_data)) goto fail; /* Verify received signature */ if (!bt_crypto_verify_att_sign(att->crypto, sign->key, pdu, pdu_len)) goto fail; return true; fail: util_debug(att->debug_callback, att->debug_data, "ATT failed to verify signature: 0x%02x", opcode); return false; } static void handle_notify(struct bt_att_chan *chan, uint8_t *pdu, ssize_t pdu_len) { struct bt_att *att = chan->att; const struct queue_entry *entry; bool found; uint8_t opcode = pdu[0]; bt_att_ref(att); found = false; entry = queue_get_entries(att->notify_list); while (entry) { struct att_notify *notify = entry->data; entry = entry->next; if (!opcode_match(notify->opcode, opcode)) continue; if ((opcode & ATT_OP_SIGNED_MASK) && att->crypto) { if (!handle_signed(att, pdu, pdu_len)) return; pdu_len -= BT_ATT_SIGNATURE_LEN; } /* BLUETOOTH CORE SPECIFICATION Version 5.1 | Vol 3, Part G * page 2370 * * 4.3.1 Exchange MTU * * This sub-procedure shall not be used on a BR/EDR physical * link since the MTU size is negotiated using L2CAP channel * configuration procedures. */ if (bt_att_get_link_type(att) == BT_ATT_BREDR) { switch (opcode) { case BT_ATT_OP_MTU_REQ: goto not_supported; } } found = true; if (notify->callback) notify->callback(chan, opcode, pdu + 1, pdu_len - 1, notify->user_data); /* callback could remove all entries from notify list */ if (queue_isempty(att->notify_list)) break; } not_supported: /* * If this was not a command and no handler was registered for it, * respond with "Not Supported" */ if (!found && get_op_type(opcode) != ATT_OP_TYPE_CMD) respond_not_supported(att, opcode); bt_att_unref(att); } static bool can_read_data(struct io *io, void *user_data) { struct bt_att_chan *chan = user_data; struct bt_att *att = chan->att; uint8_t opcode; uint8_t *pdu; ssize_t bytes_read; bytes_read = read(chan->fd, chan->buf, chan->mtu); if (bytes_read < 0) return false; util_debug(att->debug_callback, att->debug_data, "(chan %p) ATT received: %zd", chan, bytes_read); util_hexdump('>', chan->buf, bytes_read, att->debug_callback, att->debug_data); if (bytes_read < ATT_MIN_PDU_LEN) return true; pdu = chan->buf; opcode = pdu[0]; bt_att_ref(att); /* Act on the received PDU based on the opcode type */ switch (get_op_type(opcode)) { case ATT_OP_TYPE_RSP: util_debug(att->debug_callback, att->debug_data, "(chan %p) ATT response received: 0x%02x", chan, opcode); handle_rsp(chan, opcode, pdu + 1, bytes_read - 1); break; case ATT_OP_TYPE_CONF: util_debug(att->debug_callback, att->debug_data, "(chan %p) ATT confirmation received: 0x%02x", chan, opcode); handle_conf(chan, pdu + 1, bytes_read - 1); break; case ATT_OP_TYPE_REQ: /* * If a request is currently pending, then the sequential * protocol was violated. Disconnect the bearer, which will * promptly notify the upper layer via disconnect handlers. */ if (chan->in_req) { util_debug(att->debug_callback, att->debug_data, "(chan %p) Received request while " "another is pending: 0x%02x", chan, opcode); io_shutdown(chan->io); bt_att_unref(chan->att); return false; } chan->in_req = true; /* fall through */ case ATT_OP_TYPE_CMD: case ATT_OP_TYPE_NFY: case ATT_OP_TYPE_UNKNOWN: case ATT_OP_TYPE_IND: /* fall through */ default: /* For all other opcodes notify the upper layer of the PDU and * let them act on it. */ util_debug(att->debug_callback, att->debug_data, "(chan %p) ATT PDU received: 0x%02x", chan, opcode); handle_notify(chan, pdu, bytes_read); break; } bt_att_unref(att); return true; } static bool is_io_l2cap_based(int fd) { int domain; int proto; int err; socklen_t len; domain = 0; len = sizeof(domain); err = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &len); if (err < 0) return false; if (domain != AF_BLUETOOTH) return false; proto = 0; len = sizeof(proto); err = getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &proto, &len); if (err < 0) return false; return proto == BTPROTO_L2CAP; } static void bt_att_free(struct bt_att *att) { bt_crypto_unref(att->crypto); if (att->timeout_destroy) att->timeout_destroy(att->timeout_data); if (att->debug_destroy) att->debug_destroy(att->debug_data); free(att->local_sign); free(att->remote_sign); queue_destroy(att->req_queue, NULL); queue_destroy(att->ind_queue, NULL); queue_destroy(att->write_queue, NULL); queue_destroy(att->notify_list, NULL); queue_destroy(att->disconn_list, NULL); queue_destroy(att->chans, bt_att_chan_free); free(att); } static uint16_t io_get_mtu(int fd) { socklen_t len; struct l2cap_options l2o; len = sizeof(l2o); if (!getsockopt(fd, SOL_L2CAP, L2CAP_OPTIONS, &l2o, &len)) return l2o.omtu; if (!getsockopt(fd, SOL_BLUETOOTH, BT_SNDMTU, &l2o.omtu, &len)) return l2o.omtu; return 0; } static uint8_t io_get_type(int fd) { struct sockaddr_l2 src; socklen_t len; if (!is_io_l2cap_based(fd)) return BT_ATT_LOCAL; len = sizeof(src); memset(&src, 0, len); if (getsockname(fd, (void *)&src, &len) < 0) return -errno; if (src.l2_bdaddr_type == BDADDR_BREDR) return BT_ATT_BREDR; return BT_ATT_LE; } static struct bt_att_chan *bt_att_chan_new(int fd, uint8_t type) { struct bt_att_chan *chan; if (fd < 0) return NULL; chan = new0(struct bt_att_chan, 1); chan->fd = fd; chan->io = io_new(fd); if (!chan->io) goto fail; if (!io_set_read_handler(chan->io, can_read_data, chan, NULL)) goto fail; if (!io_set_disconnect_handler(chan->io, disconnect_cb, chan, NULL)) goto fail; chan->type = type; switch (chan->type) { case BT_ATT_LOCAL: chan->sec_level = BT_ATT_SECURITY_LOW; /* fall through */ case BT_ATT_LE: chan->mtu = BT_ATT_DEFAULT_LE_MTU; break; default: chan->mtu = io_get_mtu(chan->fd); } if (chan->mtu < BT_ATT_DEFAULT_LE_MTU) goto fail; chan->buf = malloc(chan->mtu); if (!chan->buf) goto fail; chan->queue = queue_new(); return chan; fail: bt_att_chan_free(chan); return NULL; } static void bt_att_attach_chan(struct bt_att *att, struct bt_att_chan *chan) { /* Push to head as EATT channels have higher priority */ queue_push_head(att->chans, chan); chan->att = att; if (chan->mtu > att->mtu) att->mtu = chan->mtu; io_set_close_on_destroy(chan->io, att->close_on_unref); util_debug(att->debug_callback, att->debug_data, "Channel %p attached", chan); wakeup_chan_writer(chan, NULL); } struct bt_att *bt_att_new(int fd, bool ext_signed) { struct bt_att *att; struct bt_att_chan *chan; chan = bt_att_chan_new(fd, io_get_type(fd)); if (!chan) return NULL; att = new0(struct bt_att, 1); att->chans = queue_new(); att->mtu = chan->mtu; /* crypto is optional, if not available leave it NULL */ if (!ext_signed) att->crypto = bt_crypto_new(); att->req_queue = queue_new(); att->ind_queue = queue_new(); att->write_queue = queue_new(); att->notify_list = queue_new(); att->disconn_list = queue_new(); bt_att_attach_chan(att, chan); return bt_att_ref(att); } struct bt_att *bt_att_ref(struct bt_att *att) { if (!att) return NULL; __sync_fetch_and_add(&att->ref_count, 1); return att; } void bt_att_unref(struct bt_att *att) { if (!att) return; if (__sync_sub_and_fetch(&att->ref_count, 1)) return; bt_att_unregister_all(att); bt_att_cancel_all(att); bt_att_free(att); } bool bt_att_set_close_on_unref(struct bt_att *att, bool do_close) { const struct queue_entry *entry; if (!att) return false; att->close_on_unref = do_close; for (entry = queue_get_entries(att->chans); entry; entry = entry->next) { struct bt_att_chan *chan = entry->data; if (!io_set_close_on_destroy(chan->io, do_close)) return false; } return true; } int bt_att_attach_fd(struct bt_att *att, int fd) { struct bt_att_chan *chan; if (!att || fd < 0) return -EINVAL; chan = bt_att_chan_new(fd, BT_ATT_EATT); if (!chan) return -EINVAL; bt_att_attach_chan(att, chan); return 0; } int bt_att_get_fd(struct bt_att *att) { struct bt_att_chan *chan; if (!att) return -1; if (queue_isempty(att->chans)) return -ENOTCONN; chan = queue_peek_tail(att->chans); return chan->fd; } int bt_att_get_channels(struct bt_att *att) { if (!att) return 0; return queue_length(att->chans); } bool bt_att_set_debug(struct bt_att *att, bt_att_debug_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { if (!att) return false; if (att->debug_destroy) att->debug_destroy(att->debug_data); att->debug_callback = callback; att->debug_destroy = destroy; att->debug_data = user_data; return true; } uint16_t bt_att_get_mtu(struct bt_att *att) { if (!att) return 0; return att->mtu; } bool bt_att_set_mtu(struct bt_att *att, uint16_t mtu) { struct bt_att_chan *chan; void *buf; if (!att) return false; if (mtu < BT_ATT_DEFAULT_LE_MTU) return false; /* Original channel is always the last */ chan = queue_peek_tail(att->chans); if (!chan) return -ENOTCONN; buf = malloc(mtu); if (!buf) return false; free(chan->buf); chan->mtu = mtu; chan->buf = buf; if (chan->mtu > att->mtu) att->mtu = chan->mtu; return true; } uint8_t bt_att_get_link_type(struct bt_att *att) { struct bt_att_chan *chan; if (!att) return -EINVAL; chan = queue_peek_tail(att->chans); if (!chan) return -ENOTCONN; return chan->type; } bool bt_att_set_timeout_cb(struct bt_att *att, bt_att_timeout_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { if (!att) return false; if (att->timeout_destroy) att->timeout_destroy(att->timeout_data); att->timeout_callback = callback; att->timeout_destroy = destroy; att->timeout_data = user_data; return true; } unsigned int bt_att_register_disconnect(struct bt_att *att, bt_att_disconnect_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { struct att_disconn *disconn; if (!att || queue_isempty(att->chans)) return 0; disconn = new0(struct att_disconn, 1); disconn->callback = callback; disconn->destroy = destroy; disconn->user_data = user_data; if (att->next_reg_id < 1) att->next_reg_id = 1; disconn->id = att->next_reg_id++; if (!queue_push_tail(att->disconn_list, disconn)) { free(disconn); return 0; } return disconn->id; } bool bt_att_unregister_disconnect(struct bt_att *att, unsigned int id) { struct att_disconn *disconn; if (!att || !id) return false; /* Check if disconnect is running */ if (queue_isempty(att->chans)) { disconn = queue_find(att->disconn_list, match_disconn_id, UINT_TO_PTR(id)); if (!disconn) return false; disconn->removed = true; return true; } disconn = queue_remove_if(att->disconn_list, match_disconn_id, UINT_TO_PTR(id)); if (!disconn) return false; destroy_att_disconn(disconn); return true; } unsigned int bt_att_send(struct bt_att *att, uint8_t opcode, const void *pdu, uint16_t length, bt_att_response_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { struct att_send_op *op; bool result; if (!att || queue_isempty(att->chans)) return 0; op = create_att_send_op(att, opcode, pdu, length, callback, user_data, destroy); if (!op) return 0; if (att->next_send_id < 1) att->next_send_id = 1; op->id = att->next_send_id++; /* Add the op to the correct queue based on its type */ switch (op->type) { case ATT_OP_TYPE_REQ: result = queue_push_tail(att->req_queue, op); break; case ATT_OP_TYPE_IND: result = queue_push_tail(att->ind_queue, op); break; case ATT_OP_TYPE_CMD: case ATT_OP_TYPE_NFY: case ATT_OP_TYPE_UNKNOWN: case ATT_OP_TYPE_RSP: case ATT_OP_TYPE_CONF: default: result = queue_push_tail(att->write_queue, op); break; } if (!result) { free(op->pdu); free(op); return 0; } wakeup_writer(att); return op->id; } unsigned int bt_att_chan_send(struct bt_att_chan *chan, uint8_t opcode, const void *pdu, uint16_t len, bt_att_response_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { struct att_send_op *op; if (!chan || !chan->att) return -EINVAL; op = create_att_send_op(chan->att, opcode, pdu, len, callback, user_data, destroy); if (!op) return -EINVAL; if (!queue_push_tail(chan->queue, op)) { free(op->pdu); free(op); return 0; } wakeup_chan_writer(chan, NULL); return op->id; } static bool match_op_id(const void *a, const void *b) { const struct att_send_op *op = a; unsigned int id = PTR_TO_UINT(b); return op->id == id; } bool bt_att_chan_cancel(struct bt_att_chan *chan, unsigned int id) { struct att_send_op *op; if (chan->pending_req && chan->pending_req->id == id) { /* Don't cancel the pending request; remove it's handlers */ cancel_att_send_op(chan->pending_req); return true; } if (chan->pending_ind && chan->pending_ind->id == id) { /* Don't cancel the pending indication; remove it's handlers. */ cancel_att_send_op(chan->pending_ind); return true; } op = queue_remove_if(chan->queue, match_op_id, UINT_TO_PTR(id)); if (!op) return false; destroy_att_send_op(op); wakeup_chan_writer(chan, NULL); return true; } bool bt_att_cancel(struct bt_att *att, unsigned int id) { const struct queue_entry *entry; struct att_send_op *op; if (!att || !id) return false; /* Lookuo request on each channel first */ for (entry = queue_get_entries(att->chans); entry; entry = entry->next) { struct bt_att_chan *chan = entry->data; if (bt_att_chan_cancel(chan, id)) return true; } op = queue_remove_if(att->req_queue, match_op_id, UINT_TO_PTR(id)); if (op) goto done; op = queue_remove_if(att->ind_queue, match_op_id, UINT_TO_PTR(id)); if (op) goto done; op = queue_remove_if(att->write_queue, match_op_id, UINT_TO_PTR(id)); if (op) goto done; if (!op) return false; done: destroy_att_send_op(op); wakeup_writer(att); return true; } bool bt_att_cancel_all(struct bt_att *att) { const struct queue_entry *entry; if (!att) return false; queue_remove_all(att->req_queue, NULL, NULL, destroy_att_send_op); queue_remove_all(att->ind_queue, NULL, NULL, destroy_att_send_op); queue_remove_all(att->write_queue, NULL, NULL, destroy_att_send_op); for (entry = queue_get_entries(att->chans); entry; entry = entry->next) { struct bt_att_chan *chan = entry->data; if (chan->pending_req) /* Don't cancel the pending request; remove it's * handlers */ cancel_att_send_op(chan->pending_req); if (chan->pending_ind) /* Don't cancel the pending request; remove it's * handlers */ cancel_att_send_op(chan->pending_ind); } return true; } static uint8_t att_ecode_from_error(int err) { /* * If the error fits in a single byte, treat it as an ATT protocol * error as is. Since "0" is not a valid ATT protocol error code, we map * that to UNLIKELY below. */ if (err > 0 && err < UINT8_MAX) return err; /* * Since we allow UNIX errnos, map them to appropriate ATT protocol * and "Common Profile and Service" error codes. */ switch (err) { case -ENOENT: return BT_ATT_ERROR_INVALID_HANDLE; case -ENOMEM: return BT_ATT_ERROR_INSUFFICIENT_RESOURCES; case -EALREADY: return BT_ERROR_ALREADY_IN_PROGRESS; case -EOVERFLOW: return BT_ERROR_OUT_OF_RANGE; } return BT_ATT_ERROR_UNLIKELY; } int bt_att_chan_send_error_rsp(struct bt_att_chan *chan, uint8_t opcode, uint16_t handle, int error) { struct bt_att_pdu_error_rsp pdu; uint8_t ecode; if (!chan || !chan->att || !opcode) return -EINVAL; ecode = att_ecode_from_error(error); memset(&pdu, 0, sizeof(pdu)); pdu.opcode = opcode; put_le16(handle, &pdu.handle); pdu.ecode = ecode; return bt_att_chan_send_rsp(chan, BT_ATT_OP_ERROR_RSP, &pdu, sizeof(pdu)); } unsigned int bt_att_register(struct bt_att *att, uint8_t opcode, bt_att_notify_func_t callback, void *user_data, bt_att_destroy_func_t destroy) { struct att_notify *notify; if (!att || !callback || queue_isempty(att->chans)) return 0; notify = new0(struct att_notify, 1); notify->opcode = opcode; notify->callback = callback; notify->destroy = destroy; notify->user_data = user_data; if (att->next_reg_id < 1) att->next_reg_id = 1; notify->id = att->next_reg_id++; if (!queue_push_tail(att->notify_list, notify)) { free(notify); return 0; } return notify->id; } bool bt_att_unregister(struct bt_att *att, unsigned int id) { struct att_notify *notify; if (!att || !id) return false; notify = queue_remove_if(att->notify_list, match_notify_id, UINT_TO_PTR(id)); if (!notify) return false; destroy_att_notify(notify); return true; } bool bt_att_unregister_all(struct bt_att *att) { if (!att) return false; queue_remove_all(att->notify_list, NULL, NULL, destroy_att_notify); queue_remove_all(att->disconn_list, NULL, NULL, destroy_att_disconn); return true; } int bt_att_get_security(struct bt_att *att, uint8_t *enc_size) { struct bt_att_chan *chan; int ret; if (!att) return -EINVAL; chan = queue_peek_tail(att->chans); if (!chan) return -ENOTCONN; ret = bt_att_chan_get_security(chan); if (ret < 0) return ret; if (enc_size) *enc_size = att->enc_size; return ret; } bool bt_att_set_security(struct bt_att *att, int level) { struct bt_att_chan *chan; if (!att || level < BT_ATT_SECURITY_AUTO || level > BT_ATT_SECURITY_HIGH) return false; chan = queue_peek_tail(att->chans); if (!chan) return -ENOTCONN; return bt_att_chan_set_security(chan, level); } void bt_att_set_enc_key_size(struct bt_att *att, uint8_t enc_size) { if (!att) return; att->enc_size = enc_size; } static bool sign_set_key(struct sign_info **sign, uint8_t key[16], bt_att_counter_func_t func, void *user_data) { if (!(*sign)) *sign = new0(struct sign_info, 1); (*sign)->counter = func; (*sign)->user_data = user_data; memcpy((*sign)->key, key, 16); return true; } bool bt_att_set_local_key(struct bt_att *att, uint8_t sign_key[16], bt_att_counter_func_t func, void *user_data) { if (!att) return false; return sign_set_key(&att->local_sign, sign_key, func, user_data); } bool bt_att_set_remote_key(struct bt_att *att, uint8_t sign_key[16], bt_att_counter_func_t func, void *user_data) { if (!att) return false; return sign_set_key(&att->remote_sign, sign_key, func, user_data); } bool bt_att_has_crypto(struct bt_att *att) { if (!att) return false; return att->crypto ? true : false; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_4406_0
crossvul-cpp_data_good_2579_9
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_wrap */ #include "mglueP.h" static OM_uint32 val_wrap_args(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (output_message_buffer != GSS_C_NO_BUFFER) { output_message_buffer->length = 0; output_message_buffer->value = NULL; } /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (input_message_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (output_message_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_wrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_args(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_wrap) { status = mech->gss_wrap(minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else if (mech->gss_wrap_aead || (mech->gss_wrap_iov && mech->gss_wrap_iov_length)) { status = gssint_wrap_aead(mech, minor_status, ctx, conf_req_flag, (gss_qop_t)qop_req, GSS_C_NO_BUFFER, input_message_buffer, conf_state, output_message_buffer); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_seal(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, int qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { return gss_wrap(minor_status, context_handle, conf_req_flag, (gss_qop_t) qop_req, input_message_buffer, conf_state, output_message_buffer); } /* * It is only possible to implement gss_wrap_size_limit() on top * of gss_wrap_iov_length() for mechanisms that do not use any * padding and have fixed length headers/trailers. */ static OM_uint32 gssint_wrap_size_limit_iov_shim(gss_mechanism mech, OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { gss_iov_buffer_desc iov[4]; OM_uint32 status; OM_uint32 ohlen; iov[0].type = GSS_IOV_BUFFER_TYPE_HEADER; iov[0].buffer.value = NULL; iov[0].buffer.length = 0; iov[1].type = GSS_IOV_BUFFER_TYPE_DATA; iov[1].buffer.length = req_output_size; iov[1].buffer.value = NULL; iov[2].type = GSS_IOV_BUFFER_TYPE_PADDING; iov[2].buffer.value = NULL; iov[2].buffer.length = 0; iov[3].type = GSS_IOV_BUFFER_TYPE_TRAILER; iov[3].buffer.value = NULL; iov[3].buffer.length = 0; assert(mech->gss_wrap_iov_length); status = mech->gss_wrap_iov_length(minor_status, context_handle, conf_req_flag, qop_req, NULL, iov, sizeof(iov)/sizeof(iov[0])); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); return status; } ohlen = iov[0].buffer.length + iov[3].buffer.length; if (iov[2].buffer.length == 0 && ohlen < req_output_size) *max_input_size = req_output_size - ohlen; else *max_input_size = 0; return GSS_S_COMPLETE; } /* * New for V2 */ OM_uint32 KRB5_CALLCONV gss_wrap_size_limit(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { gss_union_ctx_id_t ctx; gss_mechanism mech; OM_uint32 major_status; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (max_input_size == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return (GSS_S_BAD_MECH); if (mech->gss_wrap_size_limit) major_status = mech->gss_wrap_size_limit(minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, req_output_size, max_input_size); else if (mech->gss_wrap_iov_length) major_status = gssint_wrap_size_limit_iov_shim(mech, minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, req_output_size, max_input_size); else major_status = GSS_S_UNAVAILABLE; if (major_status != GSS_S_COMPLETE) map_error(minor_status, mech); return major_status; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_9
crossvul-cpp_data_bad_1406_0
/** * File: GIF Output * * Write GIF images. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" #include "gdhelpers.h" /* Code drawn from ppmtogif.c, from the pbmplus package ** ** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>. A ** Lempel-Zim compression based on "compress". ** ** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl> ** ** Copyright (C) 1989 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. ** ** The Graphics Interchange Format(c) is the Copyright property of ** CompuServe Incorporated. GIF(sm) is a Service Mark property of ** CompuServe Incorporated. */ /* a code_int must be able to hold 2**GIFBITS values of type int, and also -1 */ typedef int code_int; #ifdef SIGNED_COMPARE_SLOW typedef unsigned long int count_int; typedef unsigned short int count_short; #else /* SIGNED_COMPARE_SLOW */ typedef long int count_int; #endif /* SIGNED_COMPARE_SLOW */ /* 2.0.28: threadsafe */ #define maxbits GIFBITS /* should NEVER generate this code */ #define maxmaxcode ((code_int)1 << GIFBITS) #define HSIZE 5003 /* 80% occupancy */ #define hsize HSIZE /* Apparently invariant, left over from compress */ typedef struct { int Width, Height; int curx, cury; long CountDown; int Pass; int Interlace; int n_bits; code_int maxcode; count_int htab [HSIZE]; unsigned short codetab [HSIZE]; /* first unused entry */ code_int free_ent; /* block compression parameters -- after all codes are used up, * and compression rate changes, start over. */ int clear_flg; int offset; long int in_count; /* # of codes output (for debugging) */ long int out_count; int g_init_bits; gdIOCtx * g_outfile; int ClearCode; int EOFCode; unsigned long cur_accum; int cur_bits; int a_count; char accum[ 256 ]; } GifCtx; static int gifPutWord(int w, gdIOCtx *out); static int colorstobpp(int colors); static void BumpPixel(GifCtx *ctx); static int GIFNextPixel(gdImagePtr im, GifCtx *ctx); static void GIFEncode(gdIOCtxPtr fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im); static void GIFAnimEncode(gdIOCtxPtr fp, int IWidth, int IHeight, int LeftOfs, int TopOfs, int GInterlace, int Transparent, int Delay, int Disposal, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im); static void compress(int init_bits, gdIOCtx *outfile, gdImagePtr im, GifCtx *ctx); static void output(code_int code, GifCtx *ctx); static void cl_block(GifCtx *ctx); static void cl_hash(register count_int chsize, GifCtx *ctx); static void char_init(GifCtx *ctx); static void char_out(int c, GifCtx *ctx); static void flush_char(GifCtx *ctx); /* Function: gdImageGifPtr Identical to <gdImageGif> except that it returns a pointer to a memory area with the GIF data. This memory must be freed by the caller when it is no longer needed. The caller *must* invoke <gdFree>, not _free()_. This is because it is not guaranteed that libgd will use the same implementation of malloc, free, etc. as your proggram. The 'size' parameter receives the total size of the block of memory. Parameters: im - The image to write size - Output: the size of the resulting image. Returns: A pointer to the GIF data or NULL if an error occurred. */ BGD_DECLARE(void *) gdImageGifPtr(gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) return NULL; gdImageGifCtx(im, out); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } /* Function: gdImageGif <gdImageGif> outputs the specified image to the specified file in GIF format. The file must be open for binary writing. (Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file; under Unix there is no penalty for doing so). <gdImageGif> does not close the file; your code must do so. GIF does not support true color; GIF images can contain a maximum of 256 colors. If the image to be written is a truecolor image, such as those created with gdImageCreateTrueColor or loaded from a JPEG or a truecolor PNG image file, a palette-based temporary image will automatically be created internally using the <gdImageCreatePaletteFromTrueColor> function. The original image pixels are not modified. This conversion produces high quality palettes but does require some CPU time. If you are regularly converting truecolor to palette in this way, you should consider creating your image as a palette-based image in the first place. Variants: <gdImageGifCtx> outputs the image via a <gdIOCtx> struct. <gdImageGifPtr> stores the image in a large array of bytes. Parameters: im - The image to write outFile - The FILE pointer to write the image to. Returns: Nothing Example: > gdImagePtr im; > int black, white; > FILE *out; > // Create the image > im = gdImageCreate(100, 100); > // Allocate background > white = gdImageColorAllocate(im, 255, 255, 255); > // Allocate drawing color > black = gdImageColorAllocate(im, 0, 0, 0); > // Draw rectangle > gdImageRectangle(im, 0, 0, 99, 99, black); > // Open output file in binary mode > out = fopen("rect.gif", "wb"); > // Write GIF > gdImageGif(im, out); > // Close file > fclose(out); > // Destroy image > gdImageDestroy(im); */ BGD_DECLARE(void) gdImageGif(gdImagePtr im, FILE *outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) return; gdImageGifCtx(im, out); out->gd_free(out); } /* Function: gdImageGifCtx Writes a GIF image via a <gdIOCtx>. See <gdImageGif>. Parameters: im - The image to write out - The <gdIOCtx> struct used to do the writing. Returns: Nothing. */ BGD_DECLARE(void) gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if(im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if(!pim) { return; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if(pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } } /* Function: gdImageGifAnimBeginPtr Like <gdImageGifAnimBegin> except that it outputs to a memory buffer. See <gdImageGifAnimBegin>. The returned memory must be freed by the caller when it is no longer needed. **The caller must invoke <gdFree>(), not free()**, unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time (but don't; it could always change). The 'size' parameter receives the total size of the block of memory. Parameters: im - The reference image size - Output: the size in bytes of the result. GlobalCM - Global colormap flag: 1 -> yes, 0 -> no, -1 -> do default Loops - Loop count; 0 -> infinite, -1 means no loop Returns: A pointer to the resulting data (the contents of the start of the GIF) or NULL if an error occurred. */ BGD_DECLARE(void *) gdImageGifAnimBeginPtr(gdImagePtr im, int *size, int GlobalCM, int Loops) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) return NULL; gdImageGifAnimBeginCtx(im, out, GlobalCM, Loops); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } /* Function: gdImageGifAnimBegin This function must be called as the first function when creating a GIF animation. It writes the correct GIF file headers to selected file output, and prepares for frames to be added for the animation. The image argument is not used to produce an image frame to the file, it is only used to establish the GIF animation frame size, interlacing options and the color palette. <gdImageGifAnimAdd> is used to add the first and subsequent frames to the animation, and the animation must be terminated by writing a semicolon character (;) to it or by using gdImageGifAnimEnd to do that. The GlobalCM flag indicates if a global color map (or palette) is used in the GIF89A header. A nonzero value specifies that a global color map should be used to reduce the size of the animation. Of course, if the color maps of individual frames differ greatly, a global color map may not be a good idea. GlobalCM=1 means write global color map, GlobalCM=0 means do not, and GlobalCM=-1 means to do the default, which currently is to use a global color map. If Loops is 0 or greater, the Netscape 2.0 extension for animation loop count is written. 0 means infinite loop count. -1 means that the extension is not added which results in no looping. -1 is the default. Variants: <gdImageGifAnimBeginCtx> outputs the image via a <gdIOCtx> struct. <gdImageGifAnimBeginPtr> stores the image in a large array of bytes. Parameters: im - The reference image outfile - The output FILE*. GlobalCM - Global colormap flag: 1 -> yes, 0 -> no, -1 -> do default Loops - Loop count; 0 -> infinite, -1 means no loop Returns: Nothing. Example: See <gdImageGifAnimBegin>. */ BGD_DECLARE(void) gdImageGifAnimBegin(gdImagePtr im, FILE *outFile, int GlobalCM, int Loops) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) return; gdImageGifAnimBeginCtx(im, out, GlobalCM, Loops); out->gd_free(out); } /* Function: gdImageGifAnimBeginCtx Like <gdImageGifAnimBegin> except that it outputs to <gdIOCtx>. See <gdImageGifAnimBegin>. Parameters: im - The reference image out - Pointer to the output <gdIOCtx>. GlobalCM - Global colormap flag: 1 -> yes, 0 -> no, -1 -> do default Loops - Loop count; 0 -> infinite, -1 means no loop Returns: Nothing. */ BGD_DECLARE(void) gdImageGifAnimBeginCtx(gdImagePtr im, gdIOCtxPtr out, int GlobalCM, int Loops) { int B; int RWidth, RHeight; int Resolution; int ColorMapSize; int BitsPerPixel; int Background = 0; int i; /* Default is to use global color map */ if (GlobalCM < 0) { GlobalCM = 1; } BitsPerPixel = colorstobpp(im->colorsTotal); ColorMapSize = 1 << BitsPerPixel; RWidth = im->sx; RHeight = im->sy; Resolution = BitsPerPixel; /* Write the Magic header */ gdPutBuf("GIF89a", 6, out); /* Write out the screen width and height */ gifPutWord(RWidth, out); gifPutWord(RHeight, out); /* Indicate that there is a global colour map */ B = GlobalCM ? 0x80 : 0; /* OR in the resolution */ B |= (Resolution - 1) << 4; /* OR in the Bits per Pixel */ B |= (BitsPerPixel - 1); /* Write it out */ gdPutC(B, out); /* Write out the Background colour */ gdPutC(Background, out); /* Byte of 0's (future expansion) */ gdPutC(0, out); /* Write out the Global Colour Map */ if(GlobalCM) { for(i = 0; i < ColorMapSize; ++i) { gdPutC(im->red[i], out); gdPutC(im->green[i], out); gdPutC(im->blue[i], out); } } if(Loops >= 0) { gdPutBuf("!\377\13NETSCAPE2.0\3\1", 16, out); gifPutWord(Loops, out); gdPutC(0, out); } } /* Function: gdImageGifAnimAddPtr Like <gdImageGifAnimAdd> (which contains more information) except that it stores the data to write into memory and returns a pointer to it. This memory must be freed by the caller when it is no longer needed. **The caller must invoke <gdFree>(), not free(),** unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time (but don't; it could always change). The 'size' parameter receives the total size of the block of memory. Parameters: im - The image to add. size - Output: the size of the resulting buffer. LocalCM - Flag. If 1, use a local color map for this frame. LeftOfs - Left offset of image in frame. TopOfs - Top offset of image in frame. Delay - Delay before next frame (in 1/100 seconds) Disposal - MODE: How to treat this frame when the next one loads. previm - NULL or a pointer to the previous image written. Returns: Pointer to the resulting data or NULL if an error occurred. */ BGD_DECLARE(void *) gdImageGifAnimAddPtr(gdImagePtr im, int *size, int LocalCM, int LeftOfs, int TopOfs, int Delay, int Disposal, gdImagePtr previm) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) return NULL; gdImageGifAnimAddCtx(im, out, LocalCM, LeftOfs, TopOfs, Delay, Disposal, previm); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } /* Function: gdImageGifAnimAdd This function writes GIF animation frames to GIF animation, which was initialized with <gdImageGifAnimBegin>. With _LeftOfs_ and _TopOfs_ you can place this frame in different offset than (0,0) inside the image screen as defined in <gdImageGifAnimBegin>. Delay between the previous frame and this frame is in 1/100s units. _Disposal_ is usually <gdDisposalNone>, meaning that the pixels changed by this frame should remain on the display when the next frame begins to render, but can also be <gdDisposalUnknown> (not recommended), <gdDisposalRestoreBackground> (restores the first allocated color of the global palette), or <gdDisposalRestorePrevious> (restores the appearance of the affected area before the frame was rendered). Only <gdDisposalNone> is a sensible choice for the first frame. If _previm_ is passed, the built-in GIF optimizer will always use <gdDisposalNone> regardless of the Disposal parameter. Setting the _LocalCM_ flag to 1 adds a local palette for this image to the animation. Otherwise the global palette is assumed and the user must make sure the palettes match. Use <gdImagePaletteCopy> to do that. Automatic optimization is activated by giving the previous image as a parameter. This function then compares the images and only writes the changed pixels to the new frame in animation. The _Disposal_ parameter for optimized animations must be set to 1, also for the first frame. _LeftOfs_ and _TopOfs_ parameters are ignored for optimized frames. To achieve good optimization, it is usually best to use a single global color map. To allow <gdImageGifAnimAdd> to compress unchanged pixels via the use of a transparent color, the image must include a transparent color. Variants: <gdImageGifAnimAddCtx> outputs its data via a <gdIOCtx> struct. <gdImageGifAnimAddPtr> outputs its data to a memory buffer which it returns. Parameters: im - The image to add. outfile - The output FILE* being written. LocalCM - Flag. If 1, use a local color map for this frame. LeftOfs - Left offset of image in frame. TopOfs - Top offset of image in frame. Delay - Delay before next frame (in 1/100 seconds) Disposal - MODE: How to treat this frame when the next one loads. previm - NULL or a pointer to the previous image written. Returns: Nothing. Example: (start code) { gdImagePtr im, im2, im3; int black, white, trans; FILE *out; im = gdImageCreate(100, 100); // Create the image white = gdImageColorAllocate(im, 255, 255, 255); // Allocate background black = gdImageColorAllocate(im, 0, 0, 0); // Allocate drawing color trans = gdImageColorAllocate(im, 1, 1, 1); // trans clr for compression gdImageRectangle(im, 0, 0, 10, 10, black); // Draw rectangle out = fopen("anim.gif", "wb");// Open output file in binary mode gdImageGifAnimBegin(im, out, 1, 3);// Write GIF hdr, global clr map,loops // Write the first frame. No local color map. Delay = 1s gdImageGifAnimAdd(im, out, 0, 0, 0, 100, 1, NULL); // construct the second frame im2 = gdImageCreate(100, 100); (void)gdImageColorAllocate(im2, 255, 255, 255); // White background gdImagePaletteCopy (im2, im); // Make sure the palette is identical gdImageRectangle(im2, 0, 0, 15, 15, black); // Draw something // Allow animation compression with transparent pixels gdImageColorTransparent (im2, trans); gdImageGifAnimAdd(im2, out, 0, 0, 0, 100, 1, im); // Add second frame // construct the third frame im3 = gdImageCreate(100, 100); (void)gdImageColorAllocate(im3, 255, 255, 255); // white background gdImagePaletteCopy (im3, im); // Make sure the palette is identical gdImageRectangle(im3, 0, 0, 15, 20, black); // Draw something // Allow animation compression with transparent pixels gdImageColorTransparent (im3, trans); // Add the third frame, compressing against the second one gdImageGifAnimAdd(im3, out, 0, 0, 0, 100, 1, im2); gdImageGifAnimEnd(out); // End marker, same as putc(';', out); fclose(out); // Close file // Destroy images gdImageDestroy(im); gdImageDestroy(im2); gdImageDestroy(im3); } (end code) */ BGD_DECLARE(void) gdImageGifAnimAdd(gdImagePtr im, FILE *outFile, int LocalCM, int LeftOfs, int TopOfs, int Delay, int Disposal, gdImagePtr previm) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) return; gdImageGifAnimAddCtx(im, out, LocalCM, LeftOfs, TopOfs, Delay, Disposal, previm); out->gd_free(out); } static int comparewithmap(gdImagePtr im1, gdImagePtr im2, int c1, int c2, int *colorMap) { if(!colorMap) { return c1 == c2; } if(-2 != colorMap[c1]) { return colorMap[c1] == c2; } return (colorMap[c1] = gdImageColorExactAlpha(im2, im1->red[c1], im1->green[c1], im1->blue[c1], im1->alpha[c1])) == c2; } /* Function: gdImageGifAnimAddCtx Adds an animation frame via a <gdIOCtxPtr>. See gdImageGifAnimAdd>. Parameters: im - The image to add. out - The output <gdIOCtxPtr>. LocalCM - Flag. If 1, use a local color map for this frame. LeftOfs - Left offset of image in frame. TopOfs - Top offset of image in frame. Delay - Delay before next frame (in 1/100 seconds) Disposal - MODE: How to treat this frame when the next one loads. previm - NULL or a pointer to the previous image written. Returns: Nothing. */ BGD_DECLARE(void) gdImageGifAnimAddCtx(gdImagePtr im, gdIOCtxPtr out, int LocalCM, int LeftOfs, int TopOfs, int Delay, int Disposal, gdImagePtr previm) { gdImagePtr pim = NULL, tim = im; int interlace, transparent, BitsPerPixel; interlace = im->interlace; transparent = im->transparent; /* Default is no local color map */ if(LocalCM < 0) { LocalCM = 0; } if(im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if (!pim) { return; } tim = pim; } if (previm) { /* create optimized animation. Compare this image to the previous image and crop the temporary copy of current image to include only changed rectangular area. Also replace unchanged pixels inside this area with transparent color. Transparent color needs to be already allocated! Preconditions: TopOfs, LeftOfs are assumed 0 Images should be of same size. If not, a temporary copy is made with the same size as previous image. */ gdImagePtr prev_pim = 0, prev_tim = previm; int x, y; int min_x = 0; int min_y = tim->sy; int max_x = 0; int max_y = 0; int colorMap[256]; if (previm->trueColor) { prev_pim = gdImageCreatePaletteFromTrueColor(previm, 1, 256); if (!prev_pim) { goto fail_end; } prev_tim = prev_pim; } for (x = 0; x < 256; ++x) { colorMap[x] = -2; } /* First find bounding box of changed areas. */ /* first find the top changed row */ for (y = 0; y < tim->sy; ++y) { for (x = 0; x < tim->sx; ++x) { if (!comparewithmap(prev_tim, tim, prev_tim->pixels[y][x], tim->pixels[y][x], colorMap)) { min_y = max_y = y; min_x = max_x = x; goto break_top; } } } break_top: if (tim->sy == min_y) { /* No changes in this frame!! Encode empty image. */ transparent = 0; min_x = min_y = 1; max_x = max_y = 0; } else { /* Then the bottom row */ for (y = tim->sy - 1; y > min_y; --y) { for (x = 0; x < tim->sx; ++x) { if (!comparewithmap (prev_tim, tim, prev_tim->pixels[y][x], tim->pixels[y][x], colorMap)) { max_y = y; if(x < min_x) { min_x = x; } if(x > max_x) { max_x = x; } goto break_bot; } } } break_bot: /* left side */ for (x = 0; x < min_x; ++x) { for (y = min_y; y <= max_y; ++y) { if (!comparewithmap (prev_tim, tim, prev_tim->pixels[y][x], tim->pixels[y][x], colorMap)) { min_x = x; goto break_left; } } } break_left: /* right side */ for (x = tim->sx - 1; x > max_x; --x) { for (y = min_y; y <= max_y; ++y) { if (!comparewithmap (prev_tim, tim, prev_tim->pixels[y][x], tim->pixels[y][x], colorMap)) { max_x = x; goto break_right; } } } break_right: ; } LeftOfs = min_x; TopOfs = min_y; Disposal = 1; /* Make a copy of the image with the new offsets. But only if necessary. */ if (min_x != 0 || max_x != tim->sx - 1 || min_y != 0 || max_y != tim->sy - 1 || transparent >= 0) { gdImagePtr pim2 = gdImageCreate(max_x-min_x + 1, max_y-min_y + 1); if (!pim2) { if (prev_pim) { gdImageDestroy(prev_pim); } goto fail_end; } gdImagePaletteCopy(pim2, LocalCM ? tim : prev_tim); gdImageCopy(pim2, tim, 0, 0, min_x, min_y, max_x - min_x + 1, max_y - min_y + 1); if (pim) { gdImageDestroy(pim); } tim = pim = pim2; } /* now let's compare pixels for transparent optimization. But only if transparent is set. */ if (transparent >= 0) { for(y = 0; y < tim->sy; ++y) { for (x = 0; x < tim->sx; ++x) { if(comparewithmap (prev_tim, tim, prev_tim->pixels[min_y + y][min_x + x], tim->pixels[y][x], 0)) { gdImageSetPixel(tim, x, y, transparent); break; } } } } if(prev_pim) { gdImageDestroy(prev_pim); } } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFAnimEncode( out, tim->sx, tim->sy, LeftOfs, TopOfs, interlace, transparent, Delay, Disposal, BitsPerPixel, LocalCM ? tim->red : 0, tim->green, tim->blue, tim); fail_end: if(pim) { /* Destroy palette based temporary image. */ gdImageDestroy(pim); } } /* Function: gdImageGifAnimEnd Terminates the GIF file properly. (Previous versions of this function's documentation suggested just manually writing a semicolon (';') instead since that is all this function does. While that has no longer changed, we now suggest that you do not do this and instead always call <gdImageGifAnimEnd> (or equivalent) since later versions could possibly do more or different things.) Variants: <gdImageGifAnimEndCtx> outputs its data via a <gdIOCtx> struct. <gdImageGifAnimEndPtr> outputs its data to a memory buffer which it returns. Parameters: outfile - the destination FILE*. Returns: Nothing. */ BGD_DECLARE(void) gdImageGifAnimEnd(FILE *outFile) { #if 1 putc(';', outFile); #else gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) return; gdImageGifAnimEndCtx(out); out->gd_free(out); #endif } /* Function: gdImageGifAnimEndPtr Like <gdImageGifAnimEnd> (which contains more information) except that it stores the data to write into memory and returns a pointer to it. This memory must be freed by the caller when it is no longer needed. **The caller must invoke <gdFree>(), not free(),** unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time (but don't; it could always change). The 'size' parameter receives the total size of the block of memory. Parameters: size - Output: the size of the resulting buffer. Returns: Pointer to the resulting data or NULL if an error occurred. */ BGD_DECLARE(void *) gdImageGifAnimEndPtr(int *size) { char *rv = (char *) gdMalloc(1); if(!rv) { return 0; } *rv = ';'; *size = 1; return (void *)rv; } /* Function: gdImageGifAnimEndCtx Like <gdImageGifAnimEnd>, but writes its data via a <gdIOCtx>. Parameters: out - the destination <gdIOCtx>. Returns: Nothing. */ BGD_DECLARE(void) gdImageGifAnimEndCtx(gdIOCtx *out) { /* * Write the GIF file terminator */ gdPutC(';', out); } static int colorstobpp(int colors) { int bpp = 0; if(colors <= 2) bpp = 1; else if(colors <= 4) bpp = 2; else if(colors <= 8) bpp = 3; else if(colors <= 16) bpp = 4; else if(colors <= 32) bpp = 5; else if(colors <= 64) bpp = 6; else if(colors <= 128) bpp = 7; else if(colors <= 256) bpp = 8; return bpp; } /***************************************************************************** * * GIFENCODE.C - GIF Image compression interface * * GIFEncode( FName, GHeight, GWidth, GInterlace, Background, Transparent, * BitsPerPixel, Red, Green, Blue, gdImagePtr ) * *****************************************************************************/ #define TRUE 1 #define FALSE 0 /* Bump the 'curx' and 'cury' to point to the next pixel */ static void BumpPixel(GifCtx *ctx) { /* Bump the current X position */ ++(ctx->curx); /* If we are at the end of a scan line, set curx back to the beginning * If we are interlaced, bump the cury to the appropriate spot, * otherwise, just increment it. */ if(ctx->curx == ctx->Width) { ctx->curx = 0; if(!ctx->Interlace) { ++(ctx->cury); } else { switch(ctx->Pass) { case 0: ctx->cury += 8; if(ctx->cury >= ctx->Height) { ++(ctx->Pass); ctx->cury = 4; } break; case 1: ctx->cury += 8; if(ctx->cury >= ctx->Height) { ++(ctx->Pass); ctx->cury = 2; } break; case 2: ctx->cury += 4; if(ctx->cury >= ctx->Height) { ++(ctx->Pass); ctx->cury = 1; } break; case 3: ctx->cury += 2; break; } } } } /* Return the next pixel from the image */ static int GIFNextPixel(gdImagePtr im, GifCtx *ctx) { int r; if(ctx->CountDown == 0) { return EOF; } --(ctx->CountDown); r = gdImageGetPixel(im, ctx->curx, ctx->cury); BumpPixel(ctx); return r; } /* public */ static void GIFEncode(gdIOCtxPtr fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im) { int B; int RWidth, RHeight; int LeftOfs, TopOfs; int Resolution; int ColorMapSize; int InitCodeSize; int i; GifCtx ctx; memset(&ctx, 0, sizeof(ctx)); ctx.Interlace = GInterlace; ctx.in_count = 1; ColorMapSize = 1 << BitsPerPixel; RWidth = ctx.Width = GWidth; RHeight = ctx.Height = GHeight; LeftOfs = TopOfs = 0; Resolution = BitsPerPixel; /* Calculate number of bits we are expecting */ ctx.CountDown = (long)ctx.Width * (long)ctx.Height; /* Indicate which pass we are on (if interlace) */ ctx.Pass = 0; /* The initial code size */ if(BitsPerPixel <= 1) { InitCodeSize = 2; } else { InitCodeSize = BitsPerPixel; } /* Set up the current x and y position */ ctx.curx = ctx.cury = 0; /* Write the Magic header */ gdPutBuf(Transparent < 0 ? "GIF87a" : "GIF89a", 6, fp); /* Write out the screen width and height */ gifPutWord(RWidth, fp); gifPutWord(RHeight, fp); /* Indicate that there is a global colour map */ /* Yes, there is a color map */ B = 0x80; /* OR in the resolution */ B |= (Resolution - 1) << 4; /* OR in the Bits per Pixel */ B |= (BitsPerPixel - 1); /* Write it out */ gdPutC(B, fp); /* Write out the Background colour */ gdPutC(Background, fp); /* Byte of 0's (future expansion) */ gdPutC(0, fp); /* Write out the Global Colour Map */ for(i = 0; i < ColorMapSize; ++i) { gdPutC(Red[i], fp); gdPutC(Green[i], fp); gdPutC(Blue[i], fp); } /* Write out extension for transparent colour index, if necessary. */ if(Transparent >= 0) { gdPutC('!', fp); gdPutC(0xf9, fp); gdPutC(4, fp); gdPutC(1, fp); gdPutC(0, fp); gdPutC(0, fp); gdPutC((unsigned char) Transparent, fp); gdPutC(0, fp); } /* Write an Image separator */ gdPutC(',', fp); /* Write the Image header */ gifPutWord(LeftOfs, fp); gifPutWord(TopOfs, fp); gifPutWord(ctx.Width, fp); gifPutWord(ctx.Height, fp); /* Write out whether or not the image is interlaced */ if(ctx.Interlace) { gdPutC(0x40, fp); } else { gdPutC(0x00, fp); } /* Write out the initial code size */ gdPutC(InitCodeSize, fp); /* Go and actually compress the data */ compress(InitCodeSize + 1, fp, im, &ctx); /* Write out a Zero-length packet (to end the series) */ gdPutC(0, fp); /* Write the GIF file terminator */ gdPutC(';', fp); } static void GIFAnimEncode(gdIOCtxPtr fp, int IWidth, int IHeight, int LeftOfs, int TopOfs, int GInterlace, int Transparent, int Delay, int Disposal, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im) { int B; int ColorMapSize; int InitCodeSize; int i; GifCtx ctx; memset(&ctx, 0, sizeof(ctx)); ctx.Interlace = GInterlace; ctx.in_count = 1; ColorMapSize = 1 << BitsPerPixel; if(LeftOfs < 0) { LeftOfs = 0; } if(TopOfs < 0) { TopOfs = 0; } if(Delay < 0) { Delay = 100; } if(Disposal < 0) { Disposal = 1; } ctx.Width = IWidth; ctx.Height = IHeight; /* Calculate number of bits we are expecting */ ctx.CountDown = (long)ctx.Width * (long)ctx.Height; /* Indicate which pass we are on (if interlace) */ ctx.Pass = 0; /* The initial code size */ if(BitsPerPixel <= 1) { InitCodeSize = 2; } else { InitCodeSize = BitsPerPixel; } /* Set up the current x and y position */ ctx.curx = ctx.cury = 0; /* Write out extension for image animation and looping */ gdPutC('!', fp); gdPutC(0xf9, fp); gdPutC(4, fp); gdPutC((Transparent >= 0 ? 1 : 0) | (Disposal << 2), fp); gdPutC((unsigned char)(Delay & 255), fp); gdPutC((unsigned char)((Delay >> 8) & 255), fp); gdPutC((unsigned char) Transparent, fp); gdPutC(0, fp); /* Write an Image separator */ gdPutC(',', fp); /* Write out the Image header */ gifPutWord(LeftOfs, fp); gifPutWord(TopOfs, fp); gifPutWord(ctx.Width, fp); gifPutWord(ctx.Height, fp); /* Indicate that there is a local colour map */ B = (Red && Green && Blue) ? 0x80 : 0; /* OR in the interlacing */ B |= ctx.Interlace ? 0x40 : 0; /* OR in the Bits per Pixel */ B |= (Red && Green && Blue) ? (BitsPerPixel - 1) : 0; /* Write it out */ gdPutC(B, fp); /* Write out the Local Colour Map */ if(Red && Green && Blue) { for(i = 0; i < ColorMapSize; ++i) { gdPutC(Red[i], fp); gdPutC(Green[i], fp); gdPutC(Blue[i], fp); } } /* Write out the initial code size */ gdPutC(InitCodeSize, fp); /* Go and actually compress the data */ compress(InitCodeSize + 1, fp, im, &ctx); /* Write out a Zero-length packet (to end the series) */ gdPutC(0, fp); } /*************************************************************************** * * GIFCOMPR.C - GIF Image compression routines * * Lempel-Ziv compression based on 'compress'. GIF modifications by * David Rowley (mgardi@watdcsu.waterloo.edu) * ***************************************************************************/ /* General DEFINEs */ #define GIFBITS 12 #ifdef NO_UCHAR typedef char char_type; #else /* NO_UCHAR */ typedef unsigned char char_type; #endif /* NO_UCHAR */ /* * * GIF Image compression - modified 'compress' * * Based on: compress.c - File compression ala IEEE Computer, June 1984. * * By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) * Jim McKie (decvax!mcvax!jim) * Steve Davies (decvax!vax135!petsd!peora!srd) * Ken Turkowski (decvax!decwrl!turtlevax!ken) * James A. Woods (decvax!ihnp4!ames!jaw) * Joe Orost (decvax!vax135!petsd!joe) * */ #include <ctype.h> #define ARGVAL() (*++(*argv) || (--argc && *++argv)) #ifdef COMPATIBLE /* But wrong! */ # define MAXCODE(n_bits) ((code_int) 1 << (n_bits) - 1) #else /* COMPATIBLE */ # define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1) #endif /* COMPATIBLE */ #define HashTabOf(i) ctx->htab[i] #define CodeTabOf(i) ctx->codetab[i] /* * To save much memory, we overlay the table used by compress() with those * used by decompress(). The tab_prefix table is the same size and type * as the codetab. The tab_suffix table needs 2**GIFBITS characters. We * get this from the beginning of htab. The output stack uses the rest * of htab, and contains characters. There is plenty of room for any * possible stack (stack used to be 8000 characters). */ #define tab_prefixof(i) CodeTabOf(i) #define tab_suffixof(i) ((char_type*)(htab))[i] #define de_stack ((char_type*)&tab_suffixof((code_int)1 << GIFBITS)) /* * compress stdin to stdout * * Algorithm: use open addressing double hashing (no chaining) on the * prefix code / next character combination. We do a variant of Knuth's * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime * secondary probe. Here, the modular division first probe is gives way * to a faster exclusive-or manipulation. Also do block compression with * an adaptive reset, whereby the code table is cleared when the compression * ratio decreases, but after the table fills. The variable-length output * codes are re-sized at this point, and a special CLEAR code is generated * for the decompressor. Late addition: construct the table according to * file size for noticeable speed improvement on small files. Please direct * questions about this implementation to ames!jaw. */ static void output(code_int code, GifCtx *ctx); static void compress(int init_bits, gdIOCtxPtr outfile, gdImagePtr im, GifCtx *ctx) { register long fcode; register code_int i; register int c; register code_int ent; register code_int disp; register code_int hsize_reg; register int hshift; /* Set up the globals: * g_init_bits - initial number of bits * g_outfile - pointer to output file */ ctx->g_init_bits = init_bits; ctx->g_outfile = outfile; /* Set up the necessary values */ ctx->offset = 0; ctx->out_count = 0; ctx->clear_flg = 0; ctx->in_count = 1; ctx->maxcode = MAXCODE(ctx->n_bits = ctx->g_init_bits); ctx->ClearCode = (1 << (init_bits - 1)); ctx->EOFCode = ctx->ClearCode + 1; ctx->free_ent = ctx->ClearCode + 2; char_init(ctx); ent = GIFNextPixel(im, ctx); hshift = 0; for(fcode = (long)hsize; fcode < 65536L; fcode *= 2L) { ++hshift; } hshift = 8 - hshift; /* set hash code range bound */ hsize_reg = hsize; cl_hash((count_int) hsize_reg, ctx); /* clear hash table */ output((code_int)ctx->ClearCode, ctx); #ifdef SIGNED_COMPARE_SLOW while((c = GIFNextPixel(im)) != (unsigned) EOF) { #else /* SIGNED_COMPARE_SLOW */ while((c = GIFNextPixel(im, ctx)) != EOF) { #endif /* SIGNED_COMPARE_SLOW */ ++(ctx->in_count); fcode = (long) (((long) c << maxbits) + ent); i = (((code_int)c << hshift) ^ ent); /* xor hashing */ if(HashTabOf(i) == fcode) { ent = CodeTabOf (i); continue; } else if ((long)HashTabOf (i) < 0) {/* empty slot */ goto nomatch; } disp = hsize_reg - i; /* secondary hash (after G. Knott) */ if(i == 0) { disp = 1; } probe: if((i -= disp) < 0) { i += hsize_reg; } if(HashTabOf(i) == fcode) { ent = CodeTabOf (i); continue; } if((long)HashTabOf(i) > 0) { goto probe; } nomatch: output((code_int) ent, ctx); ++(ctx->out_count); ent = c; #ifdef SIGNED_COMPARE_SLOW if((unsigned) ctx->free_ent < (unsigned) maxmaxcode) { #else /*SIGNED_COMPARE_SLOW*/ if (ctx->free_ent < maxmaxcode) { /* } */ #endif /*SIGNED_COMPARE_SLOW*/ CodeTabOf(i) = ctx->free_ent++; /* code -> hashtable */ HashTabOf(i) = fcode; } else { cl_block(ctx); } } /* Put out the final code. */ output((code_int)ent, ctx); ++(ctx->out_count); output((code_int) ctx->EOFCode, ctx); } /***************************************************************** * TAG( output ) * * Output the given code. * Inputs: * code: A n_bits-bit integer. If == -1, then EOF. This assumes * that n_bits =< (long)wordsize - 1. * Outputs: * Outputs code to the file. * Assumptions: * Chars are 8 bits long. * Algorithm: * Maintain a GIFBITS character long buffer (so that 8 codes will * fit in it exactly). Use the VAX insv instruction to insert each * code in turn. When the buffer fills up empty it and start over. */ static const unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; /* Arbitrary value to mark output is done. When we see EOFCode, then we don't * expect to see any more data. If we do (e.g. corrupt image inputs), cur_bits * might be negative, so flag it to return early. */ #define CUR_BITS_FINISHED -1000 static void output(code_int code, GifCtx *ctx) { if (ctx->cur_bits == CUR_BITS_FINISHED) return; ctx->cur_accum &= masks[ctx->cur_bits]; if(ctx->cur_bits > 0) { ctx->cur_accum |= ((long)code << ctx->cur_bits); } else { ctx->cur_accum = code; } ctx->cur_bits += ctx->n_bits; while(ctx->cur_bits >= 8) { char_out((unsigned int)(ctx->cur_accum & 0xff), ctx); ctx->cur_accum >>= 8; ctx->cur_bits -= 8; } /* * If the next entry is going to be too big for the code size, * then increase it, if possible. */ if(ctx->free_ent > ctx->maxcode || ctx->clear_flg) { if(ctx->clear_flg) { ctx->maxcode = MAXCODE (ctx->n_bits = ctx->g_init_bits); ctx->clear_flg = 0; } else { ++(ctx->n_bits); if(ctx->n_bits == maxbits) { ctx->maxcode = maxmaxcode; } else { ctx->maxcode = MAXCODE(ctx->n_bits); } } } if(code == ctx->EOFCode) { /* At EOF, write the rest of the buffer. */ while(ctx->cur_bits > 0) { char_out((unsigned int)(ctx->cur_accum & 0xff), ctx); ctx->cur_accum >>= 8; ctx->cur_bits -= 8; } /* Flag that it's done to prevent re-entry. */ ctx->cur_bits = CUR_BITS_FINISHED; flush_char(ctx); } } /* * Clear out the hash table */ static void cl_block (GifCtx *ctx) /* table clear for block compress */ { cl_hash((count_int) hsize, ctx); ctx->free_ent = ctx->ClearCode + 2; ctx->clear_flg = 1; output((code_int)ctx->ClearCode, ctx); } static void cl_hash(register count_int chsize, GifCtx *ctx) /* reset code table */ { register count_int *htab_p = ctx->htab+chsize; register long i; register long m1 = -1; i = chsize - 16; do { /* might use Sys V memset(3) here */ *(htab_p - 16) = m1; *(htab_p - 15) = m1; *(htab_p - 14) = m1; *(htab_p - 13) = m1; *(htab_p - 12) = m1; *(htab_p - 11) = m1; *(htab_p - 10) = m1; *(htab_p - 9) = m1; *(htab_p - 8) = m1; *(htab_p - 7) = m1; *(htab_p - 6) = m1; *(htab_p - 5) = m1; *(htab_p - 4) = m1; *(htab_p - 3) = m1; *(htab_p - 2) = m1; *(htab_p - 1) = m1; htab_p -= 16; } while((i -= 16) >= 0); for(i += 16; i > 0; --i) { *--htab_p = m1; } } /****************************************************************************** * * GIF Specific routines * ******************************************************************************/ /* * Set up the 'byte output' routine */ static void char_init(GifCtx *ctx) { ctx->a_count = 0; } /* * Add a character to the end of the current packet, and if it is 254 * characters, flush the packet to disk. */ static void char_out(int c, GifCtx *ctx) { ctx->accum[ctx->a_count++] = c; if(ctx->a_count >= 254) { flush_char(ctx); } } /* * Flush the packet to disk, and reset the accumulator */ static void flush_char(GifCtx *ctx) { if(ctx->a_count > 0) { gdPutC(ctx->a_count, ctx->g_outfile); gdPutBuf(ctx->accum, ctx->a_count, ctx->g_outfile); ctx->a_count = 0; } } static int gifPutWord(int w, gdIOCtx *out) { /* Byte order is little-endian */ gdPutC(w & 0xFF, out); gdPutC((w >> 8) & 0xFF, out); return 0; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1406_0
crossvul-cpp_data_good_348_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL || sec_attr_len) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_7
crossvul-cpp_data_good_5168_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tsukada Takuya <tsukada@fminn.nagano.nagano.jp> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #if HAVE_MBREGEX #include "ext/standard/php_smart_str.h" #include "ext/standard/info.h" #include "php_mbregex.h" #include "mbstring.h" #include "php_onig_compat.h" /* must come prior to the oniguruma header */ #include <oniguruma.h> #undef UChar ZEND_EXTERN_MODULE_GLOBALS(mbstring) struct _zend_mb_regex_globals { OnigEncoding default_mbctype; OnigEncoding current_mbctype; HashTable ht_rc; zval *search_str; zval *search_str_val; unsigned int search_pos; php_mb_regex_t *search_re; OnigRegion *search_regs; OnigOptionType regex_default_options; OnigSyntaxType *regex_default_syntax; }; #define MBREX(g) (MBSTRG(mb_regex_globals)->g) /* {{{ static void php_mb_regex_free_cache() */ static void php_mb_regex_free_cache(php_mb_regex_t **pre) { onig_free(*pre); } /* }}} */ /* {{{ _php_mb_regex_globals_ctor */ static int _php_mb_regex_globals_ctor(zend_mb_regex_globals *pglobals TSRMLS_DC) { pglobals->default_mbctype = ONIG_ENCODING_EUC_JP; pglobals->current_mbctype = ONIG_ENCODING_EUC_JP; zend_hash_init(&(pglobals->ht_rc), 0, NULL, (void (*)(void *)) php_mb_regex_free_cache, 1); pglobals->search_str = (zval*) NULL; pglobals->search_re = (php_mb_regex_t*)NULL; pglobals->search_pos = 0; pglobals->search_regs = (OnigRegion*)NULL; pglobals->regex_default_options = ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; pglobals->regex_default_syntax = ONIG_SYNTAX_RUBY; return SUCCESS; } /* }}} */ /* {{{ _php_mb_regex_globals_dtor */ static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC) { zend_hash_destroy(&pglobals->ht_rc); } /* }}} */ /* {{{ php_mb_regex_globals_alloc */ zend_mb_regex_globals *php_mb_regex_globals_alloc(TSRMLS_D) { zend_mb_regex_globals *pglobals = pemalloc( sizeof(zend_mb_regex_globals), 1); if (!pglobals) { return NULL; } if (SUCCESS != _php_mb_regex_globals_ctor(pglobals TSRMLS_CC)) { pefree(pglobals, 1); return NULL; } return pglobals; } /* }}} */ /* {{{ php_mb_regex_globals_free */ void php_mb_regex_globals_free(zend_mb_regex_globals *pglobals TSRMLS_DC) { if (!pglobals) { return; } _php_mb_regex_globals_dtor(pglobals TSRMLS_CC); pefree(pglobals, 1); } /* }}} */ /* {{{ PHP_MINIT_FUNCTION(mb_regex) */ PHP_MINIT_FUNCTION(mb_regex) { onig_init(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION(mb_regex) */ PHP_MSHUTDOWN_FUNCTION(mb_regex) { onig_end(); return SUCCESS; } /* }}} */ /* {{{ PHP_RINIT_FUNCTION(mb_regex) */ PHP_RINIT_FUNCTION(mb_regex) { return MBSTRG(mb_regex_globals) ? SUCCESS: FAILURE; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION(mb_regex) */ PHP_RSHUTDOWN_FUNCTION(mb_regex) { MBREX(current_mbctype) = MBREX(default_mbctype); if (MBREX(search_str) != NULL) { zval_ptr_dtor(&MBREX(search_str)); MBREX(search_str) = (zval *)NULL; } MBREX(search_pos) = 0; if (MBREX(search_regs) != NULL) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *)NULL; } zend_hash_clean(&MBREX(ht_rc)); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION(mb_regex) */ PHP_MINFO_FUNCTION(mb_regex) { char buf[32]; php_info_print_table_start(); php_info_print_table_row(2, "Multibyte (japanese) regex support", "enabled"); snprintf(buf, sizeof(buf), "%d.%d.%d", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY); #ifdef PHP_ONIG_BUNDLED #ifdef USE_COMBINATION_EXPLOSION_CHECK php_info_print_table_row(2, "Multibyte regex (oniguruma) backtrack check", "On"); #else /* USE_COMBINATION_EXPLOSION_CHECK */ php_info_print_table_row(2, "Multibyte regex (oniguruma) backtrack check", "Off"); #endif /* USE_COMBINATION_EXPLOSION_CHECK */ #endif /* PHP_BUNDLED_ONIG */ php_info_print_table_row(2, "Multibyte regex (oniguruma) version", buf); php_info_print_table_end(); } /* }}} */ /* * encoding name resolver */ /* {{{ encoding name map */ typedef struct _php_mb_regex_enc_name_map_t { const char *names; OnigEncoding code; } php_mb_regex_enc_name_map_t; php_mb_regex_enc_name_map_t enc_name_map[] = { #ifdef ONIG_ENCODING_EUC_JP { "EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0", ONIG_ENCODING_EUC_JP }, #endif #ifdef ONIG_ENCODING_UTF8 { "UTF-8\0UTF8\0", ONIG_ENCODING_UTF8 }, #endif #ifdef ONIG_ENCODING_UTF16_BE { "UTF-16\0UTF-16BE\0", ONIG_ENCODING_UTF16_BE }, #endif #ifdef ONIG_ENCODING_UTF16_LE { "UTF-16LE\0", ONIG_ENCODING_UTF16_LE }, #endif #ifdef ONIG_ENCODING_UTF32_BE { "UCS-4\0UTF-32\0UTF-32BE\0", ONIG_ENCODING_UTF32_BE }, #endif #ifdef ONIG_ENCODING_UTF32_LE { "UCS-4LE\0UTF-32LE\0", ONIG_ENCODING_UTF32_LE }, #endif #ifdef ONIG_ENCODING_SJIS { "SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0", ONIG_ENCODING_SJIS }, #endif #ifdef ONIG_ENCODING_BIG5 { "BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0", ONIG_ENCODING_BIG5 }, #endif #ifdef ONIG_ENCODING_EUC_CN { "EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0", ONIG_ENCODING_EUC_CN }, #endif #ifdef ONIG_ENCODING_EUC_TW { "EUC-TW\0EUCTW\0EUC_TW\0", ONIG_ENCODING_EUC_TW }, #endif #ifdef ONIG_ENCODING_EUC_KR { "EUC-KR\0EUCKR\0EUC_KR\0", ONIG_ENCODING_EUC_KR }, #endif #if defined(ONIG_ENCODING_KOI8) && !PHP_ONIG_BAD_KOI8_ENTRY { "KOI8\0KOI-8\0", ONIG_ENCODING_KOI8 }, #endif #ifdef ONIG_ENCODING_KOI8_R { "KOI8R\0KOI8-R\0KOI-8R\0", ONIG_ENCODING_KOI8_R }, #endif #ifdef ONIG_ENCODING_ISO_8859_1 { "ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0", ONIG_ENCODING_ISO_8859_1 }, #endif #ifdef ONIG_ENCODING_ISO_8859_2 { "ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0", ONIG_ENCODING_ISO_8859_2 }, #endif #ifdef ONIG_ENCODING_ISO_8859_3 { "ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0", ONIG_ENCODING_ISO_8859_3 }, #endif #ifdef ONIG_ENCODING_ISO_8859_4 { "ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0", ONIG_ENCODING_ISO_8859_4 }, #endif #ifdef ONIG_ENCODING_ISO_8859_5 { "ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0", ONIG_ENCODING_ISO_8859_5 }, #endif #ifdef ONIG_ENCODING_ISO_8859_6 { "ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0", ONIG_ENCODING_ISO_8859_6 }, #endif #ifdef ONIG_ENCODING_ISO_8859_7 { "ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0", ONIG_ENCODING_ISO_8859_7 }, #endif #ifdef ONIG_ENCODING_ISO_8859_8 { "ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0", ONIG_ENCODING_ISO_8859_8 }, #endif #ifdef ONIG_ENCODING_ISO_8859_9 { "ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0", ONIG_ENCODING_ISO_8859_9 }, #endif #ifdef ONIG_ENCODING_ISO_8859_10 { "ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0", ONIG_ENCODING_ISO_8859_10 }, #endif #ifdef ONIG_ENCODING_ISO_8859_11 { "ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0", ONIG_ENCODING_ISO_8859_11 }, #endif #ifdef ONIG_ENCODING_ISO_8859_13 { "ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0", ONIG_ENCODING_ISO_8859_13 }, #endif #ifdef ONIG_ENCODING_ISO_8859_14 { "ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0", ONIG_ENCODING_ISO_8859_14 }, #endif #ifdef ONIG_ENCODING_ISO_8859_15 { "ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0", ONIG_ENCODING_ISO_8859_15 }, #endif #ifdef ONIG_ENCODING_ISO_8859_16 { "ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0", ONIG_ENCODING_ISO_8859_16 }, #endif #ifdef ONIG_ENCODING_ASCII { "ASCII\0US-ASCII\0US_ASCII\0ISO646\0", ONIG_ENCODING_ASCII }, #endif { NULL, ONIG_ENCODING_UNDEF } }; /* }}} */ /* {{{ php_mb_regex_name2mbctype */ static OnigEncoding _php_mb_regex_name2mbctype(const char *pname) { const char *p; php_mb_regex_enc_name_map_t *mapping; if (pname == NULL || !*pname) { return ONIG_ENCODING_UNDEF; } for (mapping = enc_name_map; mapping->names != NULL; mapping++) { for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) { if (strcasecmp(p, pname) == 0) { return mapping->code; } } } return ONIG_ENCODING_UNDEF; } /* }}} */ /* {{{ php_mb_regex_mbctype2name */ static const char *_php_mb_regex_mbctype2name(OnigEncoding mbctype) { php_mb_regex_enc_name_map_t *mapping; for (mapping = enc_name_map; mapping->names != NULL; mapping++) { if (mapping->code == mbctype) { return mapping->names; } } return NULL; } /* }}} */ /* {{{ php_mb_regex_set_mbctype */ int php_mb_regex_set_mbctype(const char *encname TSRMLS_DC) { OnigEncoding mbctype = _php_mb_regex_name2mbctype(encname); if (mbctype == ONIG_ENCODING_UNDEF) { return FAILURE; } MBREX(current_mbctype) = mbctype; return SUCCESS; } /* }}} */ /* {{{ php_mb_regex_set_default_mbctype */ int php_mb_regex_set_default_mbctype(const char *encname TSRMLS_DC) { OnigEncoding mbctype = _php_mb_regex_name2mbctype(encname); if (mbctype == ONIG_ENCODING_UNDEF) { return FAILURE; } MBREX(default_mbctype) = mbctype; return SUCCESS; } /* }}} */ /* {{{ php_mb_regex_get_mbctype */ const char *php_mb_regex_get_mbctype(TSRMLS_D) { return _php_mb_regex_mbctype2name(MBREX(current_mbctype)); } /* }}} */ /* {{{ php_mb_regex_get_default_mbctype */ const char *php_mb_regex_get_default_mbctype(TSRMLS_D) { return _php_mb_regex_mbctype2name(MBREX(default_mbctype)); } /* }}} */ /* * regex cache */ /* {{{ php_mbregex_compile_pattern */ static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC) { int err_code = 0; int found = 0; php_mb_regex_t *retval = NULL, **rc = NULL; OnigErrorInfo err_info; OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc); if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) { if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) { onig_error_code_to_str(err_str, err_code, err_info); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str); retval = NULL; goto out; } zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL); } else if (found == SUCCESS) { retval = *rc; } out: return retval; } /* }}} */ /* {{{ _php_mb_regex_get_option_string */ static size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } /* }}} */ /* {{{ _php_mb_regex_init_options */ static void _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != NULL) { n = 0; while(n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != NULL) *eval = 1; break; default: break; } } if (option != NULL) *option|=optm; } } /* }}} */ /* * php functions */ /* {{{ proto string mb_regex_encoding([string encoding]) Returns the current encoding for regex as a string. */ PHP_FUNCTION(mb_regex_encoding) { size_t argc = ZEND_NUM_ARGS(); char *encoding; int encoding_len; OnigEncoding mbctype; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &encoding, &encoding_len) == FAILURE) { return; } if (argc == 0) { const char *retval = _php_mb_regex_mbctype2name(MBREX(current_mbctype)); if (retval == NULL) { RETURN_FALSE; } RETURN_STRING((char *)retval, 1); } else if (argc == 1) { mbctype = _php_mb_regex_name2mbctype(encoding); if (mbctype == ONIG_ENCODING_UNDEF) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown encoding \"%s\"", encoding); RETURN_FALSE; } MBREX(current_mbctype) = mbctype; RETURN_TRUE; } } /* }}} */ /* {{{ _php_mb_regex_ereg_exec */ static void _php_mb_regex_ereg_exec(INTERNAL_FUNCTION_PARAMETERS, int icase) { zval **arg_pattern, *array; char *string; int string_len; php_mb_regex_t *re; OnigRegion *regs = NULL; int i, match_len, beg, end; OnigOptionType options; char *str; array = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zs|z", &arg_pattern, &string, &string_len, &array) == FAILURE) { RETURN_FALSE; } options = MBREX(regex_default_options); if (icase) { options |= ONIG_OPTION_IGNORECASE; } /* compile the regular expression from the supplied regex */ if (Z_TYPE_PP(arg_pattern) != IS_STRING) { /* we convert numbers to integers and treat them as a string */ if (Z_TYPE_PP(arg_pattern) == IS_DOUBLE) { convert_to_long_ex(arg_pattern); /* get rid of decimal places */ } convert_to_string_ex(arg_pattern); /* don't bother doing an extended regex with just a number */ } if (!Z_STRVAL_PP(arg_pattern) || Z_STRLEN_PP(arg_pattern) == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "empty pattern"); RETVAL_FALSE; goto out; } re = php_mbregex_compile_pattern(Z_STRVAL_PP(arg_pattern), Z_STRLEN_PP(arg_pattern), options, MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC); if (re == NULL) { RETVAL_FALSE; goto out; } regs = onig_region_new(); /* actually execute the regular expression */ if (onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), (OnigUChar *)string, (OnigUChar *)(string + string_len), regs, 0) < 0) { RETVAL_FALSE; goto out; } match_len = 1; str = string; if (array != NULL) { match_len = regs->end[0] - regs->beg[0]; zval_dtor(array); array_init(array); for (i = 0; i < regs->num_regs; i++) { beg = regs->beg[i]; end = regs->end[i]; if (beg >= 0 && beg < end && end <= string_len) { add_index_stringl(array, i, (char *)&str[beg], end - beg, 1); } else { add_index_bool(array, i, 0); } } } if (match_len == 0) { match_len = 1; } RETVAL_LONG(match_len); out: if (regs != NULL) { onig_region_free(regs, 1); } } /* }}} */ /* {{{ proto int mb_ereg(string pattern, string string [, array registers]) Regular expression match for multibyte string */ PHP_FUNCTION(mb_ereg) { _php_mb_regex_ereg_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int mb_eregi(string pattern, string string [, array registers]) Case-insensitive regular expression match for multibyte string */ PHP_FUNCTION(mb_eregi) { _php_mb_regex_ereg_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ _php_mb_regex_ereg_replace_exec */ static void _php_mb_regex_ereg_replace_exec(INTERNAL_FUNCTION_PARAMETERS, OnigOptionType options, int is_callable) { zval **arg_pattern_zval; char *arg_pattern; int arg_pattern_len; char *replace; int replace_len; zend_fcall_info arg_replace_fci; zend_fcall_info_cache arg_replace_fci_cache; char *string; int string_len; char *p; php_mb_regex_t *re; OnigSyntaxType *syntax; OnigRegion *regs = NULL; smart_str out_buf = { 0 }; smart_str eval_buf = { 0 }; smart_str *pbuf; int i, err, eval, n; OnigUChar *pos; OnigUChar *string_lim; char *description = NULL; char pat_buf[2]; const mbfl_encoding *enc; { const char *current_enc_name; current_enc_name = _php_mb_regex_mbctype2name(MBREX(current_mbctype)); if (current_enc_name == NULL || (enc = mbfl_name2encoding(current_enc_name)) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error"); RETURN_FALSE; } } eval = 0; { char *option_str = NULL; int option_str_len = 0; if (!is_callable) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zss|s", &arg_pattern_zval, &replace, &replace_len, &string, &string_len, &option_str, &option_str_len) == FAILURE) { RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zfs|s", &arg_pattern_zval, &arg_replace_fci, &arg_replace_fci_cache, &string, &string_len, &option_str, &option_str_len) == FAILURE) { RETURN_FALSE; } } if (option_str != NULL) { _php_mb_regex_init_options(option_str, option_str_len, &options, &syntax, &eval); } else { options |= MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); } } if (Z_TYPE_PP(arg_pattern_zval) == IS_STRING) { arg_pattern = Z_STRVAL_PP(arg_pattern_zval); arg_pattern_len = Z_STRLEN_PP(arg_pattern_zval); } else { /* FIXME: this code is not multibyte aware! */ convert_to_long_ex(arg_pattern_zval); pat_buf[0] = (char)Z_LVAL_PP(arg_pattern_zval); pat_buf[1] = '\0'; arg_pattern = pat_buf; arg_pattern_len = 1; } /* create regex pattern buffer */ re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, options, MBREX(current_mbctype), syntax TSRMLS_CC); if (re == NULL) { RETURN_FALSE; } if (eval || is_callable) { pbuf = &eval_buf; description = zend_make_compiled_string_description("mbregex replace" TSRMLS_CC); } else { pbuf = &out_buf; description = NULL; } if (is_callable) { if (eval) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Option 'e' cannot be used with replacement callback"); RETURN_FALSE; } } /* do the actual work */ err = 0; pos = (OnigUChar *)string; string_lim = (OnigUChar*)(string + string_len); regs = onig_region_new(); while (err >= 0) { err = onig_search(re, (OnigUChar *)string, (OnigUChar *)string_lim, pos, (OnigUChar *)string_lim, regs, 0); if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in php_mbereg_replace_exec(): %s", err_str); break; } if (err >= 0) { #if moriyoshi_0 if (regs->beg[0] == regs->end[0]) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty regular expression"); break; } #endif /* copy the part of the string before the match */ smart_str_appendl(&out_buf, pos, (size_t)((OnigUChar *)(string + regs->beg[0]) - pos)); if (!is_callable) { /* copy replacement and backrefs */ i = 0; p = replace; while (i < replace_len) { int fwd = (int) php_mb_mbchar_bytes_ex(p, enc); n = -1; if ((replace_len - i) >= 2 && fwd == 1 && p[0] == '\\' && p[1] >= '0' && p[1] <= '9') { n = p[1] - '0'; } if (n >= 0 && n < regs->num_regs) { if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] && regs->end[n] <= string_len) { smart_str_appendl(pbuf, string + regs->beg[n], regs->end[n] - regs->beg[n]); } p += 2; i += 2; } else { smart_str_appendl(pbuf, p, fwd); p += fwd; i += fwd; } } } if (eval) { zval v; /* null terminate buffer */ smart_str_0(&eval_buf); /* do eval */ if (zend_eval_stringl(eval_buf.c, eval_buf.len, &v, description TSRMLS_CC) == FAILURE) { efree(description); php_error_docref(NULL TSRMLS_CC,E_ERROR, "Failed evaluating code: %s%s", PHP_EOL, eval_buf.c); /* zend_error() does not return in this case */ } /* result of eval */ convert_to_string(&v); smart_str_appendl(&out_buf, Z_STRVAL(v), Z_STRLEN(v)); /* Clean up */ eval_buf.len = 0; zval_dtor(&v); } else if (is_callable) { zval *retval_ptr = NULL; zval **args[1]; zval *subpats; int i; MAKE_STD_ZVAL(subpats); array_init(subpats); for (i = 0; i < regs->num_regs; i++) { add_next_index_stringl(subpats, string + regs->beg[i], regs->end[i] - regs->beg[i], 1); } args[0] = &subpats; /* null terminate buffer */ smart_str_0(&eval_buf); arg_replace_fci.param_count = 1; arg_replace_fci.params = args; arg_replace_fci.retval_ptr_ptr = &retval_ptr; if (zend_call_function(&arg_replace_fci, &arg_replace_fci_cache TSRMLS_CC) == SUCCESS && arg_replace_fci.retval_ptr_ptr && retval_ptr) { convert_to_string_ex(&retval_ptr); smart_str_appendl(&out_buf, Z_STRVAL_P(retval_ptr), Z_STRLEN_P(retval_ptr)); eval_buf.len = 0; zval_ptr_dtor(&retval_ptr); } else { if (!EG(exception)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call custom replacement function"); } } zval_ptr_dtor(&subpats); } n = regs->end[0]; if ((pos - (OnigUChar *)string) < n) { pos = (OnigUChar *)string + n; } else { if (pos < string_lim) { smart_str_appendl(&out_buf, pos, 1); } pos++; } } else { /* nomatch */ /* stick that last bit of string on our output */ if (string_lim - pos > 0) { smart_str_appendl(&out_buf, pos, string_lim - pos); } } onig_region_free(regs, 0); } if (description) { efree(description); } if (regs != NULL) { onig_region_free(regs, 1); } smart_str_free(&eval_buf); if (err <= -2) { smart_str_free(&out_buf); RETVAL_FALSE; } else { smart_str_appendc(&out_buf, '\0'); RETVAL_STRINGL((char *)out_buf.c, out_buf.len - 1, 0); } } /* }}} */ /* {{{ proto string mb_ereg_replace(string pattern, string replacement, string string [, string option]) Replace regular expression for multibyte string */ PHP_FUNCTION(mb_ereg_replace) { _php_mb_regex_ereg_replace_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 0); } /* }}} */ /* {{{ proto string mb_eregi_replace(string pattern, string replacement, string string) Case insensitive replace regular expression for multibyte string */ PHP_FUNCTION(mb_eregi_replace) { _php_mb_regex_ereg_replace_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, ONIG_OPTION_IGNORECASE, 0); } /* }}} */ /* {{{ proto string mb_ereg_replace_callback(string pattern, string callback, string string [, string option]) regular expression for multibyte string using replacement callback */ PHP_FUNCTION(mb_ereg_replace_callback) { _php_mb_regex_ereg_replace_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 1); } /* }}} */ /* {{{ proto array mb_split(string pattern, string string [, int limit]) split multibyte string into array by regular expression */ PHP_FUNCTION(mb_split) { char *arg_pattern; int arg_pattern_len; php_mb_regex_t *re; OnigRegion *regs = NULL; char *string; OnigUChar *pos, *chunk_pos; int string_len; int n, err; long count = -1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) { RETURN_FALSE; } if (count > 0) { count--; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC)) == NULL) { RETURN_FALSE; } array_init(return_value); chunk_pos = pos = (OnigUChar *)string; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while (count != 0 && (pos - (OnigUChar *)string) < string_len) { int beg, end; err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0); if (err < 0) { break; } beg = regs->beg[0], end = regs->end[0]; /* add it to the array */ if ((pos - (OnigUChar *)string) < end) { if (beg < string_len && beg >= (chunk_pos - (OnigUChar *)string)) { add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos), 1); --count; } else { err = -2; break; } /* point at our new starting point */ chunk_pos = pos = (OnigUChar *)string + end; } else { pos++; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str); zval_dtor(return_value); RETURN_FALSE; } /* otherwise we just have one last element to add to the array */ n = ((OnigUChar *)(string + string_len) - chunk_pos); if (n > 0) { add_next_index_stringl(return_value, (char *)chunk_pos, n, 1); } else { add_next_index_stringl(return_value, "", 0, 1); } } /* }}} */ /* {{{ proto bool mb_ereg_match(string pattern, string string [,string option]) Regular expression match for multibyte string */ PHP_FUNCTION(mb_ereg_match) { char *arg_pattern; int arg_pattern_len; char *string; int string_len; php_mb_regex_t *re; OnigSyntaxType *syntax; OnigOptionType option = 0; int err; { char *option_str = NULL; int option_str_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|s", &arg_pattern, &arg_pattern_len, &string, &string_len, &option_str, &option_str_len)==FAILURE) { RETURN_FALSE; } if (option_str != NULL) { _php_mb_regex_init_options(option_str, option_str_len, &option, &syntax, NULL); } else { option |= MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); } } if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) { RETURN_FALSE; } /* match */ err = onig_match(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), (OnigUChar *)string, NULL, 0); if (err >= 0) { RETVAL_TRUE; } else { RETVAL_FALSE; } } /* }}} */ /* regex search */ /* {{{ _php_mb_regex_ereg_search_exec */ static void _php_mb_regex_ereg_search_exec(INTERNAL_FUNCTION_PARAMETERS, int mode) { size_t argc = ZEND_NUM_ARGS(); char *arg_pattern, *arg_options; int arg_pattern_len, arg_options_len; int n, i, err, pos, len, beg, end; OnigOptionType option; OnigUChar *str; OnigSyntaxType *syntax; if (zend_parse_parameters(argc TSRMLS_CC, "|ss", &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) { return; } option = MBREX(regex_default_options); if (argc == 2) { option = 0; _php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL); } if (argc > 0) { /* create regex pattern buffer */ if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), MBREX(regex_default_syntax) TSRMLS_CC)) == NULL) { RETURN_FALSE; } } pos = MBREX(search_pos); str = NULL; len = 0; if (MBREX(search_str) != NULL && Z_TYPE_P(MBREX(search_str)) == IS_STRING){ str = (OnigUChar *)Z_STRVAL_P(MBREX(search_str)); len = Z_STRLEN_P(MBREX(search_str)); } if (MBREX(search_re) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No regex given"); RETURN_FALSE; } if (str == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No string given"); RETURN_FALSE; } if (MBREX(search_regs)) { onig_region_free(MBREX(search_regs), 1); } MBREX(search_regs) = onig_region_new(); err = onig_search(MBREX(search_re), str, str + len, str + pos, str + len, MBREX(search_regs), 0); if (err == ONIG_MISMATCH) { MBREX(search_pos) = len; RETVAL_FALSE; } else if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex search failure in mbregex_search(): %s", err_str); RETVAL_FALSE; } else { if (MBREX(search_regs)->beg[0] == MBREX(search_regs)->end[0]) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty regular expression"); } switch (mode) { case 1: array_init(return_value); beg = MBREX(search_regs)->beg[0]; end = MBREX(search_regs)->end[0]; add_next_index_long(return_value, beg); add_next_index_long(return_value, end - beg); break; case 2: array_init(return_value); n = MBREX(search_regs)->num_regs; for (i = 0; i < n; i++) { beg = MBREX(search_regs)->beg[i]; end = MBREX(search_regs)->end[i]; if (beg >= 0 && beg <= end && end <= len) { add_index_stringl(return_value, i, (char *)&str[beg], end - beg, 1); } else { add_index_bool(return_value, i, 0); } } break; default: RETVAL_TRUE; break; } end = MBREX(search_regs)->end[0]; if (pos < end) { MBREX(search_pos) = end; } else { MBREX(search_pos) = pos + 1; } } if (err < 0) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *)NULL; } } /* }}} */ /* {{{ proto bool mb_ereg_search([string pattern[, string option]]) Regular expression search for multibyte string */ PHP_FUNCTION(mb_ereg_search) { _php_mb_regex_ereg_search_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto array mb_ereg_search_pos([string pattern[, string option]]) Regular expression search for multibyte string */ PHP_FUNCTION(mb_ereg_search_pos) { _php_mb_regex_ereg_search_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto array mb_ereg_search_regs([string pattern[, string option]]) Regular expression search for multibyte string */ PHP_FUNCTION(mb_ereg_search_regs) { _php_mb_regex_ereg_search_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2); } /* }}} */ /* {{{ proto bool mb_ereg_search_init(string string [, string pattern[, string option]]) Initialize string and regular expression for search. */ PHP_FUNCTION(mb_ereg_search_init) { size_t argc = ZEND_NUM_ARGS(); zval *arg_str; char *arg_pattern = NULL, *arg_options = NULL; int arg_pattern_len = 0, arg_options_len = 0; OnigSyntaxType *syntax = NULL; OnigOptionType option; if (zend_parse_parameters(argc TSRMLS_CC, "z|ss", &arg_str, &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) { return; } if (argc > 1 && arg_pattern_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty pattern"); RETURN_FALSE; } option = MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); if (argc == 3) { option = 0; _php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL); } if (argc > 1) { /* create regex pattern buffer */ if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) { RETURN_FALSE; } } if (MBREX(search_str) != NULL) { zval_ptr_dtor(&MBREX(search_str)); MBREX(search_str) = (zval *)NULL; } MBREX(search_str) = arg_str; Z_ADDREF_P(MBREX(search_str)); SEPARATE_ZVAL_IF_NOT_REF(&MBREX(search_str)); MBREX(search_pos) = 0; if (MBREX(search_regs) != NULL) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *) NULL; } RETURN_TRUE; } /* }}} */ /* {{{ proto array mb_ereg_search_getregs(void) Get matched substring of the last time */ PHP_FUNCTION(mb_ereg_search_getregs) { int n, i, len, beg, end; OnigUChar *str; if (MBREX(search_regs) != NULL && Z_TYPE_P(MBREX(search_str)) == IS_STRING && Z_STRVAL_P(MBREX(search_str)) != NULL) { array_init(return_value); str = (OnigUChar *)Z_STRVAL_P(MBREX(search_str)); len = Z_STRLEN_P(MBREX(search_str)); n = MBREX(search_regs)->num_regs; for (i = 0; i < n; i++) { beg = MBREX(search_regs)->beg[i]; end = MBREX(search_regs)->end[i]; if (beg >= 0 && beg <= end && end <= len) { add_index_stringl(return_value, i, (char *)&str[beg], end - beg, 1); } else { add_index_bool(return_value, i, 0); } } } else { RETVAL_FALSE; } } /* }}} */ /* {{{ proto int mb_ereg_search_getpos(void) Get search start position */ PHP_FUNCTION(mb_ereg_search_getpos) { RETVAL_LONG(MBREX(search_pos)); } /* }}} */ /* {{{ proto bool mb_ereg_search_setpos(int position) Set search start position */ PHP_FUNCTION(mb_ereg_search_setpos) { long position; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &position) == FAILURE) { return; } if (position < 0 || (MBREX(search_str) != NULL && Z_TYPE_P(MBREX(search_str)) == IS_STRING && position >= Z_STRLEN_P(MBREX(search_str)))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Position is out of range"); MBREX(search_pos) = 0; RETURN_FALSE; } MBREX(search_pos) = position; RETURN_TRUE; } /* }}} */ /* {{{ php_mb_regex_set_options */ static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) { if (prev_options != NULL) { *prev_options = MBREX(regex_default_options); } if (prev_syntax != NULL) { *prev_syntax = MBREX(regex_default_syntax); } MBREX(regex_default_options) = options; MBREX(regex_default_syntax) = syntax; } /* }}} */ /* {{{ proto string mb_regex_set_options([string options]) Set or get the default options for mbregex functions */ PHP_FUNCTION(mb_regex_set_options) { OnigOptionType opt; OnigSyntaxType *syntax; char *string = NULL; int string_len; char buf[16]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &string, &string_len) == FAILURE) { RETURN_FALSE; } if (string != NULL) { opt = 0; syntax = NULL; _php_mb_regex_init_options(string, string_len, &opt, &syntax, NULL); _php_mb_regex_set_options(opt, syntax, NULL, NULL TSRMLS_CC); } else { opt = MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); } _php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax); RETVAL_STRING(buf, 1); } /* }}} */ #endif /* HAVE_MBREGEX */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: fdm=marker * vim: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-415/c/good_5168_0
crossvul-cpp_data_good_347_3
/* * card-tcos.c: Support for TCOS cards * * Copyright (C) 2011 Peter Koch <pk@opensc-project.org> * Copyright (C) 2002 g10 Code GmbH * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <ctype.h> #include <time.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table tcos_atrs[] = { /* Infineon SLE44 */ { "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66S */ { "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX320P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX322P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Philips P5CT072 */ { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, /* Philips P5CT080 */ { "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_card_operations tcos_ops; static struct sc_card_driver tcos_drv = { "TCOS 3.0", "tcos", &tcos_ops, NULL, 0, NULL }; static const struct sc_card_operations *iso_ops = NULL; typedef struct tcos_data_st { unsigned int pad_flags; unsigned int next_sign; } tcos_data; static int tcos_finish(sc_card_t *card) { free(card->drv_data); return 0; } static int tcos_match_card(sc_card_t *card) { int i; i = _sc_match_atr(card, tcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int tcos_init(sc_card_t *card) { unsigned long flags; tcos_data *data = malloc(sizeof(tcos_data)); if (!data) return SC_ERROR_OUT_OF_MEMORY; card->name = "TCOS"; card->drv_data = (void *)data; card->cla = 0x00; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); if (card->type == SC_CARD_TYPE_TCOS_V3) { card->caps |= SC_CARD_CAP_APDU_EXT; _sc_card_add_rsa_alg(card, 1280, flags, 0); _sc_card_add_rsa_alg(card, 1536, flags, 0); _sc_card_add_rsa_alg(card, 1792, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return 0; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static int tcos_construct_fci(const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; size_t n; /* FIXME: possible buffer overflow */ *p++ = 0x6F; /* FCI */ p++; /* File size */ buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x81, buf, 2, p, 16, &p); /* File descriptor */ n = 0; buf[n] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_WORKING_EF: break; case SC_FILE_TYPE_DF: buf[0] |= 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } buf[n++] |= file->ef_structure & 7; if ( (file->ef_structure & 7) > 1) { /* record structured file */ buf[n++] = 0x41; /* indicate 3rd byte */ buf[n++] = file->record_length; } sc_asn1_put_tag(0x82, buf, n, p, 8, &p); /* File identifier */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, 16, &p); /* Directory name */ if (file->type == SC_FILE_TYPE_DF) { if (file->namelen) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, 16, &p); } else { /* TCOS needs one, so we use a faked one */ snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu", (unsigned long) time (NULL)); sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p); } } /* File descriptor extension */ if (file->prop_attr_len && file->prop_attr) { n = file->prop_attr_len; memcpy(buf, file->prop_attr, n); } else { n = 0; buf[n++] = 0x01; /* not invalidated, permanent */ if (file->type == SC_FILE_TYPE_WORKING_EF) buf[n++] = 0x00; /* generic data file */ } sc_asn1_put_tag(0x85, buf, n, p, 16, &p); /* Security attributes */ if (file->sec_attr_len && file->sec_attr) { memcpy(buf, file->sec_attr, file->sec_attr_len); n = file->sec_attr_len; } else { /* no attributes given - fall back to default one */ memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */ memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */ memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */ memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/ n = 24; } sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p); /* fixup length of FCI */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int tcos_create_file(sc_card_t *card, sc_file_t *file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; len = SC_MAX_APDU_BUFFER_SIZE; r = tcos_construct_fci(file, sbuf, &len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.cla |= 0x80; /* this is an proprietary extension */ apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static unsigned int map_operations (int commandbyte ) { unsigned int op = (unsigned int)-1; switch ( (commandbyte & 0xfe) ) { case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break; case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break; case 0xe0: /* create */ op = SC_AC_OP_CREATE; break; case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break; case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break; case 0x82: /* external auth */ op = SC_AC_OP_READ; break; case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break; case 0x88: /* internal auth */ op = SC_AC_OP_READ; break; case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break; case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break; case 0xb0: /* read binary */ op = SC_AC_OP_READ; break; case 0xb2: /* read record */ op = SC_AC_OP_READ; break; case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break; case 0xa4: /* select */ op = SC_AC_OP_SELECT; break; case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break; case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break; case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break; case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break; case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break; case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break; } return op; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static void parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { unsigned int op; /* list directory is not covered by ACLs - so always add an entry */ sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES, SC_AC_NONE, SC_AC_KEY_REF_NONE); /* FIXME: check for what LOCK is used */ sc_file_add_acl_entry (file, SC_AC_OP_LOCK, SC_AC_NONE, SC_AC_KEY_REF_NONE); for (; len >= 6; len -= 6, buf += 6) { /* FIXME: temporary hacks */ if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */ sc_file_add_acl_entry (file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/ sc_file_add_acl_entry (file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/ sc_file_add_acl_entry (file, SC_AC_OP_UPDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */ sc_file_add_acl_entry (file, SC_AC_OP_WRITE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_CREATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else { /* the first byte tells use the command or the command group. We have to mask bit 0 because this one distinguish between AND/OR combination of PINs*/ op = map_operations (buf[0]); if (op == (unsigned int)-1) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown security command byte %02x\n", buf[0]); continue; } if (!buf[1]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_CHV, buf[1]); if (!buf[2] && !buf[3]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_TERM, (buf[2]<<8)|buf[3]); } } } static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ size_t j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: file->namelen = MIN(sizeof file->name, len); memcpy(file->name, d, file->namelen); break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1; int r, count = 0; assert(card != NULL); ctx = card->ctx; for (p1=1; p1<=2; p1++) { sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n", apdu.resplen / 2, p1 == 1 ? "DF" : "EF"); memcpy(buf, apdu.resp, apdu.resplen); buf += apdu.resplen; buflen -= apdu.resplen; count += apdu.resplen; } return count; } static int tcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r; u8 sbuf[2]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } sbuf[0] = path->value[0]; sbuf[1] = path->value[1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_context_t *ctx; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p; int r, default_key, tcos3; tcos_data *data; assert(card != NULL && env != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "No Key-Reference in SecEnvironment\n"); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n", env->key_ref[0], env->key_ref_len); /* Key-Reference 0x80 ?? */ default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n", tcos3, !!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); data->pad_flags = env->algorithm_flags; data->next_sign = default_key; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8); p = sbuf; *p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10; if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { *p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } apdu.data = sbuf; apdu.lc = apdu.datalen = (p - sbuf); r=sc_transmit_apdu(card, &apdu); if (r) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Detected Signature-Only key\n"); if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS; } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_restore_security_env(sc_card_t *card, int se_num) { return 0; } static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { size_t i, dlen=datalen; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int tcos3, r; assert(card != NULL && data != NULL && out != NULL); tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); if(((tcos_data *)card->drv_data)->next_sign){ if(datalen>48){ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A); memcpy(sbuf, data, datalen); dlen=datalen; } else { int keylen= tcos3 ? 256 : 128; sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = tcos3 ? 256 : 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) { int keylen=128; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); } if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len = apdu.resplen>outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){ offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset; offset=(offset<len-1) ? offset+1 : 0; } memcpy(out, apdu.resp+offset, len-offset); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the NullPIN method will be activated, otherwise the permanent operation will be done on the active file. */ static int tcos_setperm(sc_card_t *card, int enable_nullpin) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 0; apdu.datalen = 0; apdu.data = NULL; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; if (!serial) return SC_ERROR_INVALID_ARGUMENTS; /* see if we have cached serial number */ if (card->serialnr.len) { memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } card->serialnr.len = sizeof card->serialnr.value; r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0); if (r < 0) { card->serialnr.len = 0; return r; } /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_TCOS_SETPERM: return tcos_setperm(card, !!ptr); case SC_CARDCTL_GET_SERIALNR: return tcos_get_serialnr(card, (sc_serial_number_t *)ptr); } return SC_ERROR_NOT_SUPPORTED; } struct sc_card_driver * sc_get_tcos_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; tcos_ops = *iso_drv->ops; tcos_ops.match_card = tcos_match_card; tcos_ops.init = tcos_init; tcos_ops.finish = tcos_finish; tcos_ops.create_file = tcos_create_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.select_file = tcos_select_file; tcos_ops.list_files = tcos_list_files; tcos_ops.delete_file = tcos_delete_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.compute_signature = tcos_compute_signature; tcos_ops.decipher = tcos_decipher; tcos_ops.restore_security_env = tcos_restore_security_env; tcos_ops.card_ctl = tcos_card_ctl; return &tcos_drv; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_3
crossvul-cpp_data_bad_1360_0
/** * @file parser_yang.c * @author Pavol Vican * @brief YANG parser for libyang * * Copyright (c) 2015 CESNET, z.s.p.o. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #include <ctype.h> #include <assert.h> #include "parser_yang.h" #include "parser_yang_lex.h" #include "parser.h" #include "xpath.h" static void yang_free_import(struct ly_ctx *ctx, struct lys_import *imp, uint8_t start, uint8_t size); static int yang_check_must(struct lys_module *module, struct lys_restr *must, uint size, struct unres_schema *unres); static void yang_free_include(struct ly_ctx *ctx, struct lys_include *inc, uint8_t start, uint8_t size); static int yang_check_sub_module(struct lys_module *module, struct unres_schema *unres, struct lys_node *node); static void free_yang_common(struct lys_module *module, struct lys_node *node); static int yang_check_nodes(struct lys_module *module, struct lys_node *parent, struct lys_node *nodes, int options, struct unres_schema *unres); static int yang_fill_ext_substm_index(struct lys_ext_instance_complex *ext, LY_STMT stmt, enum yytokentype keyword); static void yang_free_nodes(struct ly_ctx *ctx, struct lys_node *node); void lys_iffeature_free(struct ly_ctx *ctx, struct lys_iffeature *iffeature, uint8_t iffeature_size, int shallow, void (*private_destructor)(const struct lys_node *node, void *priv)); static int yang_check_string(struct lys_module *module, const char **target, char *what, char *where, char *value, struct lys_node *node) { if (*target) { LOGVAL(module->ctx, LYE_TOOMANY, (node) ? LY_VLOG_LYS : LY_VLOG_NONE, node, what, where); free(value); return 1; } else { *target = lydict_insert_zc(module->ctx, value); return 0; } } int yang_read_common(struct lys_module *module, char *value, enum yytokentype type) { int ret = 0; switch (type) { case MODULE_KEYWORD: module->name = lydict_insert_zc(module->ctx, value); break; case NAMESPACE_KEYWORD: ret = yang_check_string(module, &module->ns, "namespace", "module", value, NULL); break; case ORGANIZATION_KEYWORD: ret = yang_check_string(module, &module->org, "organization", "module", value, NULL); break; case CONTACT_KEYWORD: ret = yang_check_string(module, &module->contact, "contact", "module", value, NULL); break; default: free(value); LOGINT(module->ctx); ret = EXIT_FAILURE; break; } return ret; } int yang_check_version(struct lys_module *module, struct lys_submodule *submodule, char *value, int repeat) { int ret = EXIT_SUCCESS; if (repeat) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "yang version", "module"); ret = EXIT_FAILURE; } else { if (!strcmp(value, "1")) { if (submodule) { if (module->version > 1) { LOGVAL(module->ctx, LYE_INVER, LY_VLOG_NONE, NULL); ret = EXIT_FAILURE; } submodule->version = 1; } else { module->version = 1; } } else if (!strcmp(value, "1.1")) { if (submodule) { if (module->version != 2) { LOGVAL(module->ctx, LYE_INVER, LY_VLOG_NONE, NULL); ret = EXIT_FAILURE; } submodule->version = 2; } else { module->version = 2; } } else { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "yang-version"); ret = EXIT_FAILURE; } } free(value); return ret; } int yang_read_prefix(struct lys_module *module, struct lys_import *imp, char *value) { int ret = 0; if (!imp && lyp_check_identifier(module->ctx, value, LY_IDENT_PREFIX, module, NULL)) { free(value); return EXIT_FAILURE; } if (imp) { ret = yang_check_string(module, &imp->prefix, "prefix", "import", value, NULL); } else { ret = yang_check_string(module, &module->prefix, "prefix", "module", value, NULL); } return ret; } static int yang_fill_import(struct lys_module *module, struct lys_import *imp_old, struct lys_import *imp_new, char *value, struct unres_schema *unres) { const char *exp; int rc; if (!imp_old->prefix) { LOGVAL(module->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "import"); goto error; } else { if (lyp_check_identifier(module->ctx, imp_old->prefix, LY_IDENT_PREFIX, module, NULL)) { goto error; } } memcpy(imp_new, imp_old, sizeof *imp_old); exp = lydict_insert_zc(module->ctx, value); rc = lyp_check_import(module, exp, imp_new); lydict_remove(module->ctx, exp); module->imp_size++; if (rc || yang_check_ext_instance(module, &imp_new->ext, imp_new->ext_size, imp_new, unres)) { return EXIT_FAILURE; } return EXIT_SUCCESS; error: free(value); lydict_remove(module->ctx, imp_old->dsc); lydict_remove(module->ctx, imp_old->ref); lydict_remove(module->ctx, imp_old->prefix); lys_extension_instances_free(module->ctx, imp_old->ext, imp_old->ext_size, NULL); return EXIT_FAILURE; } int yang_read_description(struct lys_module *module, void *node, char *value, char *where, enum yytokentype type) { int ret; char *dsc = "description"; switch (type) { case MODULE_KEYWORD: ret = yang_check_string(module, &module->dsc, dsc, "module", value, NULL); break; case REVISION_KEYWORD: ret = yang_check_string(module, &((struct lys_revision *)node)->dsc, dsc, where, value, NULL); break; case IMPORT_KEYWORD: ret = yang_check_string(module, &((struct lys_import *)node)->dsc, dsc, where, value, NULL); break; case INCLUDE_KEYWORD: ret = yang_check_string(module, &((struct lys_include *)node)->dsc, dsc, where, value, NULL); break; case NODE_PRINT: ret = yang_check_string(module, &((struct lys_node *)node)->dsc, dsc, where, value, node); break; default: ret = yang_check_string(module, &((struct lys_node *)node)->dsc, dsc, where, value, NULL); break; } return ret; } int yang_read_reference(struct lys_module *module, void *node, char *value, char *where, enum yytokentype type) { int ret; char *ref = "reference"; switch (type) { case MODULE_KEYWORD: ret = yang_check_string(module, &module->ref, ref, "module", value, NULL); break; case REVISION_KEYWORD: ret = yang_check_string(module, &((struct lys_revision *)node)->ref, ref, where, value, NULL); break; case IMPORT_KEYWORD: ret = yang_check_string(module, &((struct lys_import *)node)->ref, ref, where, value, NULL); break; case INCLUDE_KEYWORD: ret = yang_check_string(module, &((struct lys_include *)node)->ref, ref, where, value, NULL); break; case NODE_PRINT: ret = yang_check_string(module, &((struct lys_node *)node)->ref, ref, where, value, node); break; default: ret = yang_check_string(module, &((struct lys_node *)node)->ref, ref, where, value, NULL); break; } return ret; } int yang_fill_iffeature(struct lys_module *module, struct lys_iffeature *iffeature, void *parent, char *value, struct unres_schema *unres, int parent_is_feature) { const char *exp; int ret; if ((module->version != 2) && ((value[0] == '(') || strchr(value, ' '))) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "if-feature"); free(value); return EXIT_FAILURE; } if (!(exp = transform_iffeat_schema2json(module, value))) { free(value); return EXIT_FAILURE; } free(value); ret = resolve_iffeature_compile(iffeature, exp, (struct lys_node *)parent, parent_is_feature, unres); lydict_remove(module->ctx, exp); return (ret) ? EXIT_FAILURE : EXIT_SUCCESS; } int yang_read_base(struct lys_module *module, struct lys_ident *ident, char *value, struct unres_schema *unres) { const char *exp; exp = transform_schema2json(module, value); free(value); if (!exp) { return EXIT_FAILURE; } if (unres_schema_add_str(module, unres, ident, UNRES_IDENT, exp) == -1) { lydict_remove(module->ctx, exp); return EXIT_FAILURE; } lydict_remove(module->ctx, exp); return EXIT_SUCCESS; } int yang_read_message(struct lys_module *module,struct lys_restr *save,char *value, char *what, int message) { int ret; if (message == ERROR_APP_TAG_KEYWORD) { ret = yang_check_string(module, &save->eapptag, "error_app_tag", what, value, NULL); } else { ret = yang_check_string(module, &save->emsg, "error_message", what, value, NULL); } return ret; } int yang_read_presence(struct lys_module *module, struct lys_node_container *cont, char *value) { if (cont->presence) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, cont, "presence", "container"); free(value); return EXIT_FAILURE; } else { cont->presence = lydict_insert_zc(module->ctx, value); return EXIT_SUCCESS; } } void * yang_read_when(struct lys_module *module, struct lys_node *node, enum yytokentype type, char *value) { struct lys_when *retval; retval = calloc(1, sizeof *retval); LY_CHECK_ERR_RETURN(!retval, LOGMEM(module->ctx); free(value), NULL); retval->cond = transform_schema2json(module, value); if (!retval->cond) { goto error; } switch (type) { case CONTAINER_KEYWORD: if (((struct lys_node_container *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "container"); goto error; } ((struct lys_node_container *)node)->when = retval; break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: if (((struct lys_node_anydata *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", (type == ANYXML_KEYWORD) ? "anyxml" : "anydata"); goto error; } ((struct lys_node_anydata *)node)->when = retval; break; case CHOICE_KEYWORD: if (((struct lys_node_choice *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "choice"); goto error; } ((struct lys_node_choice *)node)->when = retval; break; case CASE_KEYWORD: if (((struct lys_node_case *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "case"); goto error; } ((struct lys_node_case *)node)->when = retval; break; case LEAF_KEYWORD: if (((struct lys_node_leaf *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "leaf"); goto error; } ((struct lys_node_leaf *)node)->when = retval; break; case LEAF_LIST_KEYWORD: if (((struct lys_node_leaflist *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "leaflist"); goto error; } ((struct lys_node_leaflist *)node)->when = retval; break; case LIST_KEYWORD: if (((struct lys_node_list *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "list"); goto error; } ((struct lys_node_list *)node)->when = retval; break; case USES_KEYWORD: if (((struct lys_node_uses *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "uses"); goto error; } ((struct lys_node_uses *)node)->when = retval; break; case AUGMENT_KEYWORD: if (((struct lys_node_augment *)node)->when) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_LYS, node, "when", "augment"); goto error; } ((struct lys_node_augment *)node)->when = retval; break; case EXTENSION_INSTANCE: *(struct lys_when **)node = retval; break; default: goto error; break; } free(value); return retval; error: free(value); lydict_remove(module->ctx, retval->cond); free(retval); return NULL; } void * yang_read_node(struct lys_module *module, struct lys_node *parent, struct lys_node **root, char *value, int nodetype, int sizeof_struct) { struct lys_node *node, **child; node = calloc(1, sizeof_struct); LY_CHECK_ERR_RETURN(!node, LOGMEM(module->ctx); free(value), NULL); LOGDBG(LY_LDGYANG, "parsing %s statement \"%s\"", strnodetype(nodetype), value); node->name = lydict_insert_zc(module->ctx, value); node->module = module; node->nodetype = nodetype; node->parent = parent; /* insert the node into the schema tree */ child = (parent) ? &parent->child : root; if (*child) { (*child)->prev->next = node; (*child)->prev = node; } else { *child = node; node->prev = node; } return node; } int yang_read_default(struct lys_module *module, void *node, char *value, enum yytokentype type) { int ret; switch (type) { case LEAF_KEYWORD: ret = yang_check_string(module, &((struct lys_node_leaf *) node)->dflt, "default", "leaf", value, node); break; case TYPEDEF_KEYWORD: ret = yang_check_string(module, &((struct lys_tpdf *) node)->dflt, "default", "typedef", value, NULL); break; default: free(value); LOGINT(module->ctx); ret = EXIT_FAILURE; break; } return ret; } int yang_read_units(struct lys_module *module, void *node, char *value, enum yytokentype type) { int ret; switch (type) { case LEAF_KEYWORD: ret = yang_check_string(module, &((struct lys_node_leaf *) node)->units, "units", "leaf", value, node); break; case LEAF_LIST_KEYWORD: ret = yang_check_string(module, &((struct lys_node_leaflist *) node)->units, "units", "leaflist", value, node); break; case TYPEDEF_KEYWORD: ret = yang_check_string(module, &((struct lys_tpdf *) node)->units, "units", "typedef", value, NULL); break; case ADD_KEYWORD: case REPLACE_KEYWORD: case DELETE_KEYWORD: ret = yang_check_string(module, &((struct lys_deviate *) node)->units, "units", "deviate", value, NULL); break; default: free(value); LOGINT(module->ctx); ret = EXIT_FAILURE; break; } return ret; } int yang_read_key(struct lys_module *module, struct lys_node_list *list, struct unres_schema *unres) { char *exp, *value; exp = value = (char *) list->keys; while ((value = strpbrk(value, " \t\n"))) { list->keys_size++; while (isspace(*value)) { value++; } } list->keys_size++; list->keys_str = lydict_insert_zc(module->ctx, exp); list->keys = calloc(list->keys_size, sizeof *list->keys); LY_CHECK_ERR_RETURN(!list->keys, LOGMEM(module->ctx), EXIT_FAILURE); if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) { return EXIT_FAILURE; } return EXIT_SUCCESS; } int yang_fill_unique(struct lys_module *module, struct lys_node_list *list, struct lys_unique *unique, char *value, struct unres_schema *unres) { int i, j; char *vaux, c; struct unres_list_uniq *unique_info; /* count the number of unique leafs in the value */ vaux = value; while ((vaux = strpbrk(vaux, " \t\n"))) { unique->expr_size++; while (isspace(*vaux)) { vaux++; } } unique->expr_size++; unique->expr = calloc(unique->expr_size, sizeof *unique->expr); LY_CHECK_ERR_GOTO(!unique->expr, LOGMEM(module->ctx), error); for (i = 0; i < unique->expr_size; i++) { vaux = strpbrk(value, " \t\n"); if (vaux) { c = *vaux; *vaux = '\0'; } /* store token into unique structure (includes converting prefix to the module name) */ unique->expr[i] = transform_schema2json(module, value); if (!unique->expr[i]) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_LYS, list, value, "unique"); goto error; } if (vaux) { *vaux = c; } /* check that the expression does not repeat */ for (j = 0; j < i; j++) { if (ly_strequal(unique->expr[j], unique->expr[i], 1)) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_LYS, list, unique->expr[i], "unique"); LOGVAL(module->ctx, LYE_SPEC, LY_VLOG_LYS, list, "The identifier is not unique"); goto error; } } /* try to resolve leaf */ if (unres) { unique_info = malloc(sizeof *unique_info); LY_CHECK_ERR_GOTO(!unique_info, LOGMEM(module->ctx), error); unique_info->list = (struct lys_node *)list; unique_info->expr = unique->expr[i]; unique_info->trg_type = &unique->trg_type; if (unres_schema_add_node(module, unres, unique_info, UNRES_LIST_UNIQ, NULL) == -1) { goto error; } } else { if (resolve_unique((struct lys_node *)list, unique->expr[i], &unique->trg_type)) { goto error; } } /* move to next token */ value = vaux; while(value && isspace(*value)) { value++; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_unique(struct lys_module *module, struct lys_node_list *list, struct unres_schema *unres) { uint8_t k; char *str; for (k = 0; k < list->unique_size; k++) { str = (char *)list->unique[k].expr; if (yang_fill_unique(module, list, &list->unique[k], str, unres)) { goto error; } free(str); } return EXIT_SUCCESS; error: free(str); return EXIT_FAILURE; } int yang_read_leafref_path(struct lys_module *module, struct yang_type *stype, char *value) { if (stype->base && (stype->base != LY_TYPE_LEAFREF)) { LOGVAL(module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "require-instance"); goto error; } if (stype->type->info.lref.path) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "path", "type"); goto error; } stype->type->info.lref.path = lydict_insert_zc(module->ctx, value); stype->base = LY_TYPE_LEAFREF; return EXIT_SUCCESS; error: free(value); return EXIT_FAILURE; } int yang_read_require_instance(struct ly_ctx *ctx, struct yang_type *stype, int req) { if (stype->base && (stype->base != LY_TYPE_LEAFREF)) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "require-instance"); return EXIT_FAILURE; } if (stype->type->info.lref.req) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "require-instance", "type"); return EXIT_FAILURE; } stype->type->info.lref.req = req; stype->base = LY_TYPE_LEAFREF; return EXIT_SUCCESS; } int yang_check_type(struct lys_module *module, struct lys_node *parent, struct yang_type *typ, struct lys_type *type, int tpdftype, struct unres_schema *unres) { struct ly_ctx *ctx = module->ctx; int rc, ret = -1; unsigned int i, j; int8_t req; const char *name, *value, *module_name = NULL; LY_DATA_TYPE base = 0, base_tmp; struct lys_node *siter; struct lys_type *dertype; struct lys_type_enum *enms_sc = NULL; struct lys_type_bit *bits_sc = NULL; struct lys_type_bit bit_tmp; struct yang_type *yang; value = transform_schema2json(module, typ->name); if (!value) { goto error; } i = parse_identifier(value); if (i < 1) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, value[-i], &value[-i]); lydict_remove(ctx, value); goto error; } /* module name */ name = value; if (value[i]) { module_name = lydict_insert(ctx, value, i); name += i; if ((name[0] != ':') || (parse_identifier(name + 1) < 1)) { LOGVAL(ctx, LYE_INCHAR, LY_VLOG_NONE, NULL, name[0], name); lydict_remove(ctx, module_name); lydict_remove(ctx, value); goto error; } ++name; } rc = resolve_superior_type(name, module_name, module, parent, &type->der); if (rc == -1) { LOGVAL(ctx, LYE_INMOD, LY_VLOG_NONE, NULL, module_name); lydict_remove(ctx, module_name); lydict_remove(ctx, value); goto error; /* the type could not be resolved or it was resolved to an unresolved typedef or leafref */ } else if (rc == EXIT_FAILURE) { LOGVAL(ctx, LYE_NORESOLV, LY_VLOG_NONE, NULL, "type", name); lydict_remove(ctx, module_name); lydict_remove(ctx, value); ret = EXIT_FAILURE; goto error; } lydict_remove(ctx, module_name); lydict_remove(ctx, value); if (type->value_flags & LY_VALUE_UNRESGRP) { /* resolved type in grouping, decrease the grouping's nacm number to indicate that one less * unresolved item left inside the grouping, LYTYPE_GRP used as a flag for types inside a grouping. */ for (siter = parent; siter && (siter->nodetype != LYS_GROUPING); siter = lys_parent(siter)); if (siter) { assert(((struct lys_node_grp *)siter)->unres_count); ((struct lys_node_grp *)siter)->unres_count--; } else { LOGINT(ctx); goto error; } type->value_flags &= ~LY_VALUE_UNRESGRP; } /* check status */ if (lyp_check_status(type->parent->flags, type->parent->module, type->parent->name, type->der->flags, type->der->module, type->der->name, parent)) { goto error; } base = typ->base; base_tmp = type->base; type->base = type->der->type.base; if (base == 0) { base = type->der->type.base; } switch (base) { case LY_TYPE_STRING: if (type->base == LY_TYPE_BINARY) { if (type->info.str.pat_count) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Binary type could not include pattern statement."); goto error; } type->info.binary.length = type->info.str.length; if (type->info.binary.length && lyp_check_length_range(ctx, type->info.binary.length->expr, type)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, type->info.binary.length->expr, "length"); goto error; } } else if (type->base == LY_TYPE_STRING) { if (type->info.str.length && lyp_check_length_range(ctx, type->info.str.length->expr, type)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, type->info.str.length->expr, "length"); goto error; } } else { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } break; case LY_TYPE_DEC64: if (type->base == LY_TYPE_DEC64) { /* mandatory sub-statement(s) check */ if (!type->info.dec64.dig && !type->der->type.der) { /* decimal64 type directly derived from built-in type requires fraction-digits */ LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "fraction-digits", "type"); goto error; } if (type->info.dec64.dig && type->der->type.der) { /* type is not directly derived from buit-in type and fraction-digits statement is prohibited */ LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "fraction-digits"); goto error; } /* copy fraction-digits specification from parent type for easier internal use */ if (type->der->type.der) { type->info.dec64.dig = type->der->type.info.dec64.dig; type->info.dec64.div = type->der->type.info.dec64.div; } if (type->info.dec64.range && lyp_check_length_range(ctx, type->info.dec64.range->expr, type)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, type->info.dec64.range->expr, "range"); goto error; } } else if (type->base >= LY_TYPE_INT8 && type->base <=LY_TYPE_UINT64) { if (type->info.dec64.dig) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Numerical type could not include fraction statement."); goto error; } type->info.num.range = type->info.dec64.range; if (type->info.num.range && lyp_check_length_range(ctx, type->info.num.range->expr, type)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, type->info.num.range->expr, "range"); goto error; } } else { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } break; case LY_TYPE_ENUM: if (type->base != LY_TYPE_ENUM) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } dertype = &type->der->type; if (!dertype->der) { if (!type->info.enums.count) { /* type is derived directly from buit-in enumeartion type and enum statement is required */ LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "enum", "type"); goto error; } } else { for (; !dertype->info.enums.count; dertype = &dertype->der->type); if (module->version < 2 && type->info.enums.count) { /* type is not directly derived from built-in enumeration type and enum statement is prohibited * in YANG 1.0, since YANG 1.1 enum statements can be used to restrict the base enumeration type */ LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "enum"); goto error; } /* restricted enumeration type - the name MUST be used in the base type */ enms_sc = dertype->info.enums.enm; for (i = 0; i < type->info.enums.count; i++) { for (j = 0; j < dertype->info.enums.count; j++) { if (ly_strequal(enms_sc[j].name, type->info.enums.enm[i].name, 1)) { break; } } if (j == dertype->info.enums.count) { LOGVAL(ctx, LYE_ENUM_INNAME, LY_VLOG_NONE, NULL, type->info.enums.enm[i].name); goto error; } if (type->info.enums.enm[i].flags & LYS_AUTOASSIGNED) { /* automatically assign value from base type */ type->info.enums.enm[i].value = enms_sc[j].value; } else { /* check that the assigned value corresponds to the original * value of the enum in the base type */ if (type->info.enums.enm[i].value != enms_sc[j].value) { /* type->info.enums.enm[i].value - assigned value in restricted enum * enms_sc[j].value - value assigned to the corresponding enum (detected above) in base type */ LOGVAL(ctx, LYE_ENUM_INVAL, LY_VLOG_NONE, NULL, type->info.enums.enm[i].value, type->info.enums.enm[i].name, enms_sc[j].value); goto error; } } } } break; case LY_TYPE_BITS: if (type->base != LY_TYPE_BITS) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } dertype = &type->der->type; if (!dertype->der) { if (!type->info.bits.count) { /* type is derived directly from buit-in bits type and bit statement is required */ LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "bit", "type"); goto error; } } else { for (; !dertype->info.enums.count; dertype = &dertype->der->type); if (module->version < 2 && type->info.bits.count) { /* type is not directly derived from buit-in bits type and bit statement is prohibited, * since YANG 1.1 the bit statements can be used to restrict the base bits type */ LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "bit"); goto error; } bits_sc = dertype->info.bits.bit; for (i = 0; i < type->info.bits.count; i++) { for (j = 0; j < dertype->info.bits.count; j++) { if (ly_strequal(bits_sc[j].name, type->info.bits.bit[i].name, 1)) { break; } } if (j == dertype->info.bits.count) { LOGVAL(ctx, LYE_BITS_INNAME, LY_VLOG_NONE, NULL, type->info.bits.bit[i].name); goto error; } /* restricted bits type */ if (type->info.bits.bit[i].flags & LYS_AUTOASSIGNED) { /* automatically assign position from base type */ type->info.bits.bit[i].pos = bits_sc[j].pos; } else { /* check that the assigned position corresponds to the original * position of the bit in the base type */ if (type->info.bits.bit[i].pos != bits_sc[j].pos) { /* type->info.bits.bit[i].pos - assigned position in restricted bits * bits_sc[j].pos - position assigned to the corresponding bit (detected above) in base type */ LOGVAL(ctx, LYE_BITS_INVAL, LY_VLOG_NONE, NULL, type->info.bits.bit[i].pos, type->info.bits.bit[i].name, bits_sc[j].pos); goto error; } } } } for (i = type->info.bits.count; i > 0; i--) { j = i - 1; /* keep them ordered by position */ while (j && type->info.bits.bit[j - 1].pos > type->info.bits.bit[j].pos) { /* switch them */ memcpy(&bit_tmp, &type->info.bits.bit[j], sizeof bit_tmp); memcpy(&type->info.bits.bit[j], &type->info.bits.bit[j - 1], sizeof bit_tmp); memcpy(&type->info.bits.bit[j - 1], &bit_tmp, sizeof bit_tmp); j--; } } break; case LY_TYPE_LEAFREF: if (type->base == LY_TYPE_INST) { if (type->info.lref.path) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "path"); goto error; } if ((req = type->info.lref.req)) { type->info.inst.req = req; } } else if (type->base == LY_TYPE_LEAFREF) { /* require-instance only YANG 1.1 */ if (type->info.lref.req && (module->version < 2)) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "require-instance"); goto error; } /* flag resolving for later use */ if (!tpdftype) { for (siter = parent; siter && siter->nodetype != LYS_GROUPING; siter = lys_parent(siter)); if (siter) { /* just a flag - do not resolve */ tpdftype = 1; } } if (type->info.lref.path) { if (type->der->type.der) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "path"); goto error; } value = type->info.lref.path; /* store in the JSON format */ type->info.lref.path = transform_schema2json(module, value); lydict_remove(ctx, value); if (!type->info.lref.path) { goto error; } /* try to resolve leafref path only when this is instantiated * leaf, so it is not: * - typedef's type, * - in grouping definition, * - just instantiated in a grouping definition, * because in those cases the nodes referenced in path might not be present * and it is not a bug. */ if (!tpdftype && unres_schema_add_node(module, unres, type, UNRES_TYPE_LEAFREF, parent) == -1) { goto error; } } else if (!type->der->type.der) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "path", "type"); goto error; } else { /* copy leafref definition into the derived type */ type->info.lref.path = lydict_insert(ctx, type->der->type.info.lref.path, 0); /* and resolve the path at the place we are (if not in grouping/typedef) */ if (!tpdftype && unres_schema_add_node(module, unres, type, UNRES_TYPE_LEAFREF, parent) == -1) { goto error; } } } else { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } break; case LY_TYPE_IDENT: if (type->base != LY_TYPE_IDENT) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } if (type->der->type.der) { if (type->info.ident.ref) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); goto error; } } else { if (!type->info.ident.ref) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "base", "type"); goto error; } } break; case LY_TYPE_UNION: if (type->base != LY_TYPE_UNION) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } if (!type->info.uni.types) { if (type->der->type.der) { /* this is just a derived type with no additional type specified/required */ assert(type->der->type.base == LY_TYPE_UNION); type->info.uni.has_ptr_type = type->der->type.info.uni.has_ptr_type; break; } LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "(union) type"); goto error; } for (i = 0; i < type->info.uni.count; i++) { dertype = &type->info.uni.types[i]; if (dertype->base == LY_TYPE_DER) { yang = (struct yang_type *)dertype->der; dertype->der = NULL; dertype->parent = type->parent; if (yang_check_type(module, parent, yang, dertype, tpdftype, unres)) { dertype->der = (struct lys_tpdf *)yang; ret = EXIT_FAILURE; type->base = base_tmp; base = 0; goto error; } else { lydict_remove(ctx, yang->name); free(yang); } } if (module->version < 2) { if (dertype->base == LY_TYPE_EMPTY) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, "empty", typ->name); goto error; } else if (dertype->base == LY_TYPE_LEAFREF) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, "leafref", typ->name); goto error; } } if ((dertype->base == LY_TYPE_INST) || (dertype->base == LY_TYPE_LEAFREF) || ((dertype->base == LY_TYPE_UNION) && dertype->info.uni.has_ptr_type)) { type->info.uni.has_ptr_type = 1; } } break; default: if (base >= LY_TYPE_BINARY && base <= LY_TYPE_UINT64) { if (type->base != base) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid restriction in type \"%s\".", type->parent->name); goto error; } } else { LOGINT(ctx); goto error; } } /* if derived type has extension, which need validate data */ dertype = &type->der->type; while (dertype->der) { if (dertype->parent->flags & LYS_VALID_EXT) { type->parent->flags |= LYS_VALID_EXT; } dertype = &dertype->der->type; } return EXIT_SUCCESS; error: if (base) { type->base = base_tmp; } return ret; } void yang_free_type_union(struct ly_ctx *ctx, struct lys_type *type) { struct lys_type *stype; struct yang_type *yang; unsigned int i; for (i = 0; i < type->info.uni.count; ++i) { stype = &type->info.uni.types[i]; if (stype->base == LY_TYPE_DER) { yang = (struct yang_type *)stype->der; stype->base = yang->base; lydict_remove(ctx, yang->name); free(yang); } else if (stype->base == LY_TYPE_UNION) { yang_free_type_union(ctx, stype); } } } void * yang_read_type(struct ly_ctx *ctx, void *parent, char *value, enum yytokentype type) { struct yang_type *typ; struct lys_deviate *dev; typ = calloc(1, sizeof *typ); LY_CHECK_ERR_RETURN(!typ, LOGMEM(ctx), NULL); typ->flags = LY_YANG_STRUCTURE_FLAG; switch (type) { case LEAF_KEYWORD: if (((struct lys_node_leaf *)parent)->type.der) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, parent, "type", "leaf"); goto error; } ((struct lys_node_leaf *)parent)->type.der = (struct lys_tpdf *)typ; ((struct lys_node_leaf *)parent)->type.parent = (struct lys_tpdf *)parent; typ->type = &((struct lys_node_leaf *)parent)->type; break; case LEAF_LIST_KEYWORD: if (((struct lys_node_leaflist *)parent)->type.der) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, parent, "type", "leaf-list"); goto error; } ((struct lys_node_leaflist *)parent)->type.der = (struct lys_tpdf *)typ; ((struct lys_node_leaflist *)parent)->type.parent = (struct lys_tpdf *)parent; typ->type = &((struct lys_node_leaflist *)parent)->type; break; case UNION_KEYWORD: ((struct lys_type *)parent)->der = (struct lys_tpdf *)typ; typ->type = (struct lys_type *)parent; break; case TYPEDEF_KEYWORD: if (((struct lys_tpdf *)parent)->type.der) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "type", "typedef"); goto error; } ((struct lys_tpdf *)parent)->type.der = (struct lys_tpdf *)typ; typ->type = &((struct lys_tpdf *)parent)->type; break; case REPLACE_KEYWORD: /* deviation replace type*/ dev = (struct lys_deviate *)parent; if (dev->type) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "type", "deviation"); goto error; } dev->type = calloc(1, sizeof *dev->type); LY_CHECK_ERR_GOTO(!dev->type, LOGMEM(ctx), error); dev->type->der = (struct lys_tpdf *)typ; typ->type = dev->type; break; case EXTENSION_INSTANCE: ((struct lys_type *)parent)->der = (struct lys_tpdf *)typ; typ->type = parent; break; default: goto error; break; } typ->name = lydict_insert_zc(ctx, value); return typ; error: free(value); free(typ); return NULL; } void * yang_read_length(struct ly_ctx *ctx, struct yang_type *stype, char *value, int is_ext_instance) { struct lys_restr *length; if (is_ext_instance) { length = (struct lys_restr *)stype; } else { if (stype->base == 0 || stype->base == LY_TYPE_STRING) { stype->base = LY_TYPE_STRING; } else { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected length statement."); goto error; } if (stype->type->info.str.length) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "length", "type"); goto error; } length = calloc(1, sizeof *length); LY_CHECK_ERR_GOTO(!length, LOGMEM(ctx), error); stype->type->info.str.length = length; } length->expr = lydict_insert_zc(ctx, value); return length; error: free(value); return NULL; } int yang_read_pattern(struct ly_ctx *ctx, struct lys_restr *pattern, void **precomp, char *value, char modifier) { char *buf; size_t len; if (precomp && lyp_precompile_pattern(ctx, value, (pcre**)&precomp[0], (pcre_extra**)&precomp[1])) { free(value); return EXIT_FAILURE; } len = strlen(value); buf = malloc((len + 2) * sizeof *buf); /* modifier byte + value + terminating NULL byte */ LY_CHECK_ERR_RETURN(!buf, LOGMEM(ctx); free(value), EXIT_FAILURE); buf[0] = modifier; strcpy(&buf[1], value); free(value); pattern->expr = lydict_insert_zc(ctx, buf); return EXIT_SUCCESS; } void * yang_read_range(struct ly_ctx *ctx, struct yang_type *stype, char *value, int is_ext_instance) { struct lys_restr * range; if (is_ext_instance) { range = (struct lys_restr *)stype; } else { if (stype->base != 0 && stype->base != LY_TYPE_DEC64) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected range statement."); goto error; } stype->base = LY_TYPE_DEC64; if (stype->type->info.dec64.range) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "range", "type"); goto error; } range = calloc(1, sizeof *range); LY_CHECK_ERR_GOTO(!range, LOGMEM(ctx), error); stype->type->info.dec64.range = range; } range->expr = lydict_insert_zc(ctx, value); return range; error: free(value); return NULL; } int yang_read_fraction(struct ly_ctx *ctx, struct yang_type *typ, uint32_t value) { uint32_t i; if (typ->base == 0 || typ->base == LY_TYPE_DEC64) { typ->base = LY_TYPE_DEC64; } else { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected fraction-digits statement."); goto error; } if (typ->type->info.dec64.dig) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "fraction-digits", "type"); goto error; } /* range check */ if (value < 1 || value > 18) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", value, "fraction-digits"); goto error; } typ->type->info.dec64.dig = value; typ->type->info.dec64.div = 10; for (i = 1; i < value; i++) { typ->type->info.dec64.div *= 10; } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_enum(struct ly_ctx *ctx, struct yang_type *typ, struct lys_type_enum *enm, char *value) { int i, j; typ->base = LY_TYPE_ENUM; if (!value[0]) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "enum name"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Enum name must not be empty."); free(value); goto error; } enm->name = lydict_insert_zc(ctx, value); /* the assigned name MUST NOT have any leading or trailing whitespace characters */ if (isspace(enm->name[0]) || isspace(enm->name[strlen(enm->name) - 1])) { LOGVAL(ctx, LYE_ENUM_WS, LY_VLOG_NONE, NULL, enm->name); goto error; } j = typ->type->info.enums.count - 1; /* check the name uniqueness */ for (i = 0; i < j; i++) { if (ly_strequal(typ->type->info.enums.enm[i].name, enm->name, 1)) { LOGVAL(ctx, LYE_ENUM_DUPNAME, LY_VLOG_NONE, NULL, enm->name); goto error; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_check_enum(struct ly_ctx *ctx, struct yang_type *typ, struct lys_type_enum *enm, int64_t *value, int assign) { int i, j; if (!assign) { /* assign value automatically */ if (*value > INT32_MAX) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, "2147483648", "enum/value"); goto error; } enm->value = *value; enm->flags |= LYS_AUTOASSIGNED; (*value)++; } else if (typ->type->info.enums.enm == enm) { /* change value, which is assigned automatically, if first enum has value. */ *value = typ->type->info.enums.enm[0].value; (*value)++; } /* check that the value is unique */ j = typ->type->info.enums.count-1; for (i = 0; i < j; i++) { if (typ->type->info.enums.enm[i].value == typ->type->info.enums.enm[j].value) { LOGVAL(ctx, LYE_ENUM_DUPVAL, LY_VLOG_NONE, NULL, typ->type->info.enums.enm[j].value, typ->type->info.enums.enm[j].name, typ->type->info.enums.enm[i].name); goto error; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_bit(struct ly_ctx *ctx, struct yang_type *typ, struct lys_type_bit *bit, char *value) { int i, j; typ->base = LY_TYPE_BITS; bit->name = lydict_insert_zc(ctx, value); if (lyp_check_identifier(ctx, bit->name, LY_IDENT_SIMPLE, NULL, NULL)) { goto error; } j = typ->type->info.bits.count - 1; /* check the name uniqueness */ for (i = 0; i < j; i++) { if (ly_strequal(typ->type->info.bits.bit[i].name, bit->name, 1)) { LOGVAL(ctx, LYE_BITS_DUPNAME, LY_VLOG_NONE, NULL, bit->name); goto error; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_check_bit(struct ly_ctx *ctx, struct yang_type *typ, struct lys_type_bit *bit, int64_t *value, int assign) { int i,j; if (!assign) { /* assign value automatically */ if (*value > UINT32_MAX) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, "4294967295", "bit/position"); goto error; } bit->pos = (uint32_t)*value; bit->flags |= LYS_AUTOASSIGNED; (*value)++; } j = typ->type->info.bits.count - 1; /* check that the value is unique */ for (i = 0; i < j; i++) { if (typ->type->info.bits.bit[i].pos == bit->pos) { LOGVAL(ctx, LYE_BITS_DUPVAL, LY_VLOG_NONE, NULL, bit->pos, bit->name, typ->type->info.bits.bit[i].name); goto error; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_augment(struct lys_module *module, struct lys_node *parent, struct lys_node_augment *aug, char *value) { aug->nodetype = LYS_AUGMENT; aug->target_name = transform_schema2json(module, value); free(value); if (!aug->target_name) { return EXIT_FAILURE; } aug->parent = parent; aug->module = module; return EXIT_SUCCESS; } void * yang_read_deviate_unsupported(struct ly_ctx *ctx, struct lys_deviation *dev) { if (dev->deviate_size) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "\"not-supported\" deviation cannot be combined with any other deviation."); return NULL; } dev->deviate = calloc(1, sizeof *dev->deviate); LY_CHECK_ERR_RETURN(!dev->deviate, LOGMEM(ctx), NULL); dev->deviate[dev->deviate_size].mod = LY_DEVIATE_NO; dev->deviate_size = 1; return dev->deviate; } void * yang_read_deviate(struct ly_ctx *ctx, struct lys_deviation *dev, LYS_DEVIATE_TYPE mod) { struct lys_deviate *deviate; if (dev->deviate_size && dev->deviate[0].mod == LY_DEVIATE_NO) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "not-supported"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "\"not-supported\" deviation cannot be combined with any other deviation."); return NULL; } if (!(dev->deviate_size % LY_YANG_ARRAY_SIZE)) { deviate = realloc(dev->deviate, (LY_YANG_ARRAY_SIZE + dev->deviate_size) * sizeof *deviate); LY_CHECK_ERR_RETURN(!deviate, LOGMEM(ctx), NULL); memset(deviate + dev->deviate_size, 0, LY_YANG_ARRAY_SIZE * sizeof *deviate); dev->deviate = deviate; } dev->deviate[dev->deviate_size].mod = mod; return &dev->deviate[dev->deviate_size++]; } int yang_read_deviate_units(struct ly_ctx *ctx, struct lys_deviate *deviate, struct lys_node *dev_target) { const char **stritem; int j; /* check target node type */ if (dev_target->nodetype == LYS_LEAFLIST) { stritem = &((struct lys_node_leaflist *)dev_target)->units; } else if (dev_target->nodetype == LYS_LEAF) { stritem = &((struct lys_node_leaf *)dev_target)->units; } else { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "units"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"units\" property."); goto error; } if (deviate->mod == LY_DEVIATE_DEL) { /* check values */ if (!ly_strequal(*stritem, deviate->units, 1)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, deviate->units, "units"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Value differs from the target being deleted."); goto error; } /* remove current units value of the target */ lydict_remove(ctx, *stritem); *stritem = NULL; /* remove its extensions */ j = -1; while ((j = lys_ext_iter(dev_target->ext, dev_target->ext_size, j + 1, LYEXT_SUBSTMT_UNITS)) != -1) { lyp_ext_instance_rm(ctx, &dev_target->ext, &dev_target->ext_size, j); --j; } } else { if (deviate->mod == LY_DEVIATE_ADD) { /* check that there is no current value */ if (*stritem) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "units"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Adding property that already exists."); goto error; } } else { /* replace */ if (!*stritem) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "units"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Replacing a property that does not exist."); goto error; } } /* remove current units value of the target ... */ lydict_remove(ctx, *stritem); /* ... and replace it with the value specified in deviation */ *stritem = lydict_insert(ctx, deviate->units, 0); } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_deviate_unique(struct lys_deviate *deviate, struct lys_node *dev_target) { struct ly_ctx *ctx = dev_target->module->ctx; struct lys_node_list *list; struct lys_unique *unique; /* check target node type */ if (dev_target->nodetype != LYS_LIST) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"unique\" property."); goto error; } list = (struct lys_node_list *)dev_target; if (deviate->mod == LY_DEVIATE_ADD) { /* reallocate the unique array of the target */ unique = ly_realloc(list->unique, (deviate->unique_size + list->unique_size) * sizeof *unique); LY_CHECK_ERR_GOTO(!unique, LOGMEM(ctx), error); list->unique = unique; memset(unique + list->unique_size, 0, deviate->unique_size * sizeof *unique); } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_fill_deviate_default(struct ly_ctx *ctx, struct lys_deviate *deviate, struct lys_node *dev_target, struct ly_set *dflt_check, const char *value) { struct lys_node *node; struct lys_node_choice *choice; struct lys_node_leaf *leaf; struct lys_node_leaflist *llist; int rc, i, j; unsigned int u; u = strlen(value); if (dev_target->nodetype == LYS_CHOICE) { choice = (struct lys_node_choice *)dev_target; rc = resolve_choice_default_schema_nodeid(value, choice->child, (const struct lys_node **)&node); if (rc || !node) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); goto error; } if (deviate->mod == LY_DEVIATE_DEL) { if (!choice->dflt || (choice->dflt != node)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Value differs from the target being deleted."); goto error; } choice->dflt = NULL; /* remove extensions of this default instance from the target node */ j = -1; while ((j = lys_ext_iter(dev_target->ext, dev_target->ext_size, j + 1, LYEXT_SUBSTMT_DEFAULT)) != -1) { lyp_ext_instance_rm(ctx, &dev_target->ext, &dev_target->ext_size, j); --j; } } else { /* add or replace */ choice->dflt = node; if (!choice->dflt) { /* default branch not found */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); goto error; } } } else if (dev_target->nodetype == LYS_LEAF) { leaf = (struct lys_node_leaf *)dev_target; if (deviate->mod == LY_DEVIATE_DEL) { if (!leaf->dflt || !ly_strequal(leaf->dflt, value, 1)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Value differs from the target being deleted."); goto error; } /* remove value */ lydict_remove(ctx, leaf->dflt); leaf->dflt = NULL; leaf->flags &= ~LYS_DFLTJSON; /* remove extensions of this default instance from the target node */ j = -1; while ((j = lys_ext_iter(dev_target->ext, dev_target->ext_size, j + 1, LYEXT_SUBSTMT_DEFAULT)) != -1) { lyp_ext_instance_rm(ctx, &dev_target->ext, &dev_target->ext_size, j); --j; } } else { /* add (already checked) and replace */ /* remove value */ lydict_remove(ctx, leaf->dflt); leaf->flags &= ~LYS_DFLTJSON; /* set new value */ leaf->dflt = lydict_insert(ctx, value, u); /* remember to check it later (it may not fit now, but the type can be deviated too) */ ly_set_add(dflt_check, dev_target, 0); } } else { /* LYS_LEAFLIST */ llist = (struct lys_node_leaflist *)dev_target; if (deviate->mod == LY_DEVIATE_DEL) { /* find and remove the value in target list */ for (i = 0; i < llist->dflt_size; i++) { if (llist->dflt[i] && ly_strequal(llist->dflt[i], value, 1)) { /* match, remove the value */ lydict_remove(llist->module->ctx, llist->dflt[i]); llist->dflt[i] = NULL; /* remove extensions of this default instance from the target node */ j = -1; while ((j = lys_ext_iter(dev_target->ext, dev_target->ext_size, j + 1, LYEXT_SUBSTMT_DEFAULT)) != -1) { if (dev_target->ext[j]->insubstmt_index == i) { lyp_ext_instance_rm(ctx, &dev_target->ext, &dev_target->ext_size, j); --j; } else if (dev_target->ext[j]->insubstmt_index > i) { /* decrease the substatement index of the extension because of the changed array of defaults */ dev_target->ext[j]->insubstmt_index--; } } break; } } if (i == llist->dflt_size) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The default value to delete not found in the target node."); goto error; } } else { /* add or replace, anyway we place items into the deviate's list which propagates to the target */ /* we just want to check that the value isn't already in the list */ for (i = 0; i < llist->dflt_size; i++) { if (ly_strequal(llist->dflt[i], value, 1)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", value); goto error; } } /* store it in target node */ llist->dflt[llist->dflt_size++] = lydict_insert(ctx, value, u); /* remember to check it later (it may not fit now, but the type can be deviated too) */ ly_set_add(dflt_check, dev_target, 0); llist->flags &= ~LYS_DFLTJSON; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_deviate_default(struct lys_module *module, struct lys_deviate *deviate, struct lys_node *dev_target, struct ly_set * dflt_check) { struct ly_ctx *ctx = module->ctx; int i; struct lys_node_leaflist *llist; const char **dflt; /* check target node type */ if (module->version < 2 && dev_target->nodetype == LYS_LEAFLIST) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"default\" property."); goto error; } else if (deviate->dflt_size > 1 && dev_target->nodetype != LYS_LEAFLIST) { /* from YANG 1.1 */ LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow multiple \"default\" properties."); goto error; } else if (!(dev_target->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"default\" property."); goto error; } if (deviate->mod == LY_DEVIATE_ADD) { /* check that there is no current value */ if ((dev_target->nodetype == LYS_LEAF && ((struct lys_node_leaf *)dev_target)->dflt) || (dev_target->nodetype == LYS_CHOICE && ((struct lys_node_choice *)dev_target)->dflt)) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Adding property that already exists."); goto error; } /* check collision with mandatory/min-elements */ if ((dev_target->flags & LYS_MAND_TRUE) || (dev_target->nodetype == LYS_LEAFLIST && ((struct lys_node_leaflist *)dev_target)->min)) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "default", "deviation"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Adding the \"default\" statement is forbidden on %s statement.", (dev_target->flags & LYS_MAND_TRUE) ? "nodes with the \"mandatory\"" : "leaflists with non-zero \"min-elements\""); goto error; } } else if (deviate->mod == LY_DEVIATE_RPL) { /* check that there was a value before */ if (((dev_target->nodetype & (LYS_LEAF | LYS_LEAFLIST)) && !((struct lys_node_leaf *)dev_target)->dflt) || (dev_target->nodetype == LYS_CHOICE && !((struct lys_node_choice *)dev_target)->dflt)) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Replacing a property that does not exist."); goto error; } } if (dev_target->nodetype == LYS_LEAFLIST) { /* reallocate default list in the target */ llist = (struct lys_node_leaflist *)dev_target; if (deviate->mod == LY_DEVIATE_ADD) { /* reallocate (enlarge) the unique array of the target */ dflt = realloc(llist->dflt, (deviate->dflt_size + llist->dflt_size) * sizeof *dflt); LY_CHECK_ERR_GOTO(!dflt, LOGMEM(ctx), error); llist->dflt = dflt; } else if (deviate->mod == LY_DEVIATE_RPL) { /* reallocate (replace) the unique array of the target */ for (i = 0; i < llist->dflt_size; i++) { lydict_remove(ctx, llist->dflt[i]); } dflt = realloc(llist->dflt, deviate->dflt_size * sizeof *dflt); LY_CHECK_ERR_GOTO(!dflt, LOGMEM(ctx), error); llist->dflt = dflt; llist->dflt_size = 0; } } for (i = 0; i < deviate->dflt_size; ++i) { if (yang_fill_deviate_default(ctx, deviate, dev_target, dflt_check, deviate->dflt[i])) { goto error; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_check_deviate_mandatory(struct lys_deviate *deviate, struct lys_node *dev_target) { struct ly_ctx *ctx = dev_target->module->ctx; struct lys_node *parent; /* check target node type */ if (!(dev_target->nodetype & (LYS_LEAF | LYS_CHOICE | LYS_ANYDATA))) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"mandatory\" property."); goto error; } if (deviate->mod == LY_DEVIATE_ADD) { /* check that there is no current value */ if (dev_target->flags & LYS_MAND_MASK) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Adding property that already exists."); goto error; } else { if (dev_target->nodetype == LYS_LEAF && ((struct lys_node_leaf *)dev_target)->dflt) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "leaf"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); goto error; } else if (dev_target->nodetype == LYS_CHOICE && ((struct lys_node_choice *)dev_target)->dflt) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "choice"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The \"mandatory\" statement is forbidden on choices with \"default\"."); goto error; } } } else { /* replace */ if (!(dev_target->flags & LYS_MAND_MASK)) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Replacing a property that does not exist."); goto error; } } /* remove current mandatory value of the target ... */ dev_target->flags &= ~LYS_MAND_MASK; /* ... and replace it with the value specified in deviation */ dev_target->flags |= deviate->flags & LYS_MAND_MASK; /* check for mandatory node in default case, first find the closest parent choice to the changed node */ for (parent = dev_target->parent; parent && !(parent->nodetype & (LYS_CHOICE | LYS_GROUPING | LYS_ACTION)); parent = parent->parent) { if (parent->nodetype == LYS_CONTAINER && ((struct lys_node_container *)parent)->presence) { /* stop also on presence containers */ break; } } /* and if it is a choice with the default case, check it for presence of a mandatory node in it */ if (parent && parent->nodetype == LYS_CHOICE && ((struct lys_node_choice *)parent)->dflt) { if (lyp_check_mandatory_choice(parent)) { goto error; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_read_deviate_minmax(struct lys_deviate *deviate, struct lys_node *dev_target, uint32_t value, int type) { struct ly_ctx *ctx = dev_target->module->ctx; uint32_t *ui32val, *min, *max; /* check target node type */ if (dev_target->nodetype == LYS_LEAFLIST) { max = &((struct lys_node_leaflist *)dev_target)->max; min = &((struct lys_node_leaflist *)dev_target)->min; } else if (dev_target->nodetype == LYS_LIST) { max = &((struct lys_node_list *)dev_target)->max; min = &((struct lys_node_list *)dev_target)->min; } else { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, (type) ? "max-elements" : "min-elements"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"%s\" property.", (type) ? "max-elements" : "min-elements"); goto error; } ui32val = (type) ? max : min; if (deviate->mod == LY_DEVIATE_ADD) { /* check that there is no current value */ if (*ui32val) { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, (type) ? "max-elements" : "min-elements"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Adding property that already exists."); goto error; } } else if (deviate->mod == LY_DEVIATE_RPL) { /* unfortunately, there is no way to check reliably that there * was a value before, it could have been the default */ } /* add (already checked) and replace */ /* set new value specified in deviation */ *ui32val = value; /* check min-elements is smaller than max-elements */ if (*max && *min > *max) { if (type) { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"max-elements\".", value); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "\"max-elements\" is smaller than \"min-elements\"."); } else { LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"min-elements\".", value); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "\"min-elements\" is bigger than \"max-elements\"."); } goto error; } return EXIT_SUCCESS; error: return EXIT_FAILURE; } int yang_check_deviate_must(struct lys_module *module, struct unres_schema *unres, struct lys_deviate *deviate, struct lys_node *dev_target) { struct ly_ctx *ctx = module->ctx; int i, j, erase_must = 1; struct lys_restr **trg_must, *must; uint8_t *trg_must_size; /* check target node type */ switch (dev_target->nodetype) { case LYS_LEAF: trg_must = &((struct lys_node_leaf *)dev_target)->must; trg_must_size = &((struct lys_node_leaf *)dev_target)->must_size; break; case LYS_CONTAINER: trg_must = &((struct lys_node_container *)dev_target)->must; trg_must_size = &((struct lys_node_container *)dev_target)->must_size; break; case LYS_LEAFLIST: trg_must = &((struct lys_node_leaflist *)dev_target)->must; trg_must_size = &((struct lys_node_leaflist *)dev_target)->must_size; break; case LYS_LIST: trg_must = &((struct lys_node_list *)dev_target)->must; trg_must_size = &((struct lys_node_list *)dev_target)->must_size; break; case LYS_ANYXML: case LYS_ANYDATA: trg_must = &((struct lys_node_anydata *)dev_target)->must; trg_must_size = &((struct lys_node_anydata *)dev_target)->must_size; break; default: LOGVAL(ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "must"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"must\" property."); goto error; } /* flag will be checked again, clear it for now */ dev_target->flags &= ~(LYS_XPCONF_DEP | LYS_XPSTATE_DEP); if (deviate->mod == LY_DEVIATE_ADD) { /* reallocate the must array of the target */ must = ly_realloc(*trg_must, (deviate->must_size + *trg_must_size) * sizeof *must); LY_CHECK_ERR_GOTO(!must, LOGMEM(ctx), error); *trg_must = must; memcpy(&(*trg_must)[*trg_must_size], deviate->must, deviate->must_size * sizeof *must); *trg_must_size = *trg_must_size + deviate->must_size; erase_must = 0; } else if (deviate->mod == LY_DEVIATE_DEL) { /* find must to delete, we are ok with just matching conditions */ for (j = 0; j < deviate->must_size; ++j) { for (i = 0; i < *trg_must_size; i++) { if (ly_strequal(deviate->must[j].expr, (*trg_must)[i].expr, 1)) { /* we have a match, free the must structure ... */ lys_restr_free(module->ctx, &((*trg_must)[i]), NULL); /* ... and maintain the array */ (*trg_must_size)--; if (i != *trg_must_size) { memcpy(&(*trg_must)[i], &(*trg_must)[*trg_must_size], sizeof *must); } if (!(*trg_must_size)) { free(*trg_must); *trg_must = NULL; } else { memset(&(*trg_must)[*trg_must_size], 0, sizeof *must); } i = -1; /* set match flag */ break; } } if (i != -1) { /* no match found */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, deviate->must[j].expr, "must"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Value does not match any must from the target."); goto error; } } } if (yang_check_must(module, deviate->must, deviate->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && *trg_must_size && (unres_schema_add_node(module, unres, dev_target, UNRES_XPATH, NULL) == -1)) { goto error; } return EXIT_SUCCESS; error: if (deviate->mod == LY_DEVIATE_ADD && erase_must) { for (i = 0; i < deviate->must_size; ++i) { lys_restr_free(module->ctx, &deviate->must[i], NULL); } free(deviate->must); } return EXIT_FAILURE; } int yang_deviate_delete_unique(struct lys_module *module, struct lys_deviate *deviate, struct lys_node_list *list, int index, char * value) { struct ly_ctx *ctx = module->ctx; int i, j, k; /* find unique structures to delete */ for (i = 0; i < list->unique_size; i++) { if (list->unique[i].expr_size != deviate->unique[index].expr_size) { continue; } for (j = 0; j < deviate->unique[index].expr_size; j++) { if (!ly_strequal(list->unique[i].expr[j], deviate->unique[index].expr[j], 1)) { break; } } if (j == deviate->unique[index].expr_size) { /* we have a match, free the unique structure ... */ for (j = 0; j < list->unique[i].expr_size; j++) { lydict_remove(ctx, list->unique[i].expr[j]); } free(list->unique[i].expr); /* ... and maintain the array */ list->unique_size--; if (i != list->unique_size) { list->unique[i].expr_size = list->unique[list->unique_size].expr_size; list->unique[i].expr = list->unique[list->unique_size].expr; } if (!list->unique_size) { free(list->unique); list->unique = NULL; } else { list->unique[list->unique_size].expr_size = 0; list->unique[list->unique_size].expr = NULL; } k = i; /* remember index for removing extensions */ i = -1; /* set match flag */ break; } } if (i != -1) { /* no match found */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "unique"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Value differs from the target being deleted."); return EXIT_FAILURE; } /* remove extensions of this unique instance from the target node */ j = -1; while ((j = lys_ext_iter(list->ext, list->ext_size, j + 1, LYEXT_SUBSTMT_UNIQUE)) != -1) { if (list->ext[j]->insubstmt_index == k) { lyp_ext_instance_rm(ctx, &list->ext, &list->ext_size, j); --j; } else if (list->ext[j]->insubstmt_index > k) { /* decrease the substatement index of the extension because of the changed array of uniques */ list->ext[j]->insubstmt_index--; } } return EXIT_SUCCESS; } int yang_check_deviate_unique(struct lys_module *module, struct lys_deviate *deviate, struct lys_node *dev_target) { struct lys_node_list *list; char *str; uint i = 0; struct lys_unique *last_unique = NULL; if (yang_read_deviate_unique(deviate, dev_target)) { goto error; } list = (struct lys_node_list *)dev_target; last_unique = &list->unique[list->unique_size]; for (i = 0; i < deviate->unique_size; ++i) { str = (char *) deviate->unique[i].expr; if (deviate->mod == LY_DEVIATE_ADD) { if (yang_fill_unique(module, list, &list->unique[list->unique_size], str, NULL)) { free(str); goto error; } list->unique_size++; } else if (deviate->mod == LY_DEVIATE_DEL) { if (yang_fill_unique(module, list, &deviate->unique[i], str, NULL)) { free(str); goto error; } if (yang_deviate_delete_unique(module, deviate, list, i, str)) { free(str); goto error; } } free(str); } if (deviate->mod == LY_DEVIATE_ADD) { free(deviate->unique); deviate->unique = last_unique; } return EXIT_SUCCESS; error: if (deviate->mod == LY_DEVIATE_ADD) { for (i = i + 1; i < deviate->unique_size; ++i) { free(deviate->unique[i].expr); } free(deviate->unique); deviate->unique = last_unique; } return EXIT_FAILURE; } static int yang_fill_include(struct lys_module *trg, char *value, struct lys_include *inc, struct unres_schema *unres) { const char *str; int rc; int ret = 0; str = lydict_insert_zc(trg->ctx, value); rc = lyp_check_include(trg, str, inc, unres); if (!rc) { /* success, copy the filled data into the final array */ memcpy(&trg->inc[trg->inc_size], inc, sizeof *inc); if (yang_check_ext_instance(trg, &trg->inc[trg->inc_size].ext, trg->inc[trg->inc_size].ext_size, &trg->inc[trg->inc_size], unres)) { ret = -1; } trg->inc_size++; } else if (rc == -1) { lys_extension_instances_free(trg->ctx, inc->ext, inc->ext_size, NULL); ret = -1; } lydict_remove(trg->ctx, str); return ret; } struct lys_ext_instance * yang_ext_instance(void *node, enum yytokentype type, int is_ext_instance) { struct lys_ext_instance ***ext, **tmp, *instance = NULL; LYEXT_PAR parent_type; uint8_t *size; switch (type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: ext = &((struct lys_module *)node)->ext; size = &((struct lys_module *)node)->ext_size; parent_type = LYEXT_PAR_MODULE; break; case BELONGS_TO_KEYWORD: if (is_ext_instance) { ext = &((struct lys_ext_instance *)node)->ext; size = &((struct lys_ext_instance *)node)->ext_size; parent_type = LYEXT_PAR_EXTINST; } else { ext = &((struct lys_module *)node)->ext; size = &((struct lys_module *)node)->ext_size; parent_type = LYEXT_PAR_MODULE; } break; case IMPORT_KEYWORD: ext = &((struct lys_import *)node)->ext; size = &((struct lys_import *)node)->ext_size; parent_type = LYEXT_PAR_IMPORT; break; case INCLUDE_KEYWORD: ext = &((struct lys_include *)node)->ext; size = &((struct lys_include *)node)->ext_size; parent_type = LYEXT_PAR_INCLUDE; break; case REVISION_KEYWORD: ext = &((struct lys_revision *)node)->ext; size = &((struct lys_revision *)node)->ext_size; parent_type = LYEXT_PAR_REVISION; break; case GROUPING_KEYWORD: case CONTAINER_KEYWORD: case LEAF_KEYWORD: case LEAF_LIST_KEYWORD: case LIST_KEYWORD: case CHOICE_KEYWORD: case CASE_KEYWORD: case ANYXML_KEYWORD: case ANYDATA_KEYWORD: case USES_KEYWORD: case AUGMENT_KEYWORD: case ACTION_KEYWORD: case RPC_KEYWORD: case INPUT_KEYWORD: case OUTPUT_KEYWORD: case NOTIFICATION_KEYWORD: ext = &((struct lys_node *)node)->ext; size = &((struct lys_node *)node)->ext_size; parent_type = LYEXT_PAR_NODE; break; case ARGUMENT_KEYWORD: if (is_ext_instance) { ext = &((struct lys_ext_instance *)node)->ext; size = &((struct lys_ext_instance *)node)->ext_size; parent_type = LYEXT_PAR_EXTINST; } else { ext = &((struct lys_ext *)node)->ext; size = &((struct lys_ext *)node)->ext_size; parent_type = LYEXT_PAR_EXT; } break; case EXTENSION_KEYWORD: ext = &((struct lys_ext *)node)->ext; size = &((struct lys_ext *)node)->ext_size; parent_type = LYEXT_PAR_EXT; break; case FEATURE_KEYWORD: ext = &((struct lys_feature *)node)->ext; size = &((struct lys_feature *)node)->ext_size; parent_type = LYEXT_PAR_FEATURE; break; case IDENTITY_KEYWORD: ext = &((struct lys_ident *)node)->ext; size = &((struct lys_ident *)node)->ext_size; parent_type = LYEXT_PAR_IDENT; break; case IF_FEATURE_KEYWORD: ext = &((struct lys_iffeature *)node)->ext; size = &((struct lys_iffeature *)node)->ext_size; parent_type = LYEXT_PAR_IFFEATURE; break; case TYPEDEF_KEYWORD: ext = &((struct lys_tpdf *)node)->ext; size = &((struct lys_tpdf *)node)->ext_size; parent_type = LYEXT_PAR_TPDF; break; case TYPE_KEYWORD: ext = &((struct yang_type *)node)->type->ext; size = &((struct yang_type *)node)->type->ext_size; parent_type = LYEXT_PAR_TYPE; break; case LENGTH_KEYWORD: case PATTERN_KEYWORD: case RANGE_KEYWORD: case MUST_KEYWORD: ext = &((struct lys_restr *)node)->ext; size = &((struct lys_restr *)node)->ext_size; parent_type = LYEXT_PAR_RESTR; break; case WHEN_KEYWORD: ext = &((struct lys_when *)node)->ext; size = &((struct lys_when *)node)->ext_size; parent_type = LYEXT_PAR_RESTR; break; case ENUM_KEYWORD: ext = &((struct lys_type_enum *)node)->ext; size = &((struct lys_type_enum *)node)->ext_size; parent_type = LYEXT_PAR_TYPE_ENUM; break; case BIT_KEYWORD: ext = &((struct lys_type_bit *)node)->ext; size = &((struct lys_type_bit *)node)->ext_size; parent_type = LYEXT_PAR_TYPE_BIT; break; case REFINE_KEYWORD: ext = &((struct lys_type_bit *)node)->ext; size = &((struct lys_type_bit *)node)->ext_size; parent_type = LYEXT_PAR_REFINE; break; case DEVIATION_KEYWORD: ext = &((struct lys_deviation *)node)->ext; size = &((struct lys_deviation *)node)->ext_size; parent_type = LYEXT_PAR_DEVIATION; break; case NOT_SUPPORTED_KEYWORD: case ADD_KEYWORD: case DELETE_KEYWORD: case REPLACE_KEYWORD: ext = &((struct lys_deviate *)node)->ext; size = &((struct lys_deviate *)node)->ext_size; parent_type = LYEXT_PAR_DEVIATE; break; case EXTENSION_INSTANCE: ext = &((struct lys_ext_instance *)node)->ext; size = &((struct lys_ext_instance *)node)->ext_size; parent_type = LYEXT_PAR_EXTINST; break; default: LOGINT(NULL); return NULL; } instance = calloc(1, sizeof *instance); if (!instance) { goto error; } instance->parent_type = parent_type; tmp = realloc(*ext, (*size + 1) * sizeof *tmp); if (!tmp) { goto error; } tmp[*size] = instance; *ext = tmp; (*size)++; return instance; error: LOGMEM(NULL); free(instance); return NULL; } void * yang_read_ext(struct lys_module *module, void *actual, char *ext_name, char *ext_arg, enum yytokentype actual_type, enum yytokentype backup_type, int is_ext_instance) { struct lys_ext_instance *instance; LY_STMT stmt = LY_STMT_UNKNOWN; LYEXT_SUBSTMT insubstmt; uint8_t insubstmt_index = 0; if (backup_type != NODE) { switch (actual_type) { case YANG_VERSION_KEYWORD: insubstmt = LYEXT_SUBSTMT_VERSION; stmt = LY_STMT_VERSION; break; case NAMESPACE_KEYWORD: insubstmt = LYEXT_SUBSTMT_NAMESPACE; stmt = LY_STMT_NAMESPACE; break; case PREFIX_KEYWORD: insubstmt = LYEXT_SUBSTMT_PREFIX; stmt = LY_STMT_PREFIX; break; case REVISION_DATE_KEYWORD: insubstmt = LYEXT_SUBSTMT_REVISIONDATE; stmt = LY_STMT_REVISIONDATE; break; case DESCRIPTION_KEYWORD: insubstmt = LYEXT_SUBSTMT_DESCRIPTION; stmt = LY_STMT_DESCRIPTION; break; case REFERENCE_KEYWORD: insubstmt = LYEXT_SUBSTMT_REFERENCE; stmt = LY_STMT_REFERENCE; break; case CONTACT_KEYWORD: insubstmt = LYEXT_SUBSTMT_CONTACT; stmt = LY_STMT_CONTACT; break; case ORGANIZATION_KEYWORD: insubstmt = LYEXT_SUBSTMT_ORGANIZATION; stmt = LY_STMT_ORGANIZATION; break; case YIN_ELEMENT_KEYWORD: insubstmt = LYEXT_SUBSTMT_YINELEM; stmt = LY_STMT_YINELEM; break; case STATUS_KEYWORD: insubstmt = LYEXT_SUBSTMT_STATUS; stmt = LY_STMT_STATUS; break; case BASE_KEYWORD: insubstmt = LYEXT_SUBSTMT_BASE; stmt = LY_STMT_BASE; if (backup_type == IDENTITY_KEYWORD) { insubstmt_index = ((struct lys_ident *)actual)->base_size; } else if (backup_type == TYPE_KEYWORD) { insubstmt_index = ((struct yang_type *)actual)->type->info.ident.count; } break; case DEFAULT_KEYWORD: insubstmt = LYEXT_SUBSTMT_DEFAULT; stmt = LY_STMT_DEFAULT; switch (backup_type) { case LEAF_LIST_KEYWORD: insubstmt_index = ((struct lys_node_leaflist *)actual)->dflt_size; break; case REFINE_KEYWORD: insubstmt_index = ((struct lys_refine *)actual)->dflt_size; break; case ADD_KEYWORD: insubstmt_index = ((struct lys_deviate *)actual)->dflt_size; break; default: /* nothing changes */ break; } break; case UNITS_KEYWORD: insubstmt = LYEXT_SUBSTMT_UNITS; stmt = LY_STMT_UNITS; break; case REQUIRE_INSTANCE_KEYWORD: insubstmt = LYEXT_SUBSTMT_REQINSTANCE; stmt = LY_STMT_REQINSTANCE; break; case PATH_KEYWORD: insubstmt = LYEXT_SUBSTMT_PATH; stmt = LY_STMT_PATH; break; case ERROR_MESSAGE_KEYWORD: insubstmt = LYEXT_SUBSTMT_ERRMSG; stmt = LY_STMT_ERRMSG; break; case ERROR_APP_TAG_KEYWORD: insubstmt = LYEXT_SUBSTMT_ERRTAG; stmt = LY_STMT_ERRTAG; break; case MODIFIER_KEYWORD: insubstmt = LYEXT_SUBSTMT_MODIFIER; stmt = LY_STMT_MODIFIER; break; case FRACTION_DIGITS_KEYWORD: insubstmt = LYEXT_SUBSTMT_DIGITS; stmt = LY_STMT_DIGITS; break; case VALUE_KEYWORD: insubstmt = LYEXT_SUBSTMT_VALUE; stmt = LY_STMT_VALUE; break; case POSITION_KEYWORD: insubstmt = LYEXT_SUBSTMT_POSITION; stmt = LY_STMT_POSITION; break; case PRESENCE_KEYWORD: insubstmt = LYEXT_SUBSTMT_PRESENCE; stmt = LY_STMT_PRESENCE; break; case CONFIG_KEYWORD: insubstmt = LYEXT_SUBSTMT_CONFIG; stmt = LY_STMT_CONFIG; break; case MANDATORY_KEYWORD: insubstmt = LYEXT_SUBSTMT_MANDATORY; stmt = LY_STMT_MANDATORY; break; case MIN_ELEMENTS_KEYWORD: insubstmt = LYEXT_SUBSTMT_MIN; stmt = LY_STMT_MIN; break; case MAX_ELEMENTS_KEYWORD: insubstmt = LYEXT_SUBSTMT_MAX; stmt = LY_STMT_MAX; break; case ORDERED_BY_KEYWORD: insubstmt = LYEXT_SUBSTMT_ORDEREDBY; stmt = LY_STMT_ORDEREDBY; break; case KEY_KEYWORD: insubstmt = LYEXT_SUBSTMT_KEY; stmt = LY_STMT_KEY; break; case UNIQUE_KEYWORD: insubstmt = LYEXT_SUBSTMT_UNIQUE; stmt = LY_STMT_UNIQUE; switch (backup_type) { case LIST_KEYWORD: insubstmt_index = ((struct lys_node_list *)actual)->unique_size; break; case ADD_KEYWORD: case DELETE_KEYWORD: case REPLACE_KEYWORD: insubstmt_index = ((struct lys_deviate *)actual)->unique_size; break; default: /* nothing changes */ break; } break; default: LOGINT(module->ctx); return NULL; } instance = yang_ext_instance(actual, backup_type, is_ext_instance); } else { switch (actual_type) { case ARGUMENT_KEYWORD: insubstmt = LYEXT_SUBSTMT_ARGUMENT; stmt = LY_STMT_ARGUMENT; break; case BELONGS_TO_KEYWORD: insubstmt = LYEXT_SUBSTMT_BELONGSTO; stmt = LY_STMT_BELONGSTO; break; default: insubstmt = LYEXT_SUBSTMT_SELF; break; } instance = yang_ext_instance(actual, actual_type, is_ext_instance); } if (!instance) { return NULL; } instance->insubstmt = insubstmt; instance->insubstmt_index = insubstmt_index; instance->flags |= LYEXT_OPT_YANG; instance->def = (struct lys_ext *)ext_name; /* hack for UNRES */ instance->arg_value = lydict_insert_zc(module->ctx, ext_arg); if (is_ext_instance && stmt != LY_STMT_UNKNOWN && instance->parent_type == LYEXT_PAR_EXTINST) { instance->insubstmt_index = yang_fill_ext_substm_index(actual, stmt, backup_type); } return instance; } static int check_status_flag(struct lys_node *node, struct lys_node *parent) { struct ly_ctx *ctx = node->module->ctx; char *str; if (node->nodetype & (LYS_OUTPUT | LYS_INPUT)) { return EXIT_SUCCESS; } if (parent && (parent->flags & (LYS_STATUS_DEPRC | LYS_STATUS_OBSLT))) { /* status is not inherited by specification, but it not make sense to have * current in deprecated or deprecated in obsolete, so we print warning * and fix the schema by inheriting */ if (!(node->flags & (LYS_STATUS_MASK))) { /* status not explicitely specified on the current node -> inherit */ str = lys_path(node, LYS_PATH_FIRST_PREFIX); LOGWRN(ctx, "Missing status in %s subtree (%s), inheriting.", parent->flags & LYS_STATUS_DEPRC ? "deprecated" : "obsolete", str); free(str); node->flags |= parent->flags & LYS_STATUS_MASK; } else if ((parent->flags & LYS_STATUS_MASK) > (node->flags & LYS_STATUS_MASK)) { /* invalid combination of statuses */ switch (node->flags & LYS_STATUS_MASK) { case 0: case LYS_STATUS_CURR: LOGVAL(ctx, LYE_INSTATUS, LY_VLOG_LYS, parent, "current", strnodetype(node->nodetype), "is child of", parent->flags & LYS_STATUS_DEPRC ? "deprecated" : "obsolete", parent->name); break; case LYS_STATUS_DEPRC: LOGVAL(ctx, LYE_INSTATUS, LY_VLOG_LYS, parent, "deprecated", strnodetype(node->nodetype), "is child of", "obsolete", parent->name); break; } return EXIT_FAILURE; } } return EXIT_SUCCESS; } int store_config_flag(struct lys_node *node, int options) { switch (node->nodetype) { case LYS_CONTAINER: case LYS_LEAF: case LYS_LEAFLIST: case LYS_LIST: case LYS_CHOICE: case LYS_ANYDATA: case LYS_ANYXML: if (options & LYS_PARSE_OPT_CFG_IGNORE) { node->flags |= node->flags & (~(LYS_CONFIG_MASK | LYS_CONFIG_SET)); } else if (!(options & LYS_PARSE_OPT_CFG_NOINHERIT)) { if (!(node->flags & LYS_CONFIG_MASK)) { /* get config flag from parent */ if (node->parent) { node->flags |= node->parent->flags & LYS_CONFIG_MASK; } else { /* default config is true */ node->flags |= LYS_CONFIG_W; } } } break; case LYS_CASE: if (!(options & (LYS_PARSE_OPT_CFG_IGNORE | LYS_PARSE_OPT_CFG_NOINHERIT))) { if (!(node->flags & LYS_CONFIG_MASK)) { /* get config flag from parent */ if (node->parent) { node->flags |= node->parent->flags & LYS_CONFIG_MASK; } else { /* default config is true */ node->flags |= LYS_CONFIG_W; } } } break; default: break; } return EXIT_SUCCESS; } int yang_parse_mem(struct lys_module *module, struct lys_submodule *submodule, struct unres_schema *unres, const char *data, unsigned int size_data, struct lys_node **node) { unsigned int size; YY_BUFFER_STATE bp; yyscan_t scanner = NULL; int ret = 0; struct lys_module *trg; struct yang_parameter param; size = (size_data) ? size_data : strlen(data) + 2; yylex_init(&scanner); yyset_extra(module->ctx, scanner); bp = yy_scan_buffer((char *)data, size, scanner); yy_switch_to_buffer(bp, scanner); memset(&param, 0, sizeof param); param.module = module; param.submodule = submodule; param.unres = unres; param.node = node; param.flags |= YANG_REMOVE_IMPORT; if (yyparse(scanner, &param)) { if (param.flags & YANG_REMOVE_IMPORT) { trg = (submodule) ? (struct lys_module *)submodule : module; yang_free_import(trg->ctx, trg->imp, 0, trg->imp_size); yang_free_include(trg->ctx, trg->inc, 0, trg->inc_size); trg->inc_size = 0; trg->imp_size = 0; } ret = (param.flags & YANG_EXIST_MODULE) ? 1 : -1; } yy_delete_buffer(bp, scanner); yylex_destroy(scanner); return ret; } int yang_parse_ext_substatement(struct lys_module *module, struct unres_schema *unres, const char *data, char *ext_name, struct lys_ext_instance_complex *ext) { unsigned int size; YY_BUFFER_STATE bp; yyscan_t scanner = NULL; int ret = 0; struct yang_parameter param; struct lys_node *node = NULL; if (!data) { return EXIT_SUCCESS; } size = strlen(data) + 2; yylex_init(&scanner); bp = yy_scan_buffer((char *)data, size, scanner); yy_switch_to_buffer(bp, scanner); memset(&param, 0, sizeof param); param.module = module; param.unres = unres; param.node = &node; param.actual_node = (void **)ext; param.data_node = (void **)ext_name; param.flags |= EXT_INSTANCE_SUBSTMT; if (yyparse(scanner, &param)) { yang_free_nodes(module->ctx, node); ret = -1; } else { /* success parse, but it needs some sematic controls */ if (node && yang_check_nodes(module, (struct lys_node *)ext, node, LYS_PARSE_OPT_CFG_NOINHERIT, unres)) { ret = -1; } } yy_delete_buffer(bp, scanner); yylex_destroy(scanner); return ret; } struct lys_module * yang_read_module(struct ly_ctx *ctx, const char* data, unsigned int size, const char *revision, int implement) { struct lys_module *module = NULL, *tmp_mod; struct unres_schema *unres = NULL; struct lys_node *node = NULL; int ret; unres = calloc(1, sizeof *unres); LY_CHECK_ERR_GOTO(!unres, LOGMEM(ctx), error); module = calloc(1, sizeof *module); LY_CHECK_ERR_GOTO(!module, LOGMEM(ctx), error); /* initiale module */ module->ctx = ctx; module->type = 0; module->implemented = (implement ? 1 : 0); /* add into the list of processed modules */ if (lyp_check_circmod_add(module)) { goto error; } ret = yang_parse_mem(module, NULL, unres, data, size, &node); if (ret == -1) { if (ly_vecode(ctx) == LYVE_SUBMODULE && !module->name) { /* Remove this module from the list of processed modules, as we're about to free it */ lyp_check_circmod_pop(ctx); free(module); module = NULL; } else { free_yang_common(module, node); } goto error; } else if (ret == 1) { assert(!unres->count); } else { if (yang_check_sub_module(module, unres, node)) { goto error; } if (!implement && module->implemented && lys_make_implemented_r(module, unres)) { goto error; } if (unres->count && resolve_unres_schema(module, unres)) { goto error; } /* check correctness of includes */ if (lyp_check_include_missing(module)) { goto error; } } lyp_sort_revisions(module); if (lyp_rfn_apply_ext(module) || lyp_deviation_apply_ext(module)) { goto error; } if (revision) { /* check revision of the parsed model */ if (!module->rev_size || strcmp(revision, module->rev[0].date)) { LOGVRB("Module \"%s\" parsed with the wrong revision (\"%s\" instead \"%s\").", module->name, module->rev[0].date, revision); goto error; } } /* add into context if not already there */ if (!ret) { if (lyp_ctx_add_module(module)) { goto error; } /* remove our submodules from the parsed submodules list */ lyp_del_includedup(module, 0); } else { tmp_mod = module; /* get the model from the context */ module = (struct lys_module *)ly_ctx_get_module(ctx, module->name, revision, 0); assert(module); /* free what was parsed */ lys_free(tmp_mod, NULL, 0, 0); } unres_schema_free(NULL, &unres, 0); lyp_check_circmod_pop(ctx); LOGVRB("Module \"%s%s%s\" successfully parsed as %s.", module->name, (module->rev_size ? "@" : ""), (module->rev_size ? module->rev[0].date : ""), (module->implemented ? "implemented" : "imported")); return module; error: /* cleanup */ unres_schema_free(module, &unres, 1); if (!module) { if (ly_vecode(ctx) != LYVE_SUBMODULE) { LOGERR(ctx, ly_errno, "Module parsing failed."); } return NULL; } if (module->name) { LOGERR(ctx, ly_errno, "Module \"%s\" parsing failed.", module->name); } else { LOGERR(ctx, ly_errno, "Module parsing failed."); } lyp_check_circmod_pop(ctx); lys_sub_module_remove_devs_augs(module); lyp_del_includedup(module, 1); lys_free(module, NULL, 0, 1); return NULL; } struct lys_submodule * yang_read_submodule(struct lys_module *module, const char *data, unsigned int size, struct unres_schema *unres) { struct lys_submodule *submodule; struct lys_node *node = NULL; submodule = calloc(1, sizeof *submodule); LY_CHECK_ERR_GOTO(!submodule, LOGMEM(module->ctx), error); submodule->ctx = module->ctx; submodule->type = 1; submodule->implemented = module->implemented; submodule->belongsto = module; /* add into the list of processed modules */ if (lyp_check_circmod_add((struct lys_module *)submodule)) { goto error; } /* module cannot be changed in this case and 1 cannot be returned */ if (yang_parse_mem(module, submodule, unres, data, size, &node)) { free_yang_common((struct lys_module *)submodule, node); goto error; } lyp_sort_revisions((struct lys_module *)submodule); if (yang_check_sub_module((struct lys_module *)submodule, unres, node)) { goto error; } lyp_check_circmod_pop(module->ctx); LOGVRB("Submodule \"%s\" successfully parsed.", submodule->name); return submodule; error: /* cleanup */ if (!submodule || !submodule->name) { free(submodule); LOGERR(module->ctx, ly_errno, "Submodule parsing failed."); return NULL; } LOGERR(module->ctx, ly_errno, "Submodule \"%s\" parsing failed.", submodule->name); unres_schema_free((struct lys_module *)submodule, &unres, 0); lyp_check_circmod_pop(module->ctx); lys_sub_module_remove_devs_augs((struct lys_module *)submodule); lys_submodule_module_data_free(submodule); lys_submodule_free(submodule, NULL); return NULL; } static int read_indent(const char *input, int indent, int size, int in_index, int *out_index, char *output) { int k = 0, j; while (in_index < size) { if (input[in_index] == ' ') { k++; } else if (input[in_index] == '\t') { /* RFC 6020 6.1.3 tab character is treated as 8 space characters */ k += 8; } else if (input[in_index] == '\\' && input[in_index + 1] == 't') { /* RFC 6020 6.1.3 tab character is treated as 8 space characters */ k += 8; ++in_index; } else { break; } ++in_index; if (k >= indent) { for (j = k - indent; j > 0; --j) { output[*out_index] = ' '; if (j > 1) { ++(*out_index); } } break; } } return in_index - 1; } char * yang_read_string(struct ly_ctx *ctx, const char *input, char *output, int size, int offset, int indent) { int i = 0, out_index = offset, space = 0; while (i < size) { switch (input[i]) { case '\n': out_index -= space; output[out_index] = '\n'; space = 0; i = read_indent(input, indent, size, i + 1, &out_index, output); break; case ' ': case '\t': output[out_index] = input[i]; ++space; break; case '\\': if (input[i + 1] == 'n') { out_index -= space; output[out_index] = '\n'; space = 0; i = read_indent(input, indent, size, i + 2, &out_index, output); } else if (input[i + 1] == 't') { output[out_index] = '\t'; ++i; ++space; } else if (input[i + 1] == '\\') { output[out_index] = '\\'; ++i; } else if ((i + 1) != size && input[i + 1] == '"') { output[out_index] = '"'; ++i; } else { /* backslash must not be followed by any other character */ LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, input + i); return NULL; } break; default: output[out_index] = input[i]; space = 0; break; } ++i; ++out_index; } output[out_index] = '\0'; if (size != out_index) { output = realloc(output, out_index + 1); LY_CHECK_ERR_RETURN(!output, LOGMEM(ctx), NULL); } return output; } /* free function */ void yang_type_free(struct ly_ctx *ctx, struct lys_type *type) { struct yang_type *stype = (struct yang_type *)type->der; unsigned int i; if (!stype) { return ; } if (type->base == LY_TYPE_DER || type->base == LY_TYPE_UNION) { lydict_remove(ctx, stype->name); if (stype->base == LY_TYPE_IDENT && (!(stype->flags & LYS_NO_ERASE_IDENTITY))) { for (i = 0; i < type->info.ident.count; ++i) { free(type->info.ident.ref[i]); } } if (stype->base == LY_TYPE_UNION) { for (i = 0; i < type->info.uni.count; ++i) { yang_type_free(ctx, &type->info.uni.types[i]); } free(type->info.uni.types); type->base = LY_TYPE_DER; } else { type->base = stype->base; } free(stype); type->der = NULL; } lys_type_free(ctx, type, NULL); memset(type, 0, sizeof (struct lys_type)); } static void yang_tpdf_free(struct ly_ctx *ctx, struct lys_tpdf *tpdf, uint16_t start, uint16_t size) { uint8_t i; assert(ctx); if (!tpdf) { return; } for (i = start; i < size; ++i) { lydict_remove(ctx, tpdf[i].name); lydict_remove(ctx, tpdf[i].dsc); lydict_remove(ctx, tpdf[i].ref); yang_type_free(ctx, &tpdf[i].type); lydict_remove(ctx, tpdf[i].units); lydict_remove(ctx, tpdf[i].dflt); lys_extension_instances_free(ctx, tpdf[i].ext, tpdf[i].ext_size, NULL); } } static void yang_free_import(struct ly_ctx *ctx, struct lys_import *imp, uint8_t start, uint8_t size) { uint8_t i; for (i = start; i < size; ++i){ free((char *)imp[i].module); lydict_remove(ctx, imp[i].prefix); lydict_remove(ctx, imp[i].dsc); lydict_remove(ctx, imp[i].ref); lys_extension_instances_free(ctx, imp[i].ext, imp[i].ext_size, NULL); } } static void yang_free_include(struct ly_ctx *ctx, struct lys_include *inc, uint8_t start, uint8_t size) { uint8_t i; for (i = start; i < size; ++i){ free((char *)inc[i].submodule); lydict_remove(ctx, inc[i].dsc); lydict_remove(ctx, inc[i].ref); lys_extension_instances_free(ctx, inc[i].ext, inc[i].ext_size, NULL); } } static void yang_free_ident_base(struct lys_ident *ident, uint32_t start, uint32_t size) { uint32_t i; uint8_t j; /* free base name */ for (i = start; i < size; ++i) { for (j = 0; j < ident[i].base_size; ++j) { free(ident[i].base[j]); } } } static void yang_free_grouping(struct ly_ctx *ctx, struct lys_node_grp * grp) { yang_tpdf_free(ctx, grp->tpdf, 0, grp->tpdf_size); free(grp->tpdf); } static void yang_free_container(struct ly_ctx *ctx, struct lys_node_container * cont) { uint8_t i; yang_tpdf_free(ctx, cont->tpdf, 0, cont->tpdf_size); free(cont->tpdf); lydict_remove(ctx, cont->presence); for (i = 0; i < cont->must_size; ++i) { lys_restr_free(ctx, &cont->must[i], NULL); } free(cont->must); lys_when_free(ctx, cont->when, NULL); } static void yang_free_leaf(struct ly_ctx *ctx, struct lys_node_leaf *leaf) { uint8_t i; for (i = 0; i < leaf->must_size; i++) { lys_restr_free(ctx, &leaf->must[i], NULL); } free(leaf->must); lys_when_free(ctx, leaf->when, NULL); yang_type_free(ctx, &leaf->type); lydict_remove(ctx, leaf->units); lydict_remove(ctx, leaf->dflt); } static void yang_free_leaflist(struct ly_ctx *ctx, struct lys_node_leaflist *leaflist) { uint8_t i; for (i = 0; i < leaflist->must_size; i++) { lys_restr_free(ctx, &leaflist->must[i], NULL); } free(leaflist->must); for (i = 0; i < leaflist->dflt_size; i++) { lydict_remove(ctx, leaflist->dflt[i]); } free(leaflist->dflt); lys_when_free(ctx, leaflist->when, NULL); yang_type_free(ctx, &leaflist->type); lydict_remove(ctx, leaflist->units); } static void yang_free_list(struct ly_ctx *ctx, struct lys_node_list *list) { uint8_t i; yang_tpdf_free(ctx, list->tpdf, 0, list->tpdf_size); free(list->tpdf); for (i = 0; i < list->must_size; ++i) { lys_restr_free(ctx, &list->must[i], NULL); } free(list->must); lys_when_free(ctx, list->when, NULL); for (i = 0; i < list->unique_size; ++i) { free(list->unique[i].expr); } free(list->unique); free(list->keys); } static void yang_free_choice(struct ly_ctx *ctx, struct lys_node_choice *choice) { free(choice->dflt); lys_when_free(ctx, choice->when, NULL); } static void yang_free_anydata(struct ly_ctx *ctx, struct lys_node_anydata *anydata) { uint8_t i; for (i = 0; i < anydata->must_size; ++i) { lys_restr_free(ctx, &anydata->must[i], NULL); } free(anydata->must); lys_when_free(ctx, anydata->when, NULL); } static void yang_free_inout(struct ly_ctx *ctx, struct lys_node_inout *inout) { uint8_t i; yang_tpdf_free(ctx, inout->tpdf, 0, inout->tpdf_size); free(inout->tpdf); for (i = 0; i < inout->must_size; ++i) { lys_restr_free(ctx, &inout->must[i], NULL); } free(inout->must); } static void yang_free_notif(struct ly_ctx *ctx, struct lys_node_notif *notif) { uint8_t i; yang_tpdf_free(ctx, notif->tpdf, 0, notif->tpdf_size); free(notif->tpdf); for (i = 0; i < notif->must_size; ++i) { lys_restr_free(ctx, &notif->must[i], NULL); } free(notif->must); } static void yang_free_uses(struct ly_ctx *ctx, struct lys_node_uses *uses) { int i, j; for (i = 0; i < uses->refine_size; i++) { lydict_remove(ctx, uses->refine[i].target_name); lydict_remove(ctx, uses->refine[i].dsc); lydict_remove(ctx, uses->refine[i].ref); for (j = 0; j < uses->refine[i].must_size; j++) { lys_restr_free(ctx, &uses->refine[i].must[j], NULL); } free(uses->refine[i].must); for (j = 0; j < uses->refine[i].dflt_size; j++) { lydict_remove(ctx, uses->refine[i].dflt[j]); } free(uses->refine[i].dflt); if (uses->refine[i].target_type & LYS_CONTAINER) { lydict_remove(ctx, uses->refine[i].mod.presence); } lys_extension_instances_free(ctx, uses->refine[i].ext, uses->refine[i].ext_size, NULL); } free(uses->refine); lys_when_free(ctx, uses->when, NULL); } static void yang_free_nodes(struct ly_ctx *ctx, struct lys_node *node) { struct lys_node *tmp, *child, *sibling; if (!node) { return; } tmp = node; while (tmp) { child = tmp->child; sibling = tmp->next; /* common part */ lydict_remove(ctx, tmp->name); if (!(tmp->nodetype & (LYS_INPUT | LYS_OUTPUT))) { lys_iffeature_free(ctx, tmp->iffeature, tmp->iffeature_size, 0, NULL); lydict_remove(ctx, tmp->dsc); lydict_remove(ctx, tmp->ref); } switch (tmp->nodetype) { case LYS_GROUPING: case LYS_RPC: case LYS_ACTION: yang_free_grouping(ctx, (struct lys_node_grp *)tmp); break; case LYS_CONTAINER: yang_free_container(ctx, (struct lys_node_container *)tmp); break; case LYS_LEAF: yang_free_leaf(ctx, (struct lys_node_leaf *)tmp); break; case LYS_LEAFLIST: yang_free_leaflist(ctx, (struct lys_node_leaflist *)tmp); break; case LYS_LIST: yang_free_list(ctx, (struct lys_node_list *)tmp); break; case LYS_CHOICE: yang_free_choice(ctx, (struct lys_node_choice *)tmp); break; case LYS_CASE: lys_when_free(ctx, ((struct lys_node_case *)tmp)->when, NULL); break; case LYS_ANYXML: case LYS_ANYDATA: yang_free_anydata(ctx, (struct lys_node_anydata *)tmp); break; case LYS_INPUT: case LYS_OUTPUT: yang_free_inout(ctx, (struct lys_node_inout *)tmp); break; case LYS_NOTIF: yang_free_notif(ctx, (struct lys_node_notif *)tmp); break; case LYS_USES: yang_free_uses(ctx, (struct lys_node_uses *)tmp); break; default: break; } lys_extension_instances_free(ctx, tmp->ext, tmp->ext_size, NULL); yang_free_nodes(ctx, child); free(tmp); tmp = sibling; } } static void yang_free_augment(struct ly_ctx *ctx, struct lys_node_augment *aug) { lydict_remove(ctx, aug->target_name); lydict_remove(ctx, aug->dsc); lydict_remove(ctx, aug->ref); lys_iffeature_free(ctx, aug->iffeature, aug->iffeature_size, 0, NULL); lys_when_free(ctx, aug->when, NULL); yang_free_nodes(ctx, aug->child); lys_extension_instances_free(ctx, aug->ext, aug->ext_size, NULL); } static void yang_free_deviate(struct ly_ctx *ctx, struct lys_deviation *dev, uint index) { uint i, j; for (i = index; i < dev->deviate_size; ++i) { lydict_remove(ctx, dev->deviate[i].units); if (dev->deviate[i].type) { yang_type_free(ctx, dev->deviate[i].type); free(dev->deviate[i].type); } for (j = 0; j < dev->deviate[i].dflt_size; ++j) { lydict_remove(ctx, dev->deviate[i].dflt[j]); } free(dev->deviate[i].dflt); for (j = 0; j < dev->deviate[i].must_size; ++j) { lys_restr_free(ctx, &dev->deviate[i].must[j], NULL); } free(dev->deviate[i].must); for (j = 0; j < dev->deviate[i].unique_size; ++j) { free(dev->deviate[i].unique[j].expr); } free(dev->deviate[i].unique); lys_extension_instances_free(ctx, dev->deviate[i].ext, dev->deviate[i].ext_size, NULL); } } void yang_free_ext_data(struct yang_ext_substmt *substmt) { int i; if (!substmt) { return; } free(substmt->ext_substmt); if (substmt->ext_modules) { for (i = 0; substmt->ext_modules[i]; ++i) { free(substmt->ext_modules[i]); } free(substmt->ext_modules); } free(substmt); } /* free common item from module and submodule */ static void free_yang_common(struct lys_module *module, struct lys_node *node) { uint i; yang_tpdf_free(module->ctx, module->tpdf, 0, module->tpdf_size); module->tpdf_size = 0; yang_free_ident_base(module->ident, 0, module->ident_size); yang_free_nodes(module->ctx, node); for (i = 0; i < module->augment_size; ++i) { yang_free_augment(module->ctx, &module->augment[i]); } module->augment_size = 0; for (i = 0; i < module->deviation_size; ++i) { yang_free_deviate(module->ctx, &module->deviation[i], 0); free(module->deviation[i].deviate); lydict_remove(module->ctx, module->deviation[i].target_name); lydict_remove(module->ctx, module->deviation[i].dsc); lydict_remove(module->ctx, module->deviation[i].ref); } module->deviation_size = 0; } /* check function*/ int yang_check_ext_instance(struct lys_module *module, struct lys_ext_instance ***ext, uint size, void *parent, struct unres_schema *unres) { struct unres_ext *info; uint i; for (i = 0; i < size; ++i) { info = malloc(sizeof *info); LY_CHECK_ERR_RETURN(!info, LOGMEM(module->ctx), EXIT_FAILURE); info->data.yang = (*ext)[i]->parent; info->datatype = LYS_IN_YANG; info->parent = parent; info->mod = module; info->parent_type = (*ext)[i]->parent_type; info->substmt = (*ext)[i]->insubstmt; info->substmt_index = (*ext)[i]->insubstmt_index; info->ext_index = i; if (unres_schema_add_node(module, unres, ext, UNRES_EXT, (struct lys_node *)info) == -1) { return EXIT_FAILURE; } } return EXIT_SUCCESS; } int yang_check_imports(struct lys_module *module, struct unres_schema *unres) { struct lys_import *imp; struct lys_include *inc; uint8_t imp_size, inc_size, j = 0, i = 0; char *s; imp = module->imp; imp_size = module->imp_size; inc = module->inc; inc_size = module->inc_size; if (imp_size) { module->imp = calloc(imp_size, sizeof *module->imp); module->imp_size = 0; LY_CHECK_ERR_GOTO(!module->imp, LOGMEM(module->ctx), error); } if (inc_size) { module->inc = calloc(inc_size, sizeof *module->inc); module->inc_size = 0; LY_CHECK_ERR_GOTO(!module->inc, LOGMEM(module->ctx), error); } for (i = 0; i < imp_size; ++i) { s = (char *) imp[i].module; imp[i].module = NULL; if (yang_fill_import(module, &imp[i], &module->imp[module->imp_size], s, unres)) { ++i; goto error; } } for (j = 0; j < inc_size; ++j) { s = (char *) inc[j].submodule; inc[j].submodule = NULL; if (yang_fill_include(module, s, &inc[j], unres)) { ++j; goto error; } } free(inc); free(imp); return EXIT_SUCCESS; error: yang_free_import(module->ctx, imp, i, imp_size); yang_free_include(module->ctx, inc, j, inc_size); free(imp); free(inc); return EXIT_FAILURE; } static int yang_check_iffeatures(struct lys_module *module, void *ptr, void *parent, enum yytokentype type, struct unres_schema *unres) { struct lys_iffeature *iffeature; uint8_t *ptr_size, size, i; char *s; int parent_is_feature = 0; switch (type) { case FEATURE_KEYWORD: iffeature = ((struct lys_feature *)parent)->iffeature; size = ((struct lys_feature *)parent)->iffeature_size; ptr_size = &((struct lys_feature *)parent)->iffeature_size; parent_is_feature = 1; break; case IDENTITY_KEYWORD: iffeature = ((struct lys_ident *)parent)->iffeature; size = ((struct lys_ident *)parent)->iffeature_size; ptr_size = &((struct lys_ident *)parent)->iffeature_size; break; case ENUM_KEYWORD: iffeature = ((struct lys_type_enum *)ptr)->iffeature; size = ((struct lys_type_enum *)ptr)->iffeature_size; ptr_size = &((struct lys_type_enum *)ptr)->iffeature_size; break; case BIT_KEYWORD: iffeature = ((struct lys_type_bit *)ptr)->iffeature; size = ((struct lys_type_bit *)ptr)->iffeature_size; ptr_size = &((struct lys_type_bit *)ptr)->iffeature_size; break; case REFINE_KEYWORD: iffeature = ((struct lys_refine *)ptr)->iffeature; size = ((struct lys_refine *)ptr)->iffeature_size; ptr_size = &((struct lys_refine *)ptr)->iffeature_size; break; default: iffeature = ((struct lys_node *)parent)->iffeature; size = ((struct lys_node *)parent)->iffeature_size; ptr_size = &((struct lys_node *)parent)->iffeature_size; break; } *ptr_size = 0; for (i = 0; i < size; ++i) { s = (char *)iffeature[i].features; iffeature[i].features = NULL; if (yang_fill_iffeature(module, &iffeature[i], parent, s, unres, parent_is_feature)) { *ptr_size = size; return EXIT_FAILURE; } if (yang_check_ext_instance(module, &iffeature[i].ext, iffeature[i].ext_size, &iffeature[i], unres)) { *ptr_size = size; return EXIT_FAILURE; } (*ptr_size)++; } return EXIT_SUCCESS; } static int yang_check_identityref(struct lys_module *module, struct lys_type *type, struct unres_schema *unres) { uint size, i; int rc; struct lys_ident **ref; const char *value; char *expr; ref = type->info.ident.ref; size = type->info.ident.count; type->info.ident.count = 0; type->info.ident.ref = NULL; ((struct yang_type *)type->der)->flags |= LYS_NO_ERASE_IDENTITY; for (i = 0; i < size; ++i) { expr = (char *)ref[i]; /* store in the JSON format */ value = transform_schema2json(module, expr); free(expr); if (!value) { goto error; } rc = unres_schema_add_str(module, unres, type, UNRES_TYPE_IDENTREF, value); lydict_remove(module->ctx, value); if (rc == -1) { goto error; } } free(ref); return EXIT_SUCCESS; error: for (i = i+1; i < size; ++i) { free(ref[i]); } free(ref); return EXIT_FAILURE; } int yang_fill_type(struct lys_module *module, struct lys_type *type, struct yang_type *stype, void *parent, struct unres_schema *unres) { unsigned int i, j; type->parent = parent; if (yang_check_ext_instance(module, &type->ext, type->ext_size, type, unres)) { return EXIT_FAILURE; } for (j = 0; j < type->ext_size; ++j) { if (type->ext[j]->flags & LYEXT_OPT_VALID) { type->parent->flags |= LYS_VALID_EXT; break; } } switch (stype->base) { case LY_TYPE_ENUM: for (i = 0; i < type->info.enums.count; ++i) { if (yang_check_iffeatures(module, &type->info.enums.enm[i], parent, ENUM_KEYWORD, unres)) { return EXIT_FAILURE; } if (yang_check_ext_instance(module, &type->info.enums.enm[i].ext, type->info.enums.enm[i].ext_size, &type->info.enums.enm[i], unres)) { return EXIT_FAILURE; } for (j = 0; j < type->info.enums.enm[i].ext_size; ++j) { if (type->info.enums.enm[i].ext[j]->flags & LYEXT_OPT_VALID) { type->parent->flags |= LYS_VALID_EXT; break; } } } break; case LY_TYPE_BITS: for (i = 0; i < type->info.bits.count; ++i) { if (yang_check_iffeatures(module, &type->info.bits.bit[i], parent, BIT_KEYWORD, unres)) { return EXIT_FAILURE; } if (yang_check_ext_instance(module, &type->info.bits.bit[i].ext, type->info.bits.bit[i].ext_size, &type->info.bits.bit[i], unres)) { return EXIT_FAILURE; } for (j = 0; j < type->info.bits.bit[i].ext_size; ++j) { if (type->info.bits.bit[i].ext[j]->flags & LYEXT_OPT_VALID) { type->parent->flags |= LYS_VALID_EXT; break; } } } break; case LY_TYPE_IDENT: if (yang_check_identityref(module, type, unres)) { return EXIT_FAILURE; } break; case LY_TYPE_STRING: if (type->info.str.length) { if (yang_check_ext_instance(module, &type->info.str.length->ext, type->info.str.length->ext_size, type->info.str.length, unres)) { return EXIT_FAILURE; } for (j = 0; j < type->info.str.length->ext_size; ++j) { if (type->info.str.length->ext[j]->flags & LYEXT_OPT_VALID) { type->parent->flags |= LYS_VALID_EXT; break; } } } for (i = 0; i < type->info.str.pat_count; ++i) { if (yang_check_ext_instance(module, &type->info.str.patterns[i].ext, type->info.str.patterns[i].ext_size, &type->info.str.patterns[i], unres)) { return EXIT_FAILURE; } for (j = 0; j < type->info.str.patterns[i].ext_size; ++j) { if (type->info.str.patterns[i].ext[j]->flags & LYEXT_OPT_VALID) { type->parent->flags |= LYS_VALID_EXT; break; } } } break; case LY_TYPE_DEC64: if (type->info.dec64.range) { if (yang_check_ext_instance(module, &type->info.dec64.range->ext, type->info.dec64.range->ext_size, type->info.dec64.range, unres)) { return EXIT_FAILURE; } for (j = 0; j < type->info.dec64.range->ext_size; ++j) { if (type->info.dec64.range->ext[j]->flags & LYEXT_OPT_VALID) { type->parent->flags |= LYS_VALID_EXT; break; } } } break; case LY_TYPE_UNION: for (i = 0; i < type->info.uni.count; ++i) { if (yang_fill_type(module, &type->info.uni.types[i], (struct yang_type *)type->info.uni.types[i].der, parent, unres)) { return EXIT_FAILURE; } } break; default: /* nothing checks */ break; } return EXIT_SUCCESS; } int yang_check_typedef(struct lys_module *module, struct lys_node *parent, struct unres_schema *unres) { struct lys_tpdf *tpdf; uint8_t *ptr_tpdf_size = NULL; uint16_t j, i, tpdf_size, *ptr_tpdf_size16 = NULL; if (!parent) { tpdf = module->tpdf; //ptr_tpdf_size = &module->tpdf_size; ptr_tpdf_size16 = &module->tpdf_size; } else { switch (parent->nodetype) { case LYS_GROUPING: tpdf = ((struct lys_node_grp *)parent)->tpdf; ptr_tpdf_size16 = &((struct lys_node_grp *)parent)->tpdf_size; break; case LYS_CONTAINER: tpdf = ((struct lys_node_container *)parent)->tpdf; ptr_tpdf_size16 = &((struct lys_node_container *)parent)->tpdf_size; break; case LYS_LIST: tpdf = ((struct lys_node_list *)parent)->tpdf; ptr_tpdf_size = &((struct lys_node_list *)parent)->tpdf_size; break; case LYS_RPC: case LYS_ACTION: tpdf = ((struct lys_node_rpc_action *)parent)->tpdf; ptr_tpdf_size16 = &((struct lys_node_rpc_action *)parent)->tpdf_size; break; case LYS_INPUT: case LYS_OUTPUT: tpdf = ((struct lys_node_inout *)parent)->tpdf; ptr_tpdf_size16 = &((struct lys_node_inout *)parent)->tpdf_size; break; case LYS_NOTIF: tpdf = ((struct lys_node_notif *)parent)->tpdf; ptr_tpdf_size16 = &((struct lys_node_notif *)parent)->tpdf_size; break; default: LOGINT(module->ctx); return EXIT_FAILURE; } } if (ptr_tpdf_size16) { tpdf_size = *ptr_tpdf_size16; *ptr_tpdf_size16 = 0; } else { tpdf_size = *ptr_tpdf_size; *ptr_tpdf_size = 0; } for (i = 0; i < tpdf_size; ++i) { if (lyp_check_identifier(module->ctx, tpdf[i].name, LY_IDENT_TYPE, module, parent)) { goto error; } if (yang_fill_type(module, &tpdf[i].type, (struct yang_type *)tpdf[i].type.der, &tpdf[i], unres)) { goto error; } if (yang_check_ext_instance(module, &tpdf[i].ext, tpdf[i].ext_size, &tpdf[i], unres)) { goto error; } for (j = 0; j < tpdf[i].ext_size; ++j) { if (tpdf[i].ext[j]->flags & LYEXT_OPT_VALID) { tpdf[i].flags |= LYS_VALID_EXT; break; } } if (unres_schema_add_node(module, unres, &tpdf[i].type, UNRES_TYPE_DER_TPDF, parent) == -1) { goto error; } if (ptr_tpdf_size16) { (*ptr_tpdf_size16)++; } else { (*ptr_tpdf_size)++; } /* check default value*/ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && unres_schema_add_node(module, unres, &tpdf[i].type, UNRES_TYPEDEF_DFLT, (struct lys_node *)(&tpdf[i].dflt)) == -1) { ++i; goto error; } } return EXIT_SUCCESS; error: yang_tpdf_free(module->ctx, tpdf, i, tpdf_size); return EXIT_FAILURE; } static int yang_check_identities(struct lys_module *module, struct unres_schema *unres) { uint32_t i, size, base_size; uint8_t j; size = module->ident_size; module->ident_size = 0; for (i = 0; i < size; ++i) { base_size = module->ident[i].base_size; module->ident[i].base_size = 0; for (j = 0; j < base_size; ++j) { if (yang_read_base(module, &module->ident[i], (char *)module->ident[i].base[j], unres)) { ++j; module->ident_size = size; goto error; } } module->ident_size++; if (yang_check_iffeatures(module, NULL, &module->ident[i], IDENTITY_KEYWORD, unres)) { goto error; } if (yang_check_ext_instance(module, &module->ident[i].ext, module->ident[i].ext_size, &module->ident[i], unres)) { goto error; } } return EXIT_SUCCESS; error: for (; j< module->ident[i].base_size; ++j) { free(module->ident[i].base[j]); } yang_free_ident_base(module->ident, i + 1, size); return EXIT_FAILURE; } static int yang_check_must(struct lys_module *module, struct lys_restr *must, uint size, struct unres_schema *unres) { uint i; for (i = 0; i < size; ++i) { if (yang_check_ext_instance(module, &must[i].ext, must[i].ext_size, &must[i], unres)) { return EXIT_FAILURE; } } return EXIT_SUCCESS; } static int yang_check_container(struct lys_module *module, struct lys_node_container *cont, struct lys_node **child, int options, struct unres_schema *unres) { if (yang_check_typedef(module, (struct lys_node *)cont, unres)) { goto error; } if (yang_check_iffeatures(module, NULL, cont, CONTAINER_KEYWORD, unres)) { goto error; } if (yang_check_nodes(module, (struct lys_node *)cont, *child, options, unres)) { *child = NULL; goto error; } *child = NULL; if (cont->when && yang_check_ext_instance(module, &cont->when->ext, cont->when->ext_size, cont->when, unres)) { goto error; } if (yang_check_must(module, cont->must, cont->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (cont->when || cont->must_size)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)cont)) { goto error; } } else { if (unres_schema_add_node(module, unres, cont, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_leaf(struct lys_module *module, struct lys_node_leaf *leaf, int options, struct unres_schema *unres) { if (yang_fill_type(module, &leaf->type, (struct yang_type *)leaf->type.der, leaf, unres)) { yang_type_free(module->ctx, &leaf->type); goto error; } if (yang_check_iffeatures(module, NULL, leaf, LEAF_KEYWORD, unres)) { yang_type_free(module->ctx, &leaf->type); goto error; } if (unres_schema_add_node(module, unres, &leaf->type, UNRES_TYPE_DER, (struct lys_node *)leaf) == -1) { yang_type_free(module->ctx, &leaf->type); goto error; } if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (unres_schema_add_node(module, unres, &leaf->type, UNRES_TYPE_DFLT, (struct lys_node *)&leaf->dflt) == -1)) { goto error; } if (leaf->when && yang_check_ext_instance(module, &leaf->when->ext, leaf->when->ext_size, leaf->when, unres)) { goto error; } if (yang_check_must(module, leaf->must, leaf->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (leaf->when || leaf->must_size)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)leaf)) { goto error; } } else { if (unres_schema_add_node(module, unres, leaf, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_leaflist(struct lys_module *module, struct lys_node_leaflist *leaflist, int options, struct unres_schema *unres) { int i, j; if (yang_fill_type(module, &leaflist->type, (struct yang_type *)leaflist->type.der, leaflist, unres)) { yang_type_free(module->ctx, &leaflist->type); goto error; } if (yang_check_iffeatures(module, NULL, leaflist, LEAF_LIST_KEYWORD, unres)) { yang_type_free(module->ctx, &leaflist->type); goto error; } if (unres_schema_add_node(module, unres, &leaflist->type, UNRES_TYPE_DER, (struct lys_node *)leaflist) == -1) { yang_type_free(module->ctx, &leaflist->type); goto error; } for (i = 0; i < leaflist->dflt_size; ++i) { /* check for duplicity in case of configuration data, * in case of status data duplicities are allowed */ if (leaflist->flags & LYS_CONFIG_W) { for (j = i +1; j < leaflist->dflt_size; ++j) { if (ly_strequal(leaflist->dflt[i], leaflist->dflt[j], 1)) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_LYS, leaflist, leaflist->dflt[i], "default"); LOGVAL(module->ctx, LYE_SPEC, LY_VLOG_LYS, leaflist, "Duplicated default value \"%s\".", leaflist->dflt[i]); goto error; } } } /* check default value (if not defined, there still could be some restrictions * that need to be checked against a default value from a derived type) */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (unres_schema_add_node(module, unres, &leaflist->type, UNRES_TYPE_DFLT, (struct lys_node *)(&leaflist->dflt[i])) == -1)) { goto error; } } if (leaflist->when && yang_check_ext_instance(module, &leaflist->when->ext, leaflist->when->ext_size, leaflist->when, unres)) { goto error; } if (yang_check_must(module, leaflist->must, leaflist->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (leaflist->when || leaflist->must_size)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)leaflist)) { goto error; } } else { if (unres_schema_add_node(module, unres, leaflist, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_list(struct lys_module *module, struct lys_node_list *list, struct lys_node **child, int options, struct unres_schema *unres) { struct lys_node *node; if (yang_check_typedef(module, (struct lys_node *)list, unres)) { goto error; } if (yang_check_iffeatures(module, NULL, list, LIST_KEYWORD, unres)) { goto error; } if (list->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ list->flags &= 0x7F; } /* check - if list is configuration, key statement is mandatory * (but only if we are not in a grouping or augment, then the check is deferred) */ for (node = (struct lys_node *)list; node && !(node->nodetype & (LYS_GROUPING | LYS_AUGMENT | LYS_EXT)); node = node->parent); if (!node && (list->flags & LYS_CONFIG_W) && !list->keys) { LOGVAL(module->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, list, "key", "list"); goto error; } if (yang_check_nodes(module, (struct lys_node *)list, *child, options, unres)) { *child = NULL; goto error; } *child = NULL; if (list->keys && yang_read_key(module, list, unres)) { goto error; } if (yang_read_unique(module, list, unres)) { goto error; } if (list->when && yang_check_ext_instance(module, &list->when->ext, list->when->ext_size, list->when, unres)) { goto error; } if (yang_check_must(module, list->must, list->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (list->when || list->must_size)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)list)) { goto error; } } else { if (unres_schema_add_node(module, unres, list, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_choice(struct lys_module *module, struct lys_node_choice *choice, struct lys_node **child, int options, struct unres_schema *unres) { char *value; if (yang_check_iffeatures(module, NULL, choice, CHOICE_KEYWORD, unres)) { free(choice->dflt); choice->dflt = NULL; goto error; } if (yang_check_nodes(module, (struct lys_node *)choice, *child, options, unres)) { *child = NULL; free(choice->dflt); choice->dflt = NULL; goto error; } *child = NULL; if (choice->dflt) { value = (char *)choice->dflt; choice->dflt = NULL; if (unres_schema_add_str(module, unres, choice, UNRES_CHOICE_DFLT, value) == -1) { free(value); goto error; } free(value); } if (choice->when && yang_check_ext_instance(module, &choice->when->ext, choice->when->ext_size, choice->when, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && choice->when) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)choice)) { goto error; } } else { if (unres_schema_add_node(module, unres, choice, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_rpc_action(struct lys_module *module, struct lys_node_rpc_action *rpc, struct lys_node **child, int options, struct unres_schema *unres) { struct lys_node *node; if (rpc->nodetype == LYS_ACTION) { for (node = rpc->parent; node; node = lys_parent(node)) { if ((node->nodetype & (LYS_RPC | LYS_ACTION | LYS_NOTIF)) || ((node->nodetype == LYS_LIST) && !((struct lys_node_list *)node)->keys)) { LOGVAL(module->ctx, LYE_INPAR, LY_VLOG_LYS, rpc->parent, strnodetype(node->nodetype), "action"); goto error; } } } if (yang_check_typedef(module, (struct lys_node *)rpc, unres)) { goto error; } if (yang_check_iffeatures(module, NULL, rpc, RPC_KEYWORD, unres)) { goto error; } if (yang_check_nodes(module, (struct lys_node *)rpc, *child, options | LYS_PARSE_OPT_CFG_IGNORE, unres)) { *child = NULL; goto error; } *child = NULL; return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_notif(struct lys_module *module, struct lys_node_notif *notif, struct lys_node **child, int options, struct unres_schema *unres) { if (yang_check_typedef(module, (struct lys_node *)notif, unres)) { goto error; } if (yang_check_iffeatures(module, NULL, notif, NOTIFICATION_KEYWORD, unres)) { goto error; } if (yang_check_nodes(module, (struct lys_node *)notif, *child, options | LYS_PARSE_OPT_CFG_IGNORE, unres)) { *child = NULL; goto error; } *child = NULL; if (yang_check_must(module, notif->must, notif->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && notif->must_size) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)notif)) { goto error; } } else { if (unres_schema_add_node(module, unres, notif, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_augment(struct lys_module *module, struct lys_node_augment *augment, int options, struct unres_schema *unres) { struct lys_node *child; child = augment->child; augment->child = NULL; if (yang_check_iffeatures(module, NULL, augment, AUGMENT_KEYWORD, unres)) { yang_free_nodes(module->ctx, child); goto error; } if (yang_check_nodes(module, (struct lys_node *)augment, child, options, unres)) { goto error; } if (yang_check_ext_instance(module, &augment->ext, augment->ext_size, augment, unres)) { goto error; } if (augment->when && yang_check_ext_instance(module, &augment->when->ext, augment->when->ext_size, augment->when, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && augment->when) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)augment)) { goto error; } } else { if (unres_schema_add_node(module, unres, augment, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_uses(struct lys_module *module, struct lys_node_uses *uses, int options, struct unres_schema *unres) { uint i, size; size = uses->augment_size; uses->augment_size = 0; if (yang_check_iffeatures(module, NULL, uses, USES_KEYWORD, unres)) { goto error; } for (i = 0; i < uses->refine_size; ++i) { if (yang_check_iffeatures(module, &uses->refine[i], uses, REFINE_KEYWORD, unres)) { goto error; } if (yang_check_must(module, uses->refine[i].must, uses->refine[i].must_size, unres)) { goto error; } if (yang_check_ext_instance(module, &uses->refine[i].ext, uses->refine[i].ext_size, &uses->refine[i], unres)) { goto error; } } for (i = 0; i < size; ++i) { uses->augment_size++; if (yang_check_augment(module, &uses->augment[i], options, unres)) { goto error; } } if (unres_schema_add_node(module, unres, uses, UNRES_USES, NULL) == -1) { goto error; } if (uses->when && yang_check_ext_instance(module, &uses->when->ext, uses->when->ext_size, uses->when, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && uses->when) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)uses)) { goto error; } } else { if (unres_schema_add_node(module, unres, uses, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: for (i = uses->augment_size; i < size; ++i) { yang_free_augment(module->ctx, &uses->augment[i]); } return EXIT_FAILURE; } static int yang_check_anydata(struct lys_module *module, struct lys_node_anydata *anydata, struct lys_node **child, int options, struct unres_schema *unres) { if (yang_check_iffeatures(module, NULL, anydata, ANYDATA_KEYWORD, unres)) { goto error; } if (yang_check_nodes(module, (struct lys_node *)anydata, *child, options, unres)) { *child = NULL; goto error; } *child = NULL; if (anydata->when && yang_check_ext_instance(module, &anydata->when->ext, anydata->when->ext_size, anydata->when, unres)) { goto error; } if (yang_check_must(module, anydata->must, anydata->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (anydata->when || anydata->must_size)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax((struct lys_node *)anydata)) { goto error; } } else { if (unres_schema_add_node(module, unres, anydata, UNRES_XPATH, NULL) == -1) { goto error; } } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int yang_check_nodes(struct lys_module *module, struct lys_node *parent, struct lys_node *nodes, int options, struct unres_schema *unres) { struct lys_node *node = nodes, *sibling, *child; int i; while (node) { sibling = node->next; child = node->child; node->next = NULL; node->child = NULL; node->parent = NULL; node->prev = node; if (lys_node_addchild(parent, module->type ? ((struct lys_submodule *)module)->belongsto: module, node, 0) || check_status_flag(node, parent)) { lys_node_unlink(node); yang_free_nodes(module->ctx, node); goto error; } if (node->parent != parent) { assert(node->parent->parent == parent); assert((node->parent->nodetype == LYS_CASE) && (node->parent->flags & LYS_IMPLICIT)); store_config_flag(node->parent, options); } store_config_flag(node, options); if (yang_check_ext_instance(module, &node->ext, node->ext_size, node, unres)) { goto error; } for (i = 0; i < node->ext_size; ++i) { if (node->ext[i]->flags & LYEXT_OPT_VALID) { node->flags |= LYS_VALID_EXT; break; } } switch (node->nodetype) { case LYS_GROUPING: if (yang_check_typedef(module, node, unres)) { goto error; } if (yang_check_iffeatures(module, NULL, node, GROUPING_KEYWORD, unres)) { goto error; } if (yang_check_nodes(module, node, child, options | LYS_PARSE_OPT_INGRP, unres)) { child = NULL; goto error; } break; case LYS_CONTAINER: if (yang_check_container(module, (struct lys_node_container *)node, &child, options, unres)) { goto error; } break; case LYS_LEAF: if (yang_check_leaf(module, (struct lys_node_leaf *)node, options, unres)) { child = NULL; goto error; } break; case LYS_LEAFLIST: if (yang_check_leaflist(module, (struct lys_node_leaflist *)node, options, unres)) { child = NULL; goto error; } break; case LYS_LIST: if (yang_check_list(module, (struct lys_node_list *)node, &child, options, unres)) { goto error; } break; case LYS_CHOICE: if (yang_check_choice(module, (struct lys_node_choice *)node, &child, options, unres)) { goto error; } break; case LYS_CASE: if (yang_check_iffeatures(module, NULL, node, CASE_KEYWORD, unres)) { goto error; } if (yang_check_nodes(module, node, child, options, unres)) { child = NULL; goto error; } if (((struct lys_node_case *)node)->when) { if (yang_check_ext_instance(module, &((struct lys_node_case *)node)->when->ext, ((struct lys_node_case *)node)->when->ext_size, ((struct lys_node_case *)node)->when, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (options & LYS_PARSE_OPT_INGRP)) { if (lyxp_node_check_syntax(node)) { goto error; } } else { if (unres_schema_add_node(module, unres, node, UNRES_XPATH, NULL) == -1) { goto error; } } } break; case LYS_ANYDATA: case LYS_ANYXML: if (yang_check_anydata(module, (struct lys_node_anydata *)node, &child, options, unres)) { goto error; } break; case LYS_RPC: case LYS_ACTION: if (yang_check_rpc_action(module, (struct lys_node_rpc_action *)node, &child, options, unres)){ goto error; } break; case LYS_INPUT: case LYS_OUTPUT: if (yang_check_typedef(module, node, unres)) { goto error; } if (yang_check_nodes(module, node, child, options, unres)) { child = NULL; goto error; } if (((struct lys_node_inout *)node)->must_size) { if (yang_check_must(module, ((struct lys_node_inout *)node)->must, ((struct lys_node_inout *)node)->must_size, unres)) { goto error; } /* check XPath dependencies */ if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && (options & LYS_PARSE_OPT_INGRP)) { if (lyxp_node_check_syntax(node)) { goto error; } } else { if (unres_schema_add_node(module, unres, node, UNRES_XPATH, NULL) == -1) { goto error; } } } break; case LYS_NOTIF: if (yang_check_notif(module, (struct lys_node_notif *)node, &child, options, unres)) { goto error; } break; case LYS_USES: if (yang_check_uses(module, (struct lys_node_uses *)node, options, unres)) { child = NULL; goto error; } break; default: LOGINT(module->ctx); goto error; } node = sibling; } return EXIT_SUCCESS; error: yang_free_nodes(module->ctx, sibling); yang_free_nodes(module->ctx, child); return EXIT_FAILURE; } static int yang_check_deviate(struct lys_module *module, struct unres_schema *unres, struct lys_deviate *deviate, struct lys_node *dev_target, struct ly_set *dflt_check) { struct lys_node_leaflist *llist; struct lys_type *type; struct lys_tpdf *tmp_parent; int i, j; if (yang_check_ext_instance(module, &deviate->ext, deviate->ext_size, deviate, unres)) { goto error; } if (deviate->must_size && yang_check_deviate_must(module, unres, deviate, dev_target)) { goto error; } if (deviate->unique && yang_check_deviate_unique(module, deviate, dev_target)) { goto error; } if (deviate->dflt_size) { if (yang_read_deviate_default(module, deviate, dev_target, dflt_check)) { goto error; } if (dev_target->nodetype == LYS_LEAFLIST && deviate->mod == LY_DEVIATE_DEL) { /* consolidate the final list in the target after removing items from it */ llist = (struct lys_node_leaflist *)dev_target; for (i = j = 0; j < llist->dflt_size; j++) { llist->dflt[i] = llist->dflt[j]; if (llist->dflt[i]) { i++; } } llist->dflt_size = i + 1; } } if (deviate->max_set && yang_read_deviate_minmax(deviate, dev_target, deviate->max, 1)) { goto error; } if (deviate->min_set && yang_read_deviate_minmax(deviate, dev_target, deviate->min, 0)) { goto error; } if (deviate->units && yang_read_deviate_units(module->ctx, deviate, dev_target)) { goto error; } if ((deviate->flags & LYS_CONFIG_MASK)) { /* add and replace are the same in this case */ /* remove current config value of the target ... */ dev_target->flags &= ~LYS_CONFIG_MASK; /* ... and replace it with the value specified in deviation */ dev_target->flags |= deviate->flags & LYS_CONFIG_MASK; } if ((deviate->flags & LYS_MAND_MASK) && yang_check_deviate_mandatory(deviate, dev_target)) { goto error; } if (deviate->type) { /* check target node type */ if (dev_target->nodetype == LYS_LEAF) { type = &((struct lys_node_leaf *)dev_target)->type; } else if (dev_target->nodetype == LYS_LEAFLIST) { type = &((struct lys_node_leaflist *)dev_target)->type; } else { LOGVAL(module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "type"); LOGVAL(module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Target node does not allow \"type\" property."); goto error; } /* remove type and initialize it */ tmp_parent = type->parent; lys_type_free(module->ctx, type, NULL); memcpy(type, deviate->type, sizeof *deviate->type); free(deviate->type); deviate->type = type; deviate->type->parent = tmp_parent; if (yang_fill_type(module, type, (struct yang_type *)type->der, tmp_parent, unres)) { goto error; } if (unres_schema_add_node(module, unres, deviate->type, UNRES_TYPE_DER, dev_target) == -1) { goto error; } } return EXIT_SUCCESS; error: if (deviate->type) { yang_type_free(module->ctx, deviate->type); deviate->type = NULL; } return EXIT_FAILURE; } static int yang_check_deviation(struct lys_module *module, struct unres_schema *unres, struct lys_deviation *dev) { int rc; uint i; struct lys_node *dev_target = NULL, *parent; struct ly_set *dflt_check = ly_set_new(), *set; unsigned int u; const char *value, *target_name; struct lys_node_leaflist *llist; struct lys_node_leaf *leaf; struct lys_node_inout *inout; struct unres_schema tmp_unres; struct lys_module *mod; /* resolve target node */ rc = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1); if (rc == -1) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, dev->target_name, "deviation"); ly_set_free(set); i = 0; goto free_type_error; } dev_target = set->set.s[0]; ly_set_free(set); if (dev_target->module == lys_main_module(module)) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, dev->target_name, "deviation"); LOGVAL(module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Deviating own module is not allowed."); i = 0; goto free_type_error; } if (!dflt_check) { LOGMEM(module->ctx); i = 0; goto free_type_error; } if (dev->deviate[0].mod == LY_DEVIATE_NO) { /* you cannot remove a key leaf */ if ((dev_target->nodetype == LYS_LEAF) && dev_target->parent && (dev_target->parent->nodetype == LYS_LIST)) { for (i = 0; i < ((struct lys_node_list *)dev_target->parent)->keys_size; ++i) { if (((struct lys_node_list *)dev_target->parent)->keys[i] == (struct lys_node_leaf *)dev_target) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, "not-supported", "deviation"); LOGVAL(module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "\"not-supported\" deviation cannot remove a list key."); i = 0; goto free_type_error; } } } /* unlink and store the original node */ parent = dev_target->parent; lys_node_unlink(dev_target); if (parent) { if (parent->nodetype & (LYS_AUGMENT | LYS_USES)) { /* hack for augment, because when the original will be sometime reconnected back, we actually need * to reconnect it to both - the augment and its target (which is deduced from the deviations target * path), so we need to remember the augment as an addition */ /* remember uses parent so we can reconnect to it */ dev_target->parent = parent; } else if (parent->nodetype & (LYS_RPC | LYS_ACTION)) { /* re-create implicit node */ inout = calloc(1, sizeof *inout); LY_CHECK_ERR_GOTO(!inout, LOGMEM(module->ctx), error); inout->nodetype = dev_target->nodetype; inout->name = lydict_insert(module->ctx, (inout->nodetype == LYS_INPUT) ? "input" : "output", 0); inout->module = dev_target->module; inout->flags = LYS_IMPLICIT; /* insert it manually */ assert(parent->child && !parent->child->next && (parent->child->nodetype == (inout->nodetype == LYS_INPUT ? LYS_OUTPUT : LYS_INPUT))); parent->child->next = (struct lys_node *)inout; inout->prev = parent->child; parent->child->prev = (struct lys_node *)inout; inout->parent = parent; } } dev->orig_node = dev_target; } else { /* store a shallow copy of the original node */ memset(&tmp_unres, 0, sizeof tmp_unres); dev->orig_node = lys_node_dup(dev_target->module, NULL, dev_target, &tmp_unres, 1); /* just to be safe */ if (tmp_unres.count) { LOGINT(module->ctx); i = 0; goto free_type_error; } } if (yang_check_ext_instance(module, &dev->ext, dev->ext_size, dev, unres)) { i = 0; goto free_type_error; } for (i = 0; i < dev->deviate_size; ++i) { if (yang_check_deviate(module, unres, &dev->deviate[i], dev_target, dflt_check)) { yang_free_deviate(module->ctx, dev, i + 1); dev->deviate_size = i + 1; goto free_type_error; } } /* now check whether default value, if any, matches the type */ for (u = 0; u < dflt_check->number; ++u) { value = NULL; rc = EXIT_SUCCESS; if (dflt_check->set.s[u]->nodetype == LYS_LEAF) { leaf = (struct lys_node_leaf *)dflt_check->set.s[u]; target_name = leaf->name; value = leaf->dflt; rc = unres_schema_add_node(module, unres, &leaf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&leaf->dflt)); } else { /* LYS_LEAFLIST */ llist = (struct lys_node_leaflist *)dflt_check->set.s[u]; target_name = llist->name; for (i = 0; i < llist->dflt_size; i++) { rc = unres_schema_add_node(module, unres, &llist->type, UNRES_TYPE_DFLT, (struct lys_node *)(&llist->dflt[i])); if (rc == -1) { value = llist->dflt[i]; break; } } } if (rc == -1) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "default"); LOGVAL(module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The default value \"%s\" of the deviated node \"%s\"no longer matches its type.", target_name); goto error; } } ly_set_free(dflt_check); dflt_check = NULL; /* mark all the affected modules as deviated and implemented */ for (parent = dev_target; parent; parent = lys_parent(parent)) { mod = lys_node_module(parent); if (module != mod) { mod->deviated = 1; /* main module */ parent->module->deviated = 1; /* possible submodule */ if (!mod->implemented) { mod->implemented = 1; if (unres_schema_add_node(mod, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) { goto error; } } } } return EXIT_SUCCESS; free_type_error: /* we need to free types because they are for now allocated dynamically (use i as it is now, is set correctly) */ for (; i < dev->deviate_size; ++i) { if (dev->deviate[i].type) { yang_type_free(module->ctx, dev->deviate[i].type); free(dev->deviate[i].type); dev->deviate[i].type = NULL; } } error: ly_set_free(dflt_check); return EXIT_FAILURE; } static int yang_check_sub_module(struct lys_module *module, struct unres_schema *unres, struct lys_node *node) { uint i, erase_identities = 1, erase_nodes = 1, aug_size, dev_size = 0; aug_size = module->augment_size; module->augment_size = 0; dev_size = module->deviation_size; module->deviation_size = 0; if (yang_check_typedef(module, NULL, unres)) { goto error; } if (yang_check_ext_instance(module, &module->ext, module->ext_size, module, unres)) { goto error; } /* check extension in revision */ for (i = 0; i < module->rev_size; ++i) { if (yang_check_ext_instance(module, &module->rev[i].ext, module->rev[i].ext_size, &module->rev[i], unres)) { goto error; } } /* check extension in definition of extension */ for (i = 0; i < module->extensions_size; ++i) { if (yang_check_ext_instance(module, &module->extensions[i].ext, module->extensions[i].ext_size, &module->extensions[i], unres)) { goto error; } } /* check features */ for (i = 0; i < module->features_size; ++i) { if (yang_check_iffeatures(module, NULL, &module->features[i], FEATURE_KEYWORD, unres)) { goto error; } if (yang_check_ext_instance(module, &module->features[i].ext, module->features[i].ext_size, &module->features[i], unres)) { goto error; } /* check for circular dependencies */ if (module->features[i].iffeature_size && (unres_schema_add_node(module, unres, &module->features[i], UNRES_FEATURE, NULL) == -1)) { goto error; } } erase_identities = 0; if (yang_check_identities(module, unres)) { goto error; } erase_nodes = 0; if (yang_check_nodes(module, NULL, node, 0, unres)) { goto error; } /* check deviation */ for (i = 0; i < dev_size; ++i) { module->deviation_size++; if (yang_check_deviation(module, unres, &module->deviation[i])) { goto error; } } /* check augments */ for (i = 0; i < aug_size; ++i) { module->augment_size++; if (yang_check_augment(module, &module->augment[i], 0, unres)) { goto error; } if (unres_schema_add_node(module, unres, &module->augment[i], UNRES_AUGMENT, NULL) == -1) { goto error; } } return EXIT_SUCCESS; error: if (erase_identities) { yang_free_ident_base(module->ident, 0, module->ident_size); } if (erase_nodes) { yang_free_nodes(module->ctx, node); } for (i = module->augment_size; i < aug_size; ++i) { yang_free_augment(module->ctx, &module->augment[i]); } for (i = module->deviation_size; i < dev_size; ++i) { yang_free_deviate(module->ctx, &module->deviation[i], 0); free(module->deviation[i].deviate); lydict_remove(module->ctx, module->deviation[i].target_name); lydict_remove(module->ctx, module->deviation[i].dsc); lydict_remove(module->ctx, module->deviation[i].ref); } return EXIT_FAILURE; } int yang_read_extcomplex_str(struct lys_module *module, struct lys_ext_instance_complex *ext, const char *arg_name, const char *parent_name, char *value, int parent_stmt, LY_STMT stmt) { int c; const char **str, ***p = NULL; void *reallocated; struct lyext_substmt *info; c = 0; if (stmt == LY_STMT_PREFIX && parent_stmt == LY_STMT_BELONGSTO) { /* str contains no NULL value */ str = lys_ext_complex_get_substmt(LY_STMT_BELONGSTO, ext, &info); if (info->cardinality < LY_STMT_CARD_SOME) { str++; } else { /* get the index in the array to add new item */ p = (const char ***)str; for (c = 0; p[0][c + 1]; c++); str = p[1]; } str[c] = lydict_insert_zc(module->ctx, value); } else { str = lys_ext_complex_get_substmt(stmt, ext, &info); if (!str) { LOGVAL(module->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, arg_name, parent_name); goto error; } if (info->cardinality < LY_STMT_CARD_SOME && *str) { LOGVAL(module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, arg_name, parent_name); goto error; } if (info->cardinality >= LY_STMT_CARD_SOME) { /* there can be multiple instances, str is actually const char *** */ p = (const char ***)str; if (!p[0]) { /* allocate initial array */ p[0] = calloc(2, sizeof(const char *)); LY_CHECK_ERR_GOTO(!p[0], LOGMEM(module->ctx), error); if (stmt == LY_STMT_BELONGSTO) { /* allocate another array for the belongs-to's prefixes */ p[1] = calloc(2, sizeof(const char *)); LY_CHECK_ERR_GOTO(!p[1], LOGMEM(module->ctx), error); } else if (stmt == LY_STMT_ARGUMENT) { /* allocate another array for the yin element */ ((uint8_t **)p)[1] = calloc(2, sizeof(uint8_t)); LY_CHECK_ERR_GOTO(!p[1], LOGMEM(module->ctx), error); /* default value of yin element */ ((uint8_t *)p[1])[0] = 2; } } else { /* get the index in the array to add new item */ for (c = 0; p[0][c]; c++); } str = p[0]; } str[c] = lydict_insert_zc(module->ctx, value); value = NULL; if (c) { /* enlarge the array(s) */ reallocated = realloc(p[0], (c + 2) * sizeof(const char *)); if (!reallocated) { LOGMEM(module->ctx); lydict_remove(module->ctx, p[0][c]); p[0][c] = NULL; return EXIT_FAILURE; } p[0] = reallocated; p[0][c + 1] = NULL; if (stmt == LY_STMT_BELONGSTO) { /* enlarge the second belongs-to's array with prefixes */ reallocated = realloc(p[1], (c + 2) * sizeof(const char *)); if (!reallocated) { LOGMEM(module->ctx); lydict_remove(module->ctx, p[1][c]); p[1][c] = NULL; return EXIT_FAILURE; } p[1] = reallocated; p[1][c + 1] = NULL; } else if (stmt == LY_STMT_ARGUMENT) { /* enlarge the second argument's array with yin element */ reallocated = realloc(p[1], (c + 2) * sizeof(uint8_t)); if (!reallocated) { LOGMEM(module->ctx); ((uint8_t *)p[1])[c] = 0; return EXIT_FAILURE; } p[1] = reallocated; ((uint8_t *)p[1])[c + 1] = 0; } } } return EXIT_SUCCESS; error: free(value); return EXIT_FAILURE; } static int yang_fill_ext_substm_index(struct lys_ext_instance_complex *ext, LY_STMT stmt, enum yytokentype keyword) { int c = 0, decrement = 0; const char **str, ***p = NULL; struct lyext_substmt *info; if (keyword == BELONGS_TO_KEYWORD || stmt == LY_STMT_BELONGSTO) { stmt = LY_STMT_BELONGSTO; decrement = -1; } else if (keyword == ARGUMENT_KEYWORD || stmt == LY_STMT_ARGUMENT) { stmt = LY_STMT_ARGUMENT; decrement = -1; } str = lys_ext_complex_get_substmt(stmt, ext, &info); if (!str || info->cardinality < LY_STMT_CARD_SOME || !((const char ***)str)[0]) { return 0; } else { p = (const char ***)str; /* get the index in the array */ for (c = 0; p[0][c]; c++); return c + decrement; } } void ** yang_getplace_for_extcomplex_struct(struct lys_ext_instance_complex *ext, int *index, char *parent_name, char *node_name, LY_STMT stmt) { struct ly_ctx *ctx = ext->module->ctx; int c; void **data, ***p = NULL; void *reallocated; struct lyext_substmt *info; data = lys_ext_complex_get_substmt(stmt, ext, &info); if (!data) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, node_name, parent_name); return NULL; } if (info->cardinality < LY_STMT_CARD_SOME && *data) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, node_name, parent_name); return NULL; } c = 0; if (info->cardinality >= LY_STMT_CARD_SOME) { /* there can be multiple instances, so instead of pointer to array, * we have in data pointer to pointer to array */ p = (void ***)data; data = *p; if (!data) { /* allocate initial array */ *p = data = calloc(2, sizeof(void *)); LY_CHECK_ERR_RETURN(!data, LOGMEM(ctx), NULL); } else { for (c = 0; *data; data++, c++); } } if (c) { /* enlarge the array */ reallocated = realloc(*p, (c + 2) * sizeof(void *)); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), NULL); *p = reallocated; data = *p; data[c + 1] = NULL; } if (index) { *index = c; return data; } else { return &data[c]; } } int yang_fill_extcomplex_flags(struct lys_ext_instance_complex *ext, char *parent_name, char *node_name, LY_STMT stmt, uint16_t value, uint16_t mask) { uint16_t *data; struct lyext_substmt *info; data = lys_ext_complex_get_substmt(stmt, ext, &info); if (!data) { LOGVAL(ext->module->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } if (info->cardinality < LY_STMT_CARD_SOME && (*data & mask)) { LOGVAL(ext->module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } *data |= value; return EXIT_SUCCESS; } int yang_fill_extcomplex_uint8(struct lys_ext_instance_complex *ext, char *parent_name, char *node_name, LY_STMT stmt, uint8_t value) { struct ly_ctx *ctx = ext->module->ctx; uint8_t *val, **pp = NULL, *reallocated; struct lyext_substmt *info; int i = 0; val = lys_ext_complex_get_substmt(stmt, ext, &info); if (!val) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } if (stmt == LY_STMT_DIGITS) { if (info->cardinality < LY_STMT_CARD_SOME && *val) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } if (info->cardinality >= LY_STMT_CARD_SOME) { /* there can be multiple instances */ pp = (uint8_t**)val; if (!(*pp)) { *pp = calloc(2, sizeof(uint8_t)); /* allocate initial array */ LY_CHECK_ERR_RETURN(!*pp, LOGMEM(ctx), EXIT_FAILURE); } else { for (i = 0; (*pp)[i]; i++); } val = &(*pp)[i]; } /* stored value */ *val = value; if (i) { /* enlarge the array */ reallocated = realloc(*pp, (i + 2) * sizeof *val); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), EXIT_FAILURE); *pp = reallocated; (*pp)[i + 1] = 0; } } else { if (*val) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } if (stmt == LY_STMT_REQINSTANCE) { *val = (value == 1) ? 1 : 2; } else if (stmt == LY_STMT_MODIFIER) { *val = 1; } else { LOGINT(ctx); return EXIT_FAILURE; } } return EXIT_SUCCESS; } int yang_extcomplex_node(struct lys_ext_instance_complex *ext, char *parent_name, char *node_name, struct lys_node *node, LY_STMT stmt) { struct lyext_substmt *info; struct lys_node **snode, *siter; snode = lys_ext_complex_get_substmt(stmt, ext, &info); if (!snode) { LOGVAL(ext->module->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } if (info->cardinality < LY_STMT_CARD_SOME) { LY_TREE_FOR(node, siter) { if (stmt == lys_snode2stmt(siter->nodetype)) { LOGVAL(ext->module->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, node_name, parent_name); return EXIT_FAILURE; } } } return EXIT_SUCCESS; } int yang_fill_extcomplex_module(struct ly_ctx *ctx, struct lys_ext_instance_complex *ext, char *parent_name, char **values, int implemented) { int c, i; struct lys_module **modules, ***p, *reallocated, **pp; struct lyext_substmt *info; if (!values) { return EXIT_SUCCESS; } pp = modules = lys_ext_complex_get_substmt(LY_STMT_MODULE, ext, &info); if (!modules) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "module", parent_name); return EXIT_FAILURE; } for (i = 0; values[i]; ++i) { c = 0; if (info->cardinality < LY_STMT_CARD_SOME && *modules) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "module", parent_name); return EXIT_FAILURE; } if (info->cardinality >= LY_STMT_CARD_SOME) { /* there can be multiple instances, so instead of pointer to array, * we have in modules pointer to pointer to array */ p = (struct lys_module ***)pp; modules = *p; if (!modules) { /* allocate initial array */ *p = modules = calloc(2, sizeof(struct lys_module *)); LY_CHECK_ERR_RETURN(!*p, LOGMEM(ctx), EXIT_FAILURE); } else { for (c = 0; *modules; modules++, c++); } } if (c) { /* enlarge the array */ reallocated = realloc(*p, (c + 2) * sizeof(struct lys_module *)); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), EXIT_FAILURE); *p = (struct lys_module **)reallocated; modules = *p; modules[c + 1] = NULL; } modules[c] = yang_read_module(ctx, values[i], 0, NULL, implemented); if (!modules[c]) { return EXIT_FAILURE; } } return EXIT_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1360_0
crossvul-cpp_data_bad_1361_0
/* A Bison parser, made by GNU Bison 3.2.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.2.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 2 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "libyang.h" #include "common.h" #include "context.h" #include "resolve.h" #include "parser_yang.h" #include "parser_yang_lex.h" #include "parser.h" #define YANG_ADDELEM(current_ptr, size, array_name) \ if ((size) == LY_ARRAY_MAX(size)) { \ LOGERR(trg->ctx, LY_EINT, "Reached limit (%"PRIu64") for storing %s.", LY_ARRAY_MAX(size), array_name); \ free(s); \ YYABORT; \ } else if (!((size) % LY_YANG_ARRAY_SIZE)) { \ void *tmp; \ \ tmp = realloc((current_ptr), (sizeof *(current_ptr)) * ((size) + LY_YANG_ARRAY_SIZE)); \ if (!tmp) { \ LOGMEM(trg->ctx); \ free(s); \ YYABORT; \ } \ memset(tmp + (sizeof *(current_ptr)) * (size), 0, (sizeof *(current_ptr)) * LY_YANG_ARRAY_SIZE); \ (current_ptr) = tmp; \ } \ actual = &(current_ptr)[(size)++]; \ void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...); /* pointer on the current parsed element 'actual' */ # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "parser_yang_bis.h". */ #ifndef YY_YY_PARSER_YANG_BIS_H_INCLUDED # define YY_YY_PARSER_YANG_BIS_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { UNION_KEYWORD = 258, ANYXML_KEYWORD = 259, WHITESPACE = 260, ERROR = 261, EOL = 262, STRING = 263, STRINGS = 264, IDENTIFIER = 265, IDENTIFIERPREFIX = 266, REVISION_DATE = 267, TAB = 268, DOUBLEDOT = 269, URI = 270, INTEGER = 271, NON_NEGATIVE_INTEGER = 272, ZERO = 273, DECIMAL = 274, ARGUMENT_KEYWORD = 275, AUGMENT_KEYWORD = 276, BASE_KEYWORD = 277, BELONGS_TO_KEYWORD = 278, BIT_KEYWORD = 279, CASE_KEYWORD = 280, CHOICE_KEYWORD = 281, CONFIG_KEYWORD = 282, CONTACT_KEYWORD = 283, CONTAINER_KEYWORD = 284, DEFAULT_KEYWORD = 285, DESCRIPTION_KEYWORD = 286, ENUM_KEYWORD = 287, ERROR_APP_TAG_KEYWORD = 288, ERROR_MESSAGE_KEYWORD = 289, EXTENSION_KEYWORD = 290, DEVIATION_KEYWORD = 291, DEVIATE_KEYWORD = 292, FEATURE_KEYWORD = 293, FRACTION_DIGITS_KEYWORD = 294, GROUPING_KEYWORD = 295, IDENTITY_KEYWORD = 296, IF_FEATURE_KEYWORD = 297, IMPORT_KEYWORD = 298, INCLUDE_KEYWORD = 299, INPUT_KEYWORD = 300, KEY_KEYWORD = 301, LEAF_KEYWORD = 302, LEAF_LIST_KEYWORD = 303, LENGTH_KEYWORD = 304, LIST_KEYWORD = 305, MANDATORY_KEYWORD = 306, MAX_ELEMENTS_KEYWORD = 307, MIN_ELEMENTS_KEYWORD = 308, MODULE_KEYWORD = 309, MUST_KEYWORD = 310, NAMESPACE_KEYWORD = 311, NOTIFICATION_KEYWORD = 312, ORDERED_BY_KEYWORD = 313, ORGANIZATION_KEYWORD = 314, OUTPUT_KEYWORD = 315, PATH_KEYWORD = 316, PATTERN_KEYWORD = 317, POSITION_KEYWORD = 318, PREFIX_KEYWORD = 319, PRESENCE_KEYWORD = 320, RANGE_KEYWORD = 321, REFERENCE_KEYWORD = 322, REFINE_KEYWORD = 323, REQUIRE_INSTANCE_KEYWORD = 324, REVISION_KEYWORD = 325, REVISION_DATE_KEYWORD = 326, RPC_KEYWORD = 327, STATUS_KEYWORD = 328, SUBMODULE_KEYWORD = 329, TYPE_KEYWORD = 330, TYPEDEF_KEYWORD = 331, UNIQUE_KEYWORD = 332, UNITS_KEYWORD = 333, USES_KEYWORD = 334, VALUE_KEYWORD = 335, WHEN_KEYWORD = 336, YANG_VERSION_KEYWORD = 337, YIN_ELEMENT_KEYWORD = 338, ADD_KEYWORD = 339, CURRENT_KEYWORD = 340, DELETE_KEYWORD = 341, DEPRECATED_KEYWORD = 342, FALSE_KEYWORD = 343, NOT_SUPPORTED_KEYWORD = 344, OBSOLETE_KEYWORD = 345, REPLACE_KEYWORD = 346, SYSTEM_KEYWORD = 347, TRUE_KEYWORD = 348, UNBOUNDED_KEYWORD = 349, USER_KEYWORD = 350, ACTION_KEYWORD = 351, MODIFIER_KEYWORD = 352, ANYDATA_KEYWORD = 353, NODE = 354, NODE_PRINT = 355, EXTENSION_INSTANCE = 356, SUBMODULE_EXT_KEYWORD = 357 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { int32_t i; uint32_t uint; char *str; char **p_str; void *v; char ch; struct yang_type *type; struct lys_deviation *dev; struct lys_deviate *deviate; union { uint32_t index; struct lys_node_container *container; struct lys_node_anydata *anydata; struct type_node node; struct lys_node_case *cs; struct lys_node_grp *grouping; struct lys_refine *refine; struct lys_node_notif *notif; struct lys_node_uses *uses; struct lys_node_inout *inout; struct lys_node_augment *augment; } nodes; enum yytokentype token; struct { void *actual; enum yytokentype token; } backup_token; struct { struct lys_revision **revision; int index; } revisions; }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif int yyparse (void *scanner, struct yang_parameter *param); #endif /* !YY_YY_PARSER_YANG_BIS_H_INCLUDED */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 6 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 3466 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 113 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 329 /* YYNRULES -- Number of rules. */ #define YYNRULES 827 /* YYNSTATES -- Number of states. */ #define YYNSTATES 1318 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 357 #define YYTRANSLATE(YYX) \ ((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 111, 112, 2, 103, 2, 2, 2, 107, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 106, 2, 110, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 108, 2, 109, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 104, 2, 105, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 338, 338, 339, 340, 342, 365, 368, 370, 369, 393, 404, 414, 424, 425, 431, 436, 442, 453, 463, 476, 477, 483, 485, 489, 491, 495, 497, 498, 499, 501, 509, 517, 518, 523, 534, 545, 556, 564, 569, 570, 574, 575, 586, 597, 608, 612, 614, 637, 654, 658, 660, 661, 666, 671, 676, 682, 686, 688, 692, 694, 698, 700, 704, 706, 719, 730, 731, 743, 747, 748, 752, 753, 758, 765, 765, 776, 782, 830, 849, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 864, 879, 886, 887, 891, 892, 893, 899, 904, 910, 928, 930, 931, 935, 940, 941, 963, 964, 965, 978, 983, 985, 986, 987, 988, 1003, 1017, 1022, 1023, 1038, 1039, 1040, 1046, 1051, 1057, 1114, 1119, 1120, 1122, 1138, 1143, 1144, 1169, 1170, 1184, 1185, 1191, 1196, 1202, 1206, 1208, 1261, 1272, 1275, 1278, 1283, 1288, 1294, 1299, 1305, 1310, 1319, 1320, 1324, 1371, 1372, 1374, 1375, 1379, 1385, 1398, 1399, 1400, 1404, 1405, 1407, 1411, 1429, 1434, 1436, 1437, 1453, 1458, 1467, 1468, 1472, 1488, 1493, 1498, 1503, 1509, 1513, 1529, 1544, 1545, 1549, 1550, 1560, 1565, 1570, 1575, 1581, 1585, 1596, 1608, 1609, 1612, 1620, 1631, 1632, 1647, 1648, 1649, 1661, 1667, 1672, 1678, 1683, 1685, 1686, 1701, 1706, 1707, 1712, 1716, 1718, 1723, 1725, 1726, 1727, 1740, 1752, 1753, 1755, 1763, 1775, 1776, 1791, 1792, 1793, 1805, 1811, 1816, 1822, 1827, 1829, 1830, 1846, 1850, 1852, 1856, 1858, 1862, 1864, 1868, 1870, 1880, 1887, 1888, 1892, 1893, 1899, 1904, 1909, 1910, 1911, 1912, 1913, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1929, 1939, 1946, 1947, 1970, 1971, 1972, 1973, 1974, 1979, 1985, 1991, 1996, 2001, 2002, 2003, 2008, 2009, 2011, 2051, 2061, 2064, 2065, 2066, 2069, 2074, 2075, 2080, 2086, 2092, 2098, 2103, 2109, 2119, 2174, 2177, 2178, 2179, 2182, 2193, 2198, 2199, 2205, 2218, 2231, 2241, 2247, 2252, 2258, 2268, 2315, 2318, 2319, 2320, 2321, 2330, 2336, 2342, 2355, 2368, 2378, 2384, 2389, 2394, 2395, 2396, 2397, 2402, 2404, 2414, 2421, 2422, 2442, 2445, 2446, 2447, 2457, 2464, 2471, 2478, 2484, 2490, 2492, 2493, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2507, 2517, 2524, 2525, 2539, 2540, 2541, 2542, 2548, 2553, 2558, 2561, 2571, 2578, 2588, 2595, 2596, 2619, 2622, 2623, 2624, 2625, 2632, 2639, 2646, 2651, 2657, 2667, 2674, 2675, 2707, 2708, 2709, 2710, 2716, 2721, 2726, 2727, 2729, 2730, 2732, 2745, 2750, 2751, 2783, 2786, 2800, 2816, 2838, 2889, 2908, 2927, 2948, 2969, 2974, 2980, 2981, 2984, 2999, 3008, 3009, 3011, 3022, 3031, 3032, 3033, 3034, 3040, 3045, 3050, 3051, 3052, 3057, 3059, 3074, 3081, 3091, 3098, 3099, 3123, 3126, 3127, 3133, 3138, 3143, 3144, 3145, 3152, 3160, 3175, 3205, 3206, 3207, 3208, 3209, 3211, 3226, 3256, 3265, 3272, 3273, 3305, 3306, 3307, 3308, 3314, 3319, 3324, 3325, 3326, 3328, 3340, 3360, 3361, 3367, 3373, 3375, 3376, 3378, 3379, 3382, 3390, 3395, 3396, 3398, 3399, 3400, 3402, 3410, 3415, 3416, 3448, 3449, 3455, 3456, 3462, 3468, 3475, 3482, 3490, 3499, 3507, 3512, 3513, 3545, 3546, 3552, 3553, 3559, 3566, 3574, 3579, 3580, 3594, 3595, 3596, 3602, 3608, 3615, 3622, 3630, 3639, 3648, 3653, 3654, 3658, 3659, 3664, 3670, 3675, 3677, 3678, 3679, 3692, 3697, 3699, 3700, 3701, 3714, 3718, 3720, 3725, 3727, 3728, 3748, 3753, 3755, 3756, 3757, 3777, 3782, 3784, 3785, 3786, 3798, 3867, 3872, 3873, 3877, 3881, 3883, 3884, 3886, 3890, 3892, 3892, 3899, 3902, 3911, 3930, 3932, 3933, 3936, 3936, 3953, 3953, 3960, 3960, 3967, 3970, 3972, 3974, 3975, 3977, 3979, 3981, 3982, 3984, 3986, 3987, 3989, 3990, 3992, 3994, 3997, 4000, 4002, 4003, 4005, 4006, 4008, 4010, 4021, 4022, 4025, 4026, 4038, 4039, 4041, 4042, 4044, 4045, 4051, 4052, 4055, 4056, 4057, 4081, 4082, 4085, 4091, 4095, 4100, 4101, 4102, 4105, 4110, 4120, 4122, 4123, 4125, 4126, 4128, 4129, 4130, 4132, 4133, 4135, 4136, 4138, 4139, 4143, 4144, 4171, 4209, 4210, 4212, 4214, 4216, 4217, 4219, 4220, 4222, 4223, 4226, 4227, 4230, 4232, 4233, 4236, 4236, 4243, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4253, 4254, 4255, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301, 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, 4320, 4321, 4322, 4323, 4324, 4325, 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340, 4347, 4354, 4374, 4392, 4408, 4435, 4442, 4460, 4500, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4531, 4532, 4533, 4534, 4536, 4544, 4545, 4550, 4555, 4560, 4565, 4570, 4575, 4580, 4585, 4590, 4595, 4600, 4605, 4610, 4615, 4620, 4634, 4654, 4659, 4664, 4669, 4682, 4687, 4691, 4701, 4716, 4731, 4746, 4761, 4781, 4796, 4797, 4803, 4810, 4825, 4828 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "UNION_KEYWORD", "ANYXML_KEYWORD", "WHITESPACE", "ERROR", "EOL", "STRING", "STRINGS", "IDENTIFIER", "IDENTIFIERPREFIX", "REVISION_DATE", "TAB", "DOUBLEDOT", "URI", "INTEGER", "NON_NEGATIVE_INTEGER", "ZERO", "DECIMAL", "ARGUMENT_KEYWORD", "AUGMENT_KEYWORD", "BASE_KEYWORD", "BELONGS_TO_KEYWORD", "BIT_KEYWORD", "CASE_KEYWORD", "CHOICE_KEYWORD", "CONFIG_KEYWORD", "CONTACT_KEYWORD", "CONTAINER_KEYWORD", "DEFAULT_KEYWORD", "DESCRIPTION_KEYWORD", "ENUM_KEYWORD", "ERROR_APP_TAG_KEYWORD", "ERROR_MESSAGE_KEYWORD", "EXTENSION_KEYWORD", "DEVIATION_KEYWORD", "DEVIATE_KEYWORD", "FEATURE_KEYWORD", "FRACTION_DIGITS_KEYWORD", "GROUPING_KEYWORD", "IDENTITY_KEYWORD", "IF_FEATURE_KEYWORD", "IMPORT_KEYWORD", "INCLUDE_KEYWORD", "INPUT_KEYWORD", "KEY_KEYWORD", "LEAF_KEYWORD", "LEAF_LIST_KEYWORD", "LENGTH_KEYWORD", "LIST_KEYWORD", "MANDATORY_KEYWORD", "MAX_ELEMENTS_KEYWORD", "MIN_ELEMENTS_KEYWORD", "MODULE_KEYWORD", "MUST_KEYWORD", "NAMESPACE_KEYWORD", "NOTIFICATION_KEYWORD", "ORDERED_BY_KEYWORD", "ORGANIZATION_KEYWORD", "OUTPUT_KEYWORD", "PATH_KEYWORD", "PATTERN_KEYWORD", "POSITION_KEYWORD", "PREFIX_KEYWORD", "PRESENCE_KEYWORD", "RANGE_KEYWORD", "REFERENCE_KEYWORD", "REFINE_KEYWORD", "REQUIRE_INSTANCE_KEYWORD", "REVISION_KEYWORD", "REVISION_DATE_KEYWORD", "RPC_KEYWORD", "STATUS_KEYWORD", "SUBMODULE_KEYWORD", "TYPE_KEYWORD", "TYPEDEF_KEYWORD", "UNIQUE_KEYWORD", "UNITS_KEYWORD", "USES_KEYWORD", "VALUE_KEYWORD", "WHEN_KEYWORD", "YANG_VERSION_KEYWORD", "YIN_ELEMENT_KEYWORD", "ADD_KEYWORD", "CURRENT_KEYWORD", "DELETE_KEYWORD", "DEPRECATED_KEYWORD", "FALSE_KEYWORD", "NOT_SUPPORTED_KEYWORD", "OBSOLETE_KEYWORD", "REPLACE_KEYWORD", "SYSTEM_KEYWORD", "TRUE_KEYWORD", "UNBOUNDED_KEYWORD", "USER_KEYWORD", "ACTION_KEYWORD", "MODIFIER_KEYWORD", "ANYDATA_KEYWORD", "NODE", "NODE_PRINT", "EXTENSION_INSTANCE", "SUBMODULE_EXT_KEYWORD", "'+'", "'{'", "'}'", "';'", "'/'", "'['", "']'", "'='", "'('", "')'", "$accept", "start", "tmp_string", "string_1", "string_2", "$@1", "module_arg_str", "module_stmt", "module_header_stmts", "module_header_stmt", "submodule_arg_str", "submodule_stmt", "submodule_header_stmts", "submodule_header_stmt", "yang_version_arg", "yang_version_stmt", "namespace_arg_str", "namespace_stmt", "linkage_stmts", "import_stmt", "import_arg_str", "import_opt_stmt", "include_arg_str", "include_stmt", "include_end", "include_opt_stmt", "revision_date_arg", "revision_date_stmt", "belongs_to_arg_str", "belongs_to_stmt", "prefix_arg", "prefix_stmt", "meta_stmts", "organization_arg", "organization_stmt", "contact_arg", "contact_stmt", "description_arg", "description_stmt", "reference_arg", "reference_stmt", "revision_stmts", "revision_arg_stmt", "revision_stmts_opt", "revision_stmt", "revision_end", "revision_opt_stmt", "date_arg_str", "$@2", "body_stmts_end", "body_stmts", "body_stmt", "extension_arg_str", "extension_stmt", "extension_end", "extension_opt_stmt", "argument_str", "argument_stmt", "argument_end", "yin_element_arg", "yin_element_stmt", "yin_element_arg_str", "status_arg", "status_stmt", "status_arg_str", "feature_arg_str", "feature_stmt", "feature_end", "feature_opt_stmt", "if_feature_arg", "if_feature_stmt", "if_feature_end", "identity_arg_str", "identity_stmt", "identity_end", "identity_opt_stmt", "base_arg", "base_stmt", "typedef_arg_str", "typedef_stmt", "type_opt_stmt", "type_stmt", "type_arg_str", "type_end", "type_body_stmts", "some_restrictions", "union_stmt", "union_spec", "fraction_digits_arg", "fraction_digits_stmt", "fraction_digits_arg_str", "length_stmt", "length_arg_str", "length_end", "message_opt_stmt", "pattern_sep", "pattern_stmt", "pattern_arg_str", "pattern_end", "pattern_opt_stmt", "modifier_arg", "modifier_stmt", "enum_specification", "enum_stmts", "enum_stmt", "enum_arg_str", "enum_end", "enum_opt_stmt", "value_arg", "value_stmt", "integer_value_arg_str", "range_stmt", "range_end", "path_arg", "path_stmt", "require_instance_arg", "require_instance_stmt", "require_instance_arg_str", "bits_specification", "bit_stmts", "bit_stmt", "bit_arg_str", "bit_end", "bit_opt_stmt", "position_value_arg", "position_stmt", "position_value_arg_str", "error_message_arg", "error_message_stmt", "error_app_tag_arg", "error_app_tag_stmt", "units_arg", "units_stmt", "default_arg", "default_stmt", "grouping_arg_str", "grouping_stmt", "grouping_end", "grouping_opt_stmt", "data_def_stmt", "container_arg_str", "container_stmt", "container_end", "container_opt_stmt", "leaf_stmt", "leaf_arg_str", "leaf_opt_stmt", "leaf_list_arg_str", "leaf_list_stmt", "leaf_list_opt_stmt", "list_arg_str", "list_stmt", "list_opt_stmt", "choice_arg_str", "choice_stmt", "choice_end", "choice_opt_stmt", "short_case_case_stmt", "short_case_stmt", "case_arg_str", "case_stmt", "case_end", "case_opt_stmt", "anyxml_arg_str", "anyxml_stmt", "anydata_arg_str", "anydata_stmt", "anyxml_end", "anyxml_opt_stmt", "uses_arg_str", "uses_stmt", "uses_end", "uses_opt_stmt", "refine_args_str", "refine_arg_str", "refine_stmt", "refine_end", "refine_body_opt_stmts", "uses_augment_arg_str", "uses_augment_arg", "uses_augment_stmt", "augment_arg_str", "augment_arg", "augment_stmt", "augment_opt_stmt", "action_arg_str", "action_stmt", "rpc_arg_str", "rpc_stmt", "rpc_end", "rpc_opt_stmt", "input_arg", "input_stmt", "input_output_opt_stmt", "output_arg", "output_stmt", "notification_arg_str", "notification_stmt", "notification_end", "notification_opt_stmt", "deviation_arg", "deviation_stmt", "deviation_opt_stmt", "deviation_arg_str", "deviate_body_stmt", "deviate_not_supported", "deviate_not_supported_stmt", "deviate_not_supported_end", "deviate_stmts", "deviate_add", "deviate_add_stmt", "deviate_add_end", "deviate_add_opt_stmt", "deviate_delete", "deviate_delete_stmt", "deviate_delete_end", "deviate_delete_opt_stmt", "deviate_replace", "deviate_replace_stmt", "deviate_replace_end", "deviate_replace_opt_stmt", "when_arg_str", "when_stmt", "when_end", "when_opt_stmt", "config_arg", "config_stmt", "config_arg_str", "mandatory_arg", "mandatory_stmt", "mandatory_arg_str", "presence_arg", "presence_stmt", "min_value_arg", "min_elements_stmt", "min_value_arg_str", "max_value_arg", "max_elements_stmt", "max_value_arg_str", "ordered_by_arg", "ordered_by_stmt", "ordered_by_arg_str", "must_agr_str", "must_stmt", "must_end", "unique_arg", "unique_stmt", "unique_arg_str", "key_arg", "key_stmt", "key_arg_str", "$@3", "range_arg_str", "absolute_schema_nodeid", "absolute_schema_nodeids", "absolute_schema_nodeid_opt", "descendant_schema_nodeid", "$@4", "path_arg_str", "$@5", "$@6", "absolute_path", "absolute_paths", "absolute_path_opt", "relative_path", "relative_path_part1", "relative_path_part1_opt", "descendant_path", "descendant_path_opt", "path_predicate", "path_equality_expr", "path_key_expr", "rel_path_keyexpr", "rel_path_keyexpr_part1", "rel_path_keyexpr_part1_opt", "rel_path_keyexpr_part2", "current_function_invocation", "positive_integer_value", "non_negative_integer_value", "integer_value", "integer_value_convert", "prefix_arg_str", "identifier_arg_str", "node_identifier", "identifier_ref_arg_str", "stmtend", "semicolom", "curly_bracket_close", "curly_bracket_open", "stmtsep", "unknown_statement", "string_opt", "string_opt_part1", "string_opt_part2", "unknown_string", "unknown_string_part1", "unknown_string_part2", "unknown_statement_end", "unknown_statement2_opt", "unknown_statement2", "unknown_statement2_end", "unknown_statement2_yang_stmt", "unknown_statement2_module_stmt", "unknown_statement3_opt", "unknown_statement3_opt_end", "sep_stmt", "optsep", "sep", "whitespace_opt", "string", "$@7", "strings", "identifier", "identifier1", "yang_stmt", "identifiers", "identifiers_ref", "type_ext_alloc", "typedef_ext_alloc", "iffeature_ext_alloc", "restriction_ext_alloc", "when_ext_alloc", "revision_ext_alloc", "datadef_ext_check", "not_supported_ext_check", "not_supported_ext", "datadef_ext_stmt", "restriction_ext_stmt", "ext_substatements", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 43, 123, 125, 59, 47, 91, 93, 61, 40, 41 }; # endif #define YYPACT_NINF -1012 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-1012))) #define YYTABLE_NINF -757 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 440, 100, -1012, -1012, 566, 1894, -1012, -1012, -1012, 266, 266, -1012, 266, -1012, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -8, 31, 79, 868, 70, 125, 481, 266, -1012, -1012, 3273, 3273, 3273, 2893, 3273, 71, 2703, 2703, 2703, 2703, 2703, 98, 2988, 94, 52, 287, 2703, 77, 2703, 104, 287, 3273, 2703, 2703, 182, 58, 246, 2988, 2703, 321, 2703, 279, 279, 266, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 29, -1012, 134, -1012, -1012, -1012, -22, 2798, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 151, -1012, -1012, -1012, -1012, -1012, 156, -1012, 67, -1012, -1012, -1012, 224, -1012, -1012, -1012, 161, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, 224, -1012, 224, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, 224, -1012, -1012, 224, -1012, 262, 202, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 2893, 279, 3273, 279, 2703, 279, 2703, 2703, 2703, -1012, 2703, 279, 2703, 279, 58, 279, 3273, 3273, 3273, 3273, 3273, 266, 3273, 3273, 3273, 3273, 266, 2893, 3273, 3273, -1012, -1012, 279, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, 266, 266, -1012, 266, -1012, 266, -1012, 266, -1012, 266, 266, -1012, -1012, -1012, 3368, -1012, -1012, 291, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, 266, 266, -1012, -1012, -1012, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, 266, -1012, 228, 2703, 266, 274, -1012, 189, -1012, 288, -1012, 298, -1012, 303, -1012, 370, -1012, 380, -1012, 389, -1012, 393, -1012, 407, -1012, 411, -1012, 419, -1012, 426, -1012, 463, -1012, 238, -1012, 314, -1012, 317, -1012, 505, -1012, 506, -1012, 521, -1012, 407, -1012, 279, 279, 266, 266, 266, 266, 326, 279, 279, 109, 279, 112, 608, 266, 266, -1012, 262, -1012, 3083, 266, 332, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 1964, 1994, 2191, 347, -1012, -1012, 19, -1012, 54, 266, 355, -1012, -1012, 368, 373, -1012, -1012, -1012, 48, 3368, -1012, 266, 831, 279, 186, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 127, 515, 266, -1012, -1012, -1012, 515, -1012, -1012, 188, -1012, 279, -1012, 473, -1012, 306, -1012, 2552, 266, 266, 397, 1000, -1012, -1012, -1012, -1012, 783, -1012, 230, 503, 404, 887, 359, 438, 929, 1958, 1645, 817, 947, 344, 2074, 1547, 1768, 235, 852, 279, 279, 279, 279, 266, -22, 280, -1012, 266, 266, -1012, -1012, 375, 2703, 375, 279, -1012, -1012, -1012, 224, -1012, -1012, 3368, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 3273, 2703, -1012, -1012, -1012, -8, -1012, -1012, -1012, -1012, -1012, -1012, 279, 474, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 3273, 3273, 279, 279, -1012, -1012, -1012, -1012, -1012, 125, 224, -1012, -1012, 266, 266, -1012, 399, 473, 266, 528, 528, 545, -1012, 567, -1012, 279, -1012, 279, 279, 279, 480, -1012, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 2988, 2988, 279, 279, 279, 279, 279, 279, 279, 279, 279, 266, 266, 423, -1012, 570, -1012, 428, 2046, -1012, -1012, 434, -1012, 465, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 479, -1012, -1012, -1012, 571, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, -1012, 473, 266, 279, 279, 279, 279, -1012, 266, -1012, -1012, -1012, 266, 279, 279, 266, 51, 3273, 51, 3273, 3273, 3273, 279, 266, 459, 2367, 385, 509, 279, 279, 341, 365, -1012, -1012, 483, -1012, -1012, 574, -1012, -1012, 486, -1012, -1012, 591, -1012, 592, -1012, 521, -1012, 473, -1012, 473, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 885, 1126, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 332, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 467, 492, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279, 279, 279, 473, 473, 279, 279, 279, 279, 279, 279, 279, 279, 1460, 205, 524, 216, 201, 493, 579, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 293, 279, 279, 497, 3178, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 73, 120, 133, 163, -1012, 50, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 510, 222, 279, 279, 279, 473, -1012, 824, 346, 985, 3368, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 790, 0, 2, 3, 0, 757, 1, 649, 650, 0, 0, 652, 0, 763, 0, 0, 761, 0, 0, 0, 0, 762, 0, 0, 766, 764, 765, 767, 0, 768, 769, 770, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 759, 760, 0, 771, 802, 806, 619, 792, 803, 797, 793, 794, 619, 809, 796, 815, 814, 819, 804, 813, 818, 799, 800, 795, 798, 810, 811, 805, 816, 817, 812, 820, 801, 0, 0, 0, 0, 0, 0, 0, 627, 758, 651, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 791, 822, 0, 619, 0, 619, 0, 619, 0, 0, 0, 0, 789, 787, 788, 786, 619, 0, 619, 0, 619, 0, 0, 0, 0, 0, 651, 0, 0, 0, 0, 651, 0, 0, 0, 778, 777, 780, 781, 782, 776, 775, 774, 773, 785, 772, 0, 779, 0, 784, 783, 619, 0, 629, 653, 679, 5, 669, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 666, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 670, 744, 671, 672, 673, 674, 745, 675, 676, 677, 678, 746, 747, 748, 651, 608, 0, 10, 749, 667, 668, 651, 0, 17, 0, 99, 750, 613, 0, 138, 651, 651, 0, 47, 651, 651, 529, 0, 525, 659, 662, 660, 664, 665, 663, 658, 0, 58, 656, 661, 0, 243, 0, 60, 0, 239, 0, 237, 598, 170, 0, 167, 651, 610, 563, 0, 559, 561, 609, 651, 651, 534, 0, 530, 651, 545, 0, 541, 651, 599, 540, 0, 537, 600, 651, 0, 25, 651, 651, 550, 0, 546, 0, 56, 575, 0, 213, 0, 0, 236, 0, 233, 651, 605, 0, 49, 651, 0, 535, 0, 62, 651, 651, 219, 0, 215, 74, 76, 0, 45, 651, 651, 651, 114, 0, 109, 558, 0, 555, 651, 569, 0, 241, 603, 604, 601, 209, 0, 206, 651, 602, 0, 191, 621, 620, 651, 0, 807, 0, 808, 0, 821, 0, 0, 0, 180, 0, 823, 0, 824, 0, 825, 0, 0, 0, 0, 0, 445, 0, 0, 0, 0, 452, 0, 0, 0, 619, 619, 826, 651, 651, 827, 651, 628, 651, 7, 619, 607, 619, 619, 101, 100, 618, 616, 139, 619, 619, 611, 612, 619, 528, 527, 526, 59, 651, 244, 61, 240, 238, 168, 169, 560, 651, 533, 532, 531, 543, 542, 544, 538, 539, 26, 549, 548, 547, 57, 214, 0, 578, 572, 0, 574, 582, 234, 235, 50, 606, 536, 63, 218, 217, 216, 651, 46, 111, 113, 112, 110, 556, 557, 567, 242, 207, 208, 192, 0, 625, 624, 0, 150, 0, 140, 0, 124, 0, 172, 0, 551, 0, 182, 0, 564, 0, 518, 0, 65, 0, 368, 0, 357, 0, 334, 0, 266, 0, 245, 0, 285, 0, 298, 0, 314, 0, 454, 0, 383, 0, 430, 0, 370, 447, 447, 645, 647, 632, 630, 6, 13, 20, 104, 614, 0, 0, 657, 562, 587, 577, 581, 0, 75, 570, 651, 634, 622, 623, 626, 619, 151, 149, 619, 619, 126, 125, 619, 173, 171, 619, 553, 552, 619, 183, 181, 619, 211, 210, 619, 520, 519, 619, 69, 68, 619, 372, 369, 619, 359, 358, 619, 336, 335, 619, 268, 267, 619, 247, 246, 619, 619, 619, 619, 456, 455, 619, 385, 384, 619, 434, 431, 371, 0, 0, 0, 631, 651, 27, 12, 27, 19, 0, 0, 617, 619, 0, 576, 579, 583, 580, 585, 0, 568, 636, 156, 142, 0, 175, 175, 185, 175, 522, 71, 374, 361, 338, 270, 249, 286, 300, 316, 458, 387, 436, 446, 619, 619, 619, 258, 259, 260, 261, 262, 263, 264, 265, 619, 453, 651, 627, 651, 0, 51, 0, 14, 15, 16, 51, 21, 619, 0, 102, 615, 48, 654, 584, 0, 565, 0, 0, 0, 0, 153, 154, 619, 155, 221, 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 449, 450, 451, 448, 648, 0, 0, 8, 0, 0, 619, 619, 66, 0, 66, 22, 651, 651, 108, 0, 103, 655, 0, 586, 644, 635, 638, 651, 627, 627, 643, 0, 0, 152, 159, 619, 0, 162, 619, 619, 619, 158, 157, 194, 220, 141, 147, 148, 146, 619, 144, 145, 174, 178, 179, 176, 177, 554, 184, 189, 190, 186, 187, 188, 212, 521, 523, 524, 70, 72, 73, 373, 381, 382, 380, 619, 619, 378, 379, 619, 360, 365, 366, 364, 619, 619, 619, 337, 345, 346, 344, 619, 341, 350, 351, 352, 353, 356, 619, 348, 349, 354, 355, 619, 342, 343, 269, 277, 278, 276, 619, 619, 619, 619, 619, 619, 619, 275, 274, 619, 248, 251, 252, 250, 619, 619, 619, 619, 619, 284, 296, 297, 295, 619, 619, 290, 292, 619, 293, 294, 619, 299, 312, 313, 311, 619, 619, 305, 304, 619, 307, 308, 309, 310, 619, 315, 327, 328, 326, 619, 619, 619, 619, 619, 619, 619, 322, 323, 324, 325, 619, 321, 320, 457, 462, 463, 461, 619, 619, 619, 619, 619, 0, 0, 386, 391, 392, 390, 619, 619, 619, 619, 435, 439, 440, 438, 619, 619, 619, 619, 619, 646, 651, 651, 0, 0, 28, 29, 52, 53, 54, 55, 78, 64, 0, 23, 78, 107, 106, 105, 0, 654, 637, 0, 0, 0, 224, 0, 197, 164, 165, 160, 161, 163, 193, 222, 143, 376, 375, 377, 363, 367, 362, 340, 347, 339, 272, 282, 279, 283, 280, 281, 271, 273, 254, 253, 255, 256, 257, 288, 289, 287, 291, 302, 303, 301, 306, 318, 329, 330, 333, 331, 332, 317, 319, 460, 464, 465, 466, 459, 0, 0, 389, 393, 394, 388, 437, 441, 442, 443, 444, 633, 9, 0, 31, 0, 37, 0, 77, 619, 24, 0, 588, 0, 651, 641, 639, 640, 619, 225, 619, 619, 198, 196, 619, 413, 414, 0, 651, 396, 397, 0, 651, 619, 619, 39, 38, 651, 0, 0, 0, 0, 0, 0, 619, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 67, 651, 654, 645, 227, 223, 200, 195, 619, 412, 619, 399, 398, 395, 32, 41, 11, 0, 0, 0, 0, 0, 0, 79, 18, 0, 0, 0, 0, 420, 401, 0, 0, 417, 418, 0, 567, 651, 0, 90, 474, 0, 467, 651, 0, 115, 0, 128, 0, 432, 654, 589, 654, 642, 226, 231, 232, 230, 619, 229, 199, 204, 205, 203, 619, 202, 0, 0, 30, 36, 33, 34, 35, 40, 44, 42, 43, 619, 566, 416, 619, 92, 91, 619, 473, 619, 117, 116, 619, 130, 129, 433, 0, 0, 228, 201, 415, 424, 425, 423, 619, 619, 619, 619, 619, 619, 400, 410, 411, 619, 405, 406, 407, 404, 408, 409, 619, 420, 94, 469, 119, 132, 654, 654, 422, 426, 429, 427, 428, 421, 403, 402, 0, 0, 0, 0, 0, 0, 0, 419, 93, 97, 98, 619, 96, 0, 468, 470, 471, 118, 122, 123, 121, 619, 131, 136, 137, 135, 619, 133, 597, 654, 590, 593, 95, 0, 120, 134, 0, 0, 484, 497, 477, 506, 619, 651, 475, 476, 651, 481, 651, 483, 651, 482, 654, 594, 595, 472, 0, 0, 0, 0, 592, 591, 619, 479, 478, 619, 486, 485, 619, 499, 498, 619, 508, 507, 0, 0, 488, 501, 510, 654, 480, 0, 0, 0, 0, 487, 489, 492, 493, 494, 495, 496, 619, 491, 500, 502, 505, 619, 504, 509, 619, 512, 513, 514, 515, 516, 517, 596, 490, 503, 511 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -1012, -1012, -1012, 245, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -16, -1012, -2, -9, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1011, -1012, 22, -1012, -534, -24, -1012, 658, -1012, 681, -1012, 63, -1012, 105, -41, -1012, -1012, -237, -1012, -1012, 305, -1012, -225, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -486, -1012, -1012, -1012, -1012, -1012, 41, -1012, -1012, -1012, -1012, -1012, -1012, -11, -1012, -1012, -1012, -1012, -1012, -1012, -657, -1012, -3, -1012, -653, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 23, -1012, 30, -1012, -1012, 53, -1012, 35, -1012, -1012, -1012, -1012, 10, -1012, -1012, -236, -1012, -1012, -1012, -1012, -366, -1012, 38, -1012, -1012, 40, -1012, 43, -1012, -1012, -1012, -21, -1012, -1012, -1012, -1012, -355, -1012, -1012, 12, -1012, 18, -1012, -704, -1012, -480, -1012, 16, -1012, -1012, -560, -1012, -80, -1012, -1012, -67, -1012, -1012, -1012, -63, -1012, -1012, -39, -1012, -1012, -36, -1012, -1012, -1012, -1012, -1012, -33, -1012, -1012, -1012, -28, -1012, -27, 206, -1012, -1012, 667, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -435, -1012, -62, -1012, -1012, -365, -1012, -1012, 42, 211, -1012, 44, -1012, -87, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 74, -1012, -1012, -1012, -473, -1012, -1012, -667, -1012, -1012, -675, -1012, -722, -1012, -1012, -662, -1012, -1012, -271, -1012, -1012, -35, -1012, -1012, -725, -1012, -1012, 46, -1012, -1012, -1012, -390, -319, -335, -461, -1012, -1012, -1012, -1012, 214, 97, -1012, -1012, 239, -1012, -1012, -1012, 135, -1012, -1012, -1012, -441, -1012, -1012, -1012, 155, 693, -1012, -1012, -1012, 185, -93, -328, 1164, -1012, -1012, -1012, 526, 110, -1012, -1012, -1012, -433, -1012, -1012, -1012, -1012, -1012, -143, -1012, -1012, -260, 84, -4, 1453, 166, -694, 119, -1012, 660, -12, -1012, 137, -20, -23, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 1, 261, 262, 553, 933, 263, 2, 631, 632, 269, 3, 633, 634, 944, 688, 332, 54, 686, 740, 1023, 1106, 1025, 741, 1056, 1107, 365, 55, 279, 56, 351, 57, 742, 339, 938, 293, 939, 299, 783, 356, 784, 942, 521, 943, 144, 597, 718, 366, 489, 1027, 1028, 1064, 1113, 1065, 1157, 1208, 271, 62, 438, 749, 636, 750, 371, 1174, 372, 1119, 1066, 1162, 1210, 509, 1175, 579, 1121, 1067, 1165, 1211, 275, 64, 507, 669, 711, 127, 505, 575, 705, 706, 765, 766, 307, 65, 308, 136, 511, 582, 713, 401, 137, 515, 588, 715, 388, 66, 707, 964, 708, 957, 1043, 1103, 384, 67, 385, 138, 591, 342, 68, 361, 69, 362, 709, 774, 710, 955, 1040, 1102, 347, 70, 348, 303, 785, 301, 786, 378, 73, 297, 74, 531, 670, 612, 723, 671, 529, 672, 609, 722, 673, 533, 724, 535, 674, 725, 537, 675, 726, 527, 676, 606, 721, 828, 829, 525, 1177, 603, 720, 523, 677, 545, 678, 600, 719, 541, 679, 621, 728, 1050, 1051, 919, 1087, 1142, 1046, 1047, 920, 1109, 1110, 1071, 1141, 543, 1178, 1123, 1072, 624, 729, 170, 171, 626, 172, 173, 539, 1179, 618, 727, 1116, 1074, 1209, 1117, 1249, 1250, 1251, 1271, 1252, 1253, 1254, 1274, 1288, 1255, 1256, 1277, 1289, 1257, 1258, 1280, 1290, 519, 1180, 594, 717, 284, 75, 285, 319, 76, 320, 354, 77, 328, 78, 329, 323, 79, 324, 337, 80, 338, 513, 680, 585, 374, 81, 375, 312, 82, 313, 459, 517, 646, 1112, 567, 376, 497, 343, 344, 345, 475, 476, 563, 478, 479, 565, 643, 699, 640, 950, 1126, 1237, 1238, 1244, 1268, 1127, 330, 331, 386, 387, 352, 264, 377, 276, 441, 442, 638, 443, 124, 390, 502, 503, 571, 176, 430, 629, 570, 702, 757, 1036, 758, 759, 628, 428, 391, 4, 177, 752, 294, 451, 295, 265, 266, 267, 268, 392, 83, 84, 85, 86, 87, 88, 89, 90, 91, 175, 140, 5 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 11, 901, 174, 881, 897, 92, 92, 780, 92, 160, 92, 92, 314, 92, 92, 92, 92, 71, 92, 92, 865, 877, 161, 72, 92, 639, 162, 169, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 63, 848, 92, 764, 163, 139, 808, 164, 835, 751, 165, 869, 779, 180, 180, 166, 167, 882, 898, 506, 180, 126, 60, 305, 363, 864, 876, 278, 131, 36, 277, 15, 7, 180, 8, 129, 426, 41, 427, 180, 92, 296, 296, 296, 296, 296, 542, 315, 353, 1144, 1149, 296, 690, 296, 6, 687, 180, 296, 296, 159, 180, 128, 315, 296, 61, 296, 180, 960, 7, 305, 8, 7, -573, 8, 273, 130, 92, 273, 92, 7, 92, 8, 92, 92, 92, 92, 7, 423, 8, 737, 687, 92, 7, 92, 8, 92, 92, 92, 92, 92, 321, 92, 92, 92, 92, 141, 92, 92, 92, -587, -587, -654, 645, 281, 815, 142, 843, 856, 282, 296, 892, 910, 7, 334, 8, 436, 335, 437, 11, 93, 94, 1269, 95, 1270, 96, 97, 316, 98, 99, 100, 101, 317, 102, 103, 180, 7, 635, 8, 104, 143, 180, 273, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 477, 637, 123, 298, 300, 302, 304, 14, 1272, 12, 1273, 7, 333, 8, 340, 781, 20, 273, 355, 357, 20, 1275, 424, 1276, 379, 822, 389, 130, 866, 878, 807, 20, 834, 847, 735, 868, 880, 896, 180, 433, 912, 1033, 130, 309, 435, 20, 325, 22, 23, 446, 20, 1278, 43, 1279, 358, 7, 43, 8, 46, 359, 746, 130, 46, 270, 272, 747, 280, 43, 7, 7, 8, 8, 932, 46, 273, 712, 393, 576, 395, 180, 397, 43, 399, 400, 402, 403, 43, 913, 305, 326, 1229, 405, 46, 407, 1215, 409, 410, 411, 412, 413, 141, 415, 416, 417, 418, 1224, 420, 421, 422, 953, 954, 1287, 439, 180, 440, 367, 568, 368, 569, 782, 369, 380, 381, 382, 914, 274, 613, 283, 292, 292, 292, 292, 292, 306, 311, 318, 322, 327, 292, 336, 292, 341, 346, 350, 292, 292, 360, 364, 370, 373, 292, 383, 292, 474, 278, 17, 20, 277, 19, 20, 19, 1245, 573, 1246, 574, 562, 1247, 1100, 1248, 296, 130, 296, 296, 296, 20, 296, 577, 296, 578, 33, 20, 278, 564, 133, 277, 133, 580, 18, 581, 41, 20, 583, 43, 584, 11, 43, 45, 474, 698, 11, 20, 46, 614, 126, 1189, 615, 48, 47, 48, 141, 43, 130, 11, 630, 11, 1167, 43, 1168, 38, 20, 45, 22, 23, 645, 11, 11, 43, 11, 11, -651, 1143, -651, 40, 859, 684, 1301, 43, 11, 883, 899, 11, 11, 46, 11, 695, 11, 315, 11, 795, 11, 11, 1188, 1070, 20, 1148, 43, 644, 697, 586, 1187, 587, 11, 751, 11, 1190, 698, 11, 11, 589, 145, 590, 11, 11, 11, 1129, 296, 11, 592, -651, 593, 11, 595, 703, 596, 11, 52, 763, 1212, 1213, 43, 146, 147, 1032, 788, 148, 598, 704, 599, -651, 601, 510, 602, 512, 514, 516, 149, 518, 604, 520, 605, 150, 1053, 151, 152, 607, 153, 608, 1057, 20, 683, 22, 23, 154, 1076, 20, 155, 1243, 798, 1125, 11, 11, 11, 11, 1048, 1052, 130, 701, 315, 1234, 20, 11, 11, 738, 739, 156, 1220, 11, 1300, 1305, 1267, 1297, 610, 1312, 611, 43, 7, 1145, 8, 1281, 1077, 43, 157, 1197, 158, 508, 1176, 46, 1083, 1293, 1302, 1308, 1152, 125, 49, 1158, 43, 1291, 1236, 524, 526, 528, 530, 532, 1198, 534, 536, 538, 540, 1259, 1235, 544, 546, 787, 616, 619, 617, 620, 7, 1135, 8, 315, 1286, 692, 273, 9, 1296, 572, 1311, 691, 622, 1298, 623, 1313, 1221, 689, 92, 1034, 315, 1035, 845, 858, 1307, 274, 894, 10, 823, 292, 11, 292, 292, 292, 1176, 292, 1038, 292, 1039, 364, 394, 824, 396, 693, 398, 825, 951, 844, 857, 1185, 58, 893, 274, 404, 744, 406, 1186, 408, 1041, 41, 1042, 1054, 1085, 1055, 1086, 1155, 92, 1156, 11, 826, 92, 809, 827, 59, 849, 830, 870, 884, 900, 911, 831, 832, 1160, 1163, 1161, 1164, 92, 92, 425, 1111, 946, 1111, 714, 1029, 716, 805, 814, 821, 840, 522, 863, 875, 889, 907, 918, 926, 841, 854, 1031, 1218, 890, 908, 791, 927, 792, 1044, 767, 11, 296, 11, 793, 92, 92, 768, 1140, 842, 855, 315, 769, 891, 909, 770, 928, 771, 1134, 292, 772, 296, 625, 778, 965, 92, 92, 168, 1207, 1166, 627, 804, 813, 820, 839, 853, 862, 874, 888, 906, 917, 925, 929, 902, 930, 776, 1118, 1153, 641, 789, 700, 796, 799, 802, 811, 818, 837, 851, 860, 872, 886, 904, 915, 923, 806, 816, 833, 846, 753, 867, 879, 895, 694, 921, 1260, 642, 940, 349, 940, 1294, 1303, 1309, 1037, 756, 19, 20, 1295, 777, 1310, 1101, 931, 790, 145, 797, 800, 803, 812, 819, 838, 852, 861, 873, 887, 905, 916, 924, 0, 7, 431, 8, 760, 0, 0, 273, 147, 17, 0, 148, 941, 20, 941, 43, 17, 0, 743, 19, 703, 46, 149, 126, 130, 0, 48, 945, 704, 151, 152, 0, 153, 0, 761, 762, 0, 133, 0, 154, 33, 34, 35, 0, 133, 0, 958, 42, 20, 43, 0, 0, 0, 775, 145, 46, 0, 149, 128, 130, 0, 156, 150, 141, 0, 0, 47, 48, 0, 934, 935, 0, 0, 92, 92, 146, 147, 155, 157, 148, 158, 20, 132, 20, 43, 22, 23, 836, 133, 0, 46, 0, 130, 128, 1292, 134, 0, 151, 152, 135, 153, 0, 0, 0, 748, 0, 1073, 154, 11, 11, 0, 956, 0, 11, 547, 548, 145, 43, 0, 43, 0, 17, 922, 46, 554, 20, 555, 556, 0, 156, 0, 141, 0, 557, 558, 0, 130, 559, 147, 0, 0, 148, 0, 20, 0, 33, 157, 0, 158, 133, 0, 0, 149, 292, 0, 1171, 0, 794, 0, 151, 152, 43, 153, 315, 315, 0, 0, 46, 0, 154, 0, 0, 292, 683, 0, 141, 0, 17, 0, 43, 19, 0, 11, 11, 0, 46, 0, 14, 128, 0, 1068, 156, 0, 0, 0, 0, 0, 0, 0, 801, 0, 33, 34, 35, 28, 0, 0, 0, 157, 1069, 158, 0, 0, 0, 132, 0, 0, 850, 0, 92, 92, 92, 92, 92, 92, 126, 39, 134, 48, 0, 0, 135, 0, 0, 44, 0, 0, 0, 0, 11, -166, 0, 0, 1010, 1011, 11, 0, 0, 0, 11, 0, 0, 11, 0, 315, 1306, 1133, 1139, 0, 0, 11, 0, 0, 0, 648, 0, 0, 649, 650, 0, 0, 651, 1191, 0, 652, 0, 0, 653, 0, 0, 654, 0, 0, 655, 1024, 1026, 656, 0, 0, 657, 0, 0, 658, 0, 0, 659, 1184, 0, 660, 0, 0, 661, 0, 0, 662, 663, 664, 665, 1132, 1138, 666, 0, 0, 667, 0, 11, 1261, 0, 17, 0, 11, 19, 20, 0, 0, 0, 0, 0, 0, 696, 1130, 1136, 0, 130, 1146, 1150, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 43, 0, 730, 731, 732, 1314, 1228, 1233, 0, 0, 0, 1172, 1182, 733, 1131, 1137, 0, 0, 1147, 1151, 0, 0, 0, 92, 0, 0, 745, 0, 0, 0, 0, 1092, 1093, 1094, 1095, 1096, 1097, 0, 1181, 315, 0, 773, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1173, 1183, 0, 1219, 0, 1227, 1232, 1299, 1304, 1045, 1049, 0, 0, 11, 11, 11, 11, 0, 0, 0, 936, 937, 0, 0, 1172, 1216, 1222, 1225, 1230, 0, 0, 0, 1114, 315, 1120, 1122, 1124, 0, 0, 0, 0, 0, 0, 0, 0, 959, 0, 0, 961, 962, 963, 0, 0, 0, 0, 0, 0, 0, 0, 966, 0, 0, 0, 0, 0, 0, 1173, 1217, 1223, 1226, 1231, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 967, 968, 0, 0, 969, 0, 1108, 0, 1115, 970, 971, 972, 0, 0, 0, 0, 973, 0, 0, 0, 0, 0, 0, 974, 0, 0, 0, 0, 975, 0, 0, 0, 0, 0, 0, 976, 977, 978, 979, 980, 981, 982, 0, 0, 983, 0, 0, 0, 0, 984, 985, 986, 987, 988, 0, 1240, 0, 0, 989, 990, 0, 0, 991, 0, 0, 992, 0, 0, 0, 0, 993, 994, 0, 0, 995, 0, 0, 0, 0, 996, 0, 0, 0, 0, 997, 998, 999, 1000, 1001, 1002, 1003, 0, 0, 0, 0, 1004, 0, 0, 0, 0, 0, 0, 1005, 1006, 1007, 1008, 1009, 0, 0, 0, 0, 0, 0, 1012, 1013, 1014, 1015, 449, 0, 0, 0, 1016, 1017, 1018, 1019, 1020, 450, 0, 0, 0, 452, 0, 453, 145, 454, 0, 455, 0, 0, 0, 456, 0, 0, 0, 0, 458, 0, 0, 0, 0, 0, 0, 462, 0, 146, 147, 464, 0, 148, 0, 20, 466, 0, 0, 0, 468, 0, 0, 0, 0, 471, 130, 472, 0, 0, 473, 151, 152, 0, 153, 480, 0, 0, 0, 482, 0, 154, 484, 0, 485, 0, 0, 0, 0, 488, 0, 43, 0, 490, 0, 0, 0, 46, 0, 494, 0, 0, 495, 156, 0, 141, 498, 0, 0, 178, 0, 0, 499, 0, 0, 145, 501, 0, 0, 1075, 157, 0, 158, 0, 0, 0, 0, 0, 1079, 1214, 1080, 1081, 0, 0, 1082, 0, 0, 147, 17, 0, 148, 0, 20, 1089, 1090, 0, 0, 0, 0, 0, 0, 149, 0, 130, 1098, 0, 0, 32, 151, 152, 0, 153, 0, 34, 35, 0, 133, 414, 154, 37, 0, 0, 419, 1104, 0, 1105, 0, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 128, 47, 0, 156, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 157, 0, 158, 0, 0, 0, 145, 0, 0, 885, 0, 0, 0, 0, 0, 0, 1169, 0, 0, 0, 0, 0, 1170, 0, 0, 0, 0, 146, 147, 17, 0, 148, 19, 20, 0, 1192, 0, 0, 1193, 0, 0, 1194, 0, 1195, 130, 0, 1196, 0, 0, 151, 152, 0, 153, 33, 0, 0, 0, 0, 1199, 1200, 1201, 1202, 1203, 1204, 0, 0, 0, 1205, 0, 43, 0, 432, 0, 0, 1206, 46, 0, 0, 434, 0, 0, 0, 0, 141, 0, 0, 0, 444, 445, 0, 0, 447, 448, 0, 0, 0, 0, 0, 0, 0, 158, 1239, 0, 0, 0, 0, 0, 817, 0, 0, 0, 1241, 0, 0, 0, 0, 1242, 0, 0, 457, 0, 0, 0, 0, 0, 0, 460, 461, 0, 145, 0, 463, 1262, 0, 0, 465, 0, 0, 0, 0, 0, 467, 0, 0, 469, 470, 0, 0, 0, 0, 0, 147, 1282, 0, 148, 1283, 20, 0, 1284, 481, 0, 1285, 0, 483, 0, 149, 0, 130, 486, 487, 0, 0, 151, 152, 0, 153, 0, 491, 492, 493, 133, 0, 1315, 0, 0, 0, 496, 1316, 0, 0, 1317, 0, 43, 0, 0, 0, 500, 0, 46, 0, 0, 128, 504, 0, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 0, 903, 0, 0, 0, 0, 0, 549, 550, 0, 551, 0, 552, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 560, 0, 0, 0, 0, 0, 0, 0, 561, 949, 12, 13, 14, 15, 16, 0, 0, 17, 18, 0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 29, -753, 30, 31, 0, 32, 0, 566, -754, 0, 33, 34, 35, 0, -754, 36, 0, 37, 38, 0, 39, -754, 40, 41, 42, -754, 43, 145, 44, -756, 45, 0, 46, 145, -751, -752, 47, 48, 0, 49, -755, 50, 51, 0, 0, 0, 0, 0, 0, 147, 0, 0, 148, 0, 20, 147, 52, 0, 148, 0, 0, 53, 0, 145, 0, 130, 0, 0, 0, 149, 151, 152, 0, 153, 0, 0, 151, 152, 0, 153, 0, 0, 0, 0, 133, 147, 647, 0, 148, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 149, 0, 0, 156, 0, 141, 128, 151, 152, 156, 153, 0, 0, 0, 0, 133, 145, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 158, 810, 0, 0, 0, 1058, 0, 668, 128, 0, 147, 156, 0, 148, 0, 0, 0, 0, 0, 1059, 1060, 685, 1061, 0, 149, 1062, 0, 0, 0, 0, 158, 151, 152, 0, 153, 0, 0, 681, 0, 17, 0, 154, 19, 20, 0, 0, 1030, 0, 0, 0, 0, 0, 0, 0, 130, 0, 1063, 0, 0, 0, 128, 0, 0, 156, 34, 35, 0, 133, 0, 0, 37, 0, 0, 734, 0, 736, 0, 0, 0, 43, 0, 0, 158, 0, 0, 46, 0, 126, 0, 0, 48, 0, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 871, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 947, 948, 181, 310, 0, 0, 0, 0, 0, 0, 0, 952, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 1021, 1022, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 1128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1078, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1084, 0, 0, 0, 1088, 0, 0, 0, 0, 1091, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1099, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 0, 273, 0, 1154, 0, 0, 0, 0, 0, 1159, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 754, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 0, 248, 0, 0, 0, 0, 253, 0, 0, 0, 0, 258, 259, 260, 0, 0, 0, 0, 0, 0, 755, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1263, 0, 0, 1264, 179, 1265, 0, 1266, 180, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 429, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 273, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 477, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 1236, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 0, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260 }; static const yytype_int16 yycheck[] = { 4, 726, 89, 725, 726, 9, 10, 711, 12, 89, 14, 15, 105, 17, 18, 19, 20, 5, 22, 23, 724, 725, 89, 5, 28, 559, 89, 89, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 722, 52, 706, 89, 86, 719, 89, 721, 5, 89, 724, 711, 8, 8, 89, 89, 725, 726, 393, 8, 75, 5, 17, 12, 724, 725, 96, 85, 56, 96, 23, 5, 8, 7, 84, 104, 64, 106, 8, 90, 99, 100, 101, 102, 103, 420, 105, 114, 1106, 1107, 109, 632, 111, 0, 82, 8, 115, 116, 89, 8, 76, 120, 121, 5, 123, 8, 766, 5, 17, 7, 5, 14, 7, 11, 42, 126, 11, 128, 5, 130, 7, 132, 133, 134, 135, 5, 104, 7, 8, 82, 141, 5, 143, 7, 145, 146, 147, 148, 149, 94, 151, 152, 153, 154, 81, 156, 157, 158, 107, 108, 107, 107, 88, 720, 87, 722, 723, 93, 177, 726, 727, 5, 92, 7, 104, 95, 106, 178, 9, 10, 104, 12, 106, 14, 15, 88, 17, 18, 19, 20, 93, 22, 23, 8, 5, 83, 7, 28, 70, 8, 11, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 14, 105, 52, 100, 101, 102, 103, 22, 104, 20, 106, 5, 109, 7, 111, 711, 31, 11, 115, 116, 31, 104, 104, 106, 121, 721, 123, 42, 724, 725, 719, 31, 721, 722, 683, 724, 725, 726, 8, 104, 21, 951, 42, 104, 104, 31, 107, 33, 34, 104, 31, 104, 67, 106, 88, 5, 67, 7, 73, 93, 88, 42, 73, 94, 95, 93, 97, 67, 5, 5, 7, 7, 8, 73, 11, 105, 126, 104, 128, 8, 130, 67, 132, 133, 134, 135, 67, 68, 17, 18, 105, 141, 73, 143, 105, 145, 146, 147, 148, 149, 81, 151, 152, 153, 154, 105, 156, 157, 158, 758, 759, 105, 104, 8, 106, 85, 104, 87, 106, 105, 90, 16, 17, 18, 105, 96, 104, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 107, 393, 27, 31, 393, 30, 31, 30, 84, 104, 86, 106, 474, 89, 1077, 91, 397, 42, 399, 400, 401, 31, 403, 104, 405, 106, 51, 31, 420, 107, 55, 420, 55, 104, 28, 106, 64, 31, 104, 67, 106, 414, 67, 71, 107, 108, 419, 31, 73, 104, 75, 1142, 104, 78, 77, 78, 81, 67, 42, 432, 103, 434, 1125, 67, 1127, 59, 31, 71, 33, 34, 107, 444, 445, 67, 447, 448, 5, 105, 7, 63, 105, 103, 105, 67, 457, 725, 726, 460, 461, 73, 463, 105, 465, 474, 467, 105, 469, 470, 1142, 1028, 31, 105, 67, 565, 105, 104, 1142, 106, 481, 5, 483, 1142, 108, 486, 487, 104, 4, 106, 491, 492, 493, 105, 503, 496, 104, 54, 106, 500, 104, 24, 106, 504, 97, 105, 1197, 1198, 67, 25, 26, 109, 105, 29, 104, 32, 106, 74, 104, 397, 106, 399, 400, 401, 40, 403, 104, 405, 106, 45, 104, 47, 48, 104, 50, 106, 105, 31, 628, 33, 34, 57, 105, 31, 60, 1236, 105, 85, 549, 550, 551, 552, 1010, 1011, 42, 645, 565, 1211, 31, 560, 561, 43, 44, 79, 37, 566, 1288, 1289, 1259, 1288, 104, 1290, 106, 67, 5, 1106, 7, 1268, 110, 67, 96, 111, 98, 395, 1141, 73, 104, 1288, 1289, 1290, 104, 62, 80, 104, 67, 1286, 14, 409, 410, 411, 412, 413, 107, 415, 416, 417, 418, 107, 112, 421, 422, 105, 104, 104, 106, 106, 5, 105, 7, 628, 107, 634, 11, 54, 1288, 503, 1290, 633, 104, 1288, 106, 1290, 105, 632, 635, 104, 645, 106, 722, 723, 1290, 393, 726, 74, 721, 397, 647, 399, 400, 401, 1207, 403, 104, 405, 106, 407, 127, 721, 129, 634, 131, 721, 752, 722, 723, 1142, 5, 726, 420, 140, 691, 142, 1142, 144, 104, 64, 106, 104, 104, 106, 106, 104, 683, 106, 685, 721, 687, 719, 721, 5, 722, 721, 724, 725, 726, 727, 721, 721, 104, 104, 106, 106, 703, 704, 175, 1092, 744, 1094, 652, 943, 654, 719, 720, 721, 722, 407, 724, 725, 726, 727, 728, 729, 722, 723, 946, 1208, 726, 727, 715, 729, 715, 964, 706, 734, 743, 736, 715, 738, 739, 706, 1103, 722, 723, 752, 706, 726, 727, 706, 729, 706, 1102, 503, 706, 762, 545, 711, 774, 758, 759, 89, 1192, 1123, 548, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 729, 726, 729, 711, 1094, 1111, 563, 715, 644, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 719, 720, 721, 722, 700, 724, 725, 726, 635, 728, 1244, 565, 742, 113, 744, 1288, 1289, 1290, 954, 702, 30, 31, 1288, 711, 1290, 1078, 735, 715, 4, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, -1, 5, 177, 7, 702, -1, -1, 11, 26, 27, -1, 29, 742, 31, 744, 67, 27, -1, 687, 30, 24, 73, 40, 75, 42, -1, 78, 743, 32, 47, 48, -1, 50, -1, 703, 704, -1, 55, -1, 57, 51, 52, 53, -1, 55, -1, 762, 65, 31, 67, -1, -1, -1, 105, 4, 73, -1, 40, 76, 42, -1, 79, 45, 81, -1, -1, 77, 78, -1, 738, 739, -1, -1, 912, 913, 25, 26, 60, 96, 29, 98, 31, 49, 31, 67, 33, 34, 105, 55, -1, 73, -1, 42, 76, 105, 62, -1, 47, 48, 66, 50, -1, -1, -1, 694, -1, 1028, 57, 947, 948, -1, 761, -1, 952, 423, 424, 4, 67, -1, 67, -1, 27, 105, 73, 433, 31, 435, 436, -1, 79, -1, 81, -1, 442, 443, -1, 42, 446, 26, -1, -1, 29, -1, 31, -1, 51, 96, -1, 98, 55, -1, -1, 40, 743, -1, 105, -1, 105, -1, 47, 48, 67, 50, 1010, 1011, -1, -1, 73, -1, 57, -1, -1, 762, 1101, -1, 81, -1, 27, -1, 67, 30, -1, 1021, 1022, -1, 73, -1, 22, 76, -1, 1028, 79, -1, -1, -1, -1, -1, -1, -1, 105, -1, 51, 52, 53, 39, -1, -1, -1, 96, 1028, 98, -1, -1, -1, 49, -1, -1, 105, -1, 1058, 1059, 1060, 1061, 1062, 1063, 75, 61, 62, 78, -1, -1, 66, -1, -1, 69, -1, -1, -1, -1, 1078, 75, -1, -1, 912, 913, 1084, -1, -1, -1, 1088, -1, -1, 1091, -1, 1101, 105, 1102, 1103, -1, -1, 1099, -1, -1, -1, 573, -1, -1, 576, 577, -1, -1, 580, 1142, -1, 583, -1, -1, 586, -1, -1, 589, -1, -1, 592, 934, 935, 595, -1, -1, 598, -1, -1, 601, -1, -1, 604, 1142, -1, 607, -1, -1, 610, -1, -1, 613, 614, 615, 616, 1102, 1103, 619, -1, -1, 622, -1, 1154, 1244, -1, 27, -1, 1159, 30, 31, -1, -1, -1, -1, -1, -1, 638, 1102, 1103, -1, 42, 1106, 1107, -1, -1, -1, -1, -1, -1, 51, 52, 53, -1, 55, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, -1, 67, -1, 669, 670, 671, 1291, 1210, 1211, -1, -1, -1, 1141, 1142, 680, 1102, 1103, -1, -1, 1106, 1107, -1, -1, -1, 1220, -1, -1, 693, -1, -1, -1, -1, 1058, 1059, 1060, 1061, 1062, 1063, -1, 105, 1244, -1, 708, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1141, 1142, -1, 1208, -1, 1210, 1211, 1288, 1289, 1010, 1011, -1, -1, 1263, 1264, 1265, 1266, -1, -1, -1, 740, 741, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, 1093, 1291, 1095, 1096, 1097, -1, -1, -1, -1, -1, -1, -1, -1, 765, -1, -1, 768, 769, 770, -1, -1, -1, -1, -1, -1, -1, -1, 779, -1, -1, -1, -1, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 805, 806, -1, -1, 809, -1, 1092, -1, 1094, 814, 815, 816, -1, -1, -1, -1, 821, -1, -1, -1, -1, -1, -1, 828, -1, -1, -1, -1, 833, -1, -1, -1, -1, -1, -1, 840, 841, 842, 843, 844, 845, 846, -1, -1, 849, -1, -1, -1, -1, 854, 855, 856, 857, 858, -1, 1220, -1, -1, 863, 864, -1, -1, 867, -1, -1, 870, -1, -1, -1, -1, 875, 876, -1, -1, 879, -1, -1, -1, -1, 884, -1, -1, -1, -1, 889, 890, 891, 892, 893, 894, 895, -1, -1, -1, -1, 900, -1, -1, -1, -1, -1, -1, 907, 908, 909, 910, 911, -1, -1, -1, -1, -1, -1, 918, 919, 920, 921, 284, -1, -1, -1, 926, 927, 928, 929, 930, 293, -1, -1, -1, 297, -1, 299, 4, 301, -1, 303, -1, -1, -1, 307, -1, -1, -1, -1, 312, -1, -1, -1, -1, -1, -1, 319, -1, 25, 26, 323, -1, 29, -1, 31, 328, -1, -1, -1, 332, -1, -1, -1, -1, 337, 42, 339, -1, -1, 342, 47, 48, -1, 50, 347, -1, -1, -1, 351, -1, 57, 354, -1, 356, -1, -1, -1, -1, 361, -1, 67, -1, 365, -1, -1, -1, 73, -1, 371, -1, -1, 374, 79, -1, 81, 378, -1, -1, 92, -1, -1, 384, -1, -1, 4, 388, -1, -1, 1029, 96, -1, 98, -1, -1, -1, -1, -1, 1038, 105, 1040, 1041, -1, -1, 1044, -1, -1, 26, 27, -1, 29, -1, 31, 1053, 1054, -1, -1, -1, -1, -1, -1, 40, -1, 42, 1064, -1, -1, 46, 47, 48, -1, 50, -1, 52, 53, -1, 55, 150, 57, 58, -1, -1, 155, 1083, -1, 1085, -1, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 76, 77, -1, 79, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, 98, -1, -1, -1, 4, -1, -1, 105, -1, -1, -1, -1, -1, -1, 1133, -1, -1, -1, -1, -1, 1139, -1, -1, -1, -1, 25, 26, 27, -1, 29, 30, 31, -1, 1152, -1, -1, 1155, -1, -1, 1158, -1, 1160, 42, -1, 1163, -1, -1, 47, 48, -1, 50, 51, -1, -1, -1, -1, 1175, 1176, 1177, 1178, 1179, 1180, -1, -1, -1, 1184, -1, 67, -1, 261, -1, -1, 1191, 73, -1, -1, 268, -1, -1, -1, -1, 81, -1, -1, -1, 277, 278, -1, -1, 281, 282, -1, -1, -1, -1, -1, -1, -1, 98, 1218, -1, -1, -1, -1, -1, 105, -1, -1, -1, 1228, -1, -1, -1, -1, 1233, -1, -1, 309, -1, -1, -1, -1, -1, -1, 316, 317, -1, 4, -1, 321, 1249, -1, -1, 325, -1, -1, -1, -1, -1, 331, -1, -1, 334, 335, -1, -1, -1, -1, -1, 26, 1269, -1, 29, 1272, 31, -1, 1275, 349, -1, 1278, -1, 353, -1, 40, -1, 42, 358, 359, -1, -1, 47, 48, -1, 50, -1, 367, 368, 369, 55, -1, 1299, -1, -1, -1, 376, 1304, -1, -1, 1307, -1, 67, -1, -1, -1, 386, -1, 73, -1, -1, 76, 392, -1, 79, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, 426, 427, -1, 429, -1, 431, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 451, -1, -1, -1, -1, -1, -1, -1, 459, 749, 20, 21, 22, 23, 24, -1, -1, 27, 28, -1, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, -1, 46, -1, 489, 49, -1, 51, 52, 53, -1, 55, 56, -1, 58, 59, -1, 61, 62, 63, 64, 65, 66, 67, 4, 69, 70, 71, -1, 73, 4, 75, 76, 77, 78, -1, 80, 81, 82, 83, -1, -1, -1, -1, -1, -1, 26, -1, -1, 29, -1, 31, 26, 97, -1, 29, -1, -1, 102, -1, 4, -1, 42, -1, -1, -1, 40, 47, 48, -1, 50, -1, -1, 47, 48, -1, 50, -1, -1, -1, -1, 55, 26, 568, -1, 29, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 40, -1, -1, 79, -1, 81, 76, 47, 48, 79, 50, -1, -1, -1, -1, 55, 4, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, 98, 105, -1, -1, -1, 21, -1, 105, 76, -1, 26, 79, -1, 29, -1, -1, -1, -1, -1, 35, 36, 630, 38, -1, 40, 41, -1, -1, -1, -1, 98, 47, 48, -1, 50, -1, -1, 105, -1, 27, -1, 57, 30, 31, -1, -1, 944, -1, -1, -1, -1, -1, -1, -1, 42, -1, 72, -1, -1, -1, 76, -1, -1, 79, 52, 53, -1, 55, -1, -1, 58, -1, -1, 682, -1, 684, -1, -1, -1, 67, -1, -1, 98, -1, -1, 73, -1, 75, -1, -1, 78, -1, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, 746, 747, 10, 11, -1, -1, -1, -1, -1, -1, -1, 757, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, 932, 933, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1034, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1048, -1, -1, -1, 1052, -1, -1, -1, -1, 1057, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1076, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, 11, -1, 1112, -1, -1, -1, -1, -1, 1118, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, -1, -1, -1, -1, 91, -1, -1, -1, -1, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1250, -1, -1, 1253, 4, 1255, -1, 1257, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 114, 120, 124, 419, 441, 0, 5, 7, 54, 74, 418, 20, 21, 22, 23, 24, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 43, 44, 46, 51, 52, 53, 56, 58, 59, 61, 63, 64, 65, 67, 69, 71, 73, 77, 78, 80, 82, 83, 97, 102, 130, 140, 142, 144, 147, 149, 151, 153, 170, 176, 190, 202, 214, 222, 227, 229, 238, 241, 243, 245, 247, 339, 342, 345, 347, 350, 353, 359, 362, 430, 431, 432, 433, 434, 435, 436, 437, 438, 418, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 402, 402, 75, 194, 76, 192, 42, 183, 49, 55, 62, 66, 204, 209, 224, 356, 440, 81, 335, 70, 157, 4, 25, 26, 29, 40, 45, 47, 48, 50, 57, 60, 79, 96, 98, 249, 254, 257, 261, 264, 267, 273, 277, 279, 283, 299, 304, 305, 307, 308, 310, 439, 407, 420, 419, 4, 8, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 115, 116, 119, 395, 425, 426, 427, 428, 123, 395, 169, 395, 11, 116, 189, 397, 428, 429, 141, 395, 88, 93, 116, 338, 340, 9, 11, 12, 16, 17, 18, 116, 148, 422, 424, 425, 246, 422, 150, 422, 242, 422, 240, 422, 17, 116, 201, 203, 390, 11, 116, 361, 363, 396, 425, 88, 93, 116, 341, 343, 94, 116, 349, 351, 390, 18, 116, 346, 348, 390, 391, 129, 422, 92, 95, 116, 352, 354, 146, 422, 116, 226, 371, 372, 373, 116, 237, 239, 391, 116, 143, 394, 428, 344, 422, 152, 422, 88, 93, 116, 228, 230, 12, 116, 139, 160, 85, 87, 90, 116, 175, 177, 116, 358, 360, 369, 396, 244, 422, 16, 17, 18, 116, 221, 223, 392, 393, 213, 422, 403, 418, 429, 420, 402, 420, 402, 420, 402, 420, 420, 208, 420, 420, 402, 420, 402, 420, 402, 420, 420, 420, 420, 420, 419, 420, 420, 420, 420, 419, 420, 420, 420, 104, 104, 402, 104, 106, 417, 8, 408, 424, 419, 104, 419, 104, 104, 106, 171, 104, 106, 398, 399, 401, 419, 419, 104, 419, 419, 398, 398, 423, 398, 398, 398, 398, 398, 419, 398, 364, 419, 419, 398, 419, 398, 419, 398, 419, 398, 419, 419, 398, 398, 398, 107, 374, 375, 14, 377, 378, 398, 419, 398, 419, 398, 398, 419, 419, 398, 161, 398, 419, 419, 419, 398, 398, 419, 370, 398, 398, 419, 398, 404, 405, 419, 195, 397, 191, 395, 182, 422, 205, 422, 355, 422, 210, 422, 365, 422, 334, 422, 155, 160, 276, 395, 272, 395, 266, 395, 253, 395, 248, 395, 258, 395, 260, 395, 263, 395, 309, 395, 282, 397, 298, 395, 278, 395, 402, 402, 419, 419, 419, 419, 117, 402, 402, 402, 402, 402, 402, 419, 419, 396, 376, 107, 379, 419, 368, 104, 106, 410, 406, 422, 104, 106, 196, 104, 104, 106, 184, 104, 106, 206, 104, 106, 357, 104, 106, 211, 104, 106, 225, 104, 106, 336, 104, 106, 158, 104, 106, 280, 104, 106, 274, 104, 106, 268, 104, 106, 255, 104, 106, 250, 104, 104, 104, 104, 106, 311, 104, 106, 284, 104, 106, 302, 280, 306, 306, 416, 409, 103, 121, 122, 125, 126, 83, 173, 105, 400, 144, 382, 374, 378, 380, 396, 107, 366, 419, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 105, 192, 249, 252, 254, 257, 261, 264, 267, 277, 279, 283, 356, 105, 105, 396, 103, 419, 131, 82, 128, 130, 144, 131, 128, 142, 420, 105, 402, 105, 108, 381, 382, 396, 411, 24, 32, 197, 198, 215, 217, 231, 233, 193, 105, 207, 207, 212, 207, 337, 159, 281, 275, 269, 256, 251, 259, 262, 265, 312, 285, 303, 402, 402, 402, 402, 419, 407, 419, 8, 43, 44, 132, 136, 145, 420, 145, 402, 88, 93, 116, 172, 174, 5, 421, 375, 54, 105, 403, 412, 414, 415, 427, 420, 420, 105, 190, 199, 200, 202, 204, 209, 224, 227, 229, 402, 232, 105, 151, 153, 176, 194, 245, 247, 105, 151, 153, 241, 243, 105, 105, 151, 153, 214, 241, 243, 105, 105, 151, 153, 105, 151, 153, 105, 151, 153, 176, 183, 335, 339, 342, 356, 105, 151, 153, 176, 183, 252, 335, 105, 151, 153, 176, 183, 247, 254, 257, 261, 264, 267, 270, 271, 273, 277, 279, 335, 339, 342, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 345, 356, 105, 151, 153, 176, 192, 249, 252, 299, 310, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 342, 356, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 347, 350, 353, 356, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 347, 350, 353, 356, 359, 362, 105, 151, 153, 176, 183, 192, 249, 252, 356, 21, 68, 105, 151, 153, 176, 183, 288, 293, 335, 105, 151, 153, 176, 183, 192, 249, 305, 308, 417, 8, 118, 420, 420, 402, 402, 147, 149, 151, 153, 154, 156, 127, 422, 154, 419, 419, 398, 383, 396, 419, 407, 407, 234, 395, 218, 422, 402, 194, 402, 402, 402, 216, 233, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 420, 420, 402, 402, 402, 402, 402, 402, 402, 402, 402, 419, 419, 133, 395, 135, 395, 162, 163, 157, 398, 162, 109, 421, 104, 106, 413, 413, 104, 106, 235, 104, 106, 219, 217, 116, 291, 292, 369, 116, 286, 287, 369, 104, 104, 106, 137, 105, 21, 35, 36, 38, 41, 72, 164, 166, 179, 186, 192, 249, 252, 296, 301, 310, 314, 402, 105, 110, 419, 402, 402, 402, 402, 104, 419, 104, 106, 289, 419, 402, 402, 419, 420, 420, 420, 420, 420, 420, 402, 419, 421, 416, 236, 220, 402, 402, 134, 138, 116, 294, 295, 366, 367, 165, 395, 116, 313, 316, 367, 178, 395, 185, 395, 300, 395, 85, 384, 389, 105, 105, 151, 153, 176, 183, 238, 105, 151, 153, 176, 183, 222, 297, 290, 105, 140, 144, 151, 153, 105, 140, 151, 153, 104, 368, 419, 104, 106, 167, 104, 419, 104, 106, 180, 104, 106, 187, 302, 421, 421, 402, 402, 105, 151, 153, 176, 183, 252, 273, 299, 310, 335, 105, 151, 153, 183, 247, 339, 342, 345, 347, 350, 356, 402, 402, 402, 402, 402, 111, 107, 402, 402, 402, 402, 402, 402, 402, 402, 297, 168, 315, 181, 188, 421, 421, 105, 105, 151, 153, 170, 176, 37, 105, 151, 153, 105, 151, 153, 176, 183, 105, 151, 153, 176, 183, 190, 112, 14, 385, 386, 402, 420, 402, 402, 421, 387, 84, 86, 89, 91, 317, 318, 319, 321, 322, 323, 326, 327, 330, 331, 107, 386, 396, 402, 419, 419, 419, 419, 421, 388, 104, 106, 320, 104, 106, 324, 104, 106, 328, 104, 106, 332, 421, 402, 402, 402, 402, 107, 105, 325, 329, 333, 421, 105, 245, 247, 339, 342, 347, 350, 356, 359, 105, 245, 247, 356, 359, 105, 194, 245, 247, 339, 342, 347, 350, 396, 402, 402, 402 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 113, 114, 114, 114, 115, 116, 117, 118, 117, 119, 120, 121, 122, 122, 122, 122, 123, 124, 125, 126, 126, 126, 127, 128, 129, 130, 131, 131, 131, 132, 133, 134, 134, 134, 134, 134, 135, 136, 137, 137, 138, 138, 138, 138, 139, 140, 141, 142, 143, 144, 145, 145, 145, 145, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 156, 157, 158, 158, 159, 159, 159, 161, 160, 160, 162, 163, 163, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 165, 166, 167, 167, 168, 168, 168, 168, 168, 169, 170, 171, 171, 172, 173, 173, 174, 174, 174, 175, 176, 177, 177, 177, 177, 178, 179, 180, 180, 181, 181, 181, 181, 181, 182, 183, 184, 184, 185, 186, 187, 187, 188, 188, 188, 188, 188, 188, 189, 190, 191, 192, 193, 193, 193, 193, 193, 193, 193, 194, 195, 196, 196, 197, 197, 197, 198, 198, 198, 198, 198, 198, 198, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, 206, 207, 207, 207, 207, 207, 208, 209, 210, 211, 211, 212, 212, 212, 212, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 219, 220, 220, 220, 220, 220, 220, 221, 222, 223, 223, 224, 225, 225, 226, 227, 228, 229, 230, 230, 230, 231, 232, 232, 233, 234, 235, 235, 236, 236, 236, 236, 236, 236, 237, 238, 239, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 253, 254, 255, 255, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 257, 258, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 260, 261, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 263, 264, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 266, 267, 268, 268, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 270, 270, 271, 271, 271, 271, 271, 271, 271, 272, 273, 274, 274, 275, 275, 275, 275, 275, 275, 275, 276, 277, 278, 279, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 283, 284, 284, 285, 285, 285, 285, 285, 285, 285, 285, 286, 286, 287, 288, 289, 289, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 291, 291, 292, 293, 294, 294, 295, 296, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 298, 299, 300, 301, 302, 302, 303, 303, 303, 303, 303, 303, 303, 303, 303, 304, 305, 306, 306, 306, 306, 306, 307, 308, 309, 310, 311, 311, 312, 312, 312, 312, 312, 312, 312, 312, 312, 313, 314, 315, 315, 315, 315, 316, 316, 317, 317, 318, 319, 320, 320, 321, 321, 321, 322, 323, 324, 324, 325, 325, 325, 325, 325, 325, 325, 325, 325, 326, 327, 328, 328, 329, 329, 329, 329, 329, 330, 331, 332, 332, 333, 333, 333, 333, 333, 333, 333, 333, 334, 335, 336, 336, 337, 337, 337, 338, 339, 340, 340, 340, 341, 342, 343, 343, 343, 344, 345, 346, 347, 348, 348, 349, 350, 351, 351, 351, 352, 353, 354, 354, 354, 355, 356, 357, 357, 358, 359, 360, 360, 361, 362, 364, 363, 363, 365, 366, 367, 368, 368, 370, 369, 372, 371, 373, 371, 371, 374, 375, 376, 376, 377, 378, 379, 379, 380, 381, 381, 382, 382, 383, 384, 385, 386, 387, 387, 388, 388, 389, 390, 391, 391, 392, 392, 393, 393, 394, 394, 395, 395, 396, 396, 397, 397, 397, 398, 398, 399, 400, 401, 402, 402, 402, 403, 404, 405, 406, 406, 407, 407, 408, 408, 408, 409, 409, 410, 410, 411, 411, 412, 412, 412, 413, 413, 414, 415, 416, 416, 417, 417, 418, 418, 419, 419, 420, 421, 421, 423, 422, 422, 424, 424, 424, 424, 424, 424, 424, 425, 425, 425, 426, 426, 426, 426, 426, 426, 426, 426, 426, 426, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 440, 440, 440, 440, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 1, 3, 0, 0, 6, 1, 13, 1, 0, 2, 2, 2, 1, 13, 1, 0, 2, 3, 1, 4, 1, 4, 0, 3, 3, 7, 1, 0, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 2, 1, 4, 1, 7, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 4, 1, 4, 1, 4, 1, 1, 0, 3, 4, 1, 4, 0, 2, 2, 0, 3, 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 4, 1, 0, 4, 2, 2, 1, 1, 4, 2, 2, 2, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 3, 1, 4, 1, 4, 0, 2, 3, 2, 2, 2, 1, 4, 1, 7, 0, 3, 2, 2, 2, 2, 2, 4, 1, 1, 4, 1, 1, 1, 0, 2, 2, 2, 3, 3, 2, 3, 3, 2, 0, 1, 4, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 2, 1, 4, 3, 0, 3, 4, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 4, 1, 4, 1, 4, 1, 4, 2, 2, 1, 2, 0, 2, 5, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 0, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 1, 0, 3, 3, 3, 2, 3, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 1, 4, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 2, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 7, 2, 1, 1, 7, 0, 3, 3, 2, 2, 2, 3, 3, 3, 3, 1, 4, 1, 4, 1, 4, 0, 3, 2, 2, 2, 3, 3, 3, 3, 2, 5, 0, 3, 3, 3, 3, 2, 5, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 3, 1, 7, 0, 2, 2, 5, 2, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 3, 1, 4, 0, 2, 3, 2, 2, 2, 2, 2, 2, 1, 3, 1, 4, 0, 2, 3, 2, 2, 1, 3, 1, 4, 0, 3, 2, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 2, 1, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 1, 4, 2, 1, 1, 4, 0, 3, 1, 1, 2, 2, 0, 2, 0, 3, 0, 2, 0, 2, 1, 3, 2, 0, 2, 3, 2, 0, 2, 2, 0, 2, 0, 5, 5, 5, 4, 4, 0, 2, 0, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 2, 4, 1, 1, 1, 0, 2, 2, 3, 2, 1, 0, 1, 0, 2, 0, 2, 3, 0, 5, 1, 4, 0, 3, 1, 3, 3, 1, 4, 1, 1, 0, 4, 2, 5, 1, 1, 0, 2, 2, 0, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 4, 4, 4, 4, 4 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, scanner, param, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (0) #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Print *YYLOCP on YYO. Private, do not rely on its existence. */ YY_ATTRIBUTE_UNUSED static int yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp) { int res = 0; int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0; if (0 <= yylocp->first_line) { res += YYFPRINTF (yyo, "%d", yylocp->first_line); if (0 <= yylocp->first_column) res += YYFPRINTF (yyo, ".%d", yylocp->first_column); } if (0 <= yylocp->last_line) { if (yylocp->first_line < yylocp->last_line) { res += YYFPRINTF (yyo, "-%d", yylocp->last_line); if (0 <= end_col) res += YYFPRINTF (yyo, ".%d", end_col); } else if (0 <= end_col && yylocp->first_column < end_col) res += YYFPRINTF (yyo, "-%d", end_col); } return res; } # define YY_LOCATION_PRINT(File, Loc) \ yy_location_print_ (File, &(Loc)) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, scanner, param); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { FILE *yyoutput = yyo; YYUSE (yyoutput); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyo, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { YYFPRINTF (yyo, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); YY_LOCATION_PRINT (yyo, *yylocationp); YYFPRINTF (yyo, ": "); yy_symbol_value_print (yyo, yytype, yyvaluep, yylocationp, scanner, param); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, void *scanner, struct yang_parameter *param) { unsigned long yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , scanner, param); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, yylsp, Rule, scanner, param); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return (YYSIZE_T) (yystpcpy (yyres, yystr) - yyres); } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, void *scanner, struct yang_parameter *param) { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 115: /* tmp_string */ { free((((*yyvaluep).p_str)) ? *((*yyvaluep).p_str) : NULL); } break; case 210: /* pattern_arg_str */ { free(((*yyvaluep).str)); } break; case 399: /* semicolom */ { free(((*yyvaluep).str)); } break; case 401: /* curly_bracket_open */ { free(((*yyvaluep).str)); } break; case 405: /* string_opt_part1 */ { free(((*yyvaluep).str)); } break; case 430: /* type_ext_alloc */ { yang_type_free(param->module->ctx, ((*yyvaluep).v)); } break; case 431: /* typedef_ext_alloc */ { yang_type_free(param->module->ctx, &((struct lys_tpdf *)((*yyvaluep).v))->type); } break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, &s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", &s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, &s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++c; YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)]; } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, &s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, &s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, &s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, &s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, &s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, &s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, &s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, &s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, &s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, &s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, &s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, &s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, &s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, &s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, &s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...) { free(*param->value); *param->value = NULL; if (yylloc->first_line != -1) { if (*param->data_node && (*param->data_node) == (*param->actual_node)) { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner)); } else { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); } } }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1361_0
crossvul-cpp_data_bad_2938_0
/** * collectd - src/snmp.c * Copyright (C) 2007-2012 Florian octo Forster * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: * Florian octo Forster <octo at collectd.org> **/ #include "collectd.h" #include "common.h" #include "plugin.h" #include "utils_complain.h" #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> #include <fnmatch.h> /* * Private data structes */ struct oid_s { oid oid[MAX_OID_LEN]; size_t oid_len; }; typedef struct oid_s oid_t; union instance_u { char string[DATA_MAX_NAME_LEN]; oid_t oid; }; typedef union instance_u instance_t; struct data_definition_s { char *name; /* used to reference this from the `Collect' option */ char *type; /* used to find the data_set */ _Bool is_table; instance_t instance; char *instance_prefix; oid_t *values; size_t values_len; double scale; double shift; struct data_definition_s *next; char **ignores; size_t ignores_len; int invert_match; }; typedef struct data_definition_s data_definition_t; struct host_definition_s { char *name; char *address; int version; /* snmpv1/2 options */ char *community; /* snmpv3 security options */ char *username; oid *auth_protocol; size_t auth_protocol_len; char *auth_passphrase; oid *priv_protocol; size_t priv_protocol_len; char *priv_passphrase; int security_level; char *context; void *sess_handle; c_complain_t complaint; cdtime_t interval; data_definition_t **data_list; int data_list_len; }; typedef struct host_definition_s host_definition_t; /* These two types are used to cache values in `csnmp_read_table' to handle * gaps in tables. */ struct csnmp_list_instances_s { oid_t suffix; char instance[DATA_MAX_NAME_LEN]; struct csnmp_list_instances_s *next; }; typedef struct csnmp_list_instances_s csnmp_list_instances_t; struct csnmp_table_values_s { oid_t suffix; value_t value; struct csnmp_table_values_s *next; }; typedef struct csnmp_table_values_s csnmp_table_values_t; /* * Private variables */ static data_definition_t *data_head = NULL; /* * Prototypes */ static int csnmp_read_host(user_data_t *ud); /* * Private functions */ static void csnmp_oid_init(oid_t *dst, oid const *src, size_t n) { assert(n <= STATIC_ARRAY_SIZE(dst->oid)); memcpy(dst->oid, src, sizeof(*src) * n); dst->oid_len = n; } static int csnmp_oid_compare(oid_t const *left, oid_t const *right) { return ( snmp_oid_compare(left->oid, left->oid_len, right->oid, right->oid_len)); } static int csnmp_oid_suffix(oid_t *dst, oid_t const *src, oid_t const *root) { /* Make sure "src" is in "root"s subtree. */ if (src->oid_len <= root->oid_len) return (EINVAL); if (snmp_oid_ncompare(root->oid, root->oid_len, src->oid, src->oid_len, /* n = */ root->oid_len) != 0) return (EINVAL); memset(dst, 0, sizeof(*dst)); dst->oid_len = src->oid_len - root->oid_len; memcpy(dst->oid, &src->oid[root->oid_len], dst->oid_len * sizeof(dst->oid[0])); return (0); } static int csnmp_oid_to_string(char *buffer, size_t buffer_size, oid_t const *o) { char oid_str[MAX_OID_LEN][16]; char *oid_str_ptr[MAX_OID_LEN]; for (size_t i = 0; i < o->oid_len; i++) { ssnprintf(oid_str[i], sizeof(oid_str[i]), "%lu", (unsigned long)o->oid[i]); oid_str_ptr[i] = oid_str[i]; } return (strjoin(buffer, buffer_size, oid_str_ptr, o->oid_len, /* separator = */ ".")); } static void csnmp_host_close_session(host_definition_t *host) /* {{{ */ { if (host->sess_handle == NULL) return; snmp_sess_close(host->sess_handle); host->sess_handle = NULL; } /* }}} void csnmp_host_close_session */ static void csnmp_host_definition_destroy(void *arg) /* {{{ */ { host_definition_t *hd; hd = arg; if (hd == NULL) return; if (hd->name != NULL) { DEBUG("snmp plugin: Destroying host definition for host `%s'.", hd->name); } csnmp_host_close_session(hd); sfree(hd->name); sfree(hd->address); sfree(hd->community); sfree(hd->username); sfree(hd->auth_passphrase); sfree(hd->priv_passphrase); sfree(hd->context); sfree(hd->data_list); sfree(hd); } /* }}} void csnmp_host_definition_destroy */ /* Many functions to handle the configuration. {{{ */ /* First there are many functions which do configuration stuff. It's a big * bloated and messy, I'm afraid. */ /* * Callgraph for the config stuff: * csnmp_config * +-> call_snmp_init_once * +-> csnmp_config_add_data * ! +-> csnmp_config_add_data_instance * ! +-> csnmp_config_add_data_instance_prefix * ! +-> csnmp_config_add_data_values * +-> csnmp_config_add_host * +-> csnmp_config_add_host_version * +-> csnmp_config_add_host_collect * +-> csnmp_config_add_host_auth_protocol * +-> csnmp_config_add_host_priv_protocol * +-> csnmp_config_add_host_security_level */ static void call_snmp_init_once(void) { static int have_init = 0; if (have_init == 0) init_snmp(PACKAGE_NAME); have_init = 1; } /* void call_snmp_init_once */ static int csnmp_config_add_data_instance(data_definition_t *dd, oconfig_item_t *ci) { char buffer[DATA_MAX_NAME_LEN]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (dd->is_table) { /* Instance is an OID */ dd->instance.oid.oid_len = MAX_OID_LEN; if (!read_objid(buffer, dd->instance.oid.oid, &dd->instance.oid.oid_len)) { ERROR("snmp plugin: read_objid (%s) failed.", buffer); return (-1); } } else { /* Instance is a simple string */ sstrncpy(dd->instance.string, buffer, sizeof(dd->instance.string)); } return (0); } /* int csnmp_config_add_data_instance */ static int csnmp_config_add_data_instance_prefix(data_definition_t *dd, oconfig_item_t *ci) { int status; if (!dd->is_table) { WARNING("snmp plugin: data %s: InstancePrefix is ignored when `Table' " "is set to `false'.", dd->name); return (-1); } status = cf_util_get_string(ci, &dd->instance_prefix); return status; } /* int csnmp_config_add_data_instance_prefix */ static int csnmp_config_add_data_values(data_definition_t *dd, oconfig_item_t *ci) { if (ci->values_num < 1) { WARNING("snmp plugin: `Values' needs at least one argument."); return (-1); } for (int i = 0; i < ci->values_num; i++) if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: `Values' needs only string argument."); return (-1); } sfree(dd->values); dd->values_len = 0; dd->values = malloc(sizeof(*dd->values) * ci->values_num); if (dd->values == NULL) return (-1); dd->values_len = (size_t)ci->values_num; for (int i = 0; i < ci->values_num; i++) { dd->values[i].oid_len = MAX_OID_LEN; if (NULL == snmp_parse_oid(ci->values[i].value.string, dd->values[i].oid, &dd->values[i].oid_len)) { ERROR("snmp plugin: snmp_parse_oid (%s) failed.", ci->values[i].value.string); free(dd->values); dd->values = NULL; dd->values_len = 0; return (-1); } } return (0); } /* int csnmp_config_add_data_instance */ static int csnmp_config_add_data_blacklist(data_definition_t *dd, oconfig_item_t *ci) { if (ci->values_num < 1) return (0); for (int i = 0; i < ci->values_num; i++) { if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: `Ignore' needs only string argument."); return (-1); } } dd->ignores_len = 0; dd->ignores = NULL; for (int i = 0; i < ci->values_num; ++i) { if (strarray_add(&(dd->ignores), &(dd->ignores_len), ci->values[i].value.string) != 0) { ERROR("snmp plugin: Can't allocate memory"); strarray_free(dd->ignores, dd->ignores_len); return (ENOMEM); } } return 0; } /* int csnmp_config_add_data_blacklist */ static int csnmp_config_add_data_blacklist_match_inverted(data_definition_t *dd, oconfig_item_t *ci) { if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN)) { WARNING("snmp plugin: `InvertMatch' needs exactly one boolean argument."); return (-1); } dd->invert_match = ci->values[0].value.boolean ? 1 : 0; return (0); } /* int csnmp_config_add_data_blacklist_match_inverted */ static int csnmp_config_add_data(oconfig_item_t *ci) { data_definition_t *dd; int status = 0; dd = calloc(1, sizeof(*dd)); if (dd == NULL) return (-1); status = cf_util_get_string(ci, &dd->name); if (status != 0) { free(dd); return (-1); } dd->scale = 1.0; dd->shift = 0.0; for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *option = ci->children + i; if (strcasecmp("Type", option->key) == 0) status = cf_util_get_string(option, &dd->type); else if (strcasecmp("Table", option->key) == 0) status = cf_util_get_boolean(option, &dd->is_table); else if (strcasecmp("Instance", option->key) == 0) status = csnmp_config_add_data_instance(dd, option); else if (strcasecmp("InstancePrefix", option->key) == 0) status = csnmp_config_add_data_instance_prefix(dd, option); else if (strcasecmp("Values", option->key) == 0) status = csnmp_config_add_data_values(dd, option); else if (strcasecmp("Shift", option->key) == 0) status = cf_util_get_double(option, &dd->shift); else if (strcasecmp("Scale", option->key) == 0) status = cf_util_get_double(option, &dd->scale); else if (strcasecmp("Ignore", option->key) == 0) status = csnmp_config_add_data_blacklist(dd, option); else if (strcasecmp("InvertMatch", option->key) == 0) status = csnmp_config_add_data_blacklist_match_inverted(dd, option); else { WARNING("snmp plugin: Option `%s' not allowed here.", option->key); status = -1; } if (status != 0) break; } /* for (ci->children) */ while (status == 0) { if (dd->type == NULL) { WARNING("snmp plugin: `Type' not given for data `%s'", dd->name); status = -1; break; } if (dd->values == NULL) { WARNING("snmp plugin: No `Value' given for data `%s'", dd->name); status = -1; break; } break; } /* while (status == 0) */ if (status != 0) { sfree(dd->name); sfree(dd->instance_prefix); sfree(dd->values); sfree(dd->ignores); sfree(dd); return (-1); } DEBUG("snmp plugin: dd = { name = %s, type = %s, is_table = %s, values_len = " "%zu }", dd->name, dd->type, (dd->is_table != 0) ? "true" : "false", dd->values_len); if (data_head == NULL) data_head = dd; else { data_definition_t *last; last = data_head; while (last->next != NULL) last = last->next; last->next = dd; } return (0); } /* int csnmp_config_add_data */ static int csnmp_config_add_host_version(host_definition_t *hd, oconfig_item_t *ci) { int version; if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) { WARNING("snmp plugin: The `Version' config option needs exactly one number " "argument."); return (-1); } version = (int)ci->values[0].value.number; if ((version < 1) || (version > 3)) { WARNING("snmp plugin: `Version' must either be `1', `2', or `3'."); return (-1); } hd->version = version; return (0); } /* int csnmp_config_add_host_address */ static int csnmp_config_add_host_collect(host_definition_t *host, oconfig_item_t *ci) { data_definition_t *data; data_definition_t **data_list; int data_list_len; if (ci->values_num < 1) { WARNING("snmp plugin: `Collect' needs at least one argument."); return (-1); } for (int i = 0; i < ci->values_num; i++) if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: All arguments to `Collect' must be strings."); return (-1); } data_list_len = host->data_list_len + ci->values_num; data_list = realloc(host->data_list, sizeof(data_definition_t *) * data_list_len); if (data_list == NULL) return (-1); host->data_list = data_list; for (int i = 0; i < ci->values_num; i++) { for (data = data_head; data != NULL; data = data->next) if (strcasecmp(ci->values[i].value.string, data->name) == 0) break; if (data == NULL) { WARNING("snmp plugin: No such data configured: `%s'", ci->values[i].value.string); continue; } DEBUG("snmp plugin: Collect: host = %s, data[%i] = %s;", host->name, host->data_list_len, data->name); host->data_list[host->data_list_len] = data; host->data_list_len++; } /* for (values_num) */ return (0); } /* int csnmp_config_add_host_collect */ static int csnmp_config_add_host_auth_protocol(host_definition_t *hd, oconfig_item_t *ci) { char buffer[4]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("MD5", buffer) == 0) { hd->auth_protocol = usmHMACMD5AuthProtocol; hd->auth_protocol_len = sizeof(usmHMACMD5AuthProtocol) / sizeof(oid); } else if (strcasecmp("SHA", buffer) == 0) { hd->auth_protocol = usmHMACSHA1AuthProtocol; hd->auth_protocol_len = sizeof(usmHMACSHA1AuthProtocol) / sizeof(oid); } else { WARNING("snmp plugin: The `AuthProtocol' config option must be `MD5' or " "`SHA'."); return (-1); } DEBUG("snmp plugin: host = %s; host->auth_protocol = %s;", hd->name, hd->auth_protocol == usmHMACMD5AuthProtocol ? "MD5" : "SHA"); return (0); } /* int csnmp_config_add_host_auth_protocol */ static int csnmp_config_add_host_priv_protocol(host_definition_t *hd, oconfig_item_t *ci) { char buffer[4]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("AES", buffer) == 0) { hd->priv_protocol = usmAESPrivProtocol; hd->priv_protocol_len = sizeof(usmAESPrivProtocol) / sizeof(oid); } else if (strcasecmp("DES", buffer) == 0) { hd->priv_protocol = usmDESPrivProtocol; hd->priv_protocol_len = sizeof(usmDESPrivProtocol) / sizeof(oid); } else { WARNING("snmp plugin: The `PrivProtocol' config option must be `AES' or " "`DES'."); return (-1); } DEBUG("snmp plugin: host = %s; host->priv_protocol = %s;", hd->name, hd->priv_protocol == usmAESPrivProtocol ? "AES" : "DES"); return (0); } /* int csnmp_config_add_host_priv_protocol */ static int csnmp_config_add_host_security_level(host_definition_t *hd, oconfig_item_t *ci) { char buffer[16]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("noAuthNoPriv", buffer) == 0) hd->security_level = SNMP_SEC_LEVEL_NOAUTH; else if (strcasecmp("authNoPriv", buffer) == 0) hd->security_level = SNMP_SEC_LEVEL_AUTHNOPRIV; else if (strcasecmp("authPriv", buffer) == 0) hd->security_level = SNMP_SEC_LEVEL_AUTHPRIV; else { WARNING("snmp plugin: The `SecurityLevel' config option must be " "`noAuthNoPriv', `authNoPriv', or `authPriv'."); return (-1); } DEBUG("snmp plugin: host = %s; host->security_level = %d;", hd->name, hd->security_level); return (0); } /* int csnmp_config_add_host_security_level */ static int csnmp_config_add_host(oconfig_item_t *ci) { host_definition_t *hd; int status = 0; /* Registration stuff. */ char cb_name[DATA_MAX_NAME_LEN]; hd = calloc(1, sizeof(*hd)); if (hd == NULL) return (-1); hd->version = 2; C_COMPLAIN_INIT(&hd->complaint); status = cf_util_get_string(ci, &hd->name); if (status != 0) { sfree(hd); return status; } hd->sess_handle = NULL; hd->interval = 0; for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *option = ci->children + i; status = 0; if (strcasecmp("Address", option->key) == 0) status = cf_util_get_string(option, &hd->address); else if (strcasecmp("Community", option->key) == 0) status = cf_util_get_string(option, &hd->community); else if (strcasecmp("Version", option->key) == 0) status = csnmp_config_add_host_version(hd, option); else if (strcasecmp("Collect", option->key) == 0) csnmp_config_add_host_collect(hd, option); else if (strcasecmp("Interval", option->key) == 0) cf_util_get_cdtime(option, &hd->interval); else if (strcasecmp("Username", option->key) == 0) status = cf_util_get_string(option, &hd->username); else if (strcasecmp("AuthProtocol", option->key) == 0) status = csnmp_config_add_host_auth_protocol(hd, option); else if (strcasecmp("PrivacyProtocol", option->key) == 0) status = csnmp_config_add_host_priv_protocol(hd, option); else if (strcasecmp("AuthPassphrase", option->key) == 0) status = cf_util_get_string(option, &hd->auth_passphrase); else if (strcasecmp("PrivacyPassphrase", option->key) == 0) status = cf_util_get_string(option, &hd->priv_passphrase); else if (strcasecmp("SecurityLevel", option->key) == 0) status = csnmp_config_add_host_security_level(hd, option); else if (strcasecmp("Context", option->key) == 0) status = cf_util_get_string(option, &hd->context); else { WARNING( "snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.", option->key); status = -1; } if (status != 0) break; } /* for (ci->children) */ while (status == 0) { if (hd->address == NULL) { WARNING("snmp plugin: `Address' not given for host `%s'", hd->name); status = -1; break; } if (hd->community == NULL && hd->version < 3) { WARNING("snmp plugin: `Community' not given for host `%s'", hd->name); status = -1; break; } if (hd->version == 3) { if (hd->username == NULL) { WARNING("snmp plugin: `Username' not given for host `%s'", hd->name); status = -1; break; } if (hd->security_level == 0) { WARNING("snmp plugin: `SecurityLevel' not given for host `%s'", hd->name); status = -1; break; } if (hd->security_level == SNMP_SEC_LEVEL_AUTHNOPRIV || hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) { if (hd->auth_protocol == NULL) { WARNING("snmp plugin: `AuthProtocol' not given for host `%s'", hd->name); status = -1; break; } if (hd->auth_passphrase == NULL) { WARNING("snmp plugin: `AuthPassphrase' not given for host `%s'", hd->name); status = -1; break; } } if (hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) { if (hd->priv_protocol == NULL) { WARNING("snmp plugin: `PrivacyProtocol' not given for host `%s'", hd->name); status = -1; break; } if (hd->priv_passphrase == NULL) { WARNING("snmp plugin: `PrivacyPassphrase' not given for host `%s'", hd->name); status = -1; break; } } } break; } /* while (status == 0) */ if (status != 0) { csnmp_host_definition_destroy(hd); return (-1); } DEBUG("snmp plugin: hd = { name = %s, address = %s, community = %s, version " "= %i }", hd->name, hd->address, hd->community, hd->version); ssnprintf(cb_name, sizeof(cb_name), "snmp-%s", hd->name); user_data_t ud = {.data = hd, .free_func = csnmp_host_definition_destroy}; status = plugin_register_complex_read(/* group = */ NULL, cb_name, csnmp_read_host, hd->interval, /* user_data = */ &ud); if (status != 0) { ERROR("snmp plugin: Registering complex read function failed."); csnmp_host_definition_destroy(hd); return (-1); } return (0); } /* int csnmp_config_add_host */ static int csnmp_config(oconfig_item_t *ci) { call_snmp_init_once(); for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; if (strcasecmp("Data", child->key) == 0) csnmp_config_add_data(child); else if (strcasecmp("Host", child->key) == 0) csnmp_config_add_host(child); else { WARNING("snmp plugin: Ignoring unknown config option `%s'.", child->key); } } /* for (ci->children) */ return (0); } /* int csnmp_config */ /* }}} End of the config stuff. Now the interesting part begins */ static void csnmp_host_open_session(host_definition_t *host) { struct snmp_session sess; int error; if (host->sess_handle != NULL) csnmp_host_close_session(host); snmp_sess_init(&sess); sess.peername = host->address; switch (host->version) { case 1: sess.version = SNMP_VERSION_1; break; case 3: sess.version = SNMP_VERSION_3; break; default: sess.version = SNMP_VERSION_2c; break; } if (host->version == 3) { sess.securityName = host->username; sess.securityNameLen = strlen(host->username); sess.securityLevel = host->security_level; if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) { sess.securityAuthProto = host->auth_protocol; sess.securityAuthProtoLen = host->auth_protocol_len; sess.securityAuthKeyLen = USM_AUTH_KU_LEN; error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen, (u_char *)host->auth_passphrase, strlen(host->auth_passphrase), sess.securityAuthKey, &sess.securityAuthKeyLen); if (error != SNMPERR_SUCCESS) { ERROR("snmp plugin: host %s: Error generating Ku from auth_passphrase. " "(Error %d)", host->name, error); } } if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) { sess.securityPrivProto = host->priv_protocol; sess.securityPrivProtoLen = host->priv_protocol_len; sess.securityPrivKeyLen = USM_PRIV_KU_LEN; error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen, (u_char *)host->priv_passphrase, strlen(host->priv_passphrase), sess.securityPrivKey, &sess.securityPrivKeyLen); if (error != SNMPERR_SUCCESS) { ERROR("snmp plugin: host %s: Error generating Ku from priv_passphrase. " "(Error %d)", host->name, error); } } if (host->context != NULL) { sess.contextName = host->context; sess.contextNameLen = strlen(host->context); } } else /* SNMPv1/2 "authenticates" with community string */ { sess.community = (u_char *)host->community; sess.community_len = strlen(host->community); } /* snmp_sess_open will copy the `struct snmp_session *'. */ host->sess_handle = snmp_sess_open(&sess); if (host->sess_handle == NULL) { char *errstr = NULL; snmp_error(&sess, NULL, NULL, &errstr); ERROR("snmp plugin: host %s: snmp_sess_open failed: %s", host->name, (errstr == NULL) ? "Unknown problem" : errstr); sfree(errstr); } } /* void csnmp_host_open_session */ /* TODO: Check if negative values wrap around. Problem: negative temperatures. */ static value_t csnmp_value_list_to_value(struct variable_list *vl, int type, double scale, double shift, const char *host_name, const char *data_name) { value_t ret; uint64_t tmp_unsigned = 0; int64_t tmp_signed = 0; _Bool defined = 1; /* Set to true when the original SNMP type appears to have been signed. */ _Bool prefer_signed = 0; if ((vl->type == ASN_INTEGER) || (vl->type == ASN_UINTEGER) || (vl->type == ASN_COUNTER) #ifdef ASN_TIMETICKS || (vl->type == ASN_TIMETICKS) #endif || (vl->type == ASN_GAUGE)) { tmp_unsigned = (uint32_t)*vl->val.integer; tmp_signed = (int32_t)*vl->val.integer; if (vl->type == ASN_INTEGER) prefer_signed = 1; DEBUG("snmp plugin: Parsed int32 value is %" PRIu64 ".", tmp_unsigned); } else if (vl->type == ASN_COUNTER64) { tmp_unsigned = (uint32_t)vl->val.counter64->high; tmp_unsigned = tmp_unsigned << 32; tmp_unsigned += (uint32_t)vl->val.counter64->low; tmp_signed = (int64_t)tmp_unsigned; DEBUG("snmp plugin: Parsed int64 value is %" PRIu64 ".", tmp_unsigned); } else if (vl->type == ASN_OCTET_STR) { /* We'll handle this later.. */ } else { char oid_buffer[1024] = {0}; snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vl->name, vl->name_length); #ifdef ASN_NULL if (vl->type == ASN_NULL) INFO("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)", oid_buffer); else #endif WARNING("snmp plugin: I don't know the ASN type #%i " "(OID: \"%s\", data block \"%s\", host block \"%s\")", (int)vl->type, oid_buffer, (data_name != NULL) ? data_name : "UNKNOWN", (host_name != NULL) ? host_name : "UNKNOWN"); defined = 0; } if (vl->type == ASN_OCTET_STR) { int status = -1; if (vl->val.string != NULL) { char string[64]; size_t string_length; string_length = sizeof(string) - 1; if (vl->val_len < string_length) string_length = vl->val_len; /* The strings we get from the Net-SNMP library may not be null * terminated. That is why we're using `memcpy' here and not `strcpy'. * `string_length' is set to `vl->val_len' which holds the length of the * string. -octo */ memcpy(string, vl->val.string, string_length); string[string_length] = 0; status = parse_value(string, &ret, type); if (status != 0) { ERROR("snmp plugin: host %s: csnmp_value_list_to_value: Parsing string " "as %s failed: %s", (host_name != NULL) ? host_name : "UNKNOWN", DS_TYPE_TO_STRING(type), string); } } if (status != 0) { switch (type) { case DS_TYPE_COUNTER: case DS_TYPE_DERIVE: case DS_TYPE_ABSOLUTE: memset(&ret, 0, sizeof(ret)); break; case DS_TYPE_GAUGE: ret.gauge = NAN; break; default: ERROR("snmp plugin: csnmp_value_list_to_value: Unknown " "data source type: %i.", type); ret.gauge = NAN; } } } /* if (vl->type == ASN_OCTET_STR) */ else if (type == DS_TYPE_COUNTER) { ret.counter = tmp_unsigned; } else if (type == DS_TYPE_GAUGE) { if (!defined) ret.gauge = NAN; else if (prefer_signed) ret.gauge = (scale * tmp_signed) + shift; else ret.gauge = (scale * tmp_unsigned) + shift; } else if (type == DS_TYPE_DERIVE) { if (prefer_signed) ret.derive = (derive_t)tmp_signed; else ret.derive = (derive_t)tmp_unsigned; } else if (type == DS_TYPE_ABSOLUTE) { ret.absolute = (absolute_t)tmp_unsigned; } else { ERROR("snmp plugin: csnmp_value_list_to_value: Unknown data source " "type: %i.", type); ret.gauge = NAN; } return (ret); } /* value_t csnmp_value_list_to_value */ /* csnmp_strvbcopy_hexstring converts the bit string contained in "vb" to a hex * representation and writes it to dst. Returns zero on success and ENOMEM if * dst is not large enough to hold the string. dst is guaranteed to be * nul-terminated. */ static int csnmp_strvbcopy_hexstring(char *dst, /* {{{ */ const struct variable_list *vb, size_t dst_size) { char *buffer_ptr; size_t buffer_free; dst[0] = 0; buffer_ptr = dst; buffer_free = dst_size; for (size_t i = 0; i < vb->val_len; i++) { int status; status = snprintf(buffer_ptr, buffer_free, (i == 0) ? "%02x" : ":%02x", (unsigned int)vb->val.bitstring[i]); assert(status >= 0); if (((size_t)status) >= buffer_free) /* truncated */ { dst[dst_size - 1] = 0; return ENOMEM; } else /* if (status < buffer_free) */ { buffer_ptr += (size_t)status; buffer_free -= (size_t)status; } } return 0; } /* }}} int csnmp_strvbcopy_hexstring */ /* csnmp_strvbcopy copies the octet string or bit string contained in vb to * dst. If non-printable characters are detected, it will switch to a hex * representation of the string. Returns zero on success, EINVAL if vb does not * contain a string and ENOMEM if dst is not large enough to contain the * string. */ static int csnmp_strvbcopy(char *dst, /* {{{ */ const struct variable_list *vb, size_t dst_size) { char *src; size_t num_chars; if (vb->type == ASN_OCTET_STR) src = (char *)vb->val.string; else if (vb->type == ASN_BIT_STR) src = (char *)vb->val.bitstring; else if (vb->type == ASN_IPADDRESS) { return ssnprintf(dst, dst_size, "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8 "", (uint8_t)vb->val.string[0], (uint8_t)vb->val.string[1], (uint8_t)vb->val.string[2], (uint8_t)vb->val.string[3]); } else { dst[0] = 0; return (EINVAL); } num_chars = dst_size - 1; if (num_chars > vb->val_len) num_chars = vb->val_len; for (size_t i = 0; i < num_chars; i++) { /* Check for control characters. */ if ((unsigned char)src[i] < 32) return (csnmp_strvbcopy_hexstring(dst, vb, dst_size)); dst[i] = src[i]; } dst[num_chars] = 0; dst[dst_size - 1] = 0; if (dst_size <= vb->val_len) return ENOMEM; return 0; } /* }}} int csnmp_strvbcopy */ static int csnmp_instance_list_add(csnmp_list_instances_t **head, csnmp_list_instances_t **tail, const struct snmp_pdu *res, const host_definition_t *hd, const data_definition_t *dd) { csnmp_list_instances_t *il; struct variable_list *vb; oid_t vb_name; int status; uint32_t is_matched; /* Set vb on the last variable */ for (vb = res->variables; (vb != NULL) && (vb->next_variable != NULL); vb = vb->next_variable) /* do nothing */; if (vb == NULL) return (-1); csnmp_oid_init(&vb_name, vb->name, vb->name_length); il = calloc(1, sizeof(*il)); if (il == NULL) { ERROR("snmp plugin: calloc failed."); return (-1); } il->next = NULL; status = csnmp_oid_suffix(&il->suffix, &vb_name, &dd->instance.oid); if (status != 0) { sfree(il); return (status); } /* Get instance name */ if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR) || (vb->type == ASN_IPADDRESS)) { char *ptr; csnmp_strvbcopy(il->instance, vb, sizeof(il->instance)); is_matched = 0; for (uint32_t i = 0; i < dd->ignores_len; i++) { status = fnmatch(dd->ignores[i], il->instance, 0); if (status == 0) { if (dd->invert_match == 0) { sfree(il); return 0; } else { is_matched = 1; break; } } } if (dd->invert_match != 0 && is_matched == 0) { sfree(il); return 0; } for (ptr = il->instance; *ptr != '\0'; ptr++) { if ((*ptr > 0) && (*ptr < 32)) *ptr = ' '; else if (*ptr == '/') *ptr = '_'; } DEBUG("snmp plugin: il->instance = `%s';", il->instance); } else { value_t val = csnmp_value_list_to_value( vb, DS_TYPE_COUNTER, /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name); ssnprintf(il->instance, sizeof(il->instance), "%llu", val.counter); } /* TODO: Debugging output */ if (*head == NULL) *head = il; else (*tail)->next = il; *tail = il; return (0); } /* int csnmp_instance_list_add */ static int csnmp_dispatch_table(host_definition_t *host, data_definition_t *data, csnmp_list_instances_t *instance_list, csnmp_table_values_t **value_table) { const data_set_t *ds; value_list_t vl = VALUE_LIST_INIT; csnmp_list_instances_t *instance_list_ptr; csnmp_table_values_t **value_table_ptr; size_t i; _Bool have_more; oid_t current_suffix; ds = plugin_get_ds(data->type); if (!ds) { ERROR("snmp plugin: DataSet `%s' not defined.", data->type); return (-1); } assert(ds->ds_num == data->values_len); assert(data->values_len > 0); instance_list_ptr = instance_list; value_table_ptr = calloc(data->values_len, sizeof(*value_table_ptr)); if (value_table_ptr == NULL) return (-1); for (i = 0; i < data->values_len; i++) value_table_ptr[i] = value_table[i]; vl.values_len = data->values_len; vl.values = malloc(sizeof(*vl.values) * vl.values_len); if (vl.values == NULL) { ERROR("snmp plugin: malloc failed."); sfree(value_table_ptr); return (-1); } sstrncpy(vl.host, host->name, sizeof(vl.host)); sstrncpy(vl.plugin, "snmp", sizeof(vl.plugin)); vl.interval = host->interval; have_more = 1; while (have_more) { _Bool suffix_skipped = 0; /* Determine next suffix to handle. */ if (instance_list != NULL) { if (instance_list_ptr == NULL) { have_more = 0; continue; } memcpy(&current_suffix, &instance_list_ptr->suffix, sizeof(current_suffix)); } else /* no instance configured */ { csnmp_table_values_t *ptr = value_table_ptr[0]; if (ptr == NULL) { have_more = 0; continue; } memcpy(&current_suffix, &ptr->suffix, sizeof(current_suffix)); } /* Update all the value_table_ptr to point at the entry with the same * trailing partial OID */ for (i = 0; i < data->values_len; i++) { while ( (value_table_ptr[i] != NULL) && (csnmp_oid_compare(&value_table_ptr[i]->suffix, &current_suffix) < 0)) value_table_ptr[i] = value_table_ptr[i]->next; if (value_table_ptr[i] == NULL) { have_more = 0; break; } else if (csnmp_oid_compare(&value_table_ptr[i]->suffix, &current_suffix) > 0) { /* This suffix is missing in the subtree. Indicate this with the * "suffix_skipped" flag and try the next instance / suffix. */ suffix_skipped = 1; break; } } /* for (i = 0; i < columns; i++) */ if (!have_more) break; /* Matching the values failed. Start from the beginning again. */ if (suffix_skipped) { if (instance_list != NULL) instance_list_ptr = instance_list_ptr->next; else value_table_ptr[0] = value_table_ptr[0]->next; continue; } /* if we reach this line, all value_table_ptr[i] are non-NULL and are set * to the same subid. instance_list_ptr is either NULL or points to the * same subid, too. */ #if COLLECT_DEBUG for (i = 1; i < data->values_len; i++) { assert(value_table_ptr[i] != NULL); assert(csnmp_oid_compare(&value_table_ptr[i - 1]->suffix, &value_table_ptr[i]->suffix) == 0); } assert((instance_list_ptr == NULL) || (csnmp_oid_compare(&instance_list_ptr->suffix, &value_table_ptr[0]->suffix) == 0)); #endif sstrncpy(vl.type, data->type, sizeof(vl.type)); { char temp[DATA_MAX_NAME_LEN]; if (instance_list_ptr == NULL) csnmp_oid_to_string(temp, sizeof(temp), &current_suffix); else sstrncpy(temp, instance_list_ptr->instance, sizeof(temp)); if (data->instance_prefix == NULL) sstrncpy(vl.type_instance, temp, sizeof(vl.type_instance)); else ssnprintf(vl.type_instance, sizeof(vl.type_instance), "%s%s", data->instance_prefix, temp); } for (i = 0; i < data->values_len; i++) vl.values[i] = value_table_ptr[i]->value; /* If we get here `vl.type_instance' and all `vl.values' have been set * vl.type_instance can be empty, i.e. a blank port description on a * switch if you're using IF-MIB::ifDescr as Instance. */ if (vl.type_instance[0] != '\0') plugin_dispatch_values(&vl); if (instance_list != NULL) instance_list_ptr = instance_list_ptr->next; else value_table_ptr[0] = value_table_ptr[0]->next; } /* while (have_more) */ sfree(vl.values); sfree(value_table_ptr); return (0); } /* int csnmp_dispatch_table */ static int csnmp_read_table(host_definition_t *host, data_definition_t *data) { struct snmp_pdu *req; struct snmp_pdu *res = NULL; struct variable_list *vb; const data_set_t *ds; size_t oid_list_len = data->values_len + 1; /* Holds the last OID returned by the device. We use this in the GETNEXT * request to proceed. */ oid_t oid_list[oid_list_len]; /* Set to false when an OID has left its subtree so we don't re-request it * again. */ _Bool oid_list_todo[oid_list_len]; int status; size_t i; /* `value_list_head' and `value_list_tail' implement a linked list for each * value. `instance_list_head' and `instance_list_tail' implement a linked * list of * instance names. This is used to jump gaps in the table. */ csnmp_list_instances_t *instance_list_head; csnmp_list_instances_t *instance_list_tail; csnmp_table_values_t **value_list_head; csnmp_table_values_t **value_list_tail; DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name, data->name); if (host->sess_handle == NULL) { DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL"); return (-1); } ds = plugin_get_ds(data->type); if (!ds) { ERROR("snmp plugin: DataSet `%s' not defined.", data->type); return (-1); } if (ds->ds_num != data->values_len) { ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks " "about %zu", data->type, ds->ds_num, data->values_len); return (-1); } assert(data->values_len > 0); /* We need a copy of all the OIDs, because GETNEXT will destroy them. */ memcpy(oid_list, data->values, data->values_len * sizeof(oid_t)); if (data->instance.oid.oid_len > 0) memcpy(oid_list + data->values_len, &data->instance.oid, sizeof(oid_t)); else /* no InstanceFrom option specified. */ oid_list_len--; for (i = 0; i < oid_list_len; i++) oid_list_todo[i] = 1; /* We're going to construct n linked lists, one for each "value". * value_list_head will contain pointers to the heads of these linked lists, * value_list_tail will contain pointers to the tail of the lists. */ value_list_head = calloc(data->values_len, sizeof(*value_list_head)); value_list_tail = calloc(data->values_len, sizeof(*value_list_tail)); if ((value_list_head == NULL) || (value_list_tail == NULL)) { ERROR("snmp plugin: csnmp_read_table: calloc failed."); sfree(value_list_head); sfree(value_list_tail); return (-1); } instance_list_head = NULL; instance_list_tail = NULL; status = 0; while (status == 0) { int oid_list_todo_num; req = snmp_pdu_create(SNMP_MSG_GETNEXT); if (req == NULL) { ERROR("snmp plugin: snmp_pdu_create failed."); status = -1; break; } oid_list_todo_num = 0; for (i = 0; i < oid_list_len; i++) { /* Do not rerequest already finished OIDs */ if (!oid_list_todo[i]) continue; oid_list_todo_num++; snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len); } if (oid_list_todo_num == 0) { /* The request is still empty - so we are finished */ DEBUG("snmp plugin: all variables have left their subtree"); status = 0; break; } res = NULL; status = snmp_sess_synch_response(host->sess_handle, req, &res); if ((status != STAT_SUCCESS) || (res == NULL)) { char *errstr = NULL; snmp_sess_error(host->sess_handle, NULL, NULL, &errstr); c_complain(LOG_ERR, &host->complaint, "snmp plugin: host %s: snmp_sess_synch_response failed: %s", host->name, (errstr == NULL) ? "Unknown problem" : errstr); if (res != NULL) snmp_free_pdu(res); res = NULL; /* snmp_synch_response already freed our PDU */ req = NULL; sfree(errstr); csnmp_host_close_session(host); status = -1; break; } status = 0; assert(res != NULL); c_release(LOG_INFO, &host->complaint, "snmp plugin: host %s: snmp_sess_synch_response successful.", host->name); vb = res->variables; if (vb == NULL) { status = -1; break; } for (vb = res->variables, i = 0; (vb != NULL); vb = vb->next_variable, i++) { /* Calculate value index from todo list */ while ((i < oid_list_len) && !oid_list_todo[i]) i++; /* An instance is configured and the res variable we process is the * instance value (last index) */ if ((data->instance.oid.oid_len > 0) && (i == data->values_len)) { if ((vb->type == SNMP_ENDOFMIBVIEW) || (snmp_oid_ncompare( data->instance.oid.oid, data->instance.oid.oid_len, vb->name, vb->name_length, data->instance.oid.oid_len) != 0)) { DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.", host->name, data->name); oid_list_todo[i] = 0; continue; } /* Allocate a new `csnmp_list_instances_t', insert the instance name and * add it to the list */ if (csnmp_instance_list_add(&instance_list_head, &instance_list_tail, res, host, data) != 0) { ERROR("snmp plugin: host %s: csnmp_instance_list_add failed.", host->name); status = -1; break; } } else /* The variable we are processing is a normal value */ { csnmp_table_values_t *vt; oid_t vb_name; oid_t suffix; int ret; csnmp_oid_init(&vb_name, vb->name, vb->name_length); /* Calculate the current suffix. This is later used to check that the * suffix is increasing. This also checks if we left the subtree */ ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i); if (ret != 0) { DEBUG("snmp plugin: host = %s; data = %s; i = %zu; " "Value probably left its subtree.", host->name, data->name, i); oid_list_todo[i] = 0; continue; } /* Make sure the OIDs returned by the agent are increasing. Otherwise * our * table matching algorithm will get confused. */ if ((value_list_tail[i] != NULL) && (csnmp_oid_compare(&suffix, &value_list_tail[i]->suffix) <= 0)) { DEBUG("snmp plugin: host = %s; data = %s; i = %zu; " "Suffix is not increasing.", host->name, data->name, i); oid_list_todo[i] = 0; continue; } vt = calloc(1, sizeof(*vt)); if (vt == NULL) { ERROR("snmp plugin: calloc failed."); status = -1; break; } vt->value = csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale, data->shift, host->name, data->name); memcpy(&vt->suffix, &suffix, sizeof(vt->suffix)); vt->next = NULL; if (value_list_tail[i] == NULL) value_list_head[i] = vt; else value_list_tail[i]->next = vt; value_list_tail[i] = vt; } /* Copy OID to oid_list[i] */ memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length); oid_list[i].oid_len = vb->name_length; } /* for (vb = res->variables ...) */ if (res != NULL) snmp_free_pdu(res); res = NULL; } /* while (status == 0) */ if (res != NULL) snmp_free_pdu(res); res = NULL; if (req != NULL) snmp_free_pdu(req); req = NULL; if (status == 0) csnmp_dispatch_table(host, data, instance_list_head, value_list_head); /* Free all allocated variables here */ while (instance_list_head != NULL) { csnmp_list_instances_t *next = instance_list_head->next; sfree(instance_list_head); instance_list_head = next; } for (i = 0; i < data->values_len; i++) { while (value_list_head[i] != NULL) { csnmp_table_values_t *next = value_list_head[i]->next; sfree(value_list_head[i]); value_list_head[i] = next; } } sfree(value_list_head); sfree(value_list_tail); return (0); } /* int csnmp_read_table */ static int csnmp_read_value(host_definition_t *host, data_definition_t *data) { struct snmp_pdu *req; struct snmp_pdu *res = NULL; struct variable_list *vb; const data_set_t *ds; value_list_t vl = VALUE_LIST_INIT; int status; size_t i; DEBUG("snmp plugin: csnmp_read_value (host = %s, data = %s)", host->name, data->name); if (host->sess_handle == NULL) { DEBUG("snmp plugin: csnmp_read_value: host->sess_handle == NULL"); return (-1); } ds = plugin_get_ds(data->type); if (!ds) { ERROR("snmp plugin: DataSet `%s' not defined.", data->type); return (-1); } if (ds->ds_num != data->values_len) { ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks " "about %zu", data->type, ds->ds_num, data->values_len); return (-1); } vl.values_len = ds->ds_num; vl.values = malloc(sizeof(*vl.values) * vl.values_len); if (vl.values == NULL) return (-1); for (i = 0; i < vl.values_len; i++) { if (ds->ds[i].type == DS_TYPE_COUNTER) vl.values[i].counter = 0; else vl.values[i].gauge = NAN; } sstrncpy(vl.host, host->name, sizeof(vl.host)); sstrncpy(vl.plugin, "snmp", sizeof(vl.plugin)); sstrncpy(vl.type, data->type, sizeof(vl.type)); sstrncpy(vl.type_instance, data->instance.string, sizeof(vl.type_instance)); vl.interval = host->interval; req = snmp_pdu_create(SNMP_MSG_GET); if (req == NULL) { ERROR("snmp plugin: snmp_pdu_create failed."); sfree(vl.values); return (-1); } for (i = 0; i < data->values_len; i++) snmp_add_null_var(req, data->values[i].oid, data->values[i].oid_len); status = snmp_sess_synch_response(host->sess_handle, req, &res); if ((status != STAT_SUCCESS) || (res == NULL)) { char *errstr = NULL; snmp_sess_error(host->sess_handle, NULL, NULL, &errstr); ERROR("snmp plugin: host %s: snmp_sess_synch_response failed: %s", host->name, (errstr == NULL) ? "Unknown problem" : errstr); if (res != NULL) snmp_free_pdu(res); sfree(errstr); sfree(vl.values); csnmp_host_close_session(host); return (-1); } for (vb = res->variables; vb != NULL; vb = vb->next_variable) { #if COLLECT_DEBUG char buffer[1024]; snprint_variable(buffer, sizeof(buffer), vb->name, vb->name_length, vb); DEBUG("snmp plugin: Got this variable: %s", buffer); #endif /* COLLECT_DEBUG */ for (i = 0; i < data->values_len; i++) if (snmp_oid_compare(data->values[i].oid, data->values[i].oid_len, vb->name, vb->name_length) == 0) vl.values[i] = csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale, data->shift, host->name, data->name); } /* for (res->variables) */ snmp_free_pdu(res); DEBUG("snmp plugin: -> plugin_dispatch_values (&vl);"); plugin_dispatch_values(&vl); sfree(vl.values); return (0); } /* int csnmp_read_value */ static int csnmp_read_host(user_data_t *ud) { host_definition_t *host; int status; int success; int i; host = ud->data; if (host->interval == 0) host->interval = plugin_get_interval(); if (host->sess_handle == NULL) csnmp_host_open_session(host); if (host->sess_handle == NULL) return (-1); success = 0; for (i = 0; i < host->data_list_len; i++) { data_definition_t *data = host->data_list[i]; if (data->is_table) status = csnmp_read_table(host, data); else status = csnmp_read_value(host, data); if (status == 0) success++; } if (success == 0) return (-1); return (0); } /* int csnmp_read_host */ static int csnmp_init(void) { call_snmp_init_once(); return (0); } /* int csnmp_init */ static int csnmp_shutdown(void) { data_definition_t *data_this; data_definition_t *data_next; /* When we get here, the read threads have been stopped and all the * `host_definition_t' will be freed. */ DEBUG("snmp plugin: Destroying all data definitions."); data_this = data_head; data_head = NULL; while (data_this != NULL) { data_next = data_this->next; sfree(data_this->name); sfree(data_this->type); sfree(data_this->values); sfree(data_this->ignores); sfree(data_this); data_this = data_next; } return (0); } /* int csnmp_shutdown */ void module_register(void) { plugin_register_complex_config("snmp", csnmp_config); plugin_register_init("snmp", csnmp_init); plugin_register_shutdown("snmp", csnmp_shutdown); } /* void module_register */ /* * vim: shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker */
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2938_0
crossvul-cpp_data_good_348_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); if (len > 0) { /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_6
crossvul-cpp_data_good_2579_6
/* #pragma ident "@(#)g_inquire_context.c 1.15 04/02/23 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_inquire_context */ #include "mglueP.h" #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif static OM_uint32 val_inq_ctx_args( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (targ_name != NULL) *targ_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); return (GSS_S_COMPLETE); } /* Last argument new for V2 */ OM_uint32 KRB5_CALLCONV gss_inquire_context( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { gss_union_ctx_id_t ctx; gss_mechanism mech; OM_uint32 status, temp_minor; gss_OID actual_mech; gss_name_t localTargName = NULL, localSourceName = NULL; status = val_inq_ctx_args(minor_status, context_handle, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (!mech || !mech->gss_inquire_context || !mech->gss_display_name || !mech->gss_release_name) { return (GSS_S_UNAVAILABLE); } status = mech->gss_inquire_context( minor_status, ctx->internal_ctx_id, (src_name ? &localSourceName : NULL), (targ_name ? &localTargName : NULL), lifetime_rec, &actual_mech, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); return status; } /* need to convert names */ if (src_name) { if (localSourceName) { status = gssint_convert_name_to_union_name(minor_status, mech, localSourceName, src_name); if (status != GSS_S_COMPLETE) { if (localTargName) mech->gss_release_name(&temp_minor, &localTargName); return (status); } } else { *src_name = GSS_C_NO_NAME; } } if (targ_name) { if (localTargName) { status = gssint_convert_name_to_union_name(minor_status, mech, localTargName, targ_name); if (status != GSS_S_COMPLETE) { if (src_name) (void) gss_release_name(&temp_minor, src_name); return (status); } } else { *targ_name = GSS_C_NO_NAME; } } if (mech_type) *mech_type = gssint_get_public_oid(actual_mech); return(GSS_S_COMPLETE); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_6
crossvul-cpp_data_good_349_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); if (len > 0) { /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_6
crossvul-cpp_data_bad_2579_11
/* #pragma ident "@(#)g_unseal.c 1.13 98/01/22 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine gss_unwrap */ #include "mglueP.h" OM_uint32 KRB5_CALLCONV gss_unwrap (minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t input_message_buffer; gss_buffer_t output_message_buffer; int * conf_state; gss_qop_t * qop_state; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status != NULL) *minor_status = 0; if (output_message_buffer != GSS_C_NO_BUFFER) { output_message_buffer->length = 0; output_message_buffer->value = NULL; } if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (input_message_buffer == GSS_C_NO_BUFFER || GSS_EMPTY_BUFFER(input_message_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); if (output_message_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_unwrap) { status = mech->gss_unwrap(minor_status, ctx->internal_ctx_id, input_message_buffer, output_message_buffer, conf_state, qop_state); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else if (mech->gss_unwrap_aead || mech->gss_unwrap_iov) { status = gssint_unwrap_aead(mech, minor_status, ctx, input_message_buffer, GSS_C_NO_BUFFER, output_message_buffer, conf_state, (gss_qop_t *)qop_state); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_unseal (minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t input_message_buffer; gss_buffer_t output_message_buffer; int * conf_state; int * qop_state; { return (gss_unwrap(minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, (gss_qop_t *) qop_state)); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_11
crossvul-cpp_data_bad_2579_10
/* #pragma ident "@(#)g_sign.c 1.14 98/04/23 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine gss_get_mic */ #include "mglueP.h" static OM_uint32 val_get_mic_args( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_buffer_t message_buffer, gss_buffer_t msg_token) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (msg_token != GSS_C_NO_BUFFER) { msg_token->value = NULL; msg_token->length = 0; } /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (message_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (msg_token == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_get_mic (minor_status, context_handle, qop_req, message_buffer, msg_token) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_qop_t qop_req; gss_buffer_t message_buffer; gss_buffer_t msg_token; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_get_mic_args(minor_status, context_handle, qop_req, message_buffer, msg_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_get_mic) { status = mech->gss_get_mic( minor_status, ctx->internal_ctx_id, qop_req, message_buffer, msg_token); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_sign (minor_status, context_handle, qop_req, message_buffer, msg_token) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int qop_req; gss_buffer_t message_buffer; gss_buffer_t msg_token; { return (gss_get_mic(minor_status, context_handle, (gss_qop_t) qop_req, message_buffer, msg_token)); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_10
crossvul-cpp_data_good_5242_0
/** * File: WebP IO * * Read and write WebP images. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #ifdef HAVE_LIBWEBP #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" #include "webp/decode.h" #include "webp/encode.h" #define GD_WEBP_ALLOC_STEP (4*1024) /* Function: gdImageCreateFromWebp <gdImageCreateFromWebp> is called to load truecolor images from WebP format files. Invoke <gdImageCreateFromWebp> with an already opened pointer to a file containing the desired image. <gdImageCreateFromWebp> returns a <gdImagePtr> to the new truecolor image, or NULL if unable to load the image (most often because the file is corrupt or does not contain a WebP image). <gdImageCreateFromWebp> does not close the file. You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using <gdImageDestroy>. *The returned image is always a truecolor image.* Variants: <gdImageCreateFromJpegPtr> creates an image from WebP data already in memory. <gdImageCreateFromJpegCtx> reads its data via the function pointers in a <gdIOCtx> structure. Parameters: infile - The input FILE pointer. Returns: A pointer to the new *truecolor* image. This will need to be destroyed with <gdImageDestroy> once it is no longer needed. On error, returns NULL. */ BGD_DECLARE(gdImagePtr) gdImageCreateFromWebp (FILE * inFile) { gdImagePtr im; gdIOCtx *in = gdNewFileCtx(inFile); if (!in) { return 0; } im = gdImageCreateFromWebpCtx(in); in->gd_free(in); return im; } /* Function: gdImageCreateFromWebpPtr See <gdImageCreateFromWebp>. Parameters: size - size of WebP data in bytes. data - pointer to WebP data. */ BGD_DECLARE(gdImagePtr) gdImageCreateFromWebpPtr (int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0); if (!in) return 0; im = gdImageCreateFromWebpCtx(in); in->gd_free(in); return im; } /* Function: gdImageCreateFromWebpCtx See <gdImageCreateFromWebp>. */ BGD_DECLARE(gdImagePtr) gdImageCreateFromWebpCtx (gdIOCtx * infile) { int width, height; uint8_t *filedata = NULL; uint8_t *argb = NULL; unsigned char *read, *temp; size_t size = 0, n; gdImagePtr im; int x, y; uint8_t *p; do { temp = gdRealloc(filedata, size+GD_WEBP_ALLOC_STEP); if (temp) { filedata = temp; read = temp + size; } else { if (filedata) { gdFree(filedata); } gd_error("WebP decode: realloc failed"); return NULL; } n = gdGetBuf(read, GD_WEBP_ALLOC_STEP, infile); if (n>0 && n!=EOF) { size += n; } } while (n>0 && n!=EOF); if (WebPGetInfo(filedata,size, &width, &height) == 0) { gd_error("gd-webp cannot get webp info"); gdFree(temp); return NULL; } im = gdImageCreateTrueColor(width, height); if (!im) { gdFree(temp); return NULL; } argb = WebPDecodeARGB(filedata, size, &width, &height); if (!argb) { gd_error("gd-webp cannot allocate temporary buffer"); gdFree(temp); gdImageDestroy(im); return NULL; } for (y = 0, p = argb; y < height; y++) { for (x = 0; x < width; x++) { register uint8_t a = gdAlphaMax - (*(p++) >> 1); register uint8_t r = *(p++); register uint8_t g = *(p++); register uint8_t b = *(p++); im->tpixels[y][x] = gdTrueColorAlpha(r, g, b, a); } } /* do not use gdFree here, in case gdFree/alloc is mapped to something else than libc */ free(argb); gdFree(temp); im->saveAlphaFlag = 1; return im; } /* returns 0 on success, 1 on failure */ static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; int ret = 0; if (im == NULL) { return 1; } if (!gdImageTrueColor(im)) { gd_error("Palette image not supported by webp"); return 1; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return 1; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return 1; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return 1; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error("gd-webp encoding failed"); ret = 1; goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); return ret; } /* Function: gdImageWebpCtx Write the image as WebP data via a <gdIOCtx>. See <gdImageWebpEx> for more details. Parameters: im - The image to write. outfile - The output sink. quality - Image quality. Returns: Nothing. */ BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { _gdImageWebpCtx(im, outfile, quality); } /* Function: gdImageWebpEx <gdImageWebpEx> outputs the specified image to the specified file in WebP format. The file must be open for writing. Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file, and under Unix there is no penalty for doing so. <gdImageWebpEx> does not close the file; your code must do so. If _quality_ is -1, a reasonable quality value (which should yield a good general quality / size tradeoff for most situations) is used. Otherwise _quality_ should be a value in the range 0-100, higher quality values usually implying both higher quality and larger image sizes. Variants: <gdImageWebpCtx> stores the image using a <gdIOCtx> struct. <gdImageWebpPtrEx> stores the image to RAM. Parameters: im - The image to save. outFile - The FILE pointer to write to. quality - Compression quality (0-100). Returns: Nothing. */ BGD_DECLARE(void) gdImageWebpEx (gdImagePtr im, FILE * outFile, int quality) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, quality); out->gd_free(out); } /* Function: gdImageWebp Variant of <gdImageWebpEx> which uses the default quality (-1). Parameters: im - The image to save outFile - The FILE pointer to write to. Returns: Nothing. */ BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, -1); out->gd_free(out); } /* Function: gdImageWebpPtr See <gdImageWebpEx>. */ BGD_DECLARE(void *) gdImageWebpPtr (gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) { return NULL; } if (_gdImageWebpCtx(im, out, -1)) { rv = NULL; } else { rv = gdDPExtractData(out, size); } out->gd_free(out); return rv; } /* Function: gdImageWebpPtrEx See <gdImageWebpEx>. */ BGD_DECLARE(void *) gdImageWebpPtrEx (gdImagePtr im, int *size, int quality) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) { return NULL; } if (_gdImageWebpCtx(im, out, quality)) { rv = NULL; } else { rv = gdDPExtractData(out, size); } out->gd_free(out); return rv; } #endif /* HAVE_LIBWEBP */
./CrossVul/dataset_final_sorted/CWE-415/c/good_5242_0
crossvul-cpp_data_good_1858_0
/* * History: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com), * to allow user process control of SCSI devices. * Development Sponsored by Killy Corp. NY NY * * Original driver (sg.c): * Copyright (C) 1992 Lawrence Foard * Version 2 and 3 extensions to driver: * Copyright (C) 1998 - 2014 Douglas Gilbert * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * */ static int sg_version_num = 30536; /* 2 digits for each component */ #define SG_VERSION_STR "3.5.36" /* * D. P. Gilbert (dgilbert@interlog.com), notes: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First * the kernel/module needs to be built with CONFIG_SCSI_LOGGING * (otherwise the macros compile to empty statements). * */ #include <linux/module.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/errno.h> #include <linux/mtio.h> #include <linux/ioctl.h> #include <linux/slab.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/moduleparam.h> #include <linux/cdev.h> #include <linux/idr.h> #include <linux/seq_file.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/blktrace_api.h> #include <linux/mutex.h> #include <linux/atomic.h> #include <linux/ratelimit.h> #include <linux/uio.h> #include "scsi.h" #include <scsi/scsi_dbg.h> #include <scsi/scsi_host.h> #include <scsi/scsi_driver.h> #include <scsi/scsi_ioctl.h> #include <scsi/sg.h> #include "scsi_logging.h" #ifdef CONFIG_SCSI_PROC_FS #include <linux/proc_fs.h> static char *sg_version_date = "20140603"; static int sg_proc_init(void); static void sg_proc_cleanup(void); #endif #define SG_ALLOW_DIO_DEF 0 #define SG_MAX_DEVS 32768 /* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater * than 16 bytes are "variable length" whose length is a multiple of 4 */ #define SG_MAX_CDB_SIZE 252 /* * Suppose you want to calculate the formula muldiv(x,m,d)=int(x * m / d) * Then when using 32 bit integers x * m may overflow during the calculation. * Replacing muldiv(x) by muldiv(x)=((x % d) * m) / d + int(x / d) * m * calculates the same, but prevents the overflow when both m and d * are "small" numbers (like HZ and USER_HZ). * Of course an overflow is inavoidable if the result of muldiv doesn't fit * in 32 bits. */ #define MULDIV(X,MUL,DIV) ((((X % DIV) * MUL) / DIV) + ((X / DIV) * MUL)) #define SG_DEFAULT_TIMEOUT MULDIV(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ) int sg_big_buff = SG_DEF_RESERVED_SIZE; /* N.B. This variable is readable and writeable via /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer of this size (or less if there is not enough memory) will be reserved for use by this file descriptor. [Deprecated usage: this variable is also readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into the kernel (i.e. it is not a module).] */ static int def_reserved_size = -1; /* picks up init parameter */ static int sg_allow_dio = SG_ALLOW_DIO_DEF; static int scatter_elem_sz = SG_SCATTER_SZ; static int scatter_elem_sz_prev = SG_SCATTER_SZ; #define SG_SECTOR_SZ 512 static int sg_add_device(struct device *, struct class_interface *); static void sg_remove_device(struct device *, struct class_interface *); static DEFINE_IDR(sg_index_idr); static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock file descriptor list for device */ static struct class_interface sg_interface = { .add_dev = sg_add_device, .remove_dev = sg_remove_device, }; typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */ unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */ unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */ unsigned bufflen; /* Size of (aggregate) data buffer */ struct page **pages; int page_order; char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */ unsigned char cmd_opcode; /* first byte of command */ } Sg_scatter_hold; struct sg_device; /* forward declarations */ struct sg_fd; typedef struct sg_request { /* SG_MAX_QUEUE requests outstanding per file */ struct sg_request *nextrp; /* NULL -> tail request (slist) */ struct sg_fd *parentfp; /* NULL -> not in use */ Sg_scatter_hold data; /* hold buffer, perhaps scatter list */ sg_io_hdr_t header; /* scsi command+info, see <scsi/sg.h> */ unsigned char sense_b[SCSI_SENSE_BUFFERSIZE]; char res_used; /* 1 -> using reserve buffer, 0 -> not ... */ char orphan; /* 1 -> drop on sight, 0 -> normal */ char sg_io_owned; /* 1 -> packet belongs to SG_IO */ /* done protected by rq_list_lock */ char done; /* 0->before bh, 1->before read, 2->read */ struct request *rq; struct bio *bio; struct execute_work ew; } Sg_request; typedef struct sg_fd { /* holds the state of a file descriptor */ struct list_head sfd_siblings; /* protected by device's sfd_lock */ struct sg_device *parentdp; /* owning device */ wait_queue_head_t read_wait; /* queue read until command done */ rwlock_t rq_list_lock; /* protect access to list in req_arr */ int timeout; /* defaults to SG_DEFAULT_TIMEOUT */ int timeout_user; /* defaults to SG_DEFAULT_TIMEOUT_USER */ Sg_scatter_hold reserve; /* buffer held for this file descriptor */ unsigned save_scat_len; /* original length of trunc. scat. element */ Sg_request *headrp; /* head of request slist, NULL->empty */ struct fasync_struct *async_qp; /* used by asynchronous notification */ Sg_request req_arr[SG_MAX_QUEUE]; /* used as singly-linked list */ char low_dma; /* as in parent but possibly overridden to 1 */ char force_packid; /* 1 -> pack_id input to read(), 0 -> ignored */ char cmd_q; /* 1 -> allow command queuing, 0 -> don't */ unsigned char next_cmd_len; /* 0: automatic, >0: use on next write() */ char keep_orphan; /* 0 -> drop orphan (def), 1 -> keep for read() */ char mmap_called; /* 0 -> mmap() never called on this fd */ struct kref f_ref; struct execute_work ew; } Sg_fd; typedef struct sg_device { /* holds the state of each scsi generic device */ struct scsi_device *device; wait_queue_head_t open_wait; /* queue open() when O_EXCL present */ struct mutex open_rel_lock; /* held when in open() or release() */ int sg_tablesize; /* adapter's max scatter-gather table size */ u32 index; /* device index number */ struct list_head sfds; rwlock_t sfd_lock; /* protect access to sfd list */ atomic_t detaching; /* 0->device usable, 1->device detaching */ bool exclude; /* 1->open(O_EXCL) succeeded and is active */ int open_cnt; /* count of opens (perhaps < num(sfds) ) */ char sgdebug; /* 0->off, 1->sense, 9->dump dev, 10-> all devs */ struct gendisk *disk; struct cdev * cdev; /* char_dev [sysfs: /sys/cdev/major/sg<n>] */ struct kref d_ref; } Sg_device; /* tasklet or soft irq callback */ static void sg_rq_end_io(struct request *rq, int uptodate); static int sg_start_req(Sg_request *srp, unsigned char *cmd); static int sg_finish_rem_req(Sg_request * srp); static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size); static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp); static ssize_t sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf, size_t count, int blocking, int read_only, int sg_io_owned, Sg_request **o_srp); static int sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking); static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer); static void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp); static void sg_build_reserve(Sg_fd * sfp, int req_size); static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size); static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp); static Sg_fd *sg_add_sfp(Sg_device * sdp); static void sg_remove_sfp(struct kref *); static Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id); static Sg_request *sg_add_request(Sg_fd * sfp); static int sg_remove_request(Sg_fd * sfp, Sg_request * srp); static int sg_res_in_use(Sg_fd * sfp); static Sg_device *sg_get_dev(int dev); static void sg_device_destroy(struct kref *kref); #define SZ_SG_HEADER sizeof(struct sg_header) #define SZ_SG_IO_HDR sizeof(sg_io_hdr_t) #define SZ_SG_IOVEC sizeof(sg_iovec_t) #define SZ_SG_REQ_INFO sizeof(sg_req_info_t) #define sg_printk(prefix, sdp, fmt, a...) \ sdev_prefix_printk(prefix, (sdp)->device, \ (sdp)->disk->disk_name, fmt, ##a) static int sg_allow_access(struct file *filp, unsigned char *cmd) { struct sg_fd *sfp = filp->private_data; if (sfp->parentdp->device->type == TYPE_SCANNER) return 0; return blk_verify_command(cmd, filp->f_mode & FMODE_WRITE); } static int open_wait(Sg_device *sdp, int flags) { int retval = 0; if (flags & O_EXCL) { while (sdp->open_cnt > 0) { mutex_unlock(&sdp->open_rel_lock); retval = wait_event_interruptible(sdp->open_wait, (atomic_read(&sdp->detaching) || !sdp->open_cnt)); mutex_lock(&sdp->open_rel_lock); if (retval) /* -ERESTARTSYS */ return retval; if (atomic_read(&sdp->detaching)) return -ENODEV; } } else { while (sdp->exclude) { mutex_unlock(&sdp->open_rel_lock); retval = wait_event_interruptible(sdp->open_wait, (atomic_read(&sdp->detaching) || !sdp->exclude)); mutex_lock(&sdp->open_rel_lock); if (retval) /* -ERESTARTSYS */ return retval; if (atomic_read(&sdp->detaching)) return -ENODEV; } } return retval; } /* Returns 0 on success, else a negated errno value */ static int sg_open(struct inode *inode, struct file *filp) { int dev = iminor(inode); int flags = filp->f_flags; struct request_queue *q; Sg_device *sdp; Sg_fd *sfp; int retval; nonseekable_open(inode, filp); if ((flags & O_EXCL) && (O_RDONLY == (flags & O_ACCMODE))) return -EPERM; /* Can't lock it with read only access */ sdp = sg_get_dev(dev); if (IS_ERR(sdp)) return PTR_ERR(sdp); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_open: flags=0x%x\n", flags)); /* This driver's module count bumped by fops_get in <linux/fs.h> */ /* Prevent the device driver from vanishing while we sleep */ retval = scsi_device_get(sdp->device); if (retval) goto sg_put; retval = scsi_autopm_get_device(sdp->device); if (retval) goto sdp_put; /* scsi_block_when_processing_errors() may block so bypass * check if O_NONBLOCK. Permits SCSI commands to be issued * during error recovery. Tread carefully. */ if (!((flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) { retval = -ENXIO; /* we are in error recovery for this device */ goto error_out; } mutex_lock(&sdp->open_rel_lock); if (flags & O_NONBLOCK) { if (flags & O_EXCL) { if (sdp->open_cnt > 0) { retval = -EBUSY; goto error_mutex_locked; } } else { if (sdp->exclude) { retval = -EBUSY; goto error_mutex_locked; } } } else { retval = open_wait(sdp, flags); if (retval) /* -ERESTARTSYS or -ENODEV */ goto error_mutex_locked; } /* N.B. at this point we are holding the open_rel_lock */ if (flags & O_EXCL) sdp->exclude = true; if (sdp->open_cnt < 1) { /* no existing opens */ sdp->sgdebug = 0; q = sdp->device->request_queue; sdp->sg_tablesize = queue_max_segments(q); } sfp = sg_add_sfp(sdp); if (IS_ERR(sfp)) { retval = PTR_ERR(sfp); goto out_undo; } filp->private_data = sfp; sdp->open_cnt++; mutex_unlock(&sdp->open_rel_lock); retval = 0; sg_put: kref_put(&sdp->d_ref, sg_device_destroy); return retval; out_undo: if (flags & O_EXCL) { sdp->exclude = false; /* undo if error */ wake_up_interruptible(&sdp->open_wait); } error_mutex_locked: mutex_unlock(&sdp->open_rel_lock); error_out: scsi_autopm_put_device(sdp->device); sdp_put: scsi_device_put(sdp->device); goto sg_put; } /* Release resources associated with a successful sg_open() * Returns 0 on success, else a negated errno value */ static int sg_release(struct inode *inode, struct file *filp) { Sg_device *sdp; Sg_fd *sfp; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_release\n")); mutex_lock(&sdp->open_rel_lock); scsi_autopm_put_device(sdp->device); kref_put(&sfp->f_ref, sg_remove_sfp); sdp->open_cnt--; /* possibly many open()s waiting on exlude clearing, start many; * only open(O_EXCL)s wait on 0==open_cnt so only start one */ if (sdp->exclude) { sdp->exclude = false; wake_up_interruptible_all(&sdp->open_wait); } else if (0 == sdp->open_cnt) { wake_up_interruptible(&sdp->open_wait); } mutex_unlock(&sdp->open_rel_lock); return 0; } static ssize_t sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos) { Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; int req_pack_id = -1; sg_io_hdr_t *hp; struct sg_header *old_hdr = NULL; int retval = 0; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_read: count=%d\n", (int) count)); if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; if (sfp->force_packid && (count >= SZ_SG_HEADER)) { old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL); if (!old_hdr) return -ENOMEM; if (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } if (old_hdr->reply_len < 0) { if (count >= SZ_SG_IO_HDR) { sg_io_hdr_t *new_hdr; new_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL); if (!new_hdr) { retval = -ENOMEM; goto free_old_hdr; } retval =__copy_from_user (new_hdr, buf, SZ_SG_IO_HDR); req_pack_id = new_hdr->pack_id; kfree(new_hdr); if (retval) { retval = -EFAULT; goto free_old_hdr; } } } else req_pack_id = old_hdr->pack_id; } srp = sg_get_rq_mark(sfp, req_pack_id); if (!srp) { /* now wait on packet to arrive */ if (atomic_read(&sdp->detaching)) { retval = -ENODEV; goto free_old_hdr; } if (filp->f_flags & O_NONBLOCK) { retval = -EAGAIN; goto free_old_hdr; } retval = wait_event_interruptible(sfp->read_wait, (atomic_read(&sdp->detaching) || (srp = sg_get_rq_mark(sfp, req_pack_id)))); if (atomic_read(&sdp->detaching)) { retval = -ENODEV; goto free_old_hdr; } if (retval) { /* -ERESTARTSYS as signal hit process */ goto free_old_hdr; } } if (srp->header.interface_id != '\0') { retval = sg_new_read(sfp, buf, count, srp); goto free_old_hdr; } hp = &srp->header; if (old_hdr == NULL) { old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL); if (! old_hdr) { retval = -ENOMEM; goto free_old_hdr; } } memset(old_hdr, 0, SZ_SG_HEADER); old_hdr->reply_len = (int) hp->timeout; old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */ old_hdr->pack_id = hp->pack_id; old_hdr->twelve_byte = ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0; old_hdr->target_status = hp->masked_status; old_hdr->host_status = hp->host_status; old_hdr->driver_status = hp->driver_status; if ((CHECK_CONDITION & hp->masked_status) || (DRIVER_SENSE & hp->driver_status)) memcpy(old_hdr->sense_buffer, srp->sense_b, sizeof (old_hdr->sense_buffer)); switch (hp->host_status) { /* This setup of 'result' is for backward compatibility and is best ignored by the user who should use target, host + driver status */ case DID_OK: case DID_PASSTHROUGH: case DID_SOFT_ERROR: old_hdr->result = 0; break; case DID_NO_CONNECT: case DID_BUS_BUSY: case DID_TIME_OUT: old_hdr->result = EBUSY; break; case DID_BAD_TARGET: case DID_ABORT: case DID_PARITY: case DID_RESET: case DID_BAD_INTR: old_hdr->result = EIO; break; case DID_ERROR: old_hdr->result = (srp->sense_b[0] == 0 && hp->masked_status == GOOD) ? 0 : EIO; break; default: old_hdr->result = EIO; break; } /* Now copy the result back to the user buffer. */ if (count >= SZ_SG_HEADER) { if (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } buf += SZ_SG_HEADER; if (count > old_hdr->reply_len) count = old_hdr->reply_len; if (count > SZ_SG_HEADER) { if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } } } else count = (old_hdr->result == 0) ? 0 : -EIO; sg_finish_rem_req(srp); retval = count; free_old_hdr: kfree(old_hdr); return retval; } static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp) { sg_io_hdr_t *hp = &srp->header; int err = 0, err2; int len; if (count < SZ_SG_IO_HDR) { err = -EINVAL; goto err_out; } hp->sb_len_wr = 0; if ((hp->mx_sb_len > 0) && hp->sbp) { if ((CHECK_CONDITION & hp->masked_status) || (DRIVER_SENSE & hp->driver_status)) { int sb_len = SCSI_SENSE_BUFFERSIZE; sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len; len = 8 + (int) srp->sense_b[7]; /* Additional sense length field */ len = (len > sb_len) ? sb_len : len; if (copy_to_user(hp->sbp, srp->sense_b, len)) { err = -EFAULT; goto err_out; } hp->sb_len_wr = len; } } if (hp->masked_status || hp->host_status || hp->driver_status) hp->info |= SG_INFO_CHECK; if (copy_to_user(buf, hp, SZ_SG_IO_HDR)) { err = -EFAULT; goto err_out; } err_out: err2 = sg_finish_rem_req(srp); return err ? : err2 ? : count; } static ssize_t sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos) { int mxsize, cmd_size, k; int input_size, blocking; unsigned char opcode; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; struct sg_header old_hdr; sg_io_hdr_t *hp; unsigned char cmnd[SG_MAX_CDB_SIZE]; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_write: count=%d\n", (int) count)); if (atomic_read(&sdp->detaching)) return -ENODEV; if (!((filp->f_flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) return -ENXIO; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ if (count < SZ_SG_HEADER) return -EIO; if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER)) return -EFAULT; blocking = !(filp->f_flags & O_NONBLOCK); if (old_hdr.reply_len < 0) return sg_new_write(sfp, filp, buf, count, blocking, 0, 0, NULL); if (count < (SZ_SG_HEADER + 6)) return -EIO; /* The minimum scsi command length is 6 bytes. */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp, "sg_write: queue full\n")); return -EDOM; } buf += SZ_SG_HEADER; __get_user(opcode, buf); if (sfp->next_cmd_len > 0) { cmd_size = sfp->next_cmd_len; sfp->next_cmd_len = 0; /* reset so only this write() effected */ } else { cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */ if ((opcode >= 0xc0) && old_hdr.twelve_byte) cmd_size = 12; } SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp, "sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size)); /* Determine buffer size. */ input_size = count - cmd_size; mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len; mxsize -= SZ_SG_HEADER; input_size -= SZ_SG_HEADER; if (input_size < 0) { sg_remove_request(sfp, srp); return -EIO; /* User did not pass enough bytes for this command. */ } hp = &srp->header; hp->interface_id = '\0'; /* indicator of old interface tunnelled */ hp->cmd_len = (unsigned char) cmd_size; hp->iovec_count = 0; hp->mx_sb_len = 0; if (input_size > 0) hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ? SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV; else hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE; hp->dxfer_len = mxsize; if (hp->dxfer_direction == SG_DXFER_TO_DEV) hp->dxferp = (char __user *)buf + cmd_size; else hp->dxferp = NULL; hp->sbp = NULL; hp->timeout = old_hdr.reply_len; /* structure abuse ... */ hp->flags = input_size; /* structure abuse ... */ hp->pack_id = old_hdr.pack_id; hp->usr_ptr = NULL; if (__copy_from_user(cmnd, buf, cmd_size)) return -EFAULT; /* * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV, * but is is possible that the app intended SG_DXFER_TO_DEV, because there * is a non-zero input_size, so emit a warning. */ if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) { static char cmd[TASK_COMM_LEN]; if (strcmp(current->comm, cmd)) { printk_ratelimited(KERN_WARNING "sg_write: data in/out %d/%d bytes " "for SCSI command 0x%x-- guessing " "data in;\n program %s not setting " "count and/or reply_len properly\n", old_hdr.reply_len - (int)SZ_SG_HEADER, input_size, (unsigned int) cmnd[0], current->comm); strcpy(cmd, current->comm); } } k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking); return (k < 0) ? k : count; } static ssize_t sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf, size_t count, int blocking, int read_only, int sg_io_owned, Sg_request **o_srp) { int k; Sg_request *srp; sg_io_hdr_t *hp; unsigned char cmnd[SG_MAX_CDB_SIZE]; int timeout; unsigned long ul_timeout; if (count < SZ_SG_IO_HDR) return -EINVAL; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ sfp->cmd_q = 1; /* when sg_io_hdr seen, set command queuing on */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_new_write: queue full\n")); return -EDOM; } srp->sg_io_owned = sg_io_owned; hp = &srp->header; if (__copy_from_user(hp, buf, SZ_SG_IO_HDR)) { sg_remove_request(sfp, srp); return -EFAULT; } if (hp->interface_id != 'S') { sg_remove_request(sfp, srp); return -ENOSYS; } if (hp->flags & SG_FLAG_MMAP_IO) { if (hp->dxfer_len > sfp->reserve.bufflen) { sg_remove_request(sfp, srp); return -ENOMEM; /* MMAP_IO size must fit in reserve buffer */ } if (hp->flags & SG_FLAG_DIRECT_IO) { sg_remove_request(sfp, srp); return -EINVAL; /* either MMAP_IO or DIRECT_IO (not both) */ } if (sg_res_in_use(sfp)) { sg_remove_request(sfp, srp); return -EBUSY; /* reserve buffer already being used */ } } ul_timeout = msecs_to_jiffies(srp->header.timeout); timeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX; if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) { sg_remove_request(sfp, srp); return -EMSGSIZE; } if (!access_ok(VERIFY_READ, hp->cmdp, hp->cmd_len)) { sg_remove_request(sfp, srp); return -EFAULT; /* protects following copy_from_user()s + get_user()s */ } if (__copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) { sg_remove_request(sfp, srp); return -EFAULT; } if (read_only && sg_allow_access(file, cmnd)) { sg_remove_request(sfp, srp); return -EPERM; } k = sg_common_write(sfp, srp, cmnd, timeout, blocking); if (k < 0) return k; if (o_srp) *o_srp = srp; return count; } static int sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: start_req err=%d\n", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) { if (srp->rq->cmd != srp->rq->__cmd) kfree(srp->rq->cmd); blk_end_request_all(srp->rq, -EIO); srp->rq = NULL; } sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; } static int srp_done(Sg_fd *sfp, Sg_request *srp) { unsigned long flags; int ret; read_lock_irqsave(&sfp->rq_list_lock, flags); ret = srp->done; read_unlock_irqrestore(&sfp->rq_list_lock, flags); return ret; } static int max_sectors_bytes(struct request_queue *q) { unsigned int max_sectors = queue_max_sectors(q); max_sectors = min_t(unsigned int, max_sectors, INT_MAX >> 9); return max_sectors << 9; } static long sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { void __user *p = (void __user *)arg; int __user *ip = p; int result, val, read_only; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; unsigned long iflags; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_ioctl: cmd=0x%x\n", (int) cmd_in)); read_only = (O_RDWR != (filp->f_flags & O_ACCMODE)); switch (cmd_in) { case SG_IO: if (atomic_read(&sdp->detaching)) return -ENODEV; if (!scsi_block_when_processing_errors(sdp->device)) return -ENXIO; if (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR)) return -EFAULT; result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR, 1, read_only, 1, &srp); if (result < 0) return result; result = wait_event_interruptible(sfp->read_wait, (srp_done(sfp, srp) || atomic_read(&sdp->detaching))); if (atomic_read(&sdp->detaching)) return -ENODEV; write_lock_irq(&sfp->rq_list_lock); if (srp->done) { srp->done = 2; write_unlock_irq(&sfp->rq_list_lock); result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp); return (result < 0) ? result : 0; } srp->orphan = 1; write_unlock_irq(&sfp->rq_list_lock); return result; /* -ERESTARTSYS because signal hit process */ case SG_SET_TIMEOUT: result = get_user(val, ip); if (result) return result; if (val < 0) return -EIO; if (val >= MULDIV (INT_MAX, USER_HZ, HZ)) val = MULDIV (INT_MAX, USER_HZ, HZ); sfp->timeout_user = val; sfp->timeout = MULDIV (val, HZ, USER_HZ); return 0; case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */ /* strange ..., for backward compatibility */ return sfp->timeout_user; case SG_SET_FORCE_LOW_DMA: result = get_user(val, ip); if (result) return result; if (val) { sfp->low_dma = 1; if ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) { val = (int) sfp->reserve.bufflen; sg_remove_scat(sfp, &sfp->reserve); sg_build_reserve(sfp, val); } } else { if (atomic_read(&sdp->detaching)) return -ENODEV; sfp->low_dma = sdp->device->host->unchecked_isa_dma; } return 0; case SG_GET_LOW_DMA: return put_user((int) sfp->low_dma, ip); case SG_GET_SCSI_ID: if (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t))) return -EFAULT; else { sg_scsi_id_t __user *sg_idp = p; if (atomic_read(&sdp->detaching)) return -ENODEV; __put_user((int) sdp->device->host->host_no, &sg_idp->host_no); __put_user((int) sdp->device->channel, &sg_idp->channel); __put_user((int) sdp->device->id, &sg_idp->scsi_id); __put_user((int) sdp->device->lun, &sg_idp->lun); __put_user((int) sdp->device->type, &sg_idp->scsi_type); __put_user((short) sdp->device->host->cmd_per_lun, &sg_idp->h_cmd_per_lun); __put_user((short) sdp->device->queue_depth, &sg_idp->d_queue_depth); __put_user(0, &sg_idp->unused[0]); __put_user(0, &sg_idp->unused[1]); return 0; } case SG_SET_FORCE_PACK_ID: result = get_user(val, ip); if (result) return result; sfp->force_packid = val ? 1 : 0; return 0; case SG_GET_PACK_ID: if (!access_ok(VERIFY_WRITE, ip, sizeof (int))) return -EFAULT; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) { if ((1 == srp->done) && (!srp->sg_io_owned)) { read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(srp->header.pack_id, ip); return 0; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(-1, ip); return 0; case SG_GET_NUM_WAITING: read_lock_irqsave(&sfp->rq_list_lock, iflags); for (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) { if ((1 == srp->done) && (!srp->sg_io_owned)) ++val; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return put_user(val, ip); case SG_GET_SG_TABLESIZE: return put_user(sdp->sg_tablesize, ip); case SG_SET_RESERVED_SIZE: result = get_user(val, ip); if (result) return result; if (val < 0) return -EINVAL; val = min_t(int, val, max_sectors_bytes(sdp->device->request_queue)); if (val != sfp->reserve.bufflen) { if (sg_res_in_use(sfp) || sfp->mmap_called) return -EBUSY; sg_remove_scat(sfp, &sfp->reserve); sg_build_reserve(sfp, val); } return 0; case SG_GET_RESERVED_SIZE: val = min_t(int, sfp->reserve.bufflen, max_sectors_bytes(sdp->device->request_queue)); return put_user(val, ip); case SG_SET_COMMAND_Q: result = get_user(val, ip); if (result) return result; sfp->cmd_q = val ? 1 : 0; return 0; case SG_GET_COMMAND_Q: return put_user((int) sfp->cmd_q, ip); case SG_SET_KEEP_ORPHAN: result = get_user(val, ip); if (result) return result; sfp->keep_orphan = val; return 0; case SG_GET_KEEP_ORPHAN: return put_user((int) sfp->keep_orphan, ip); case SG_NEXT_CMD_LEN: result = get_user(val, ip); if (result) return result; sfp->next_cmd_len = (val > 0) ? val : 0; return 0; case SG_GET_VERSION_NUM: return put_user(sg_version_num, ip); case SG_GET_ACCESS_COUNT: /* faked - we don't have a real access count anymore */ val = (sdp->device ? 1 : 0); return put_user(val, ip); case SG_GET_REQUEST_TABLE: if (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE)) return -EFAULT; else { sg_req_info_t *rinfo; unsigned int ms; rinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE, GFP_KERNEL); if (!rinfo) return -ENOMEM; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE; ++val, srp = srp ? srp->nextrp : srp) { memset(&rinfo[val], 0, SZ_SG_REQ_INFO); if (srp) { rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); result = __copy_to_user(p, rinfo, SZ_SG_REQ_INFO * SG_MAX_QUEUE); result = result ? -EFAULT : 0; kfree(rinfo); return result; } case SG_EMULATED_HOST: if (atomic_read(&sdp->detaching)) return -ENODEV; return put_user(sdp->device->host->hostt->emulated, ip); case SCSI_IOCTL_SEND_COMMAND: if (atomic_read(&sdp->detaching)) return -ENODEV; if (read_only) { unsigned char opcode = WRITE_6; Scsi_Ioctl_Command __user *siocp = p; if (copy_from_user(&opcode, siocp->data, 1)) return -EFAULT; if (sg_allow_access(filp, &opcode)) return -EPERM; } return sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p); case SG_SET_DEBUG: result = get_user(val, ip); if (result) return result; sdp->sgdebug = (char) val; return 0; case BLKSECTGET: return put_user(max_sectors_bytes(sdp->device->request_queue), ip); case BLKTRACESETUP: return blk_trace_setup(sdp->device->request_queue, sdp->disk->disk_name, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), NULL, (char *)arg); case BLKTRACESTART: return blk_trace_startstop(sdp->device->request_queue, 1); case BLKTRACESTOP: return blk_trace_startstop(sdp->device->request_queue, 0); case BLKTRACETEARDOWN: return blk_trace_remove(sdp->device->request_queue); case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: case SCSI_IOCTL_PROBE_HOST: case SG_GET_TRANSFORM: case SG_SCSI_RESET: if (atomic_read(&sdp->detaching)) return -ENODEV; break; default: if (read_only) return -EPERM; /* don't know so take safe approach */ break; } result = scsi_ioctl_block_when_processing_errors(sdp->device, cmd_in, filp->f_flags & O_NDELAY); if (result) return result; return scsi_ioctl(sdp->device, cmd_in, p); } #ifdef CONFIG_COMPAT static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { Sg_device *sdp; Sg_fd *sfp; struct scsi_device *sdev; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; sdev = sdp->device; if (sdev->host->hostt->compat_ioctl) { int ret; ret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg); return ret; } return -ENOIOCTLCMD; } #endif static unsigned int sg_poll(struct file *filp, poll_table * wait) { unsigned int res = 0; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; int count = 0; unsigned long iflags; sfp = filp->private_data; if (!sfp) return POLLERR; sdp = sfp->parentdp; if (!sdp) return POLLERR; poll_wait(filp, &sfp->read_wait, wait); read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) { /* if any read waiting, flag it */ if ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned)) res = POLLIN | POLLRDNORM; ++count; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); if (atomic_read(&sdp->detaching)) res |= POLLHUP; else if (!sfp->cmd_q) { if (0 == count) res |= POLLOUT | POLLWRNORM; } else if (count < SG_MAX_QUEUE) res |= POLLOUT | POLLWRNORM; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_poll: res=0x%x\n", (int) res)); return res; } static int sg_fasync(int fd, struct file *filp, int mode) { Sg_device *sdp; Sg_fd *sfp; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_fasync: mode=%d\n", mode)); return fasync_helper(fd, filp, mode, &sfp->async_qp); } static int sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { Sg_fd *sfp; unsigned long offset, len, sa; Sg_scatter_hold *rsv_schp; int k, length; if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data))) return VM_FAULT_SIGBUS; rsv_schp = &sfp->reserve; offset = vmf->pgoff << PAGE_SHIFT; if (offset >= rsv_schp->bufflen) return VM_FAULT_SIGBUS; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp, "sg_vma_fault: offset=%lu, scatg=%d\n", offset, rsv_schp->k_use_sg)); sa = vma->vm_start; length = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { len = vma->vm_end - sa; len = (len < length) ? len : length; if (offset < len) { struct page *page = nth_page(rsv_schp->pages[k], offset >> PAGE_SHIFT); get_page(page); /* increment page count */ vmf->page = page; return 0; /* success */ } sa += len; offset -= len; } return VM_FAULT_SIGBUS; } static const struct vm_operations_struct sg_mmap_vm_ops = { .fault = sg_vma_fault, }; static int sg_mmap(struct file *filp, struct vm_area_struct *vma) { Sg_fd *sfp; unsigned long req_sz, len, sa; Sg_scatter_hold *rsv_schp; int k, length; if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data))) return -ENXIO; req_sz = vma->vm_end - vma->vm_start; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp, "sg_mmap starting, vm_start=%p, len=%d\n", (void *) vma->vm_start, (int) req_sz)); if (vma->vm_pgoff) return -EINVAL; /* want no offset */ rsv_schp = &sfp->reserve; if (req_sz > rsv_schp->bufflen) return -ENOMEM; /* cannot map more than reserved buffer */ sa = vma->vm_start; length = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { len = vma->vm_end - sa; len = (len < length) ? len : length; sa += len; } sfp->mmap_called = 1; vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP; vma->vm_private_data = sfp; vma->vm_ops = &sg_mmap_vm_ops; return 0; } static void sg_rq_end_io_usercontext(struct work_struct *work) { struct sg_request *srp = container_of(work, struct sg_request, ew.work); struct sg_fd *sfp = srp->parentfp; sg_finish_rem_req(srp); kref_put(&sfp->f_ref, sg_remove_sfp); } /* * This function is a "bottom half" handler that is called by the mid * level when a command is completed (or has failed). */ static void sg_rq_end_io(struct request *rq, int uptodate) { struct sg_request *srp = rq->end_io_data; Sg_device *sdp; Sg_fd *sfp; unsigned long iflags; unsigned int ms; char *sense; int result, resid, done = 1; if (WARN_ON(srp->done != 0)) return; sfp = srp->parentfp; if (WARN_ON(sfp == NULL)) return; sdp = sfp->parentdp; if (unlikely(atomic_read(&sdp->detaching))) pr_info("%s: device detaching\n", __func__); sense = rq->sense; result = rq->errors; resid = rq->resid_len; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp, "sg_cmd_done: pack_id=%d, res=0x%x\n", srp->header.pack_id, result)); srp->header.resid = resid; ms = jiffies_to_msecs(jiffies); srp->header.duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; if (0 != result) { struct scsi_sense_hdr sshdr; srp->header.status = 0xff & result; srp->header.masked_status = status_byte(result); srp->header.msg_status = msg_byte(result); srp->header.host_status = host_byte(result); srp->header.driver_status = driver_byte(result); if ((sdp->sgdebug > 0) && ((CHECK_CONDITION == srp->header.masked_status) || (COMMAND_TERMINATED == srp->header.masked_status))) __scsi_print_sense(sdp->device, __func__, sense, SCSI_SENSE_BUFFERSIZE); /* Following if statement is a patch supplied by Eric Youngdale */ if (driver_byte(result) != 0 && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr) && !scsi_sense_is_deferred(&sshdr) && sshdr.sense_key == UNIT_ATTENTION && sdp->device->removable) { /* Detected possible disc change. Set the bit - this */ /* may be used if there are filesystems using this device */ sdp->device->changed = 1; } } /* Rely on write phase to clean out srp status values, so no "else" */ /* * Free the request as soon as it is complete so that its resources * can be reused without waiting for userspace to read() the * result. But keep the associated bio (if any) around until * blk_rq_unmap_user() can be called from user context. */ srp->rq = NULL; if (rq->cmd != rq->__cmd) kfree(rq->cmd); __blk_put_request(rq->q, rq); write_lock_irqsave(&sfp->rq_list_lock, iflags); if (unlikely(srp->orphan)) { if (sfp->keep_orphan) srp->sg_io_owned = 0; else done = 0; } srp->done = done; write_unlock_irqrestore(&sfp->rq_list_lock, iflags); if (likely(done)) { /* Now wake up any sg_read() that is waiting for this * packet. */ wake_up_interruptible(&sfp->read_wait); kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN); kref_put(&sfp->f_ref, sg_remove_sfp); } else { INIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext); schedule_work(&srp->ew.work); } } static const struct file_operations sg_fops = { .owner = THIS_MODULE, .read = sg_read, .write = sg_write, .poll = sg_poll, .unlocked_ioctl = sg_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = sg_compat_ioctl, #endif .open = sg_open, .mmap = sg_mmap, .release = sg_release, .fasync = sg_fasync, .llseek = no_llseek, }; static struct class *sg_sysfs_class; static int sg_sysfs_valid = 0; static Sg_device * sg_alloc(struct gendisk *disk, struct scsi_device *scsidp) { struct request_queue *q = scsidp->request_queue; Sg_device *sdp; unsigned long iflags; int error; u32 k; sdp = kzalloc(sizeof(Sg_device), GFP_KERNEL); if (!sdp) { sdev_printk(KERN_WARNING, scsidp, "%s: kmalloc Sg_device " "failure\n", __func__); return ERR_PTR(-ENOMEM); } idr_preload(GFP_KERNEL); write_lock_irqsave(&sg_index_lock, iflags); error = idr_alloc(&sg_index_idr, sdp, 0, SG_MAX_DEVS, GFP_NOWAIT); if (error < 0) { if (error == -ENOSPC) { sdev_printk(KERN_WARNING, scsidp, "Unable to attach sg device type=%d, minor number exceeds %d\n", scsidp->type, SG_MAX_DEVS - 1); error = -ENODEV; } else { sdev_printk(KERN_WARNING, scsidp, "%s: idr " "allocation Sg_device failure: %d\n", __func__, error); } goto out_unlock; } k = error; SCSI_LOG_TIMEOUT(3, sdev_printk(KERN_INFO, scsidp, "sg_alloc: dev=%d \n", k)); sprintf(disk->disk_name, "sg%d", k); disk->first_minor = k; sdp->disk = disk; sdp->device = scsidp; mutex_init(&sdp->open_rel_lock); INIT_LIST_HEAD(&sdp->sfds); init_waitqueue_head(&sdp->open_wait); atomic_set(&sdp->detaching, 0); rwlock_init(&sdp->sfd_lock); sdp->sg_tablesize = queue_max_segments(q); sdp->index = k; kref_init(&sdp->d_ref); error = 0; out_unlock: write_unlock_irqrestore(&sg_index_lock, iflags); idr_preload_end(); if (error) { kfree(sdp); return ERR_PTR(error); } return sdp; } static int sg_add_device(struct device *cl_dev, struct class_interface *cl_intf) { struct scsi_device *scsidp = to_scsi_device(cl_dev->parent); struct gendisk *disk; Sg_device *sdp = NULL; struct cdev * cdev = NULL; int error; unsigned long iflags; disk = alloc_disk(1); if (!disk) { pr_warn("%s: alloc_disk failed\n", __func__); return -ENOMEM; } disk->major = SCSI_GENERIC_MAJOR; error = -ENOMEM; cdev = cdev_alloc(); if (!cdev) { pr_warn("%s: cdev_alloc failed\n", __func__); goto out; } cdev->owner = THIS_MODULE; cdev->ops = &sg_fops; sdp = sg_alloc(disk, scsidp); if (IS_ERR(sdp)) { pr_warn("%s: sg_alloc failed\n", __func__); error = PTR_ERR(sdp); goto out; } error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1); if (error) goto cdev_add_err; sdp->cdev = cdev; if (sg_sysfs_valid) { struct device *sg_class_member; sg_class_member = device_create(sg_sysfs_class, cl_dev->parent, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), sdp, "%s", disk->disk_name); if (IS_ERR(sg_class_member)) { pr_err("%s: device_create failed\n", __func__); error = PTR_ERR(sg_class_member); goto cdev_add_err; } error = sysfs_create_link(&scsidp->sdev_gendev.kobj, &sg_class_member->kobj, "generic"); if (error) pr_err("%s: unable to make symlink 'generic' back " "to sg%d\n", __func__, sdp->index); } else pr_warn("%s: sg_sys Invalid\n", __func__); sdev_printk(KERN_NOTICE, scsidp, "Attached scsi generic sg%d " "type %d\n", sdp->index, scsidp->type); dev_set_drvdata(cl_dev, sdp); return 0; cdev_add_err: write_lock_irqsave(&sg_index_lock, iflags); idr_remove(&sg_index_idr, sdp->index); write_unlock_irqrestore(&sg_index_lock, iflags); kfree(sdp); out: put_disk(disk); if (cdev) cdev_del(cdev); return error; } static void sg_device_destroy(struct kref *kref) { struct sg_device *sdp = container_of(kref, struct sg_device, d_ref); unsigned long flags; /* CAUTION! Note that the device can still be found via idr_find() * even though the refcount is 0. Therefore, do idr_remove() BEFORE * any other cleanup. */ write_lock_irqsave(&sg_index_lock, flags); idr_remove(&sg_index_idr, sdp->index); write_unlock_irqrestore(&sg_index_lock, flags); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_device_destroy\n")); put_disk(sdp->disk); kfree(sdp); } static void sg_remove_device(struct device *cl_dev, struct class_interface *cl_intf) { struct scsi_device *scsidp = to_scsi_device(cl_dev->parent); Sg_device *sdp = dev_get_drvdata(cl_dev); unsigned long iflags; Sg_fd *sfp; int val; if (!sdp) return; /* want sdp->detaching non-zero as soon as possible */ val = atomic_inc_return(&sdp->detaching); if (val > 1) return; /* only want to do following once per device */ SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "%s\n", __func__)); read_lock_irqsave(&sdp->sfd_lock, iflags); list_for_each_entry(sfp, &sdp->sfds, sfd_siblings) { wake_up_interruptible_all(&sfp->read_wait); kill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP); } wake_up_interruptible_all(&sdp->open_wait); read_unlock_irqrestore(&sdp->sfd_lock, iflags); sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic"); device_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index)); cdev_del(sdp->cdev); sdp->cdev = NULL; kref_put(&sdp->d_ref, sg_device_destroy); } module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR); module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO | S_IWUSR); module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR); MODULE_AUTHOR("Douglas Gilbert"); MODULE_DESCRIPTION("SCSI generic (sg) driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(SG_VERSION_STR); MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR); MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element " "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))"); MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd"); MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))"); static int __init init_sg(void) { int rc; if (scatter_elem_sz < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = scatter_elem_sz; } if (def_reserved_size >= 0) sg_big_buff = def_reserved_size; else def_reserved_size = sg_big_buff; rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS, "sg"); if (rc) return rc; sg_sysfs_class = class_create(THIS_MODULE, "scsi_generic"); if ( IS_ERR(sg_sysfs_class) ) { rc = PTR_ERR(sg_sysfs_class); goto err_out; } sg_sysfs_valid = 1; rc = scsi_register_interface(&sg_interface); if (0 == rc) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_init(); #endif /* CONFIG_SCSI_PROC_FS */ return 0; } class_destroy(sg_sysfs_class); err_out: unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); return rc; } static void __exit exit_sg(void) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_cleanup(); #endif /* CONFIG_SCSI_PROC_FS */ scsi_unregister_interface(&sg_interface); class_destroy(sg_sysfs_class); sg_sysfs_valid = 0; unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); idr_destroy(&sg_index_idr); } static int sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { struct iovec *iov = NULL; struct iov_iter i; res = import_iovec(rw, hp->dxferp, iov_count, 0, &iov, &i); if (res < 0) return res; iov_iter_truncate(&i, hp->dxfer_len); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } static int sg_finish_rem_req(Sg_request *srp) { int ret = 0; Sg_fd *sfp = srp->parentfp; Sg_scatter_hold *req_schp = &srp->data; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_finish_rem_req: res_used=%d\n", (int) srp->res_used)); if (srp->bio) ret = blk_rq_unmap_user(srp->bio); if (srp->rq) { if (srp->rq->cmd != srp->rq->__cmd) kfree(srp->rq->cmd); blk_put_request(srp->rq); } if (srp->res_used) sg_unlink_reserve(sfp, srp); else sg_remove_scat(sfp, req_schp); sg_remove_request(sfp, srp); return ret; } static int sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize) { int sg_bufflen = tablesize * sizeof(struct page *); gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN; schp->pages = kzalloc(sg_bufflen, gfp_flags); if (!schp->pages) return -ENOMEM; schp->sglist_len = sg_bufflen; return tablesize; /* number of scat_gath elements allocated */ } static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size) { int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems; int sg_tablesize = sfp->parentdp->sg_tablesize; int blk_size = buff_size, order; gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN; if (blk_size < 0) return -EFAULT; if (0 == blk_size) ++blk_size; /* don't know why */ /* round request up to next highest SG_SECTOR_SZ byte boundary */ blk_size = ALIGN(blk_size, SG_SECTOR_SZ); SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: buff_size=%d, blk_size=%d\n", buff_size, blk_size)); /* N.B. ret_sz carried into this block ... */ mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize); if (mx_sc_elems < 0) return mx_sc_elems; /* most likely -ENOMEM */ num = scatter_elem_sz; if (unlikely(num != scatter_elem_sz_prev)) { if (num < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = PAGE_SIZE; } else scatter_elem_sz_prev = num; } if (sfp->low_dma) gfp_mask |= GFP_DMA; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) gfp_mask |= __GFP_ZERO; order = get_order(num); retry: ret_sz = 1 << (PAGE_SHIFT + order); for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems; k++, rem_sz -= ret_sz) { num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz; schp->pages[k] = alloc_pages(gfp_mask, order); if (!schp->pages[k]) goto out; if (num == scatter_elem_sz_prev) { if (unlikely(ret_sz > scatter_elem_sz_prev)) { scatter_elem_sz = ret_sz; scatter_elem_sz_prev = ret_sz; } } SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n", k, num, ret_sz)); } /* end of for loop */ schp->page_order = order; schp->k_use_sg = k; SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n", k, rem_sz)); schp->bufflen = blk_size; if (rem_sz > 0) /* must have failed */ return -ENOMEM; return 0; out: for (i = 0; i < k; i++) __free_pages(schp->pages[i], order); if (--order >= 0) goto retry; return -ENOMEM; } static void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp) { SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg)); if (schp->pages && schp->sglist_len > 0) { if (!schp->dio_in_use) { int k; for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_remove_scat: k=%d, pg=0x%p\n", k, schp->pages[k])); __free_pages(schp->pages[k], schp->page_order); } kfree(schp->pages); } } memset(schp, 0, sizeof (*schp)); } static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer) { Sg_scatter_hold *schp = &srp->data; int k, num; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp, "sg_read_oxfer: num_read_xfer=%d\n", num_read_xfer)); if ((!outp) || (num_read_xfer <= 0)) return 0; num = 1 << (PAGE_SHIFT + schp->page_order); for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { if (num > num_read_xfer) { if (__copy_to_user(outp, page_address(schp->pages[k]), num_read_xfer)) return -EFAULT; break; } else { if (__copy_to_user(outp, page_address(schp->pages[k]), num)) return -EFAULT; num_read_xfer -= num; if (num_read_xfer <= 0) break; outp += num; } } return 0; } static void sg_build_reserve(Sg_fd * sfp, int req_size) { Sg_scatter_hold *schp = &sfp->reserve; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_reserve: req_size=%d\n", req_size)); do { if (req_size < PAGE_SIZE) req_size = PAGE_SIZE; if (0 == sg_build_indirect(schp, sfp, req_size)) return; else sg_remove_scat(sfp, schp); req_size >>= 1; /* divide by 2 */ } while (req_size > (PAGE_SIZE / 2)); } static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size) { Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; int k, num, rem; srp->res_used = 1; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_link_reserve: size=%d\n", size)); rem = size; num = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg; k++) { if (rem <= num) { req_schp->k_use_sg = k + 1; req_schp->sglist_len = rsv_schp->sglist_len; req_schp->pages = rsv_schp->pages; req_schp->bufflen = size; req_schp->page_order = rsv_schp->page_order; break; } else rem -= num; } if (k >= rsv_schp->k_use_sg) SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_link_reserve: BAD size\n")); } static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp) { Sg_scatter_hold *req_schp = &srp->data; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp, "sg_unlink_reserve: req->k_use_sg=%d\n", (int) req_schp->k_use_sg)); req_schp->k_use_sg = 0; req_schp->bufflen = 0; req_schp->pages = NULL; req_schp->page_order = 0; req_schp->sglist_len = 0; sfp->save_scat_len = 0; srp->res_used = 0; } static Sg_request * sg_get_rq_mark(Sg_fd * sfp, int pack_id) { Sg_request *resp; unsigned long iflags; write_lock_irqsave(&sfp->rq_list_lock, iflags); for (resp = sfp->headrp; resp; resp = resp->nextrp) { /* look for requests that are ready + not SG_IO owned */ if ((1 == resp->done) && (!resp->sg_io_owned) && ((-1 == pack_id) || (resp->header.pack_id == pack_id))) { resp->done = 2; /* guard against other readers */ break; } } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return resp; } /* always adds to end of list */ static Sg_request * sg_add_request(Sg_fd * sfp) { int k; unsigned long iflags; Sg_request *resp; Sg_request *rp = sfp->req_arr; write_lock_irqsave(&sfp->rq_list_lock, iflags); resp = sfp->headrp; if (!resp) { memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; resp = rp; sfp->headrp = resp; } else { if (0 == sfp->cmd_q) resp = NULL; /* command queuing disallowed */ else { for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) { if (!rp->parentfp) break; } if (k < SG_MAX_QUEUE) { memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; while (resp->nextrp) resp = resp->nextrp; resp->nextrp = rp; resp = rp; } else resp = NULL; } } if (resp) { resp->nextrp = NULL; resp->header.duration = jiffies_to_msecs(jiffies); } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return resp; } /* Return of 1 for found; 0 for not found */ static int sg_remove_request(Sg_fd * sfp, Sg_request * srp) { Sg_request *prev_rp; Sg_request *rp; unsigned long iflags; int res = 0; if ((!sfp) || (!srp) || (!sfp->headrp)) return res; write_lock_irqsave(&sfp->rq_list_lock, iflags); prev_rp = sfp->headrp; if (srp == prev_rp) { sfp->headrp = prev_rp->nextrp; prev_rp->parentfp = NULL; res = 1; } else { while ((rp = prev_rp->nextrp)) { if (srp == rp) { prev_rp->nextrp = rp->nextrp; rp->parentfp = NULL; res = 1; break; } prev_rp = rp; } } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return res; } static Sg_fd * sg_add_sfp(Sg_device * sdp) { Sg_fd *sfp; unsigned long iflags; int bufflen; sfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN); if (!sfp) return ERR_PTR(-ENOMEM); init_waitqueue_head(&sfp->read_wait); rwlock_init(&sfp->rq_list_lock); kref_init(&sfp->f_ref); sfp->timeout = SG_DEFAULT_TIMEOUT; sfp->timeout_user = SG_DEFAULT_TIMEOUT_USER; sfp->force_packid = SG_DEF_FORCE_PACK_ID; sfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ? sdp->device->host->unchecked_isa_dma : 1; sfp->cmd_q = SG_DEF_COMMAND_Q; sfp->keep_orphan = SG_DEF_KEEP_ORPHAN; sfp->parentdp = sdp; write_lock_irqsave(&sdp->sfd_lock, iflags); if (atomic_read(&sdp->detaching)) { write_unlock_irqrestore(&sdp->sfd_lock, iflags); return ERR_PTR(-ENODEV); } list_add_tail(&sfp->sfd_siblings, &sdp->sfds); write_unlock_irqrestore(&sdp->sfd_lock, iflags); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_add_sfp: sfp=0x%p\n", sfp)); if (unlikely(sg_big_buff != def_reserved_size)) sg_big_buff = def_reserved_size; bufflen = min_t(int, sg_big_buff, max_sectors_bytes(sdp->device->request_queue)); sg_build_reserve(sfp, bufflen); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_add_sfp: bufflen=%d, k_use_sg=%d\n", sfp->reserve.bufflen, sfp->reserve.k_use_sg)); kref_get(&sdp->d_ref); __module_get(THIS_MODULE); return sfp; } static void sg_remove_sfp_usercontext(struct work_struct *work) { struct sg_fd *sfp = container_of(work, struct sg_fd, ew.work); struct sg_device *sdp = sfp->parentdp; /* Cleanup any responses which were never read(). */ while (sfp->headrp) sg_finish_rem_req(sfp->headrp); if (sfp->reserve.bufflen > 0) { SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp, "sg_remove_sfp: bufflen=%d, k_use_sg=%d\n", (int) sfp->reserve.bufflen, (int) sfp->reserve.k_use_sg)); sg_remove_scat(sfp, &sfp->reserve); } SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp, "sg_remove_sfp: sfp=0x%p\n", sfp)); kfree(sfp); scsi_device_put(sdp->device); kref_put(&sdp->d_ref, sg_device_destroy); module_put(THIS_MODULE); } static void sg_remove_sfp(struct kref *kref) { struct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref); struct sg_device *sdp = sfp->parentdp; unsigned long iflags; write_lock_irqsave(&sdp->sfd_lock, iflags); list_del(&sfp->sfd_siblings); write_unlock_irqrestore(&sdp->sfd_lock, iflags); INIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext); schedule_work(&sfp->ew.work); } static int sg_res_in_use(Sg_fd * sfp) { const Sg_request *srp; unsigned long iflags; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) if (srp->res_used) break; read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return srp ? 1 : 0; } #ifdef CONFIG_SCSI_PROC_FS static int sg_idr_max_id(int id, void *p, void *data) { int *k = data; if (*k < id) *k = id; return 0; } static int sg_last_dev(void) { int k = -1; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); idr_for_each(&sg_index_idr, sg_idr_max_id, &k); read_unlock_irqrestore(&sg_index_lock, iflags); return k + 1; /* origin 1 */ } #endif /* must be called with sg_index_lock held */ static Sg_device *sg_lookup_dev(int dev) { return idr_find(&sg_index_idr, dev); } static Sg_device * sg_get_dev(int dev) { struct sg_device *sdp; unsigned long flags; read_lock_irqsave(&sg_index_lock, flags); sdp = sg_lookup_dev(dev); if (!sdp) sdp = ERR_PTR(-ENXIO); else if (atomic_read(&sdp->detaching)) { /* If sdp->detaching, then the refcount may already be 0, in * which case it would be a bug to do kref_get(). */ sdp = ERR_PTR(-ENODEV); } else kref_get(&sdp->d_ref); read_unlock_irqrestore(&sg_index_lock, flags); return sdp; } #ifdef CONFIG_SCSI_PROC_FS static struct proc_dir_entry *sg_proc_sgp = NULL; static char sg_proc_sg_dirname[] = "scsi/sg"; static int sg_proc_seq_show_int(struct seq_file *s, void *v); static int sg_proc_single_open_adio(struct inode *inode, struct file *file); static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer, size_t count, loff_t *off); static const struct file_operations adio_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_adio, .read = seq_read, .llseek = seq_lseek, .write = sg_proc_write_adio, .release = single_release, }; static int sg_proc_single_open_dressz(struct inode *inode, struct file *file); static ssize_t sg_proc_write_dressz(struct file *filp, const char __user *buffer, size_t count, loff_t *off); static const struct file_operations dressz_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_dressz, .read = seq_read, .llseek = seq_lseek, .write = sg_proc_write_dressz, .release = single_release, }; static int sg_proc_seq_show_version(struct seq_file *s, void *v); static int sg_proc_single_open_version(struct inode *inode, struct file *file); static const struct file_operations version_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_version, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v); static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file); static const struct file_operations devhdr_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_devhdr, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int sg_proc_seq_show_dev(struct seq_file *s, void *v); static int sg_proc_open_dev(struct inode *inode, struct file *file); static void * dev_seq_start(struct seq_file *s, loff_t *pos); static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos); static void dev_seq_stop(struct seq_file *s, void *v); static const struct file_operations dev_fops = { .owner = THIS_MODULE, .open = sg_proc_open_dev, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations dev_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_dev, }; static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v); static int sg_proc_open_devstrs(struct inode *inode, struct file *file); static const struct file_operations devstrs_fops = { .owner = THIS_MODULE, .open = sg_proc_open_devstrs, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations devstrs_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_devstrs, }; static int sg_proc_seq_show_debug(struct seq_file *s, void *v); static int sg_proc_open_debug(struct inode *inode, struct file *file); static const struct file_operations debug_fops = { .owner = THIS_MODULE, .open = sg_proc_open_debug, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations debug_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_debug, }; struct sg_proc_leaf { const char * name; const struct file_operations * fops; }; static const struct sg_proc_leaf sg_proc_leaf_arr[] = { {"allow_dio", &adio_fops}, {"debug", &debug_fops}, {"def_reserved_size", &dressz_fops}, {"device_hdr", &devhdr_fops}, {"devices", &dev_fops}, {"device_strs", &devstrs_fops}, {"version", &version_fops} }; static int sg_proc_init(void) { int num_leaves = ARRAY_SIZE(sg_proc_leaf_arr); int k; sg_proc_sgp = proc_mkdir(sg_proc_sg_dirname, NULL); if (!sg_proc_sgp) return 1; for (k = 0; k < num_leaves; ++k) { const struct sg_proc_leaf *leaf = &sg_proc_leaf_arr[k]; umode_t mask = leaf->fops->write ? S_IRUGO | S_IWUSR : S_IRUGO; proc_create(leaf->name, mask, sg_proc_sgp, leaf->fops); } return 0; } static void sg_proc_cleanup(void) { int k; int num_leaves = ARRAY_SIZE(sg_proc_leaf_arr); if (!sg_proc_sgp) return; for (k = 0; k < num_leaves; ++k) remove_proc_entry(sg_proc_leaf_arr[k].name, sg_proc_sgp); remove_proc_entry(sg_proc_sg_dirname, NULL); } static int sg_proc_seq_show_int(struct seq_file *s, void *v) { seq_printf(s, "%d\n", *((int *)s->private)); return 0; } static int sg_proc_single_open_adio(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_int, &sg_allow_dio); } static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer, size_t count, loff_t *off) { int err; unsigned long num; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; err = kstrtoul_from_user(buffer, count, 0, &num); if (err) return err; sg_allow_dio = num ? 1 : 0; return count; } static int sg_proc_single_open_dressz(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_int, &sg_big_buff); } static ssize_t sg_proc_write_dressz(struct file *filp, const char __user *buffer, size_t count, loff_t *off) { int err; unsigned long k = ULONG_MAX; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; err = kstrtoul_from_user(buffer, count, 0, &k); if (err) return err; if (k <= 1048576) { /* limit "big buff" to 1 MB */ sg_big_buff = k; return count; } return -ERANGE; } static int sg_proc_seq_show_version(struct seq_file *s, void *v) { seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR, sg_version_date); return 0; } static int sg_proc_single_open_version(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_version, NULL); } static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v) { seq_puts(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n"); return 0; } static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_devhdr, NULL); } struct sg_proc_deviter { loff_t index; size_t max; }; static void * dev_seq_start(struct seq_file *s, loff_t *pos) { struct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL); s->private = it; if (! it) return NULL; it->index = *pos; it->max = sg_last_dev(); if (it->index >= it->max) return NULL; return it; } static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos) { struct sg_proc_deviter * it = s->private; *pos = ++it->index; return (it->index < it->max) ? it : NULL; } static void dev_seq_stop(struct seq_file *s, void *v) { kfree(s->private); } static int sg_proc_open_dev(struct inode *inode, struct file *file) { return seq_open(file, &dev_seq_ops); } static int sg_proc_seq_show_dev(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; struct scsi_device *scsidp; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if ((NULL == sdp) || (NULL == sdp->device) || (atomic_read(&sdp->detaching))) seq_puts(s, "-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n"); else { scsidp = sdp->device; seq_printf(s, "%d\t%d\t%d\t%llu\t%d\t%d\t%d\t%d\t%d\n", scsidp->host->host_no, scsidp->channel, scsidp->id, scsidp->lun, (int) scsidp->type, 1, (int) scsidp->queue_depth, (int) atomic_read(&scsidp->device_busy), (int) scsi_device_online(scsidp)); } read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } static int sg_proc_open_devstrs(struct inode *inode, struct file *file) { return seq_open(file, &devstrs_seq_ops); } static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; struct scsi_device *scsidp; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; scsidp = sdp ? sdp->device : NULL; if (sdp && scsidp && (!atomic_read(&sdp->detaching))) seq_printf(s, "%8.8s\t%16.16s\t%4.4s\n", scsidp->vendor, scsidp->model, scsidp->rev); else seq_puts(s, "<no active device>\n"); read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } /* must be called while holding sg_index_lock */ static void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp) { int k, m, new_interface, blen, usg; Sg_request *srp; Sg_fd *fp; const sg_io_hdr_t *hp; const char * cp; unsigned int ms; k = 0; list_for_each_entry(fp, &sdp->sfds, sfd_siblings) { k++; read_lock(&fp->rq_list_lock); /* irqs already disabled */ seq_printf(s, " FD(%d): timeout=%dms bufflen=%d " "(res)sgat=%d low_dma=%d\n", k, jiffies_to_msecs(fp->timeout), fp->reserve.bufflen, (int) fp->reserve.k_use_sg, (int) fp->low_dma); seq_printf(s, " cmd_q=%d f_packid=%d k_orphan=%d closed=0\n", (int) fp->cmd_q, (int) fp->force_packid, (int) fp->keep_orphan); for (m = 0, srp = fp->headrp; srp != NULL; ++m, srp = srp->nextrp) { hp = &srp->header; new_interface = (hp->interface_id == '\0') ? 0 : 1; if (srp->res_used) { if (new_interface && (SG_FLAG_MMAP_IO & hp->flags)) cp = " mmap>> "; else cp = " rb>> "; } else { if (SG_INFO_DIRECT_IO_MASK & hp->info) cp = " dio>> "; else cp = " "; } seq_puts(s, cp); blen = srp->data.bufflen; usg = srp->data.k_use_sg; seq_puts(s, srp->done ? ((1 == srp->done) ? "rcv:" : "fin:") : "act:"); seq_printf(s, " id=%d blen=%d", srp->header.pack_id, blen); if (srp->done) seq_printf(s, " dur=%d", hp->duration); else { ms = jiffies_to_msecs(jiffies); seq_printf(s, " t_o/elap=%d/%d", (new_interface ? hp->timeout : jiffies_to_msecs(fp->timeout)), (ms > hp->duration ? ms - hp->duration : 0)); } seq_printf(s, "ms sgat=%d op=0x%02x\n", usg, (int) srp->data.cmd_opcode); } if (0 == m) seq_puts(s, " No requests active\n"); read_unlock(&fp->rq_list_lock); } } static int sg_proc_open_debug(struct inode *inode, struct file *file) { return seq_open(file, &debug_seq_ops); } static int sg_proc_seq_show_debug(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; unsigned long iflags; if (it && (0 == it->index)) seq_printf(s, "max_active_device=%d def_reserved_size=%d\n", (int)it->max, sg_big_buff); read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if (NULL == sdp) goto skip; read_lock(&sdp->sfd_lock); if (!list_empty(&sdp->sfds)) { seq_printf(s, " >>> device=%s ", sdp->disk->disk_name); if (atomic_read(&sdp->detaching)) seq_puts(s, "detaching pending close "); else if (sdp->device) { struct scsi_device *scsidp = sdp->device; seq_printf(s, "%d:%d:%d:%llu em=%d", scsidp->host->host_no, scsidp->channel, scsidp->id, scsidp->lun, scsidp->host->hostt->emulated); } seq_printf(s, " sg_tablesize=%d excl=%d open_cnt=%d\n", sdp->sg_tablesize, sdp->exclude, sdp->open_cnt); sg_proc_debug_helper(s, sdp); } read_unlock(&sdp->sfd_lock); skip: read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } #endif /* CONFIG_SCSI_PROC_FS */ module_init(init_sg); module_exit(exit_sg);
./CrossVul/dataset_final_sorted/CWE-415/c/good_1858_0
crossvul-cpp_data_good_3906_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Drawing Orders * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "window.h" #include <winpr/wtypes.h> #include <winpr/crt.h> #include <freerdp/api.h> #include <freerdp/log.h> #include <freerdp/graphics.h> #include <freerdp/codec/bitmap.h> #include <freerdp/gdi/gdi.h> #include "orders.h" #include "../cache/glyph.h" #include "../cache/bitmap.h" #include "../cache/brush.h" #include "../cache/cache.h" #define TAG FREERDP_TAG("core.orders") const BYTE PRIMARY_DRAWING_ORDER_FIELD_BYTES[] = { DSTBLT_ORDER_FIELD_BYTES, PATBLT_ORDER_FIELD_BYTES, SCRBLT_ORDER_FIELD_BYTES, 0, 0, 0, 0, DRAW_NINE_GRID_ORDER_FIELD_BYTES, MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES, LINE_TO_ORDER_FIELD_BYTES, OPAQUE_RECT_ORDER_FIELD_BYTES, SAVE_BITMAP_ORDER_FIELD_BYTES, 0, MEMBLT_ORDER_FIELD_BYTES, MEM3BLT_ORDER_FIELD_BYTES, MULTI_DSTBLT_ORDER_FIELD_BYTES, MULTI_PATBLT_ORDER_FIELD_BYTES, MULTI_SCRBLT_ORDER_FIELD_BYTES, MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES, FAST_INDEX_ORDER_FIELD_BYTES, POLYGON_SC_ORDER_FIELD_BYTES, POLYGON_CB_ORDER_FIELD_BYTES, POLYLINE_ORDER_FIELD_BYTES, 0, FAST_GLYPH_ORDER_FIELD_BYTES, ELLIPSE_SC_ORDER_FIELD_BYTES, ELLIPSE_CB_ORDER_FIELD_BYTES, GLYPH_INDEX_ORDER_FIELD_BYTES }; #define PRIMARY_DRAWING_ORDER_COUNT (ARRAYSIZE(PRIMARY_DRAWING_ORDER_FIELD_BYTES)) static const BYTE CBR2_BPP[] = { 0, 0, 0, 8, 16, 24, 32 }; static const BYTE BPP_CBR2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; static const BYTE CBR23_BPP[] = { 0, 0, 0, 8, 16, 24, 32 }; static const BYTE BPP_CBR23[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; static const BYTE BMF_BPP[] = { 0, 1, 0, 8, 16, 24, 32, 0 }; static const BYTE BPP_BMF[] = { 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName, BOOL condition) { if (!condition) { if (settings->AllowUnanouncedOrdersFromServer) { WLog_Print(log, WLOG_WARN, "%s - SERVER BUG: The support for this feature was not announced!", orderName); return TRUE; } else { WLog_Print(log, WLOG_ERROR, "%s - SERVER BUG: The support for this feature was not announced! Use " "/relax-order-checks to ignore", orderName); return FALSE; } } return TRUE; } static BOOL check_alt_order_supported(wLog* log, rdpSettings* settings, BYTE orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: case ORDER_TYPE_SWITCH_SURFACE: condition = settings->OffscreenSupportLevel != 0; break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: condition = settings->DrawNineGridEnabled; break; case ORDER_TYPE_FRAME_MARKER: condition = settings->FrameMarkerCommandEnabled; break; case ORDER_TYPE_GDIPLUS_FIRST: case ORDER_TYPE_GDIPLUS_NEXT: case ORDER_TYPE_GDIPLUS_END: case ORDER_TYPE_GDIPLUS_CACHE_FIRST: case ORDER_TYPE_GDIPLUS_CACHE_NEXT: case ORDER_TYPE_GDIPLUS_CACHE_END: condition = settings->DrawGdiPlusCacheEnabled; break; case ORDER_TYPE_WINDOW: condition = settings->RemoteWndSupportLevel != WINDOW_LEVEL_NOT_SUPPORTED; break; case ORDER_TYPE_STREAM_BITMAP_FIRST: case ORDER_TYPE_STREAM_BITMAP_NEXT: case ORDER_TYPE_COMPDESK_FIRST: condition = TRUE; break; default: WLog_Print(log, WLOG_WARN, "%s - Alternate Secondary Drawing Order UNKNOWN", orderName); condition = FALSE; break; } return check_order_activated(log, settings, orderName, condition); } static BOOL check_secondary_order_supported(wLog* log, rdpSettings* settings, BYTE orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: condition = settings->BitmapCacheEnabled; break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: condition = settings->BitmapCacheEnabled; break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: condition = settings->BitmapCacheV3Enabled; break; case ORDER_TYPE_CACHE_COLOR_TABLE: condition = (settings->OrderSupport[NEG_MEMBLT_INDEX] || settings->OrderSupport[NEG_MEM3BLT_INDEX]); break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: case GLYPH_SUPPORT_ENCODE: condition = TRUE; break; case GLYPH_SUPPORT_NONE: default: condition = FALSE; break; } } break; case ORDER_TYPE_CACHE_BRUSH: condition = TRUE; break; default: WLog_Print(log, WLOG_WARN, "SECONDARY ORDER %s not supported", orderName); break; } return check_order_activated(log, settings, orderName, condition); } static BOOL check_primary_order_supported(wLog* log, rdpSettings* settings, UINT32 orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_DSTBLT: condition = settings->OrderSupport[NEG_DSTBLT_INDEX]; break; case ORDER_TYPE_SCRBLT: condition = settings->OrderSupport[NEG_SCRBLT_INDEX]; break; case ORDER_TYPE_DRAW_NINE_GRID: condition = settings->OrderSupport[NEG_DRAWNINEGRID_INDEX]; break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: condition = settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX]; break; case ORDER_TYPE_LINE_TO: condition = settings->OrderSupport[NEG_LINETO_INDEX]; break; /* [MS-RDPEGDI] 2.2.2.2.1.1.2.5 OpaqueRect (OPAQUERECT_ORDER) * suggests that PatBlt and OpaqueRect imply each other. */ case ORDER_TYPE_PATBLT: case ORDER_TYPE_OPAQUE_RECT: condition = settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] || settings->OrderSupport[NEG_PATBLT_INDEX]; break; case ORDER_TYPE_SAVE_BITMAP: condition = settings->OrderSupport[NEG_SAVEBITMAP_INDEX]; break; case ORDER_TYPE_MEMBLT: condition = settings->OrderSupport[NEG_MEMBLT_INDEX]; break; case ORDER_TYPE_MEM3BLT: condition = settings->OrderSupport[NEG_MEM3BLT_INDEX]; break; case ORDER_TYPE_MULTI_DSTBLT: condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX]; break; case ORDER_TYPE_MULTI_PATBLT: condition = settings->OrderSupport[NEG_MULTIPATBLT_INDEX]; break; case ORDER_TYPE_MULTI_SCRBLT: condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX]; break; case ORDER_TYPE_MULTI_OPAQUE_RECT: condition = settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX]; break; case ORDER_TYPE_FAST_INDEX: condition = settings->OrderSupport[NEG_FAST_INDEX_INDEX]; break; case ORDER_TYPE_POLYGON_SC: condition = settings->OrderSupport[NEG_POLYGON_SC_INDEX]; break; case ORDER_TYPE_POLYGON_CB: condition = settings->OrderSupport[NEG_POLYGON_CB_INDEX]; break; case ORDER_TYPE_POLYLINE: condition = settings->OrderSupport[NEG_POLYLINE_INDEX]; break; case ORDER_TYPE_FAST_GLYPH: condition = settings->OrderSupport[NEG_FAST_GLYPH_INDEX]; break; case ORDER_TYPE_ELLIPSE_SC: condition = settings->OrderSupport[NEG_ELLIPSE_SC_INDEX]; break; case ORDER_TYPE_ELLIPSE_CB: condition = settings->OrderSupport[NEG_ELLIPSE_CB_INDEX]; break; case ORDER_TYPE_GLYPH_INDEX: condition = settings->OrderSupport[NEG_GLYPH_INDEX_INDEX]; break; default: WLog_Print(log, WLOG_WARN, "%s Primary Drawing Order not supported", orderName); break; } return check_order_activated(log, settings, orderName, condition); } static const char* primary_order_string(UINT32 orderType) { const char* orders[] = { "[0x%02" PRIx8 "] DstBlt", "[0x%02" PRIx8 "] PatBlt", "[0x%02" PRIx8 "] ScrBlt", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] DrawNineGrid", "[0x%02" PRIx8 "] MultiDrawNineGrid", "[0x%02" PRIx8 "] LineTo", "[0x%02" PRIx8 "] OpaqueRect", "[0x%02" PRIx8 "] SaveBitmap", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] MemBlt", "[0x%02" PRIx8 "] Mem3Blt", "[0x%02" PRIx8 "] MultiDstBlt", "[0x%02" PRIx8 "] MultiPatBlt", "[0x%02" PRIx8 "] MultiScrBlt", "[0x%02" PRIx8 "] MultiOpaqueRect", "[0x%02" PRIx8 "] FastIndex", "[0x%02" PRIx8 "] PolygonSC", "[0x%02" PRIx8 "] PolygonCB", "[0x%02" PRIx8 "] Polyline", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] FastGlyph", "[0x%02" PRIx8 "] EllipseSC", "[0x%02" PRIx8 "] EllipseCB", "[0x%02" PRIx8 "] GlyphIndex" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static const char* secondary_order_string(UINT32 orderType) { const char* orders[] = { "[0x%02" PRIx8 "] Cache Bitmap", "[0x%02" PRIx8 "] Cache Color Table", "[0x%02" PRIx8 "] Cache Bitmap (Compressed)", "[0x%02" PRIx8 "] Cache Glyph", "[0x%02" PRIx8 "] Cache Bitmap V2", "[0x%02" PRIx8 "] Cache Bitmap V2 (Compressed)", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] Cache Brush", "[0x%02" PRIx8 "] Cache Bitmap V3" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static const char* altsec_order_string(BYTE orderType) { const char* orders[] = { "[0x%02" PRIx8 "] Switch Surface", "[0x%02" PRIx8 "] Create Offscreen Bitmap", "[0x%02" PRIx8 "] Stream Bitmap First", "[0x%02" PRIx8 "] Stream Bitmap Next", "[0x%02" PRIx8 "] Create NineGrid Bitmap", "[0x%02" PRIx8 "] Draw GDI+ First", "[0x%02" PRIx8 "] Draw GDI+ Next", "[0x%02" PRIx8 "] Draw GDI+ End", "[0x%02" PRIx8 "] Draw GDI+ Cache First", "[0x%02" PRIx8 "] Draw GDI+ Cache Next", "[0x%02" PRIx8 "] Draw GDI+ Cache End", "[0x%02" PRIx8 "] Windowing", "[0x%02" PRIx8 "] Desktop Composition", "[0x%02" PRIx8 "] Frame Marker" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static INLINE BOOL update_read_coord(wStream* s, INT32* coord, BOOL delta) { INT8 lsi8; INT16 lsi16; if (delta) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_INT8(s, lsi8); *coord += lsi8; } else { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_INT16(s, lsi16); *coord = lsi16; } return TRUE; } static INLINE BOOL update_write_coord(wStream* s, INT32 coord) { Stream_Write_UINT16(s, coord); return TRUE; } static INLINE BOOL update_read_color(wStream* s, UINT32* color) { BYTE byte; if (Stream_GetRemainingLength(s) < 3) return FALSE; *color = 0; Stream_Read_UINT8(s, byte); *color = (UINT32)byte; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 8) & 0xFF00; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 16) & 0xFF0000; return TRUE; } static INLINE BOOL update_write_color(wStream* s, UINT32 color) { BYTE byte; byte = (color & 0xFF); Stream_Write_UINT8(s, byte); byte = ((color >> 8) & 0xFF); Stream_Write_UINT8(s, byte); byte = ((color >> 16) & 0xFF); Stream_Write_UINT8(s, byte); return TRUE; } static INLINE BOOL update_read_colorref(wStream* s, UINT32* color) { BYTE byte; if (Stream_GetRemainingLength(s) < 4) return FALSE; *color = 0; Stream_Read_UINT8(s, byte); *color = byte; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 8); Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 16); Stream_Seek_UINT8(s); return TRUE; } static INLINE BOOL update_read_color_quad(wStream* s, UINT32* color) { return update_read_colorref(s, color); } static INLINE void update_write_color_quad(wStream* s, UINT32 color) { BYTE byte; byte = (color >> 16) & 0xFF; Stream_Write_UINT8(s, byte); byte = (color >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = color & 0xFF; Stream_Write_UINT8(s, byte); } static INLINE BOOL update_read_2byte_unsigned(wStream* s, UINT32* value) { BYTE byte; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) return FALSE; *value = (byte & 0x7F) << 8; Stream_Read_UINT8(s, byte); *value |= byte; } else { *value = (byte & 0x7F); } return TRUE; } static INLINE BOOL update_write_2byte_unsigned(wStream* s, UINT32 value) { BYTE byte; if (value > 0x7FFF) return FALSE; if (value >= 0x7F) { byte = ((value & 0x7F00) >> 8); Stream_Write_UINT8(s, byte | 0x80); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else { byte = (value & 0x7F); Stream_Write_UINT8(s, byte); } return TRUE; } static INLINE BOOL update_read_2byte_signed(wStream* s, INT32* value) { BYTE byte; BOOL negative; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); negative = (byte & 0x40) ? TRUE : FALSE; *value = (byte & 0x3F); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } if (negative) *value *= -1; return TRUE; } static INLINE BOOL update_write_2byte_signed(wStream* s, INT32 value) { BYTE byte; BOOL negative = FALSE; if (value < 0) { negative = TRUE; value *= -1; } if (value > 0x3FFF) return FALSE; if (value >= 0x3F) { byte = ((value & 0x3F00) >> 8); if (negative) byte |= 0x40; Stream_Write_UINT8(s, byte | 0x80); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else { byte = (value & 0x3F); if (negative) byte |= 0x40; Stream_Write_UINT8(s, byte); } return TRUE; } static INLINE BOOL update_read_4byte_unsigned(wStream* s, UINT32* value) { BYTE byte; BYTE count; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); count = (byte & 0xC0) >> 6; if (Stream_GetRemainingLength(s) < count) return FALSE; switch (count) { case 0: *value = (byte & 0x3F); break; case 1: *value = (byte & 0x3F) << 8; Stream_Read_UINT8(s, byte); *value |= byte; break; case 2: *value = (byte & 0x3F) << 16; Stream_Read_UINT8(s, byte); *value |= (byte << 8); Stream_Read_UINT8(s, byte); *value |= byte; break; case 3: *value = (byte & 0x3F) << 24; Stream_Read_UINT8(s, byte); *value |= (byte << 16); Stream_Read_UINT8(s, byte); *value |= (byte << 8); Stream_Read_UINT8(s, byte); *value |= byte; break; default: break; } return TRUE; } static INLINE BOOL update_write_4byte_unsigned(wStream* s, UINT32 value) { BYTE byte; if (value <= 0x3F) { Stream_Write_UINT8(s, value); } else if (value <= 0x3FFF) { byte = (value >> 8) & 0x3F; Stream_Write_UINT8(s, byte | 0x40); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else if (value <= 0x3FFFFF) { byte = (value >> 16) & 0x3F; Stream_Write_UINT8(s, byte | 0x80); byte = (value >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else if (value <= 0x3FFFFFFF) { byte = (value >> 24) & 0x3F; Stream_Write_UINT8(s, byte | 0xC0); byte = (value >> 16) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else return FALSE; return TRUE; } static INLINE BOOL update_read_delta(wStream* s, INT32* value) { BYTE byte; if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, byte); if (byte & 0x40) *value = (byte | ~0x3F); else *value = (byte & 0x3F); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } return TRUE; } #if 0 static INLINE void update_read_glyph_delta(wStream* s, UINT16* value) { BYTE byte; Stream_Read_UINT8(s, byte); if (byte == 0x80) Stream_Read_UINT16(s, *value); else *value = (byte & 0x3F); } static INLINE void update_seek_glyph_delta(wStream* s) { BYTE byte; Stream_Read_UINT8(s, byte); if (byte & 0x80) Stream_Seek_UINT8(s); } #endif static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) { if (fieldFlags & ORDER_FIELD_01) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->x); } if (fieldFlags & ORDER_FIELD_02) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->y); } if (fieldFlags & ORDER_FIELD_03) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->style); } if (fieldFlags & ORDER_FIELD_04) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->hatch); } if (brush->style & CACHED_BRUSH) { brush->index = brush->hatch; brush->bpp = BMF_BPP[brush->style & 0x07]; if (brush->bpp == 0) brush->bpp = 1; } if (fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 7) return FALSE; brush->data = (BYTE*)brush->p8x8; Stream_Read_UINT8(s, brush->data[7]); Stream_Read_UINT8(s, brush->data[6]); Stream_Read_UINT8(s, brush->data[5]); Stream_Read_UINT8(s, brush->data[4]); Stream_Read_UINT8(s, brush->data[3]); Stream_Read_UINT8(s, brush->data[2]); Stream_Read_UINT8(s, brush->data[1]); brush->data[0] = brush->hatch; } return TRUE; } static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) { if (fieldFlags & ORDER_FIELD_01) { Stream_Write_UINT8(s, brush->x); } if (fieldFlags & ORDER_FIELD_02) { Stream_Write_UINT8(s, brush->y); } if (fieldFlags & ORDER_FIELD_03) { Stream_Write_UINT8(s, brush->style); } if (brush->style & CACHED_BRUSH) { brush->hatch = brush->index; brush->bpp = BMF_BPP[brush->style & 0x07]; if (brush->bpp == 0) brush->bpp = 1; } if (fieldFlags & ORDER_FIELD_04) { Stream_Write_UINT8(s, brush->hatch); } if (fieldFlags & ORDER_FIELD_05) { brush->data = (BYTE*)brush->p8x8; Stream_Write_UINT8(s, brush->data[7]); Stream_Write_UINT8(s, brush->data[6]); Stream_Write_UINT8(s, brush->data[5]); Stream_Write_UINT8(s, brush->data[4]); Stream_Write_UINT8(s, brush->data[3]); Stream_Write_UINT8(s, brush->data[2]); Stream_Write_UINT8(s, brush->data[1]); brush->data[0] = brush->hatch; } return TRUE; } static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32 number) { UINT32 i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; if (number > 45) number = 45; zeroBitsSize = ((number + 1) / 2); if (Stream_GetRemainingLength(s) < zeroBitsSize) return FALSE; Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(rectangles, sizeof(DELTA_RECT) * number); for (i = 0; i < number; i++) { if (i % 2 == 0) flags = zeroBits[i / 2]; if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left)) return FALSE; if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top)) return FALSE; if (~flags & 0x20) { if (!update_read_delta(s, &rectangles[i].width)) return FALSE; } else if (i > 0) rectangles[i].width = rectangles[i - 1].width; else rectangles[i].width = 0; if (~flags & 0x10) { if (!update_read_delta(s, &rectangles[i].height)) return FALSE; } else if (i > 0) rectangles[i].height = rectangles[i - 1].height; else rectangles[i].height = 0; if (i > 0) { rectangles[i].left += rectangles[i - 1].left; rectangles[i].top += rectangles[i - 1].top; } flags <<= 4; } return TRUE; } static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int number, INT16 x, INT16 y) { int i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; zeroBitsSize = ((number + 3) / 4); if (Stream_GetRemainingLength(s) < zeroBitsSize) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %" PRIu32 "", zeroBitsSize); return FALSE; } Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(points, sizeof(DELTA_POINT) * number); for (i = 0; i < number; i++) { if (i % 4 == 0) flags = zeroBits[i / 4]; if ((~flags & 0x80) && !update_read_delta(s, &points[i].x)) { WLog_ERR(TAG, "update_read_delta(x) failed"); return FALSE; } if ((~flags & 0x40) && !update_read_delta(s, &points[i].y)) { WLog_ERR(TAG, "update_read_delta(y) failed"); return FALSE; } flags <<= 2; } return TRUE; } #define ORDER_FIELD_BYTE(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 1) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT8(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_2BYTE(NO, TARGET1, TARGET2) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 2) \ { \ WLog_ERR(TAG, "error reading %s or %s", #TARGET1, #TARGET2); \ return FALSE; \ } \ Stream_Read_UINT8(s, TARGET1); \ Stream_Read_UINT8(s, TARGET2); \ } \ } while (0) #define ORDER_FIELD_UINT16(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 2) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT16(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_UINT32(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 4) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT32(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_COORD(NO, TARGET) \ do \ { \ if ((orderInfo->fieldFlags & (1 << (NO - 1))) && \ !update_read_coord(s, &TARGET, orderInfo->deltaCoordinates)) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ } while (0) static INLINE BOOL ORDER_FIELD_COLOR(const ORDER_INFO* orderInfo, wStream* s, UINT32 NO, UINT32* TARGET) { if (!TARGET || !orderInfo) return FALSE; if ((orderInfo->fieldFlags & (1 << (NO - 1))) && !update_read_color(s, TARGET)) return FALSE; return TRUE; } static INLINE BOOL FIELD_SKIP_BUFFER16(wStream* s, UINT32 TARGET_LEN) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, TARGET_LEN); if (!Stream_SafeSeek(s, TARGET_LEN)) { WLog_ERR(TAG, "error skipping %" PRIu32 " bytes", TARGET_LEN); return FALSE; } return TRUE; } /* Primary Drawing Orders */ static BOOL update_read_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, DSTBLT_ORDER* dstblt) { ORDER_FIELD_COORD(1, dstblt->nLeftRect); ORDER_FIELD_COORD(2, dstblt->nTopRect); ORDER_FIELD_COORD(3, dstblt->nWidth); ORDER_FIELD_COORD(4, dstblt->nHeight); ORDER_FIELD_BYTE(5, dstblt->bRop); return TRUE; } int update_approximate_dstblt_order(ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt) { return 32; } BOOL update_write_dstblt_order(wStream* s, ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_dstblt_order(orderInfo, dstblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, dstblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, dstblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, dstblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, dstblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, dstblt->bRop); return TRUE; } static BOOL update_read_patblt_order(wStream* s, const ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { ORDER_FIELD_COORD(1, patblt->nLeftRect); ORDER_FIELD_COORD(2, patblt->nTopRect); ORDER_FIELD_COORD(3, patblt->nWidth); ORDER_FIELD_COORD(4, patblt->nHeight); ORDER_FIELD_BYTE(5, patblt->bRop); ORDER_FIELD_COLOR(orderInfo, s, 6, &patblt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 7, &patblt->foreColor); return update_read_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7); } int update_approximate_patblt_order(ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { return 32; } BOOL update_write_patblt_order(wStream* s, ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_patblt_order(orderInfo, patblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, patblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, patblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, patblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, patblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, patblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, patblt->backColor); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_color(s, patblt->foreColor); orderInfo->fieldFlags |= ORDER_FIELD_08; orderInfo->fieldFlags |= ORDER_FIELD_09; orderInfo->fieldFlags |= ORDER_FIELD_10; orderInfo->fieldFlags |= ORDER_FIELD_11; orderInfo->fieldFlags |= ORDER_FIELD_12; update_write_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7); return TRUE; } static BOOL update_read_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, SCRBLT_ORDER* scrblt) { ORDER_FIELD_COORD(1, scrblt->nLeftRect); ORDER_FIELD_COORD(2, scrblt->nTopRect); ORDER_FIELD_COORD(3, scrblt->nWidth); ORDER_FIELD_COORD(4, scrblt->nHeight); ORDER_FIELD_BYTE(5, scrblt->bRop); ORDER_FIELD_COORD(6, scrblt->nXSrc); ORDER_FIELD_COORD(7, scrblt->nYSrc); return TRUE; } int update_approximate_scrblt_order(ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt) { return 32; } BOOL update_write_scrblt_order(wStream* s, ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_scrblt_order(orderInfo, scrblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, scrblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, scrblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, scrblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, scrblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, scrblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_coord(s, scrblt->nXSrc); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_coord(s, scrblt->nYSrc); return TRUE; } static BOOL update_read_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, OPAQUE_RECT_ORDER* opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, opaque_rect->nTopRect); ORDER_FIELD_COORD(3, opaque_rect->nWidth); ORDER_FIELD_COORD(4, opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } return TRUE; } int update_approximate_opaque_rect_order(ORDER_INFO* orderInfo, const OPAQUE_RECT_ORDER* opaque_rect) { return 32; } BOOL update_write_opaque_rect_order(wStream* s, ORDER_INFO* orderInfo, const OPAQUE_RECT_ORDER* opaque_rect) { BYTE byte; int inf = update_approximate_opaque_rect_order(orderInfo, opaque_rect); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; // TODO: Color format conversion orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, opaque_rect->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, opaque_rect->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, opaque_rect->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, opaque_rect->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; byte = opaque_rect->color & 0x000000FF; Stream_Write_UINT8(s, byte); orderInfo->fieldFlags |= ORDER_FIELD_06; byte = (opaque_rect->color & 0x0000FF00) >> 8; Stream_Write_UINT8(s, byte); orderInfo->fieldFlags |= ORDER_FIELD_07; byte = (opaque_rect->color & 0x00FF0000) >> 16; Stream_Write_UINT8(s, byte); return TRUE; } static BOOL update_read_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo, DRAW_NINE_GRID_ORDER* draw_nine_grid) { ORDER_FIELD_COORD(1, draw_nine_grid->srcLeft); ORDER_FIELD_COORD(2, draw_nine_grid->srcTop); ORDER_FIELD_COORD(3, draw_nine_grid->srcRight); ORDER_FIELD_COORD(4, draw_nine_grid->srcBottom); ORDER_FIELD_UINT16(5, draw_nine_grid->bitmapId); return TRUE; } static BOOL update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DSTBLT_ORDER* multi_dstblt) { ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect); ORDER_FIELD_COORD(2, multi_dstblt->nTopRect); ORDER_FIELD_COORD(3, multi_dstblt->nWidth); ORDER_FIELD_COORD(4, multi_dstblt->nHeight); ORDER_FIELD_BYTE(5, multi_dstblt->bRop); ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_dstblt->cbData); return update_read_delta_rects(s, multi_dstblt->rectangles, multi_dstblt->numRectangles); } return TRUE; } static BOOL update_read_multi_patblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_PATBLT_ORDER* multi_patblt) { ORDER_FIELD_COORD(1, multi_patblt->nLeftRect); ORDER_FIELD_COORD(2, multi_patblt->nTopRect); ORDER_FIELD_COORD(3, multi_patblt->nWidth); ORDER_FIELD_COORD(4, multi_patblt->nHeight); ORDER_FIELD_BYTE(5, multi_patblt->bRop); ORDER_FIELD_COLOR(orderInfo, s, 6, &multi_patblt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 7, &multi_patblt->foreColor); if (!update_read_brush(s, &multi_patblt->brush, orderInfo->fieldFlags >> 7)) return FALSE; ORDER_FIELD_BYTE(13, multi_patblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_14) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_patblt->cbData); if (!update_read_delta_rects(s, multi_patblt->rectangles, multi_patblt->numRectangles)) return FALSE; } return TRUE; } static BOOL update_read_multi_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_SCRBLT_ORDER* multi_scrblt) { ORDER_FIELD_COORD(1, multi_scrblt->nLeftRect); ORDER_FIELD_COORD(2, multi_scrblt->nTopRect); ORDER_FIELD_COORD(3, multi_scrblt->nWidth); ORDER_FIELD_COORD(4, multi_scrblt->nHeight); ORDER_FIELD_BYTE(5, multi_scrblt->bRop); ORDER_FIELD_COORD(6, multi_scrblt->nXSrc); ORDER_FIELD_COORD(7, multi_scrblt->nYSrc); ORDER_FIELD_BYTE(8, multi_scrblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_scrblt->cbData); return update_read_delta_rects(s, multi_scrblt->rectangles, multi_scrblt->numRectangles); } return TRUE; } static BOOL update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect); ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth); ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_opaque_rect->cbData); return update_read_delta_rects(s, multi_opaque_rect->rectangles, multi_opaque_rect->numRectangles); } return TRUE; } static BOOL update_read_multi_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DRAW_NINE_GRID_ORDER* multi_draw_nine_grid) { ORDER_FIELD_COORD(1, multi_draw_nine_grid->srcLeft); ORDER_FIELD_COORD(2, multi_draw_nine_grid->srcTop); ORDER_FIELD_COORD(3, multi_draw_nine_grid->srcRight); ORDER_FIELD_COORD(4, multi_draw_nine_grid->srcBottom); ORDER_FIELD_UINT16(5, multi_draw_nine_grid->bitmapId); ORDER_FIELD_BYTE(6, multi_draw_nine_grid->nDeltaEntries); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_draw_nine_grid->cbData); return update_read_delta_rects(s, multi_draw_nine_grid->rectangles, multi_draw_nine_grid->nDeltaEntries); } return TRUE; } static BOOL update_read_line_to_order(wStream* s, const ORDER_INFO* orderInfo, LINE_TO_ORDER* line_to) { ORDER_FIELD_UINT16(1, line_to->backMode); ORDER_FIELD_COORD(2, line_to->nXStart); ORDER_FIELD_COORD(3, line_to->nYStart); ORDER_FIELD_COORD(4, line_to->nXEnd); ORDER_FIELD_COORD(5, line_to->nYEnd); ORDER_FIELD_COLOR(orderInfo, s, 6, &line_to->backColor); ORDER_FIELD_BYTE(7, line_to->bRop2); ORDER_FIELD_BYTE(8, line_to->penStyle); ORDER_FIELD_BYTE(9, line_to->penWidth); ORDER_FIELD_COLOR(orderInfo, s, 10, &line_to->penColor); return TRUE; } int update_approximate_line_to_order(ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to) { return 32; } BOOL update_write_line_to_order(wStream* s, ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_line_to_order(orderInfo, line_to))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT16(s, line_to->backMode); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, line_to->nXStart); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, line_to->nYStart); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, line_to->nXEnd); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_coord(s, line_to->nYEnd); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, line_to->backColor); orderInfo->fieldFlags |= ORDER_FIELD_07; Stream_Write_UINT8(s, line_to->bRop2); orderInfo->fieldFlags |= ORDER_FIELD_08; Stream_Write_UINT8(s, line_to->penStyle); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT8(s, line_to->penWidth); orderInfo->fieldFlags |= ORDER_FIELD_10; update_write_color(s, line_to->penColor); return TRUE; } static BOOL update_read_polyline_order(wStream* s, const ORDER_INFO* orderInfo, POLYLINE_ORDER* polyline) { UINT16 word; UINT32 new_num = polyline->numDeltaEntries; ORDER_FIELD_COORD(1, polyline->xStart); ORDER_FIELD_COORD(2, polyline->yStart); ORDER_FIELD_BYTE(3, polyline->bRop2); ORDER_FIELD_UINT16(4, word); ORDER_FIELD_COLOR(orderInfo, s, 5, &polyline->penColor); ORDER_FIELD_BYTE(6, new_num); if (orderInfo->fieldFlags & ORDER_FIELD_07) { DELTA_POINT* new_points; if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, polyline->cbData); new_points = (DELTA_POINT*)realloc(polyline->points, sizeof(DELTA_POINT) * new_num); if (!new_points) { WLog_ERR(TAG, "realloc(%" PRIu32 ") failed", new_num); return FALSE; } polyline->points = new_points; polyline->numDeltaEntries = new_num; return update_read_delta_points(s, polyline->points, polyline->numDeltaEntries, polyline->xStart, polyline->yStart); } return TRUE; } static BOOL update_read_memblt_order(wStream* s, const ORDER_INFO* orderInfo, MEMBLT_ORDER* memblt) { if (!s || !orderInfo || !memblt) return FALSE; ORDER_FIELD_UINT16(1, memblt->cacheId); ORDER_FIELD_COORD(2, memblt->nLeftRect); ORDER_FIELD_COORD(3, memblt->nTopRect); ORDER_FIELD_COORD(4, memblt->nWidth); ORDER_FIELD_COORD(5, memblt->nHeight); ORDER_FIELD_BYTE(6, memblt->bRop); ORDER_FIELD_COORD(7, memblt->nXSrc); ORDER_FIELD_COORD(8, memblt->nYSrc); ORDER_FIELD_UINT16(9, memblt->cacheIndex); memblt->colorIndex = (memblt->cacheId >> 8); memblt->cacheId = (memblt->cacheId & 0xFF); memblt->bitmap = NULL; return TRUE; } int update_approximate_memblt_order(ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt) { return 64; } BOOL update_write_memblt_order(wStream* s, ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt) { UINT16 cacheId; if (!Stream_EnsureRemainingCapacity(s, update_approximate_memblt_order(orderInfo, memblt))) return FALSE; cacheId = (memblt->cacheId & 0xFF) | ((memblt->colorIndex & 0xFF) << 8); orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT16(s, cacheId); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, memblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, memblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, memblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_coord(s, memblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_06; Stream_Write_UINT8(s, memblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_coord(s, memblt->nXSrc); orderInfo->fieldFlags |= ORDER_FIELD_08; update_write_coord(s, memblt->nYSrc); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT16(s, memblt->cacheIndex); return TRUE; } static BOOL update_read_mem3blt_order(wStream* s, const ORDER_INFO* orderInfo, MEM3BLT_ORDER* mem3blt) { ORDER_FIELD_UINT16(1, mem3blt->cacheId); ORDER_FIELD_COORD(2, mem3blt->nLeftRect); ORDER_FIELD_COORD(3, mem3blt->nTopRect); ORDER_FIELD_COORD(4, mem3blt->nWidth); ORDER_FIELD_COORD(5, mem3blt->nHeight); ORDER_FIELD_BYTE(6, mem3blt->bRop); ORDER_FIELD_COORD(7, mem3blt->nXSrc); ORDER_FIELD_COORD(8, mem3blt->nYSrc); ORDER_FIELD_COLOR(orderInfo, s, 9, &mem3blt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 10, &mem3blt->foreColor); if (!update_read_brush(s, &mem3blt->brush, orderInfo->fieldFlags >> 10)) return FALSE; ORDER_FIELD_UINT16(16, mem3blt->cacheIndex); mem3blt->colorIndex = (mem3blt->cacheId >> 8); mem3blt->cacheId = (mem3blt->cacheId & 0xFF); mem3blt->bitmap = NULL; return TRUE; } static BOOL update_read_save_bitmap_order(wStream* s, const ORDER_INFO* orderInfo, SAVE_BITMAP_ORDER* save_bitmap) { ORDER_FIELD_UINT32(1, save_bitmap->savedBitmapPosition); ORDER_FIELD_COORD(2, save_bitmap->nLeftRect); ORDER_FIELD_COORD(3, save_bitmap->nTopRect); ORDER_FIELD_COORD(4, save_bitmap->nRightRect); ORDER_FIELD_COORD(5, save_bitmap->nBottomRect); ORDER_FIELD_BYTE(6, save_bitmap->operation); return TRUE; } static BOOL update_read_glyph_index_order(wStream* s, const ORDER_INFO* orderInfo, GLYPH_INDEX_ORDER* glyph_index) { ORDER_FIELD_BYTE(1, glyph_index->cacheId); ORDER_FIELD_BYTE(2, glyph_index->flAccel); ORDER_FIELD_BYTE(3, glyph_index->ulCharInc); ORDER_FIELD_BYTE(4, glyph_index->fOpRedundant); ORDER_FIELD_COLOR(orderInfo, s, 5, &glyph_index->backColor); ORDER_FIELD_COLOR(orderInfo, s, 6, &glyph_index->foreColor); ORDER_FIELD_UINT16(7, glyph_index->bkLeft); ORDER_FIELD_UINT16(8, glyph_index->bkTop); ORDER_FIELD_UINT16(9, glyph_index->bkRight); ORDER_FIELD_UINT16(10, glyph_index->bkBottom); ORDER_FIELD_UINT16(11, glyph_index->opLeft); ORDER_FIELD_UINT16(12, glyph_index->opTop); ORDER_FIELD_UINT16(13, glyph_index->opRight); ORDER_FIELD_UINT16(14, glyph_index->opBottom); if (!update_read_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14)) return FALSE; ORDER_FIELD_UINT16(20, glyph_index->x); ORDER_FIELD_UINT16(21, glyph_index->y); if (orderInfo->fieldFlags & ORDER_FIELD_22) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, glyph_index->cbData); if (Stream_GetRemainingLength(s) < glyph_index->cbData) return FALSE; CopyMemory(glyph_index->data, Stream_Pointer(s), glyph_index->cbData); Stream_Seek(s, glyph_index->cbData); } return TRUE; } int update_approximate_glyph_index_order(ORDER_INFO* orderInfo, const GLYPH_INDEX_ORDER* glyph_index) { return 64; } BOOL update_write_glyph_index_order(wStream* s, ORDER_INFO* orderInfo, GLYPH_INDEX_ORDER* glyph_index) { int inf = update_approximate_glyph_index_order(orderInfo, glyph_index); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT8(s, glyph_index->cacheId); orderInfo->fieldFlags |= ORDER_FIELD_02; Stream_Write_UINT8(s, glyph_index->flAccel); orderInfo->fieldFlags |= ORDER_FIELD_03; Stream_Write_UINT8(s, glyph_index->ulCharInc); orderInfo->fieldFlags |= ORDER_FIELD_04; Stream_Write_UINT8(s, glyph_index->fOpRedundant); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_color(s, glyph_index->backColor); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, glyph_index->foreColor); orderInfo->fieldFlags |= ORDER_FIELD_07; Stream_Write_UINT16(s, glyph_index->bkLeft); orderInfo->fieldFlags |= ORDER_FIELD_08; Stream_Write_UINT16(s, glyph_index->bkTop); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT16(s, glyph_index->bkRight); orderInfo->fieldFlags |= ORDER_FIELD_10; Stream_Write_UINT16(s, glyph_index->bkBottom); orderInfo->fieldFlags |= ORDER_FIELD_11; Stream_Write_UINT16(s, glyph_index->opLeft); orderInfo->fieldFlags |= ORDER_FIELD_12; Stream_Write_UINT16(s, glyph_index->opTop); orderInfo->fieldFlags |= ORDER_FIELD_13; Stream_Write_UINT16(s, glyph_index->opRight); orderInfo->fieldFlags |= ORDER_FIELD_14; Stream_Write_UINT16(s, glyph_index->opBottom); orderInfo->fieldFlags |= ORDER_FIELD_15; orderInfo->fieldFlags |= ORDER_FIELD_16; orderInfo->fieldFlags |= ORDER_FIELD_17; orderInfo->fieldFlags |= ORDER_FIELD_18; orderInfo->fieldFlags |= ORDER_FIELD_19; update_write_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14); orderInfo->fieldFlags |= ORDER_FIELD_20; Stream_Write_UINT16(s, glyph_index->x); orderInfo->fieldFlags |= ORDER_FIELD_21; Stream_Write_UINT16(s, glyph_index->y); orderInfo->fieldFlags |= ORDER_FIELD_22; Stream_Write_UINT8(s, glyph_index->cbData); Stream_Write(s, glyph_index->data, glyph_index->cbData); return TRUE; } static BOOL update_read_fast_index_order(wStream* s, const ORDER_INFO* orderInfo, FAST_INDEX_ORDER* fast_index) { ORDER_FIELD_BYTE(1, fast_index->cacheId); ORDER_FIELD_2BYTE(2, fast_index->ulCharInc, fast_index->flAccel); ORDER_FIELD_COLOR(orderInfo, s, 3, &fast_index->backColor); ORDER_FIELD_COLOR(orderInfo, s, 4, &fast_index->foreColor); ORDER_FIELD_COORD(5, fast_index->bkLeft); ORDER_FIELD_COORD(6, fast_index->bkTop); ORDER_FIELD_COORD(7, fast_index->bkRight); ORDER_FIELD_COORD(8, fast_index->bkBottom); ORDER_FIELD_COORD(9, fast_index->opLeft); ORDER_FIELD_COORD(10, fast_index->opTop); ORDER_FIELD_COORD(11, fast_index->opRight); ORDER_FIELD_COORD(12, fast_index->opBottom); ORDER_FIELD_COORD(13, fast_index->x); ORDER_FIELD_COORD(14, fast_index->y); if (orderInfo->fieldFlags & ORDER_FIELD_15) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, fast_index->cbData); if (Stream_GetRemainingLength(s) < fast_index->cbData) return FALSE; CopyMemory(fast_index->data, Stream_Pointer(s), fast_index->cbData); Stream_Seek(s, fast_index->cbData); } return TRUE; } static BOOL update_read_fast_glyph_order(wStream* s, const ORDER_INFO* orderInfo, FAST_GLYPH_ORDER* fastGlyph) { BYTE* phold; GLYPH_DATA_V2* glyph = &fastGlyph->glyphData; ORDER_FIELD_BYTE(1, fastGlyph->cacheId); ORDER_FIELD_2BYTE(2, fastGlyph->ulCharInc, fastGlyph->flAccel); ORDER_FIELD_COLOR(orderInfo, s, 3, &fastGlyph->backColor); ORDER_FIELD_COLOR(orderInfo, s, 4, &fastGlyph->foreColor); ORDER_FIELD_COORD(5, fastGlyph->bkLeft); ORDER_FIELD_COORD(6, fastGlyph->bkTop); ORDER_FIELD_COORD(7, fastGlyph->bkRight); ORDER_FIELD_COORD(8, fastGlyph->bkBottom); ORDER_FIELD_COORD(9, fastGlyph->opLeft); ORDER_FIELD_COORD(10, fastGlyph->opTop); ORDER_FIELD_COORD(11, fastGlyph->opRight); ORDER_FIELD_COORD(12, fastGlyph->opBottom); ORDER_FIELD_COORD(13, fastGlyph->x); ORDER_FIELD_COORD(14, fastGlyph->y); if (orderInfo->fieldFlags & ORDER_FIELD_15) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, fastGlyph->cbData); if (Stream_GetRemainingLength(s) < fastGlyph->cbData) return FALSE; CopyMemory(fastGlyph->data, Stream_Pointer(s), fastGlyph->cbData); phold = Stream_Pointer(s); if (!Stream_SafeSeek(s, 1)) return FALSE; if (fastGlyph->cbData > 1) { UINT32 new_cb; /* parse optional glyph data */ glyph->cacheIndex = fastGlyph->data[0]; if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) || !update_read_2byte_unsigned(s, &glyph->cx) || !update_read_2byte_unsigned(s, &glyph->cy)) return FALSE; glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; new_cb = ((glyph->cx + 7) / 8) * glyph->cy; new_cb += ((new_cb % 4) > 0) ? 4 - (new_cb % 4) : 0; if (Stream_GetRemainingLength(s) < new_cb) return FALSE; if (new_cb) { BYTE* new_aj; new_aj = (BYTE*)realloc(glyph->aj, new_cb); if (!new_aj) return FALSE; glyph->aj = new_aj; glyph->cb = new_cb; Stream_Read(s, glyph->aj, glyph->cb); } } Stream_SetPointer(s, phold + fastGlyph->cbData); } return TRUE; } static BOOL update_read_polygon_sc_order(wStream* s, const ORDER_INFO* orderInfo, POLYGON_SC_ORDER* polygon_sc) { UINT32 num = polygon_sc->numPoints; ORDER_FIELD_COORD(1, polygon_sc->xStart); ORDER_FIELD_COORD(2, polygon_sc->yStart); ORDER_FIELD_BYTE(3, polygon_sc->bRop2); ORDER_FIELD_BYTE(4, polygon_sc->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_sc->brushColor); ORDER_FIELD_BYTE(6, num); if (orderInfo->fieldFlags & ORDER_FIELD_07) { DELTA_POINT* newpoints; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, polygon_sc->cbData); newpoints = (DELTA_POINT*)realloc(polygon_sc->points, sizeof(DELTA_POINT) * num); if (!newpoints) return FALSE; polygon_sc->points = newpoints; polygon_sc->numPoints = num; return update_read_delta_points(s, polygon_sc->points, polygon_sc->numPoints, polygon_sc->xStart, polygon_sc->yStart); } return TRUE; } static BOOL update_read_polygon_cb_order(wStream* s, const ORDER_INFO* orderInfo, POLYGON_CB_ORDER* polygon_cb) { UINT32 num = polygon_cb->numPoints; ORDER_FIELD_COORD(1, polygon_cb->xStart); ORDER_FIELD_COORD(2, polygon_cb->yStart); ORDER_FIELD_BYTE(3, polygon_cb->bRop2); ORDER_FIELD_BYTE(4, polygon_cb->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_cb->backColor); ORDER_FIELD_COLOR(orderInfo, s, 6, &polygon_cb->foreColor); if (!update_read_brush(s, &polygon_cb->brush, orderInfo->fieldFlags >> 6)) return FALSE; ORDER_FIELD_BYTE(12, num); if (orderInfo->fieldFlags & ORDER_FIELD_13) { DELTA_POINT* newpoints; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, polygon_cb->cbData); newpoints = (DELTA_POINT*)realloc(polygon_cb->points, sizeof(DELTA_POINT) * num); if (!newpoints) return FALSE; polygon_cb->points = newpoints; polygon_cb->numPoints = num; if (!update_read_delta_points(s, polygon_cb->points, polygon_cb->numPoints, polygon_cb->xStart, polygon_cb->yStart)) return FALSE; } polygon_cb->backMode = (polygon_cb->bRop2 & 0x80) ? BACKMODE_TRANSPARENT : BACKMODE_OPAQUE; polygon_cb->bRop2 = (polygon_cb->bRop2 & 0x1F); return TRUE; } static BOOL update_read_ellipse_sc_order(wStream* s, const ORDER_INFO* orderInfo, ELLIPSE_SC_ORDER* ellipse_sc) { ORDER_FIELD_COORD(1, ellipse_sc->leftRect); ORDER_FIELD_COORD(2, ellipse_sc->topRect); ORDER_FIELD_COORD(3, ellipse_sc->rightRect); ORDER_FIELD_COORD(4, ellipse_sc->bottomRect); ORDER_FIELD_BYTE(5, ellipse_sc->bRop2); ORDER_FIELD_BYTE(6, ellipse_sc->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_sc->color); return TRUE; } static BOOL update_read_ellipse_cb_order(wStream* s, const ORDER_INFO* orderInfo, ELLIPSE_CB_ORDER* ellipse_cb) { ORDER_FIELD_COORD(1, ellipse_cb->leftRect); ORDER_FIELD_COORD(2, ellipse_cb->topRect); ORDER_FIELD_COORD(3, ellipse_cb->rightRect); ORDER_FIELD_COORD(4, ellipse_cb->bottomRect); ORDER_FIELD_BYTE(5, ellipse_cb->bRop2); ORDER_FIELD_BYTE(6, ellipse_cb->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_cb->backColor); ORDER_FIELD_COLOR(orderInfo, s, 8, &ellipse_cb->foreColor); return update_read_brush(s, &ellipse_cb->brush, orderInfo->fieldFlags >> 8); } /* Secondary Drawing Orders */ static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { CACHE_BITMAP_ORDER* cache_bitmap; if (!update || !s) return NULL; cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER)); if (!cache_bitmap) goto fail; if (Stream_GetRemainingLength(s) < 9) goto fail; Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "", cache_bitmap->bitmapBpp); goto fail; } Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ if (compressed) { if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0) { BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ cache_bitmap->bitmapLength -= 8; } } if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength) goto fail; cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength); if (!cache_bitmap->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength); cache_bitmap->compressed = compressed; return cache_bitmap; fail: free_cache_bitmap_order(update->context, cache_bitmap); return NULL; } int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, UINT16* flags) { return 64 + cache_bitmap->bitmapLength; } BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, UINT16* flags) { UINT32 bitmapLength = cache_bitmap->bitmapLength; int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; *flags = NO_BITMAP_COMPRESSION_HDR; if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) bitmapLength += 8; Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */ Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ if (compressed) { if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) { BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ bitmapLength -= 8; } Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); } else { Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); } return TRUE; } static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { BYTE bitsPerPixelId; CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; if (!update || !s) return NULL; cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); if (!cache_bitmap_v2) goto fail; cache_bitmap_v2->cacheId = flags & 0x0003; cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; bitsPerPixelId = (flags & 0x0078) >> 3; cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId]; if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ goto fail; cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth; } else { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ goto fail; } if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */ goto fail; if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } } if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength) goto fail; if (cache_bitmap_v2->bitmapLength == 0) goto fail; cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength); if (!cache_bitmap_v2->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); cache_bitmap_v2->compressed = compressed; return cache_bitmap_v2; fail: free_cache_bitmap_v2_order(update->context, cache_bitmap_v2); return NULL; } int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, BOOL compressed, UINT16* flags) { return 64 + cache_bitmap_v2->bitmapLength; } BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, BOOL compressed, UINT16* flags) { BYTE bitsPerPixelId; if (!Stream_EnsureRemainingCapacity( s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags))) return FALSE; bitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp]; *flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) | ((cache_bitmap_v2->flags << 7) & 0xFF80); if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { Stream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ return FALSE; } else { if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ return FALSE; } if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */ return FALSE; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength)) return FALSE; Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); } else { if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength)) return FALSE; Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); } cache_bitmap_v2->compressed = compressed; return TRUE; } static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s, UINT16 flags) { BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; UINT32 new_len; BYTE* new_data; CACHE_BITMAP_V3_ORDER* cache_bitmap_v3; if (!update || !s) return NULL; cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER)); if (!cache_bitmap_v3) goto fail; cache_bitmap_v3->cacheId = flags & 0x00000003; cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7; bitsPerPixelId = (flags & 0x00000078) >> 3; cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId]; if (Stream_GetRemainingLength(s) < 21) goto fail; Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ bitmapData = &cache_bitmap_v3->bitmapData; Stream_Read_UINT8(s, bitmapData->bpp); if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp); goto fail; } Stream_Seek_UINT8(s); /* reserved1 (1 byte) */ Stream_Seek_UINT8(s); /* reserved2 (1 byte) */ Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Read_UINT32(s, new_len); /* length (4 bytes) */ if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len)) goto fail; new_data = (BYTE*)realloc(bitmapData->data, new_len); if (!new_data) goto fail; bitmapData->data = new_data; bitmapData->length = new_len; Stream_Read(s, bitmapData->data, bitmapData->length); return cache_bitmap_v3; fail: free_cache_bitmap_v3_order(update->context, cache_bitmap_v3); return NULL; } int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags) { BITMAP_DATA_EX* bitmapData = &cache_bitmap_v3->bitmapData; return 64 + bitmapData->length; } BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags) { BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; if (!Stream_EnsureRemainingCapacity( s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags))) return FALSE; bitmapData = &cache_bitmap_v3->bitmapData; bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp]; *flags = (cache_bitmap_v3->cacheId & 0x00000003) | ((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078); Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ Stream_Write_UINT8(s, bitmapData->bpp); Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */ Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */ Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */ Stream_Write(s, bitmapData->data, bitmapData->length); return TRUE; } static CACHE_COLOR_TABLE_ORDER* update_read_cache_color_table_order(rdpUpdate* update, wStream* s, UINT16 flags) { int i; UINT32* colorTable; CACHE_COLOR_TABLE_ORDER* cache_color_table = calloc(1, sizeof(CACHE_COLOR_TABLE_ORDER)); if (!cache_color_table) goto fail; if (Stream_GetRemainingLength(s) < 3) goto fail; Stream_Read_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */ Stream_Read_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */ if (cache_color_table->numberColors != 256) { /* This field MUST be set to 256 */ goto fail; } if (Stream_GetRemainingLength(s) < cache_color_table->numberColors * 4) goto fail; colorTable = (UINT32*)&cache_color_table->colorTable; for (i = 0; i < (int)cache_color_table->numberColors; i++) update_read_color_quad(s, &colorTable[i]); return cache_color_table; fail: free_cache_color_table_order(update->context, cache_color_table); return NULL; } int update_approximate_cache_color_table_order(const CACHE_COLOR_TABLE_ORDER* cache_color_table, UINT16* flags) { return 16 + (256 * 4); } BOOL update_write_cache_color_table_order(wStream* s, const CACHE_COLOR_TABLE_ORDER* cache_color_table, UINT16* flags) { int i, inf; UINT32* colorTable; if (cache_color_table->numberColors != 256) return FALSE; inf = update_approximate_cache_color_table_order(cache_color_table, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */ Stream_Write_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */ colorTable = (UINT32*)&cache_color_table->colorTable; for (i = 0; i < (int)cache_color_table->numberColors; i++) { update_write_color_quad(s, colorTable[i]); } return TRUE; } static CACHE_GLYPH_ORDER* update_read_cache_glyph_order(rdpUpdate* update, wStream* s, UINT16 flags) { UINT32 i; CACHE_GLYPH_ORDER* cache_glyph_order = calloc(1, sizeof(CACHE_GLYPH_ORDER)); if (!cache_glyph_order || !update || !s) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT8(s, cache_glyph_order->cacheId); /* cacheId (1 byte) */ Stream_Read_UINT8(s, cache_glyph_order->cGlyphs); /* cGlyphs (1 byte) */ for (i = 0; i < cache_glyph_order->cGlyphs; i++) { GLYPH_DATA* glyph = &cache_glyph_order->glyphData[i]; if (Stream_GetRemainingLength(s) < 10) goto fail; Stream_Read_UINT16(s, glyph->cacheIndex); Stream_Read_INT16(s, glyph->x); Stream_Read_INT16(s, glyph->y); Stream_Read_UINT16(s, glyph->cx); Stream_Read_UINT16(s, glyph->cy); glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; if (Stream_GetRemainingLength(s) < glyph->cb) goto fail; glyph->aj = (BYTE*)malloc(glyph->cb); if (!glyph->aj) goto fail; Stream_Read(s, glyph->aj, glyph->cb); } if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_order->cGlyphs > 0)) { cache_glyph_order->unicodeCharacters = calloc(cache_glyph_order->cGlyphs, sizeof(WCHAR)); if (!cache_glyph_order->unicodeCharacters) goto fail; if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_order->cGlyphs) goto fail; Stream_Read_UTF16_String(s, cache_glyph_order->unicodeCharacters, cache_glyph_order->cGlyphs); } return cache_glyph_order; fail: free_cache_glyph_order(update->context, cache_glyph_order); return NULL; } int update_approximate_cache_glyph_order(const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags) { return 2 + cache_glyph->cGlyphs * 32; } BOOL update_write_cache_glyph_order(wStream* s, const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags) { int i, inf; INT16 lsi16; const GLYPH_DATA* glyph; inf = update_approximate_cache_glyph_order(cache_glyph, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT8(s, cache_glyph->cacheId); /* cacheId (1 byte) */ Stream_Write_UINT8(s, cache_glyph->cGlyphs); /* cGlyphs (1 byte) */ for (i = 0; i < (int)cache_glyph->cGlyphs; i++) { UINT32 cb; glyph = &cache_glyph->glyphData[i]; Stream_Write_UINT16(s, glyph->cacheIndex); /* cacheIndex (2 bytes) */ lsi16 = glyph->x; Stream_Write_UINT16(s, lsi16); /* x (2 bytes) */ lsi16 = glyph->y; Stream_Write_UINT16(s, lsi16); /* y (2 bytes) */ Stream_Write_UINT16(s, glyph->cx); /* cx (2 bytes) */ Stream_Write_UINT16(s, glyph->cy); /* cy (2 bytes) */ cb = ((glyph->cx + 7) / 8) * glyph->cy; cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0; Stream_Write(s, glyph->aj, cb); } if (*flags & CG_GLYPH_UNICODE_PRESENT) { Stream_Zero(s, cache_glyph->cGlyphs * 2); } return TRUE; } static CACHE_GLYPH_V2_ORDER* update_read_cache_glyph_v2_order(rdpUpdate* update, wStream* s, UINT16 flags) { UINT32 i; CACHE_GLYPH_V2_ORDER* cache_glyph_v2 = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER)); if (!cache_glyph_v2) goto fail; cache_glyph_v2->cacheId = (flags & 0x000F); cache_glyph_v2->flags = (flags & 0x00F0) >> 4; cache_glyph_v2->cGlyphs = (flags & 0xFF00) >> 8; for (i = 0; i < cache_glyph_v2->cGlyphs; i++) { GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i]; if (Stream_GetRemainingLength(s) < 1) goto fail; Stream_Read_UINT8(s, glyph->cacheIndex); if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) || !update_read_2byte_unsigned(s, &glyph->cx) || !update_read_2byte_unsigned(s, &glyph->cy)) { goto fail; } glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; if (Stream_GetRemainingLength(s) < glyph->cb) goto fail; glyph->aj = (BYTE*)malloc(glyph->cb); if (!glyph->aj) goto fail; Stream_Read(s, glyph->aj, glyph->cb); } if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_v2->cGlyphs > 0)) { cache_glyph_v2->unicodeCharacters = calloc(cache_glyph_v2->cGlyphs, sizeof(WCHAR)); if (!cache_glyph_v2->unicodeCharacters) goto fail; if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_v2->cGlyphs) goto fail; Stream_Read_UTF16_String(s, cache_glyph_v2->unicodeCharacters, cache_glyph_v2->cGlyphs); } return cache_glyph_v2; fail: free_cache_glyph_v2_order(update->context, cache_glyph_v2); return NULL; } int update_approximate_cache_glyph_v2_order(const CACHE_GLYPH_V2_ORDER* cache_glyph_v2, UINT16* flags) { return 8 + cache_glyph_v2->cGlyphs * 32; } BOOL update_write_cache_glyph_v2_order(wStream* s, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2, UINT16* flags) { UINT32 i, inf; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; *flags = (cache_glyph_v2->cacheId & 0x000F) | ((cache_glyph_v2->flags & 0x000F) << 4) | ((cache_glyph_v2->cGlyphs & 0x00FF) << 8); for (i = 0; i < cache_glyph_v2->cGlyphs; i++) { UINT32 cb; const GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i]; Stream_Write_UINT8(s, glyph->cacheIndex); if (!update_write_2byte_signed(s, glyph->x) || !update_write_2byte_signed(s, glyph->y) || !update_write_2byte_unsigned(s, glyph->cx) || !update_write_2byte_unsigned(s, glyph->cy)) { return FALSE; } cb = ((glyph->cx + 7) / 8) * glyph->cy; cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0; Stream_Write(s, glyph->aj, cb); } if (*flags & CG_GLYPH_UNICODE_PRESENT) { Stream_Zero(s, cache_glyph_v2->cGlyphs * 2); } return TRUE; } static BOOL update_decompress_brush(wStream* s, BYTE* output, BYTE bpp) { int index; int x, y, k; BYTE byte = 0; BYTE* palette; int bytesPerPixel; palette = Stream_Pointer(s) + 16; bytesPerPixel = ((bpp + 1) / 8); if (Stream_GetRemainingLength(s) < 16) // 64 / 4 return FALSE; for (y = 7; y >= 0; y--) { for (x = 0; x < 8; x++) { if ((x % 4) == 0) Stream_Read_UINT8(s, byte); index = ((byte >> ((3 - (x % 4)) * 2)) & 0x03); for (k = 0; k < bytesPerPixel; k++) { output[((y * 8 + x) * bytesPerPixel) + k] = palette[(index * bytesPerPixel) + k]; } } } return TRUE; } static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp) { return FALSE; } static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags) { int i; BYTE iBitmapFormat; BOOL compressed = FALSE; CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER)); if (!cache_brush) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ if (iBitmapFormat > ARRAYSIZE(BMF_BPP)) goto fail; cache_brush->bpp = BMF_BPP[iBitmapFormat]; Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Read_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_Print(update->log, WLOG_ERROR, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); goto fail; } /* rows are encoded in reverse order */ if (Stream_GetRemainingLength(s) < 8) goto fail; for (i = 7; i >= 0; i--) { Stream_Read_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_decompress_brush(s, cache_brush->data, cache_brush->bpp)) goto fail; } else { /* uncompressed brush */ UINT32 scanline = (cache_brush->bpp / 8) * 8; if (Stream_GetRemainingLength(s) < scanline * 8) goto fail; for (i = 7; i >= 0; i--) { Stream_Read(s, &cache_brush->data[i * scanline], scanline); } } } } return cache_brush; fail: free_cache_brush_order(update->context, cache_brush); return NULL; } int update_approximate_cache_brush_order(const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { return 64; } BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { int i; BYTE iBitmapFormat; BOOL compressed = FALSE; if (!Stream_EnsureRemainingCapacity(s, update_approximate_cache_brush_order(cache_brush, flags))) return FALSE; iBitmapFormat = BPP_BMF[cache_brush->bpp]; Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); return FALSE; } for (i = 7; i >= 0; i--) { Stream_Write_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp)) return FALSE; } else { /* uncompressed brush */ int scanline = (cache_brush->bpp / 8) * 8; for (i = 7; i >= 0; i--) { Stream_Write(s, &cache_brush->data[i * scanline], scanline); } } } } return TRUE; } /* Alternate Secondary Drawing Orders */ static BOOL update_read_create_offscreen_bitmap_order(wStream* s, CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { UINT16 flags; BOOL deleteListPresent; OFFSCREEN_DELETE_LIST* deleteList; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT16(s, flags); /* flags (2 bytes) */ create_offscreen_bitmap->id = flags & 0x7FFF; deleteListPresent = (flags & 0x8000) ? TRUE : FALSE; Stream_Read_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */ Stream_Read_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */ deleteList = &(create_offscreen_bitmap->deleteList); if (deleteListPresent) { UINT32 i; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, deleteList->cIndices); if (deleteList->cIndices > deleteList->sIndices) { UINT16* new_indices; new_indices = (UINT16*)realloc(deleteList->indices, deleteList->cIndices * 2); if (!new_indices) return FALSE; deleteList->sIndices = deleteList->cIndices; deleteList->indices = new_indices; } if (Stream_GetRemainingLength(s) < 2 * deleteList->cIndices) return FALSE; for (i = 0; i < deleteList->cIndices; i++) { Stream_Read_UINT16(s, deleteList->indices[i]); } } else { deleteList->cIndices = 0; } return TRUE; } int update_approximate_create_offscreen_bitmap_order( const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { const OFFSCREEN_DELETE_LIST* deleteList = &(create_offscreen_bitmap->deleteList); return 32 + deleteList->cIndices * 2; } BOOL update_write_create_offscreen_bitmap_order( wStream* s, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { UINT16 flags; BOOL deleteListPresent; const OFFSCREEN_DELETE_LIST* deleteList; if (!Stream_EnsureRemainingCapacity( s, update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap))) return FALSE; deleteList = &(create_offscreen_bitmap->deleteList); flags = create_offscreen_bitmap->id & 0x7FFF; deleteListPresent = (deleteList->cIndices > 0) ? TRUE : FALSE; if (deleteListPresent) flags |= 0x8000; Stream_Write_UINT16(s, flags); /* flags (2 bytes) */ Stream_Write_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */ Stream_Write_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */ if (deleteListPresent) { int i; Stream_Write_UINT16(s, deleteList->cIndices); for (i = 0; i < (int)deleteList->cIndices; i++) { Stream_Write_UINT16(s, deleteList->indices[i]); } } return TRUE; } static BOOL update_read_switch_surface_order(wStream* s, SWITCH_SURFACE_ORDER* switch_surface) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */ return TRUE; } int update_approximate_switch_surface_order(const SWITCH_SURFACE_ORDER* switch_surface) { return 2; } BOOL update_write_switch_surface_order(wStream* s, const SWITCH_SURFACE_ORDER* switch_surface) { int inf = update_approximate_switch_surface_order(switch_surface); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */ return TRUE; } static BOOL update_read_create_nine_grid_bitmap_order(wStream* s, CREATE_NINE_GRID_BITMAP_ORDER* create_nine_grid_bitmap) { NINE_GRID_BITMAP_INFO* nineGridInfo; if (Stream_GetRemainingLength(s) < 19) return FALSE; Stream_Read_UINT8(s, create_nine_grid_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ if ((create_nine_grid_bitmap->bitmapBpp < 1) || (create_nine_grid_bitmap->bitmapBpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", create_nine_grid_bitmap->bitmapBpp); return FALSE; } Stream_Read_UINT16(s, create_nine_grid_bitmap->bitmapId); /* bitmapId (2 bytes) */ nineGridInfo = &(create_nine_grid_bitmap->nineGridInfo); Stream_Read_UINT32(s, nineGridInfo->flFlags); /* flFlags (4 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulLeftWidth); /* ulLeftWidth (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulRightWidth); /* ulRightWidth (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulTopHeight); /* ulTopHeight (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulBottomHeight); /* ulBottomHeight (2 bytes) */ update_read_colorref(s, &nineGridInfo->crTransparent); /* crTransparent (4 bytes) */ return TRUE; } static BOOL update_read_frame_marker_order(wStream* s, FRAME_MARKER_ORDER* frame_marker) { if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, frame_marker->action); /* action (4 bytes) */ return TRUE; } static BOOL update_read_stream_bitmap_first_order(wStream* s, STREAM_BITMAP_FIRST_ORDER* stream_bitmap_first) { if (Stream_GetRemainingLength(s) < 10) // 8 + 2 at least return FALSE; Stream_Read_UINT8(s, stream_bitmap_first->bitmapFlags); /* bitmapFlags (1 byte) */ Stream_Read_UINT8(s, stream_bitmap_first->bitmapBpp); /* bitmapBpp (1 byte) */ if ((stream_bitmap_first->bitmapBpp < 1) || (stream_bitmap_first->bitmapBpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", stream_bitmap_first->bitmapBpp); return FALSE; } Stream_Read_UINT16(s, stream_bitmap_first->bitmapType); /* bitmapType (2 bytes) */ Stream_Read_UINT16(s, stream_bitmap_first->bitmapWidth); /* bitmapWidth (2 bytes) */ Stream_Read_UINT16(s, stream_bitmap_first->bitmapHeight); /* bitmapHeigth (2 bytes) */ if (stream_bitmap_first->bitmapFlags & STREAM_BITMAP_V2) { if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, stream_bitmap_first->bitmapSize); /* bitmapSize (4 bytes) */ } else { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, stream_bitmap_first->bitmapSize); /* bitmapSize (2 bytes) */ } FIELD_SKIP_BUFFER16( s, stream_bitmap_first->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */ return TRUE; } static BOOL update_read_stream_bitmap_next_order(wStream* s, STREAM_BITMAP_NEXT_ORDER* stream_bitmap_next) { if (Stream_GetRemainingLength(s) < 5) return FALSE; Stream_Read_UINT8(s, stream_bitmap_next->bitmapFlags); /* bitmapFlags (1 byte) */ Stream_Read_UINT16(s, stream_bitmap_next->bitmapType); /* bitmapType (2 bytes) */ FIELD_SKIP_BUFFER16( s, stream_bitmap_next->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */ return TRUE; } static BOOL update_read_draw_gdiplus_first_order(wStream* s, DRAW_GDIPLUS_FIRST_ORDER* draw_gdiplus_first) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_first->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalSize); /* cbTotalSize (4 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_first->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_next_order(wStream* s, DRAW_GDIPLUS_NEXT_ORDER* draw_gdiplus_next) { if (Stream_GetRemainingLength(s) < 3) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ FIELD_SKIP_BUFFER16(s, draw_gdiplus_next->cbSize); /* cbSize(2 bytes) + emfRecords */ return TRUE; } static BOOL update_read_draw_gdiplus_end_order(wStream* s, DRAW_GDIPLUS_END_ORDER* draw_gdiplus_end) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_end->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalSize); /* cbTotalSize (4 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_end->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_cache_first_order(wStream* s, DRAW_GDIPLUS_CACHE_FIRST_ORDER* draw_gdiplus_cache_first) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_first->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_cache_first->cbTotalSize); /* cbTotalSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_cache_first->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_cache_next_order(wStream* s, DRAW_GDIPLUS_CACHE_NEXT_ORDER* draw_gdiplus_cache_next) { if (Stream_GetRemainingLength(s) < 7) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_next->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheIndex); /* cacheIndex (2 bytes) */ FIELD_SKIP_BUFFER16(s, draw_gdiplus_cache_next->cbSize); /* cbSize(2 bytes) + emfRecords */ return TRUE; } static BOOL update_read_draw_gdiplus_cache_end_order(wStream* s, DRAW_GDIPLUS_CACHE_END_ORDER* draw_gdiplus_cache_end) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_end->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_cache_end->cbTotalSize); /* cbTotalSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_cache_end->cbSize); /* emfRecords */ } static BOOL update_read_field_flags(wStream* s, UINT32* fieldFlags, BYTE flags, BYTE fieldBytes) { int i; BYTE byte; if (flags & ORDER_ZERO_FIELD_BYTE_BIT0) fieldBytes--; if (flags & ORDER_ZERO_FIELD_BYTE_BIT1) { if (fieldBytes > 1) fieldBytes -= 2; else fieldBytes = 0; } if (Stream_GetRemainingLength(s) < fieldBytes) return FALSE; *fieldFlags = 0; for (i = 0; i < fieldBytes; i++) { Stream_Read_UINT8(s, byte); *fieldFlags |= byte << (i * 8); } return TRUE; } BOOL update_write_field_flags(wStream* s, UINT32 fieldFlags, BYTE flags, BYTE fieldBytes) { BYTE byte; if (fieldBytes == 1) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); } else if (fieldBytes == 2) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 8) & 0xFF; Stream_Write_UINT8(s, byte); } else if (fieldBytes == 3) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 16) & 0xFF; Stream_Write_UINT8(s, byte); } else { return FALSE; } return TRUE; } static BOOL update_read_bounds(wStream* s, rdpBounds* bounds) { BYTE flags; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, flags); /* field flags */ if (flags & BOUND_LEFT) { if (!update_read_coord(s, &bounds->left, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_LEFT) { if (!update_read_coord(s, &bounds->left, TRUE)) return FALSE; } if (flags & BOUND_TOP) { if (!update_read_coord(s, &bounds->top, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_TOP) { if (!update_read_coord(s, &bounds->top, TRUE)) return FALSE; } if (flags & BOUND_RIGHT) { if (!update_read_coord(s, &bounds->right, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_RIGHT) { if (!update_read_coord(s, &bounds->right, TRUE)) return FALSE; } if (flags & BOUND_BOTTOM) { if (!update_read_coord(s, &bounds->bottom, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_BOTTOM) { if (!update_read_coord(s, &bounds->bottom, TRUE)) return FALSE; } return TRUE; } BOOL update_write_bounds(wStream* s, ORDER_INFO* orderInfo) { if (!(orderInfo->controlFlags & ORDER_BOUNDS)) return TRUE; if (orderInfo->controlFlags & ORDER_ZERO_BOUNDS_DELTAS) return TRUE; Stream_Write_UINT8(s, orderInfo->boundsFlags); /* field flags */ if (orderInfo->boundsFlags & BOUND_LEFT) { if (!update_write_coord(s, orderInfo->bounds.left)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_LEFT) { } if (orderInfo->boundsFlags & BOUND_TOP) { if (!update_write_coord(s, orderInfo->bounds.top)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_TOP) { } if (orderInfo->boundsFlags & BOUND_RIGHT) { if (!update_write_coord(s, orderInfo->bounds.right)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_RIGHT) { } if (orderInfo->boundsFlags & BOUND_BOTTOM) { if (!update_write_coord(s, orderInfo->bounds.bottom)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_BOTTOM) { } return TRUE; } static BOOL read_primary_order(wLog* log, const char* orderName, wStream* s, const ORDER_INFO* orderInfo, rdpPrimaryUpdate* primary) { BOOL rc = FALSE; if (!s || !orderInfo || !primary || !orderName) return FALSE; switch (orderInfo->orderType) { case ORDER_TYPE_DSTBLT: rc = update_read_dstblt_order(s, orderInfo, &(primary->dstblt)); break; case ORDER_TYPE_PATBLT: rc = update_read_patblt_order(s, orderInfo, &(primary->patblt)); break; case ORDER_TYPE_SCRBLT: rc = update_read_scrblt_order(s, orderInfo, &(primary->scrblt)); break; case ORDER_TYPE_OPAQUE_RECT: rc = update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect)); break; case ORDER_TYPE_DRAW_NINE_GRID: rc = update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid)); break; case ORDER_TYPE_MULTI_DSTBLT: rc = update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt)); break; case ORDER_TYPE_MULTI_PATBLT: rc = update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt)); break; case ORDER_TYPE_MULTI_SCRBLT: rc = update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt)); break; case ORDER_TYPE_MULTI_OPAQUE_RECT: rc = update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect)); break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: rc = update_read_multi_draw_nine_grid_order(s, orderInfo, &(primary->multi_draw_nine_grid)); break; case ORDER_TYPE_LINE_TO: rc = update_read_line_to_order(s, orderInfo, &(primary->line_to)); break; case ORDER_TYPE_POLYLINE: rc = update_read_polyline_order(s, orderInfo, &(primary->polyline)); break; case ORDER_TYPE_MEMBLT: rc = update_read_memblt_order(s, orderInfo, &(primary->memblt)); break; case ORDER_TYPE_MEM3BLT: rc = update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt)); break; case ORDER_TYPE_SAVE_BITMAP: rc = update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap)); break; case ORDER_TYPE_GLYPH_INDEX: rc = update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index)); break; case ORDER_TYPE_FAST_INDEX: rc = update_read_fast_index_order(s, orderInfo, &(primary->fast_index)); break; case ORDER_TYPE_FAST_GLYPH: rc = update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph)); break; case ORDER_TYPE_POLYGON_SC: rc = update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc)); break; case ORDER_TYPE_POLYGON_CB: rc = update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb)); break; case ORDER_TYPE_ELLIPSE_SC: rc = update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc)); break; case ORDER_TYPE_ELLIPSE_CB: rc = update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb)); break; default: WLog_Print(log, WLOG_WARN, "Primary Drawing Order %s not supported, ignoring", orderName); rc = TRUE; break; } if (!rc) { WLog_Print(log, WLOG_ERROR, "%s - update_read_dstblt_order() failed", orderName); return FALSE; } return TRUE; } static BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; rdpContext* context = update->context; rdpPrimaryUpdate* primary = update->primary; ORDER_INFO* orderInfo = &(primary->order_info); rdpSettings* settings = context->settings; const char* orderName; if (flags & ORDER_TYPE_CHANGE) { if (Stream_GetRemainingLength(s) < 1) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ } orderName = primary_order_string(orderInfo->orderType); if (!check_primary_order_supported(update->log, settings, orderInfo->orderType, orderName)) return FALSE; if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType])) { WLog_Print(update->log, WLOG_ERROR, "update_read_field_flags() failed"); return FALSE; } if (flags & ORDER_BOUNDS) { if (!(flags & ORDER_ZERO_BOUNDS_DELTAS)) { if (!update_read_bounds(s, &orderInfo->bounds)) { WLog_Print(update->log, WLOG_ERROR, "update_read_bounds() failed"); return FALSE; } } rc = IFCALLRESULT(FALSE, update->SetBounds, context, &orderInfo->bounds); if (!rc) return FALSE; } orderInfo->deltaCoordinates = (flags & ORDER_DELTA_COORDINATES) ? TRUE : FALSE; if (!read_primary_order(update->log, orderName, s, orderInfo, primary)) return FALSE; switch (orderInfo->orderType) { case ORDER_TYPE_DSTBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->dstblt.bRop), gdi_rop3_code(primary->dstblt.bRop)); rc = IFCALLRESULT(FALSE, primary->DstBlt, context, &primary->dstblt); } break; case ORDER_TYPE_PATBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->patblt.bRop), gdi_rop3_code(primary->patblt.bRop)); rc = IFCALLRESULT(FALSE, primary->PatBlt, context, &primary->patblt); } break; case ORDER_TYPE_SCRBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->scrblt.bRop), gdi_rop3_code(primary->scrblt.bRop)); rc = IFCALLRESULT(FALSE, primary->ScrBlt, context, &primary->scrblt); } break; case ORDER_TYPE_OPAQUE_RECT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->OpaqueRect, context, &primary->opaque_rect); } break; case ORDER_TYPE_DRAW_NINE_GRID: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->DrawNineGrid, context, &primary->draw_nine_grid); } break; case ORDER_TYPE_MULTI_DSTBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_dstblt.bRop), gdi_rop3_code(primary->multi_dstblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiDstBlt, context, &primary->multi_dstblt); } break; case ORDER_TYPE_MULTI_PATBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_patblt.bRop), gdi_rop3_code(primary->multi_patblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiPatBlt, context, &primary->multi_patblt); } break; case ORDER_TYPE_MULTI_SCRBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_scrblt.bRop), gdi_rop3_code(primary->multi_scrblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiScrBlt, context, &primary->multi_scrblt); } break; case ORDER_TYPE_MULTI_OPAQUE_RECT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->MultiOpaqueRect, context, &primary->multi_opaque_rect); } break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->MultiDrawNineGrid, context, &primary->multi_draw_nine_grid); } break; case ORDER_TYPE_LINE_TO: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->LineTo, context, &primary->line_to); } break; case ORDER_TYPE_POLYLINE: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->Polyline, context, &primary->polyline); } break; case ORDER_TYPE_MEMBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->memblt.bRop), gdi_rop3_code(primary->memblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MemBlt, context, &primary->memblt); } break; case ORDER_TYPE_MEM3BLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->mem3blt.bRop), gdi_rop3_code(primary->mem3blt.bRop)); rc = IFCALLRESULT(FALSE, primary->Mem3Blt, context, &primary->mem3blt); } break; case ORDER_TYPE_SAVE_BITMAP: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->SaveBitmap, context, &primary->save_bitmap); } break; case ORDER_TYPE_GLYPH_INDEX: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->GlyphIndex, context, &primary->glyph_index); } break; case ORDER_TYPE_FAST_INDEX: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->FastIndex, context, &primary->fast_index); } break; case ORDER_TYPE_FAST_GLYPH: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->FastGlyph, context, &primary->fast_glyph); } break; case ORDER_TYPE_POLYGON_SC: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->PolygonSC, context, &primary->polygon_sc); } break; case ORDER_TYPE_POLYGON_CB: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->PolygonCB, context, &primary->polygon_cb); } break; case ORDER_TYPE_ELLIPSE_SC: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->EllipseSC, context, &primary->ellipse_sc); } break; case ORDER_TYPE_ELLIPSE_CB: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->EllipseCB, context, &primary->ellipse_cb); } break; default: WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s not supported", orderName); break; } if (!rc) { WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s failed", orderName); return FALSE; } if (flags & ORDER_BOUNDS) { rc = IFCALLRESULT(FALSE, update->SetBounds, context, NULL); } return rc; } static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; BYTE* next; BYTE orderType; UINT16 extraFlags; UINT16 orderLength; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpSecondaryUpdate* secondary = update->secondary; const char* name; if (Stream_GetRemainingLength(s) < 5) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5"); return FALSE; } Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */ next = Stream_Pointer(s) + ((INT16)orderLength) + 7; name = secondary_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name); if (!check_secondary_order_supported(update->log, settings, orderType, name)) return FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: { const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED); CACHE_BITMAP_ORDER* order = update_read_cache_bitmap_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order); free_cache_bitmap_order(context, order); } } break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: { const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2); CACHE_BITMAP_V2_ORDER* order = update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order); free_cache_bitmap_v2_order(context, order); } } break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: { CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order); free_cache_bitmap_v3_order(context, order); } } break; case ORDER_TYPE_CACHE_COLOR_TABLE: { CACHE_COLOR_TABLE_ORDER* order = update_read_cache_color_table_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order); free_cache_color_table_order(context, order); } } break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: { CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order); free_cache_glyph_order(context, order); } } break; case GLYPH_SUPPORT_ENCODE: { CACHE_GLYPH_V2_ORDER* order = update_read_cache_glyph_v2_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order); free_cache_glyph_v2_order(context, order); } } break; case GLYPH_SUPPORT_NONE: default: break; } } break; case ORDER_TYPE_CACHE_BRUSH: /* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */ { CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order); free_cache_brush_order(context, order); } } break; default: WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name); break; } if (!rc) { WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name); } Stream_SetPointer(s, next); return rc; } static BOOL read_altsec_order(wStream* s, BYTE orderType, rdpAltSecUpdate* altsec) { BOOL rc = FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: rc = update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: rc = update_read_switch_surface_order(s, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: rc = update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: rc = update_read_frame_marker_order(s, &(altsec->frame_marker)); break; case ORDER_TYPE_STREAM_BITMAP_FIRST: rc = update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: rc = update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: rc = update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: rc = update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: rc = update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: rc = update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: rc = update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: rc = update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end)); break; case ORDER_TYPE_WINDOW: /* This order is handled elsewhere. */ rc = TRUE; break; case ORDER_TYPE_COMPDESK_FIRST: rc = TRUE; break; default: break; } return rc; } static BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags) { BYTE orderType = flags >>= 2; /* orderType is in higher 6 bits of flags field */ BOOL rc = FALSE; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpAltSecUpdate* altsec = update->altsec; const char* orderName = altsec_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Alternate Secondary Drawing Order %s", orderName); if (!check_alt_order_supported(update->log, settings, orderType, orderName)) return FALSE; if (!read_altsec_order(s, orderType, altsec)) return FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: IFCALLRET(altsec->CreateOffscreenBitmap, rc, context, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: IFCALLRET(altsec->SwitchSurface, rc, context, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: IFCALLRET(altsec->CreateNineGridBitmap, rc, context, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: IFCALLRET(altsec->FrameMarker, rc, context, &(altsec->frame_marker)); break; case ORDER_TYPE_STREAM_BITMAP_FIRST: IFCALLRET(altsec->StreamBitmapFirst, rc, context, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: IFCALLRET(altsec->StreamBitmapNext, rc, context, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: IFCALLRET(altsec->DrawGdiPlusFirst, rc, context, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: IFCALLRET(altsec->DrawGdiPlusNext, rc, context, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: IFCALLRET(altsec->DrawGdiPlusEnd, rc, context, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: IFCALLRET(altsec->DrawGdiPlusCacheFirst, rc, context, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: IFCALLRET(altsec->DrawGdiPlusCacheNext, rc, context, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: IFCALLRET(altsec->DrawGdiPlusCacheEnd, rc, context, &(altsec->draw_gdiplus_cache_end)); break; case ORDER_TYPE_WINDOW: rc = update_recv_altsec_window_order(update, s); break; case ORDER_TYPE_COMPDESK_FIRST: rc = TRUE; break; default: break; } if (!rc) { WLog_Print(update->log, WLOG_WARN, "Alternate Secondary Drawing Order %s failed", orderName); } return rc; } BOOL update_recv_order(rdpUpdate* update, wStream* s) { BOOL rc; BYTE controlFlags; if (Stream_GetRemainingLength(s) < 1) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */ if (!(controlFlags & ORDER_STANDARD)) rc = update_recv_altsec_order(update, s, controlFlags); else if (controlFlags & ORDER_SECONDARY) rc = update_recv_secondary_order(update, s, controlFlags); else rc = update_recv_primary_order(update, s, controlFlags); if (!rc) WLog_Print(update->log, WLOG_ERROR, "order flags %02" PRIx8 " failed", controlFlags); return rc; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_3906_0
crossvul-cpp_data_bad_349_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_349_0
crossvul-cpp_data_bad_349_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_349_6
crossvul-cpp_data_good_633_0
/* * Common Block IO controller cgroup interface * * Based on ideas and code from CFQ, CFS and BFQ: * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk> * * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it> * Paolo Valente <paolo.valente@unimore.it> * * Copyright (C) 2009 Vivek Goyal <vgoyal@redhat.com> * Nauman Rafique <nauman@google.com> * * For policy-specific per-blkcg data: * Copyright (C) 2015 Paolo Valente <paolo.valente@unimore.it> * Arianna Avanzini <avanzini.arianna@gmail.com> */ #include <linux/ioprio.h> #include <linux/kdev_t.h> #include <linux/module.h> #include <linux/err.h> #include <linux/blkdev.h> #include <linux/backing-dev.h> #include <linux/slab.h> #include <linux/genhd.h> #include <linux/delay.h> #include <linux/atomic.h> #include <linux/ctype.h> #include <linux/blk-cgroup.h> #include "blk.h" #define MAX_KEY_LEN 100 /* * blkcg_pol_mutex protects blkcg_policy[] and policy [de]activation. * blkcg_pol_register_mutex nests outside of it and synchronizes entire * policy [un]register operations including cgroup file additions / * removals. Putting cgroup file registration outside blkcg_pol_mutex * allows grabbing it from cgroup callbacks. */ static DEFINE_MUTEX(blkcg_pol_register_mutex); static DEFINE_MUTEX(blkcg_pol_mutex); struct blkcg blkcg_root; EXPORT_SYMBOL_GPL(blkcg_root); struct cgroup_subsys_state * const blkcg_root_css = &blkcg_root.css; static struct blkcg_policy *blkcg_policy[BLKCG_MAX_POLS]; static LIST_HEAD(all_blkcgs); /* protected by blkcg_pol_mutex */ static bool blkcg_policy_enabled(struct request_queue *q, const struct blkcg_policy *pol) { return pol && test_bit(pol->plid, q->blkcg_pols); } /** * blkg_free - free a blkg * @blkg: blkg to free * * Free @blkg which may be partially allocated. */ static void blkg_free(struct blkcg_gq *blkg) { int i; if (!blkg) return; for (i = 0; i < BLKCG_MAX_POLS; i++) if (blkg->pd[i]) blkcg_policy[i]->pd_free_fn(blkg->pd[i]); if (blkg->blkcg != &blkcg_root) blk_exit_rl(&blkg->rl); blkg_rwstat_exit(&blkg->stat_ios); blkg_rwstat_exit(&blkg->stat_bytes); kfree(blkg); } /** * blkg_alloc - allocate a blkg * @blkcg: block cgroup the new blkg is associated with * @q: request_queue the new blkg is associated with * @gfp_mask: allocation mask to use * * Allocate a new blkg assocating @blkcg and @q. */ static struct blkcg_gq *blkg_alloc(struct blkcg *blkcg, struct request_queue *q, gfp_t gfp_mask) { struct blkcg_gq *blkg; int i; /* alloc and init base part */ blkg = kzalloc_node(sizeof(*blkg), gfp_mask, q->node); if (!blkg) return NULL; if (blkg_rwstat_init(&blkg->stat_bytes, gfp_mask) || blkg_rwstat_init(&blkg->stat_ios, gfp_mask)) goto err_free; blkg->q = q; INIT_LIST_HEAD(&blkg->q_node); blkg->blkcg = blkcg; atomic_set(&blkg->refcnt, 1); /* root blkg uses @q->root_rl, init rl only for !root blkgs */ if (blkcg != &blkcg_root) { if (blk_init_rl(&blkg->rl, q, gfp_mask)) goto err_free; blkg->rl.blkg = blkg; } for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; struct blkg_policy_data *pd; if (!blkcg_policy_enabled(q, pol)) continue; /* alloc per-policy data and attach it to blkg */ pd = pol->pd_alloc_fn(gfp_mask, q->node); if (!pd) goto err_free; blkg->pd[i] = pd; pd->blkg = blkg; pd->plid = i; } return blkg; err_free: blkg_free(blkg); return NULL; } struct blkcg_gq *blkg_lookup_slowpath(struct blkcg *blkcg, struct request_queue *q, bool update_hint) { struct blkcg_gq *blkg; /* * Hint didn't match. Look up from the radix tree. Note that the * hint can only be updated under queue_lock as otherwise @blkg * could have already been removed from blkg_tree. The caller is * responsible for grabbing queue_lock if @update_hint. */ blkg = radix_tree_lookup(&blkcg->blkg_tree, q->id); if (blkg && blkg->q == q) { if (update_hint) { lockdep_assert_held(q->queue_lock); rcu_assign_pointer(blkcg->blkg_hint, blkg); } return blkg; } return NULL; } EXPORT_SYMBOL_GPL(blkg_lookup_slowpath); /* * If @new_blkg is %NULL, this function tries to allocate a new one as * necessary using %GFP_NOWAIT. @new_blkg is always consumed on return. */ static struct blkcg_gq *blkg_create(struct blkcg *blkcg, struct request_queue *q, struct blkcg_gq *new_blkg) { struct blkcg_gq *blkg; struct bdi_writeback_congested *wb_congested; int i, ret; WARN_ON_ONCE(!rcu_read_lock_held()); lockdep_assert_held(q->queue_lock); /* blkg holds a reference to blkcg */ if (!css_tryget_online(&blkcg->css)) { ret = -ENODEV; goto err_free_blkg; } wb_congested = wb_congested_get_create(q->backing_dev_info, blkcg->css.id, GFP_NOWAIT | __GFP_NOWARN); if (!wb_congested) { ret = -ENOMEM; goto err_put_css; } /* allocate */ if (!new_blkg) { new_blkg = blkg_alloc(blkcg, q, GFP_NOWAIT | __GFP_NOWARN); if (unlikely(!new_blkg)) { ret = -ENOMEM; goto err_put_congested; } } blkg = new_blkg; blkg->wb_congested = wb_congested; /* link parent */ if (blkcg_parent(blkcg)) { blkg->parent = __blkg_lookup(blkcg_parent(blkcg), q, false); if (WARN_ON_ONCE(!blkg->parent)) { ret = -ENODEV; goto err_put_congested; } blkg_get(blkg->parent); } /* invoke per-policy init */ for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_init_fn) pol->pd_init_fn(blkg->pd[i]); } /* insert */ spin_lock(&blkcg->lock); ret = radix_tree_insert(&blkcg->blkg_tree, q->id, blkg); if (likely(!ret)) { hlist_add_head_rcu(&blkg->blkcg_node, &blkcg->blkg_list); list_add(&blkg->q_node, &q->blkg_list); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_online_fn) pol->pd_online_fn(blkg->pd[i]); } } blkg->online = true; spin_unlock(&blkcg->lock); if (!ret) return blkg; /* @blkg failed fully initialized, use the usual release path */ blkg_put(blkg); return ERR_PTR(ret); err_put_congested: wb_congested_put(wb_congested); err_put_css: css_put(&blkcg->css); err_free_blkg: blkg_free(new_blkg); return ERR_PTR(ret); } /** * blkg_lookup_create - lookup blkg, try to create one if not there * @blkcg: blkcg of interest * @q: request_queue of interest * * Lookup blkg for the @blkcg - @q pair. If it doesn't exist, try to * create one. blkg creation is performed recursively from blkcg_root such * that all non-root blkg's have access to the parent blkg. This function * should be called under RCU read lock and @q->queue_lock. * * Returns pointer to the looked up or created blkg on success, ERR_PTR() * value on error. If @q is dead, returns ERR_PTR(-EINVAL). If @q is not * dead and bypassing, returns ERR_PTR(-EBUSY). */ struct blkcg_gq *blkg_lookup_create(struct blkcg *blkcg, struct request_queue *q) { struct blkcg_gq *blkg; WARN_ON_ONCE(!rcu_read_lock_held()); lockdep_assert_held(q->queue_lock); /* * This could be the first entry point of blkcg implementation and * we shouldn't allow anything to go through for a bypassing queue. */ if (unlikely(blk_queue_bypass(q))) return ERR_PTR(blk_queue_dying(q) ? -ENODEV : -EBUSY); blkg = __blkg_lookup(blkcg, q, true); if (blkg) return blkg; /* * Create blkgs walking down from blkcg_root to @blkcg, so that all * non-root blkgs have access to their parents. */ while (true) { struct blkcg *pos = blkcg; struct blkcg *parent = blkcg_parent(blkcg); while (parent && !__blkg_lookup(parent, q, false)) { pos = parent; parent = blkcg_parent(parent); } blkg = blkg_create(pos, q, NULL); if (pos == blkcg || IS_ERR(blkg)) return blkg; } } static void blkg_destroy(struct blkcg_gq *blkg) { struct blkcg *blkcg = blkg->blkcg; struct blkcg_gq *parent = blkg->parent; int i; lockdep_assert_held(blkg->q->queue_lock); lockdep_assert_held(&blkcg->lock); /* Something wrong if we are trying to remove same group twice */ WARN_ON_ONCE(list_empty(&blkg->q_node)); WARN_ON_ONCE(hlist_unhashed(&blkg->blkcg_node)); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_offline_fn) pol->pd_offline_fn(blkg->pd[i]); } if (parent) { blkg_rwstat_add_aux(&parent->stat_bytes, &blkg->stat_bytes); blkg_rwstat_add_aux(&parent->stat_ios, &blkg->stat_ios); } blkg->online = false; radix_tree_delete(&blkcg->blkg_tree, blkg->q->id); list_del_init(&blkg->q_node); hlist_del_init_rcu(&blkg->blkcg_node); /* * Both setting lookup hint to and clearing it from @blkg are done * under queue_lock. If it's not pointing to @blkg now, it never * will. Hint assignment itself can race safely. */ if (rcu_access_pointer(blkcg->blkg_hint) == blkg) rcu_assign_pointer(blkcg->blkg_hint, NULL); /* * Put the reference taken at the time of creation so that when all * queues are gone, group can be destroyed. */ blkg_put(blkg); } /** * blkg_destroy_all - destroy all blkgs associated with a request_queue * @q: request_queue of interest * * Destroy all blkgs associated with @q. */ static void blkg_destroy_all(struct request_queue *q) { struct blkcg_gq *blkg, *n; lockdep_assert_held(q->queue_lock); list_for_each_entry_safe(blkg, n, &q->blkg_list, q_node) { struct blkcg *blkcg = blkg->blkcg; spin_lock(&blkcg->lock); blkg_destroy(blkg); spin_unlock(&blkcg->lock); } q->root_blkg = NULL; q->root_rl.blkg = NULL; } /* * A group is RCU protected, but having an rcu lock does not mean that one * can access all the fields of blkg and assume these are valid. For * example, don't try to follow throtl_data and request queue links. * * Having a reference to blkg under an rcu allows accesses to only values * local to groups like group stats and group rate limits. */ void __blkg_release_rcu(struct rcu_head *rcu_head) { struct blkcg_gq *blkg = container_of(rcu_head, struct blkcg_gq, rcu_head); /* release the blkcg and parent blkg refs this blkg has been holding */ css_put(&blkg->blkcg->css); if (blkg->parent) blkg_put(blkg->parent); wb_congested_put(blkg->wb_congested); blkg_free(blkg); } EXPORT_SYMBOL_GPL(__blkg_release_rcu); /* * The next function used by blk_queue_for_each_rl(). It's a bit tricky * because the root blkg uses @q->root_rl instead of its own rl. */ struct request_list *__blk_queue_next_rl(struct request_list *rl, struct request_queue *q) { struct list_head *ent; struct blkcg_gq *blkg; /* * Determine the current blkg list_head. The first entry is * root_rl which is off @q->blkg_list and mapped to the head. */ if (rl == &q->root_rl) { ent = &q->blkg_list; /* There are no more block groups, hence no request lists */ if (list_empty(ent)) return NULL; } else { blkg = container_of(rl, struct blkcg_gq, rl); ent = &blkg->q_node; } /* walk to the next list_head, skip root blkcg */ ent = ent->next; if (ent == &q->root_blkg->q_node) ent = ent->next; if (ent == &q->blkg_list) return NULL; blkg = container_of(ent, struct blkcg_gq, q_node); return &blkg->rl; } static int blkcg_reset_stats(struct cgroup_subsys_state *css, struct cftype *cftype, u64 val) { struct blkcg *blkcg = css_to_blkcg(css); struct blkcg_gq *blkg; int i; mutex_lock(&blkcg_pol_mutex); spin_lock_irq(&blkcg->lock); /* * Note that stat reset is racy - it doesn't synchronize against * stat updates. This is a debug feature which shouldn't exist * anyway. If you get hit by a race, retry. */ hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) { blkg_rwstat_reset(&blkg->stat_bytes); blkg_rwstat_reset(&blkg->stat_ios); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; if (blkg->pd[i] && pol->pd_reset_stats_fn) pol->pd_reset_stats_fn(blkg->pd[i]); } } spin_unlock_irq(&blkcg->lock); mutex_unlock(&blkcg_pol_mutex); return 0; } const char *blkg_dev_name(struct blkcg_gq *blkg) { /* some drivers (floppy) instantiate a queue w/o disk registered */ if (blkg->q->backing_dev_info->dev) return dev_name(blkg->q->backing_dev_info->dev); return NULL; } EXPORT_SYMBOL_GPL(blkg_dev_name); /** * blkcg_print_blkgs - helper for printing per-blkg data * @sf: seq_file to print to * @blkcg: blkcg of interest * @prfill: fill function to print out a blkg * @pol: policy in question * @data: data to be passed to @prfill * @show_total: to print out sum of prfill return values or not * * This function invokes @prfill on each blkg of @blkcg if pd for the * policy specified by @pol exists. @prfill is invoked with @sf, the * policy data and @data and the matching queue lock held. If @show_total * is %true, the sum of the return values from @prfill is printed with * "Total" label at the end. * * This is to be used to construct print functions for * cftype->read_seq_string method. */ void blkcg_print_blkgs(struct seq_file *sf, struct blkcg *blkcg, u64 (*prfill)(struct seq_file *, struct blkg_policy_data *, int), const struct blkcg_policy *pol, int data, bool show_total) { struct blkcg_gq *blkg; u64 total = 0; rcu_read_lock(); hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) { spin_lock_irq(blkg->q->queue_lock); if (blkcg_policy_enabled(blkg->q, pol)) total += prfill(sf, blkg->pd[pol->plid], data); spin_unlock_irq(blkg->q->queue_lock); } rcu_read_unlock(); if (show_total) seq_printf(sf, "Total %llu\n", (unsigned long long)total); } EXPORT_SYMBOL_GPL(blkcg_print_blkgs); /** * __blkg_prfill_u64 - prfill helper for a single u64 value * @sf: seq_file to print to * @pd: policy private data of interest * @v: value to print * * Print @v to @sf for the device assocaited with @pd. */ u64 __blkg_prfill_u64(struct seq_file *sf, struct blkg_policy_data *pd, u64 v) { const char *dname = blkg_dev_name(pd->blkg); if (!dname) return 0; seq_printf(sf, "%s %llu\n", dname, (unsigned long long)v); return v; } EXPORT_SYMBOL_GPL(__blkg_prfill_u64); /** * __blkg_prfill_rwstat - prfill helper for a blkg_rwstat * @sf: seq_file to print to * @pd: policy private data of interest * @rwstat: rwstat to print * * Print @rwstat to @sf for the device assocaited with @pd. */ u64 __blkg_prfill_rwstat(struct seq_file *sf, struct blkg_policy_data *pd, const struct blkg_rwstat *rwstat) { static const char *rwstr[] = { [BLKG_RWSTAT_READ] = "Read", [BLKG_RWSTAT_WRITE] = "Write", [BLKG_RWSTAT_SYNC] = "Sync", [BLKG_RWSTAT_ASYNC] = "Async", }; const char *dname = blkg_dev_name(pd->blkg); u64 v; int i; if (!dname) return 0; for (i = 0; i < BLKG_RWSTAT_NR; i++) seq_printf(sf, "%s %s %llu\n", dname, rwstr[i], (unsigned long long)atomic64_read(&rwstat->aux_cnt[i])); v = atomic64_read(&rwstat->aux_cnt[BLKG_RWSTAT_READ]) + atomic64_read(&rwstat->aux_cnt[BLKG_RWSTAT_WRITE]); seq_printf(sf, "%s Total %llu\n", dname, (unsigned long long)v); return v; } EXPORT_SYMBOL_GPL(__blkg_prfill_rwstat); /** * blkg_prfill_stat - prfill callback for blkg_stat * @sf: seq_file to print to * @pd: policy private data of interest * @off: offset to the blkg_stat in @pd * * prfill callback for printing a blkg_stat. */ u64 blkg_prfill_stat(struct seq_file *sf, struct blkg_policy_data *pd, int off) { return __blkg_prfill_u64(sf, pd, blkg_stat_read((void *)pd + off)); } EXPORT_SYMBOL_GPL(blkg_prfill_stat); /** * blkg_prfill_rwstat - prfill callback for blkg_rwstat * @sf: seq_file to print to * @pd: policy private data of interest * @off: offset to the blkg_rwstat in @pd * * prfill callback for printing a blkg_rwstat. */ u64 blkg_prfill_rwstat(struct seq_file *sf, struct blkg_policy_data *pd, int off) { struct blkg_rwstat rwstat = blkg_rwstat_read((void *)pd + off); return __blkg_prfill_rwstat(sf, pd, &rwstat); } EXPORT_SYMBOL_GPL(blkg_prfill_rwstat); static u64 blkg_prfill_rwstat_field(struct seq_file *sf, struct blkg_policy_data *pd, int off) { struct blkg_rwstat rwstat = blkg_rwstat_read((void *)pd->blkg + off); return __blkg_prfill_rwstat(sf, pd, &rwstat); } /** * blkg_print_stat_bytes - seq_show callback for blkg->stat_bytes * @sf: seq_file to print to * @v: unused * * To be used as cftype->seq_show to print blkg->stat_bytes. * cftype->private must be set to the blkcg_policy. */ int blkg_print_stat_bytes(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_bytes), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_bytes); /** * blkg_print_stat_bytes - seq_show callback for blkg->stat_ios * @sf: seq_file to print to * @v: unused * * To be used as cftype->seq_show to print blkg->stat_ios. cftype->private * must be set to the blkcg_policy. */ int blkg_print_stat_ios(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_ios), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_ios); static u64 blkg_prfill_rwstat_field_recursive(struct seq_file *sf, struct blkg_policy_data *pd, int off) { struct blkg_rwstat rwstat = blkg_rwstat_recursive_sum(pd->blkg, NULL, off); return __blkg_prfill_rwstat(sf, pd, &rwstat); } /** * blkg_print_stat_bytes_recursive - recursive version of blkg_print_stat_bytes * @sf: seq_file to print to * @v: unused */ int blkg_print_stat_bytes_recursive(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field_recursive, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_bytes), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_bytes_recursive); /** * blkg_print_stat_ios_recursive - recursive version of blkg_print_stat_ios * @sf: seq_file to print to * @v: unused */ int blkg_print_stat_ios_recursive(struct seq_file *sf, void *v) { blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat_field_recursive, (void *)seq_cft(sf)->private, offsetof(struct blkcg_gq, stat_ios), true); return 0; } EXPORT_SYMBOL_GPL(blkg_print_stat_ios_recursive); /** * blkg_stat_recursive_sum - collect hierarchical blkg_stat * @blkg: blkg of interest * @pol: blkcg_policy which contains the blkg_stat * @off: offset to the blkg_stat in blkg_policy_data or @blkg * * Collect the blkg_stat specified by @blkg, @pol and @off and all its * online descendants and their aux counts. The caller must be holding the * queue lock for online tests. * * If @pol is NULL, blkg_stat is at @off bytes into @blkg; otherwise, it is * at @off bytes into @blkg's blkg_policy_data of the policy. */ u64 blkg_stat_recursive_sum(struct blkcg_gq *blkg, struct blkcg_policy *pol, int off) { struct blkcg_gq *pos_blkg; struct cgroup_subsys_state *pos_css; u64 sum = 0; lockdep_assert_held(blkg->q->queue_lock); rcu_read_lock(); blkg_for_each_descendant_pre(pos_blkg, pos_css, blkg) { struct blkg_stat *stat; if (!pos_blkg->online) continue; if (pol) stat = (void *)blkg_to_pd(pos_blkg, pol) + off; else stat = (void *)blkg + off; sum += blkg_stat_read(stat) + atomic64_read(&stat->aux_cnt); } rcu_read_unlock(); return sum; } EXPORT_SYMBOL_GPL(blkg_stat_recursive_sum); /** * blkg_rwstat_recursive_sum - collect hierarchical blkg_rwstat * @blkg: blkg of interest * @pol: blkcg_policy which contains the blkg_rwstat * @off: offset to the blkg_rwstat in blkg_policy_data or @blkg * * Collect the blkg_rwstat specified by @blkg, @pol and @off and all its * online descendants and their aux counts. The caller must be holding the * queue lock for online tests. * * If @pol is NULL, blkg_rwstat is at @off bytes into @blkg; otherwise, it * is at @off bytes into @blkg's blkg_policy_data of the policy. */ struct blkg_rwstat blkg_rwstat_recursive_sum(struct blkcg_gq *blkg, struct blkcg_policy *pol, int off) { struct blkcg_gq *pos_blkg; struct cgroup_subsys_state *pos_css; struct blkg_rwstat sum = { }; int i; lockdep_assert_held(blkg->q->queue_lock); rcu_read_lock(); blkg_for_each_descendant_pre(pos_blkg, pos_css, blkg) { struct blkg_rwstat *rwstat; if (!pos_blkg->online) continue; if (pol) rwstat = (void *)blkg_to_pd(pos_blkg, pol) + off; else rwstat = (void *)pos_blkg + off; for (i = 0; i < BLKG_RWSTAT_NR; i++) atomic64_add(atomic64_read(&rwstat->aux_cnt[i]) + percpu_counter_sum_positive(&rwstat->cpu_cnt[i]), &sum.aux_cnt[i]); } rcu_read_unlock(); return sum; } EXPORT_SYMBOL_GPL(blkg_rwstat_recursive_sum); /** * blkg_conf_prep - parse and prepare for per-blkg config update * @blkcg: target block cgroup * @pol: target policy * @input: input string * @ctx: blkg_conf_ctx to be filled * * Parse per-blkg config update from @input and initialize @ctx with the * result. @ctx->blkg points to the blkg to be updated and @ctx->body the * part of @input following MAJ:MIN. This function returns with RCU read * lock and queue lock held and must be paired with blkg_conf_finish(). */ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol, char *input, struct blkg_conf_ctx *ctx) __acquires(rcu) __acquires(disk->queue->queue_lock) { struct gendisk *disk; struct blkcg_gq *blkg; struct module *owner; unsigned int major, minor; int key_len, part, ret; char *body; if (sscanf(input, "%u:%u%n", &major, &minor, &key_len) != 2) return -EINVAL; body = input + key_len; if (!isspace(*body)) return -EINVAL; body = skip_spaces(body); disk = get_gendisk(MKDEV(major, minor), &part); if (!disk) return -ENODEV; if (part) { owner = disk->fops->owner; put_disk(disk); module_put(owner); return -ENODEV; } rcu_read_lock(); spin_lock_irq(disk->queue->queue_lock); if (blkcg_policy_enabled(disk->queue, pol)) blkg = blkg_lookup_create(blkcg, disk->queue); else blkg = ERR_PTR(-EOPNOTSUPP); if (IS_ERR(blkg)) { ret = PTR_ERR(blkg); rcu_read_unlock(); spin_unlock_irq(disk->queue->queue_lock); owner = disk->fops->owner; put_disk(disk); module_put(owner); /* * If queue was bypassing, we should retry. Do so after a * short msleep(). It isn't strictly necessary but queue * can be bypassing for some time and it's always nice to * avoid busy looping. */ if (ret == -EBUSY) { msleep(10); ret = restart_syscall(); } return ret; } ctx->disk = disk; ctx->blkg = blkg; ctx->body = body; return 0; } EXPORT_SYMBOL_GPL(blkg_conf_prep); /** * blkg_conf_finish - finish up per-blkg config update * @ctx: blkg_conf_ctx intiailized by blkg_conf_prep() * * Finish up after per-blkg config update. This function must be paired * with blkg_conf_prep(). */ void blkg_conf_finish(struct blkg_conf_ctx *ctx) __releases(ctx->disk->queue->queue_lock) __releases(rcu) { struct module *owner; spin_unlock_irq(ctx->disk->queue->queue_lock); rcu_read_unlock(); owner = ctx->disk->fops->owner; put_disk(ctx->disk); module_put(owner); } EXPORT_SYMBOL_GPL(blkg_conf_finish); static int blkcg_print_stat(struct seq_file *sf, void *v) { struct blkcg *blkcg = css_to_blkcg(seq_css(sf)); struct blkcg_gq *blkg; rcu_read_lock(); hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) { const char *dname; struct blkg_rwstat rwstat; u64 rbytes, wbytes, rios, wios; dname = blkg_dev_name(blkg); if (!dname) continue; spin_lock_irq(blkg->q->queue_lock); rwstat = blkg_rwstat_recursive_sum(blkg, NULL, offsetof(struct blkcg_gq, stat_bytes)); rbytes = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_READ]); wbytes = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_WRITE]); rwstat = blkg_rwstat_recursive_sum(blkg, NULL, offsetof(struct blkcg_gq, stat_ios)); rios = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_READ]); wios = atomic64_read(&rwstat.aux_cnt[BLKG_RWSTAT_WRITE]); spin_unlock_irq(blkg->q->queue_lock); if (rbytes || wbytes || rios || wios) seq_printf(sf, "%s rbytes=%llu wbytes=%llu rios=%llu wios=%llu\n", dname, rbytes, wbytes, rios, wios); } rcu_read_unlock(); return 0; } static struct cftype blkcg_files[] = { { .name = "stat", .flags = CFTYPE_NOT_ON_ROOT, .seq_show = blkcg_print_stat, }, { } /* terminate */ }; static struct cftype blkcg_legacy_files[] = { { .name = "reset_stats", .write_u64 = blkcg_reset_stats, }, { } /* terminate */ }; /** * blkcg_css_offline - cgroup css_offline callback * @css: css of interest * * This function is called when @css is about to go away and responsible * for shooting down all blkgs associated with @css. blkgs should be * removed while holding both q and blkcg locks. As blkcg lock is nested * inside q lock, this function performs reverse double lock dancing. * * This is the blkcg counterpart of ioc_release_fn(). */ static void blkcg_css_offline(struct cgroup_subsys_state *css) { struct blkcg *blkcg = css_to_blkcg(css); spin_lock_irq(&blkcg->lock); while (!hlist_empty(&blkcg->blkg_list)) { struct blkcg_gq *blkg = hlist_entry(blkcg->blkg_list.first, struct blkcg_gq, blkcg_node); struct request_queue *q = blkg->q; if (spin_trylock(q->queue_lock)) { blkg_destroy(blkg); spin_unlock(q->queue_lock); } else { spin_unlock_irq(&blkcg->lock); cpu_relax(); spin_lock_irq(&blkcg->lock); } } spin_unlock_irq(&blkcg->lock); wb_blkcg_offline(blkcg); } static void blkcg_css_free(struct cgroup_subsys_state *css) { struct blkcg *blkcg = css_to_blkcg(css); int i; mutex_lock(&blkcg_pol_mutex); list_del(&blkcg->all_blkcgs_node); for (i = 0; i < BLKCG_MAX_POLS; i++) if (blkcg->cpd[i]) blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]); mutex_unlock(&blkcg_pol_mutex); kfree(blkcg); } static struct cgroup_subsys_state * blkcg_css_alloc(struct cgroup_subsys_state *parent_css) { struct blkcg *blkcg; struct cgroup_subsys_state *ret; int i; mutex_lock(&blkcg_pol_mutex); if (!parent_css) { blkcg = &blkcg_root; } else { blkcg = kzalloc(sizeof(*blkcg), GFP_KERNEL); if (!blkcg) { ret = ERR_PTR(-ENOMEM); goto free_blkcg; } } for (i = 0; i < BLKCG_MAX_POLS ; i++) { struct blkcg_policy *pol = blkcg_policy[i]; struct blkcg_policy_data *cpd; /* * If the policy hasn't been attached yet, wait for it * to be attached before doing anything else. Otherwise, * check if the policy requires any specific per-cgroup * data: if it does, allocate and initialize it. */ if (!pol || !pol->cpd_alloc_fn) continue; cpd = pol->cpd_alloc_fn(GFP_KERNEL); if (!cpd) { ret = ERR_PTR(-ENOMEM); goto free_pd_blkcg; } blkcg->cpd[i] = cpd; cpd->blkcg = blkcg; cpd->plid = i; if (pol->cpd_init_fn) pol->cpd_init_fn(cpd); } spin_lock_init(&blkcg->lock); INIT_RADIX_TREE(&blkcg->blkg_tree, GFP_NOWAIT | __GFP_NOWARN); INIT_HLIST_HEAD(&blkcg->blkg_list); #ifdef CONFIG_CGROUP_WRITEBACK INIT_LIST_HEAD(&blkcg->cgwb_list); #endif list_add_tail(&blkcg->all_blkcgs_node, &all_blkcgs); mutex_unlock(&blkcg_pol_mutex); return &blkcg->css; free_pd_blkcg: for (i--; i >= 0; i--) if (blkcg->cpd[i]) blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]); free_blkcg: kfree(blkcg); mutex_unlock(&blkcg_pol_mutex); return ret; } /** * blkcg_init_queue - initialize blkcg part of request queue * @q: request_queue to initialize * * Called from blk_alloc_queue_node(). Responsible for initializing blkcg * part of new request_queue @q. * * RETURNS: * 0 on success, -errno on failure. */ int blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) return PTR_ERR(blkg); q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; } /** * blkcg_drain_queue - drain blkcg part of request_queue * @q: request_queue to drain * * Called from blk_drain_queue(). Responsible for draining blkcg part. */ void blkcg_drain_queue(struct request_queue *q) { lockdep_assert_held(q->queue_lock); /* * @q could be exiting and already have destroyed all blkgs as * indicated by NULL root_blkg. If so, don't confuse policies. */ if (!q->root_blkg) return; blk_throtl_drain(q); } /** * blkcg_exit_queue - exit and release blkcg part of request_queue * @q: request_queue being released * * Called from blk_release_queue(). Responsible for exiting blkcg part. */ void blkcg_exit_queue(struct request_queue *q) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); blk_throtl_exit(q); } /* * We cannot support shared io contexts, as we have no mean to support * two tasks with the same ioc in two different groups without major rework * of the main cic data structures. For now we allow a task to change * its cgroup only if it's the only owner of its ioc. */ static int blkcg_can_attach(struct cgroup_taskset *tset) { struct task_struct *task; struct cgroup_subsys_state *dst_css; struct io_context *ioc; int ret = 0; /* task_lock() is needed to avoid races with exit_io_context() */ cgroup_taskset_for_each(task, dst_css, tset) { task_lock(task); ioc = task->io_context; if (ioc && atomic_read(&ioc->nr_tasks) > 1) ret = -EINVAL; task_unlock(task); if (ret) break; } return ret; } static void blkcg_bind(struct cgroup_subsys_state *root_css) { int i; mutex_lock(&blkcg_pol_mutex); for (i = 0; i < BLKCG_MAX_POLS; i++) { struct blkcg_policy *pol = blkcg_policy[i]; struct blkcg *blkcg; if (!pol || !pol->cpd_bind_fn) continue; list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) if (blkcg->cpd[pol->plid]) pol->cpd_bind_fn(blkcg->cpd[pol->plid]); } mutex_unlock(&blkcg_pol_mutex); } struct cgroup_subsys io_cgrp_subsys = { .css_alloc = blkcg_css_alloc, .css_offline = blkcg_css_offline, .css_free = blkcg_css_free, .can_attach = blkcg_can_attach, .bind = blkcg_bind, .dfl_cftypes = blkcg_files, .legacy_cftypes = blkcg_legacy_files, .legacy_name = "blkio", #ifdef CONFIG_MEMCG /* * This ensures that, if available, memcg is automatically enabled * together on the default hierarchy so that the owner cgroup can * be retrieved from writeback pages. */ .depends_on = 1 << memory_cgrp_id, #endif }; EXPORT_SYMBOL_GPL(io_cgrp_subsys); /** * blkcg_activate_policy - activate a blkcg policy on a request_queue * @q: request_queue of interest * @pol: blkcg policy to activate * * Activate @pol on @q. Requires %GFP_KERNEL context. @q goes through * bypass mode to populate its blkgs with policy_data for @pol. * * Activation happens with @q bypassed, so nobody would be accessing blkgs * from IO path. Update of each blkg is protected by both queue and blkcg * locks so that holding either lock and testing blkcg_policy_enabled() is * always enough for dereferencing policy data. * * The caller is responsible for synchronizing [de]activations and policy * [un]registerations. Returns 0 on success, -errno on failure. */ int blkcg_activate_policy(struct request_queue *q, const struct blkcg_policy *pol) { struct blkg_policy_data *pd_prealloc = NULL; struct blkcg_gq *blkg; int ret; if (blkcg_policy_enabled(q, pol)) return 0; if (q->mq_ops) blk_mq_freeze_queue(q); else blk_queue_bypass_start(q); pd_prealloc: if (!pd_prealloc) { pd_prealloc = pol->pd_alloc_fn(GFP_KERNEL, q->node); if (!pd_prealloc) { ret = -ENOMEM; goto out_bypass_end; } } spin_lock_irq(q->queue_lock); list_for_each_entry(blkg, &q->blkg_list, q_node) { struct blkg_policy_data *pd; if (blkg->pd[pol->plid]) continue; pd = pol->pd_alloc_fn(GFP_NOWAIT | __GFP_NOWARN, q->node); if (!pd) swap(pd, pd_prealloc); if (!pd) { spin_unlock_irq(q->queue_lock); goto pd_prealloc; } blkg->pd[pol->plid] = pd; pd->blkg = blkg; pd->plid = pol->plid; if (pol->pd_init_fn) pol->pd_init_fn(pd); } __set_bit(pol->plid, q->blkcg_pols); ret = 0; spin_unlock_irq(q->queue_lock); out_bypass_end: if (q->mq_ops) blk_mq_unfreeze_queue(q); else blk_queue_bypass_end(q); if (pd_prealloc) pol->pd_free_fn(pd_prealloc); return ret; } EXPORT_SYMBOL_GPL(blkcg_activate_policy); /** * blkcg_deactivate_policy - deactivate a blkcg policy on a request_queue * @q: request_queue of interest * @pol: blkcg policy to deactivate * * Deactivate @pol on @q. Follows the same synchronization rules as * blkcg_activate_policy(). */ void blkcg_deactivate_policy(struct request_queue *q, const struct blkcg_policy *pol) { struct blkcg_gq *blkg; if (!blkcg_policy_enabled(q, pol)) return; if (q->mq_ops) blk_mq_freeze_queue(q); else blk_queue_bypass_start(q); spin_lock_irq(q->queue_lock); __clear_bit(pol->plid, q->blkcg_pols); list_for_each_entry(blkg, &q->blkg_list, q_node) { /* grab blkcg lock too while removing @pd from @blkg */ spin_lock(&blkg->blkcg->lock); if (blkg->pd[pol->plid]) { if (pol->pd_offline_fn) pol->pd_offline_fn(blkg->pd[pol->plid]); pol->pd_free_fn(blkg->pd[pol->plid]); blkg->pd[pol->plid] = NULL; } spin_unlock(&blkg->blkcg->lock); } spin_unlock_irq(q->queue_lock); if (q->mq_ops) blk_mq_unfreeze_queue(q); else blk_queue_bypass_end(q); } EXPORT_SYMBOL_GPL(blkcg_deactivate_policy); /** * blkcg_policy_register - register a blkcg policy * @pol: blkcg policy to register * * Register @pol with blkcg core. Might sleep and @pol may be modified on * successful registration. Returns 0 on success and -errno on failure. */ int blkcg_policy_register(struct blkcg_policy *pol) { struct blkcg *blkcg; int i, ret; mutex_lock(&blkcg_pol_register_mutex); mutex_lock(&blkcg_pol_mutex); /* find an empty slot */ ret = -ENOSPC; for (i = 0; i < BLKCG_MAX_POLS; i++) if (!blkcg_policy[i]) break; if (i >= BLKCG_MAX_POLS) goto err_unlock; /* register @pol */ pol->plid = i; blkcg_policy[pol->plid] = pol; /* allocate and install cpd's */ if (pol->cpd_alloc_fn) { list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) { struct blkcg_policy_data *cpd; cpd = pol->cpd_alloc_fn(GFP_KERNEL); if (!cpd) goto err_free_cpds; blkcg->cpd[pol->plid] = cpd; cpd->blkcg = blkcg; cpd->plid = pol->plid; pol->cpd_init_fn(cpd); } } mutex_unlock(&blkcg_pol_mutex); /* everything is in place, add intf files for the new policy */ if (pol->dfl_cftypes) WARN_ON(cgroup_add_dfl_cftypes(&io_cgrp_subsys, pol->dfl_cftypes)); if (pol->legacy_cftypes) WARN_ON(cgroup_add_legacy_cftypes(&io_cgrp_subsys, pol->legacy_cftypes)); mutex_unlock(&blkcg_pol_register_mutex); return 0; err_free_cpds: if (pol->cpd_alloc_fn) { list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) { if (blkcg->cpd[pol->plid]) { pol->cpd_free_fn(blkcg->cpd[pol->plid]); blkcg->cpd[pol->plid] = NULL; } } } blkcg_policy[pol->plid] = NULL; err_unlock: mutex_unlock(&blkcg_pol_mutex); mutex_unlock(&blkcg_pol_register_mutex); return ret; } EXPORT_SYMBOL_GPL(blkcg_policy_register); /** * blkcg_policy_unregister - unregister a blkcg policy * @pol: blkcg policy to unregister * * Undo blkcg_policy_register(@pol). Might sleep. */ void blkcg_policy_unregister(struct blkcg_policy *pol) { struct blkcg *blkcg; mutex_lock(&blkcg_pol_register_mutex); if (WARN_ON(blkcg_policy[pol->plid] != pol)) goto out_unlock; /* kill the intf files first */ if (pol->dfl_cftypes) cgroup_rm_cftypes(pol->dfl_cftypes); if (pol->legacy_cftypes) cgroup_rm_cftypes(pol->legacy_cftypes); /* remove cpds and unregister */ mutex_lock(&blkcg_pol_mutex); if (pol->cpd_alloc_fn) { list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) { if (blkcg->cpd[pol->plid]) { pol->cpd_free_fn(blkcg->cpd[pol->plid]); blkcg->cpd[pol->plid] = NULL; } } } blkcg_policy[pol->plid] = NULL; mutex_unlock(&blkcg_pol_mutex); out_unlock: mutex_unlock(&blkcg_pol_register_mutex); } EXPORT_SYMBOL_GPL(blkcg_policy_unregister);
./CrossVul/dataset_final_sorted/CWE-415/c/good_633_0
crossvul-cpp_data_bad_2579_6
/* #pragma ident "@(#)g_inquire_context.c 1.15 04/02/23 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_inquire_context */ #include "mglueP.h" #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif static OM_uint32 val_inq_ctx_args( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (targ_name != NULL) *targ_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); return (GSS_S_COMPLETE); } /* Last argument new for V2 */ OM_uint32 KRB5_CALLCONV gss_inquire_context( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { gss_union_ctx_id_t ctx; gss_mechanism mech; OM_uint32 status, temp_minor; gss_OID actual_mech; gss_name_t localTargName = NULL, localSourceName = NULL; status = val_inq_ctx_args(minor_status, context_handle, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech || !mech->gss_inquire_context || !mech->gss_display_name || !mech->gss_release_name) { return (GSS_S_UNAVAILABLE); } status = mech->gss_inquire_context( minor_status, ctx->internal_ctx_id, (src_name ? &localSourceName : NULL), (targ_name ? &localTargName : NULL), lifetime_rec, &actual_mech, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); return status; } /* need to convert names */ if (src_name) { if (localSourceName) { status = gssint_convert_name_to_union_name(minor_status, mech, localSourceName, src_name); if (status != GSS_S_COMPLETE) { if (localTargName) mech->gss_release_name(&temp_minor, &localTargName); return (status); } } else { *src_name = GSS_C_NO_NAME; } } if (targ_name) { if (localTargName) { status = gssint_convert_name_to_union_name(minor_status, mech, localTargName, targ_name); if (status != GSS_S_COMPLETE) { if (src_name) (void) gss_release_name(&temp_minor, src_name); return (status); } } else { *targ_name = GSS_C_NO_NAME; } } if (mech_type) *mech_type = gssint_get_public_oid(actual_mech); return(GSS_S_COMPLETE); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_6
crossvul-cpp_data_good_3161_0
/* * net/dccp/input.c * * An implementation of the DCCP protocol * Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/dccp.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <net/sock.h> #include "ackvec.h" #include "ccid.h" #include "dccp.h" /* rate-limit for syncs in reply to sequence-invalid packets; RFC 4340, 7.5.4 */ int sysctl_dccp_sync_ratelimit __read_mostly = HZ / 8; static void dccp_enqueue_skb(struct sock *sk, struct sk_buff *skb) { __skb_pull(skb, dccp_hdr(skb)->dccph_doff * 4); __skb_queue_tail(&sk->sk_receive_queue, skb); skb_set_owner_r(skb, sk); sk->sk_data_ready(sk); } static void dccp_fin(struct sock *sk, struct sk_buff *skb) { /* * On receiving Close/CloseReq, both RD/WR shutdown are performed. * RFC 4340, 8.3 says that we MAY send further Data/DataAcks after * receiving the closing segment, but there is no guarantee that such * data will be processed at all. */ sk->sk_shutdown = SHUTDOWN_MASK; sock_set_flag(sk, SOCK_DONE); dccp_enqueue_skb(sk, skb); } static int dccp_rcv_close(struct sock *sk, struct sk_buff *skb) { int queued = 0; switch (sk->sk_state) { /* * We ignore Close when received in one of the following states: * - CLOSED (may be a late or duplicate packet) * - PASSIVE_CLOSEREQ (the peer has sent a CloseReq earlier) * - RESPOND (already handled by dccp_check_req) */ case DCCP_CLOSING: /* * Simultaneous-close: receiving a Close after sending one. This * can happen if both client and server perform active-close and * will result in an endless ping-pong of crossing and retrans- * mitted Close packets, which only terminates when one of the * nodes times out (min. 64 seconds). Quicker convergence can be * achieved when one of the nodes acts as tie-breaker. * This is ok as both ends are done with data transfer and each * end is just waiting for the other to acknowledge termination. */ if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT) break; /* fall through */ case DCCP_REQUESTING: case DCCP_ACTIVE_CLOSEREQ: dccp_send_reset(sk, DCCP_RESET_CODE_CLOSED); dccp_done(sk); break; case DCCP_OPEN: case DCCP_PARTOPEN: /* Give waiting application a chance to read pending data */ queued = 1; dccp_fin(sk, skb); dccp_set_state(sk, DCCP_PASSIVE_CLOSE); /* fall through */ case DCCP_PASSIVE_CLOSE: /* * Retransmitted Close: we have already enqueued the first one. */ sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); } return queued; } static int dccp_rcv_closereq(struct sock *sk, struct sk_buff *skb) { int queued = 0; /* * Step 7: Check for unexpected packet types * If (S.is_server and P.type == CloseReq) * Send Sync packet acknowledging P.seqno * Drop packet and return */ if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT) { dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNC); return queued; } /* Step 13: process relevant Client states < CLOSEREQ */ switch (sk->sk_state) { case DCCP_REQUESTING: dccp_send_close(sk, 0); dccp_set_state(sk, DCCP_CLOSING); break; case DCCP_OPEN: case DCCP_PARTOPEN: /* Give waiting application a chance to read pending data */ queued = 1; dccp_fin(sk, skb); dccp_set_state(sk, DCCP_PASSIVE_CLOSEREQ); /* fall through */ case DCCP_PASSIVE_CLOSEREQ: sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); } return queued; } static u16 dccp_reset_code_convert(const u8 code) { const u16 error_code[] = { [DCCP_RESET_CODE_CLOSED] = 0, /* normal termination */ [DCCP_RESET_CODE_UNSPECIFIED] = 0, /* nothing known */ [DCCP_RESET_CODE_ABORTED] = ECONNRESET, [DCCP_RESET_CODE_NO_CONNECTION] = ECONNREFUSED, [DCCP_RESET_CODE_CONNECTION_REFUSED] = ECONNREFUSED, [DCCP_RESET_CODE_TOO_BUSY] = EUSERS, [DCCP_RESET_CODE_AGGRESSION_PENALTY] = EDQUOT, [DCCP_RESET_CODE_PACKET_ERROR] = ENOMSG, [DCCP_RESET_CODE_BAD_INIT_COOKIE] = EBADR, [DCCP_RESET_CODE_BAD_SERVICE_CODE] = EBADRQC, [DCCP_RESET_CODE_OPTION_ERROR] = EILSEQ, [DCCP_RESET_CODE_MANDATORY_ERROR] = EOPNOTSUPP, }; return code >= DCCP_MAX_RESET_CODES ? 0 : error_code[code]; } static void dccp_rcv_reset(struct sock *sk, struct sk_buff *skb) { u16 err = dccp_reset_code_convert(dccp_hdr_reset(skb)->dccph_reset_code); sk->sk_err = err; /* Queue the equivalent of TCP fin so that dccp_recvmsg exits the loop */ dccp_fin(sk, skb); if (err && !sock_flag(sk, SOCK_DEAD)) sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); dccp_time_wait(sk, DCCP_TIME_WAIT, 0); } static void dccp_handle_ackvec_processing(struct sock *sk, struct sk_buff *skb) { struct dccp_ackvec *av = dccp_sk(sk)->dccps_hc_rx_ackvec; if (av == NULL) return; if (DCCP_SKB_CB(skb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ) dccp_ackvec_clear_state(av, DCCP_SKB_CB(skb)->dccpd_ack_seq); dccp_ackvec_input(av, skb); } static void dccp_deliver_input_to_ccids(struct sock *sk, struct sk_buff *skb) { const struct dccp_sock *dp = dccp_sk(sk); /* Don't deliver to RX CCID when node has shut down read end. */ if (!(sk->sk_shutdown & RCV_SHUTDOWN)) ccid_hc_rx_packet_recv(dp->dccps_hc_rx_ccid, sk, skb); /* * Until the TX queue has been drained, we can not honour SHUT_WR, since * we need received feedback as input to adjust congestion control. */ if (sk->sk_write_queue.qlen > 0 || !(sk->sk_shutdown & SEND_SHUTDOWN)) ccid_hc_tx_packet_recv(dp->dccps_hc_tx_ccid, sk, skb); } static int dccp_check_seqno(struct sock *sk, struct sk_buff *skb) { const struct dccp_hdr *dh = dccp_hdr(skb); struct dccp_sock *dp = dccp_sk(sk); u64 lswl, lawl, seqno = DCCP_SKB_CB(skb)->dccpd_seq, ackno = DCCP_SKB_CB(skb)->dccpd_ack_seq; /* * Step 5: Prepare sequence numbers for Sync * If P.type == Sync or P.type == SyncAck, * If S.AWL <= P.ackno <= S.AWH and P.seqno >= S.SWL, * / * P is valid, so update sequence number variables * accordingly. After this update, P will pass the tests * in Step 6. A SyncAck is generated if necessary in * Step 15 * / * Update S.GSR, S.SWL, S.SWH * Otherwise, * Drop packet and return */ if (dh->dccph_type == DCCP_PKT_SYNC || dh->dccph_type == DCCP_PKT_SYNCACK) { if (between48(ackno, dp->dccps_awl, dp->dccps_awh) && dccp_delta_seqno(dp->dccps_swl, seqno) >= 0) dccp_update_gsr(sk, seqno); else return -1; } /* * Step 6: Check sequence numbers * Let LSWL = S.SWL and LAWL = S.AWL * If P.type == CloseReq or P.type == Close or P.type == Reset, * LSWL := S.GSR + 1, LAWL := S.GAR * If LSWL <= P.seqno <= S.SWH * and (P.ackno does not exist or LAWL <= P.ackno <= S.AWH), * Update S.GSR, S.SWL, S.SWH * If P.type != Sync, * Update S.GAR */ lswl = dp->dccps_swl; lawl = dp->dccps_awl; if (dh->dccph_type == DCCP_PKT_CLOSEREQ || dh->dccph_type == DCCP_PKT_CLOSE || dh->dccph_type == DCCP_PKT_RESET) { lswl = ADD48(dp->dccps_gsr, 1); lawl = dp->dccps_gar; } if (between48(seqno, lswl, dp->dccps_swh) && (ackno == DCCP_PKT_WITHOUT_ACK_SEQ || between48(ackno, lawl, dp->dccps_awh))) { dccp_update_gsr(sk, seqno); if (dh->dccph_type != DCCP_PKT_SYNC && ackno != DCCP_PKT_WITHOUT_ACK_SEQ && after48(ackno, dp->dccps_gar)) dp->dccps_gar = ackno; } else { unsigned long now = jiffies; /* * Step 6: Check sequence numbers * Otherwise, * If P.type == Reset, * Send Sync packet acknowledging S.GSR * Otherwise, * Send Sync packet acknowledging P.seqno * Drop packet and return * * These Syncs are rate-limited as per RFC 4340, 7.5.4: * at most 1 / (dccp_sync_rate_limit * HZ) Syncs per second. */ if (time_before(now, (dp->dccps_rate_last + sysctl_dccp_sync_ratelimit))) return -1; DCCP_WARN("Step 6 failed for %s packet, " "(LSWL(%llu) <= P.seqno(%llu) <= S.SWH(%llu)) and " "(P.ackno %s or LAWL(%llu) <= P.ackno(%llu) <= S.AWH(%llu), " "sending SYNC...\n", dccp_packet_name(dh->dccph_type), (unsigned long long) lswl, (unsigned long long) seqno, (unsigned long long) dp->dccps_swh, (ackno == DCCP_PKT_WITHOUT_ACK_SEQ) ? "doesn't exist" : "exists", (unsigned long long) lawl, (unsigned long long) ackno, (unsigned long long) dp->dccps_awh); dp->dccps_rate_last = now; if (dh->dccph_type == DCCP_PKT_RESET) seqno = dp->dccps_gsr; dccp_send_sync(sk, seqno, DCCP_PKT_SYNC); return -1; } return 0; } static int __dccp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); switch (dccp_hdr(skb)->dccph_type) { case DCCP_PKT_DATAACK: case DCCP_PKT_DATA: /* * FIXME: schedule DATA_DROPPED (RFC 4340, 11.7.2) if and when * - sk_shutdown == RCV_SHUTDOWN, use Code 1, "Not Listening" * - sk_receive_queue is full, use Code 2, "Receive Buffer" */ dccp_enqueue_skb(sk, skb); return 0; case DCCP_PKT_ACK: goto discard; case DCCP_PKT_RESET: /* * Step 9: Process Reset * If P.type == Reset, * Tear down connection * S.state := TIMEWAIT * Set TIMEWAIT timer * Drop packet and return */ dccp_rcv_reset(sk, skb); return 0; case DCCP_PKT_CLOSEREQ: if (dccp_rcv_closereq(sk, skb)) return 0; goto discard; case DCCP_PKT_CLOSE: if (dccp_rcv_close(sk, skb)) return 0; goto discard; case DCCP_PKT_REQUEST: /* Step 7 * or (S.is_server and P.type == Response) * or (S.is_client and P.type == Request) * or (S.state >= OPEN and P.type == Request * and P.seqno >= S.OSR) * or (S.state >= OPEN and P.type == Response * and P.seqno >= S.OSR) * or (S.state == RESPOND and P.type == Data), * Send Sync packet acknowledging P.seqno * Drop packet and return */ if (dp->dccps_role != DCCP_ROLE_LISTEN) goto send_sync; goto check_seq; case DCCP_PKT_RESPONSE: if (dp->dccps_role != DCCP_ROLE_CLIENT) goto send_sync; check_seq: if (dccp_delta_seqno(dp->dccps_osr, DCCP_SKB_CB(skb)->dccpd_seq) >= 0) { send_sync: dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNC); } break; case DCCP_PKT_SYNC: dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNCACK); /* * From RFC 4340, sec. 5.7 * * As with DCCP-Ack packets, DCCP-Sync and DCCP-SyncAck packets * MAY have non-zero-length application data areas, whose * contents receivers MUST ignore. */ goto discard; } DCCP_INC_STATS(DCCP_MIB_INERRS); discard: __kfree_skb(skb); return 0; } int dccp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { if (dccp_check_seqno(sk, skb)) goto discard; if (dccp_parse_options(sk, NULL, skb)) return 1; dccp_handle_ackvec_processing(sk, skb); dccp_deliver_input_to_ccids(sk, skb); return __dccp_rcv_established(sk, skb, dh, len); discard: __kfree_skb(skb); return 0; } EXPORT_SYMBOL_GPL(dccp_rcv_established); static int dccp_rcv_request_sent_state_process(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { /* * Step 4: Prepare sequence numbers in REQUEST * If S.state == REQUEST, * If (P.type == Response or P.type == Reset) * and S.AWL <= P.ackno <= S.AWH, * / * Set sequence number variables corresponding to the * other endpoint, so P will pass the tests in Step 6 * / * Set S.GSR, S.ISR, S.SWL, S.SWH * / * Response processing continues in Step 10; Reset * processing continues in Step 9 * / */ if (dh->dccph_type == DCCP_PKT_RESPONSE) { const struct inet_connection_sock *icsk = inet_csk(sk); struct dccp_sock *dp = dccp_sk(sk); long tstamp = dccp_timestamp(); if (!between48(DCCP_SKB_CB(skb)->dccpd_ack_seq, dp->dccps_awl, dp->dccps_awh)) { dccp_pr_debug("invalid ackno: S.AWL=%llu, " "P.ackno=%llu, S.AWH=%llu\n", (unsigned long long)dp->dccps_awl, (unsigned long long)DCCP_SKB_CB(skb)->dccpd_ack_seq, (unsigned long long)dp->dccps_awh); goto out_invalid_packet; } /* * If option processing (Step 8) failed, return 1 here so that * dccp_v4_do_rcv() sends a Reset. The Reset code depends on * the option type and is set in dccp_parse_options(). */ if (dccp_parse_options(sk, NULL, skb)) return 1; /* Obtain usec RTT sample from SYN exchange (used by TFRC). */ if (likely(dp->dccps_options_received.dccpor_timestamp_echo)) dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * (tstamp - dp->dccps_options_received.dccpor_timestamp_echo)); /* Stop the REQUEST timer */ inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS); WARN_ON(sk->sk_send_head == NULL); kfree_skb(sk->sk_send_head); sk->sk_send_head = NULL; /* * Set ISR, GSR from packet. ISS was set in dccp_v{4,6}_connect * and GSS in dccp_transmit_skb(). Setting AWL/AWH and SWL/SWH * is done as part of activating the feature values below, since * these settings depend on the local/remote Sequence Window * features, which were undefined or not confirmed until now. */ dp->dccps_gsr = dp->dccps_isr = DCCP_SKB_CB(skb)->dccpd_seq; dccp_sync_mss(sk, icsk->icsk_pmtu_cookie); /* * Step 10: Process REQUEST state (second part) * If S.state == REQUEST, * / * If we get here, P is a valid Response from the * server (see Step 4), and we should move to * PARTOPEN state. PARTOPEN means send an Ack, * don't send Data packets, retransmit Acks * periodically, and always include any Init Cookie * from the Response * / * S.state := PARTOPEN * Set PARTOPEN timer * Continue with S.state == PARTOPEN * / * Step 12 will send the Ack completing the * three-way handshake * / */ dccp_set_state(sk, DCCP_PARTOPEN); /* * If feature negotiation was successful, activate features now; * an activation failure means that this host could not activate * one ore more features (e.g. insufficient memory), which would * leave at least one feature in an undefined state. */ if (dccp_feat_activate_values(sk, &dp->dccps_featneg)) goto unable_to_proceed; /* Make sure socket is routed, for correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); } if (sk->sk_write_pending || icsk->icsk_ack.pingpong || icsk->icsk_accept_queue.rskq_defer_accept) { /* Save one ACK. Data will be ready after * several ticks, if write_pending is set. * * It may be deleted, but with this feature tcpdumps * look so _wonderfully_ clever, that I was not able * to stand against the temptation 8) --ANK */ /* * OK, in DCCP we can as well do a similar trick, its * even in the draft, but there is no need for us to * schedule an ack here, as dccp_sendmsg does this for * us, also stated in the draft. -acme */ __kfree_skb(skb); return 0; } dccp_send_ack(sk); return -1; } out_invalid_packet: /* dccp_v4_do_rcv will send a reset */ DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_PACKET_ERROR; return 1; unable_to_proceed: DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_ABORTED; /* * We mark this socket as no longer usable, so that the loop in * dccp_sendmsg() terminates and the application gets notified. */ dccp_set_state(sk, DCCP_CLOSED); sk->sk_err = ECOMM; return 1; } static int dccp_rcv_respond_partopen_state_process(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); u32 sample = dp->dccps_options_received.dccpor_timestamp_echo; int queued = 0; switch (dh->dccph_type) { case DCCP_PKT_RESET: inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); break; case DCCP_PKT_DATA: if (sk->sk_state == DCCP_RESPOND) break; case DCCP_PKT_DATAACK: case DCCP_PKT_ACK: /* * FIXME: we should be resetting the PARTOPEN (DELACK) timer * here but only if we haven't used the DELACK timer for * something else, like sending a delayed ack for a TIMESTAMP * echo, etc, for now were not clearing it, sending an extra * ACK when there is nothing else to do in DELACK is not a big * deal after all. */ /* Stop the PARTOPEN timer */ if (sk->sk_state == DCCP_PARTOPEN) inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); /* Obtain usec RTT sample from SYN exchange (used by TFRC). */ if (likely(sample)) { long delta = dccp_timestamp() - sample; dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * delta); } dp->dccps_osr = DCCP_SKB_CB(skb)->dccpd_seq; dccp_set_state(sk, DCCP_OPEN); if (dh->dccph_type == DCCP_PKT_DATAACK || dh->dccph_type == DCCP_PKT_DATA) { __dccp_rcv_established(sk, skb, dh, len); queued = 1; /* packet was queued (by __dccp_rcv_established) */ } break; } return queued; } int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb, struct dccp_hdr *dh, unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); const int old_state = sk->sk_state; int queued = 0; /* * Step 3: Process LISTEN state * * If S.state == LISTEN, * If P.type == Request or P contains a valid Init Cookie option, * (* Must scan the packet's options to check for Init * Cookies. Only Init Cookies are processed here, * however; other options are processed in Step 8. This * scan need only be performed if the endpoint uses Init * Cookies *) * (* Generate a new socket and switch to that socket *) * Set S := new socket for this port pair * S.state = RESPOND * Choose S.ISS (initial seqno) or set from Init Cookies * Initialize S.GAR := S.ISS * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init * Cookies Continue with S.state == RESPOND * (* A Response packet will be generated in Step 11 *) * Otherwise, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (sk->sk_state == DCCP_LISTEN) { if (dh->dccph_type == DCCP_PKT_REQUEST) { if (inet_csk(sk)->icsk_af_ops->conn_request(sk, skb) < 0) return 1; consume_skb(skb); return 0; } if (dh->dccph_type == DCCP_PKT_RESET) goto discard; /* Caller (dccp_v4_do_rcv) will send Reset */ dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } else if (sk->sk_state == DCCP_CLOSED) { dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } /* Step 6: Check sequence numbers (omitted in LISTEN/REQUEST state) */ if (sk->sk_state != DCCP_REQUESTING && dccp_check_seqno(sk, skb)) goto discard; /* * Step 7: Check for unexpected packet types * If (S.is_server and P.type == Response) * or (S.is_client and P.type == Request) * or (S.state == RESPOND and P.type == Data), * Send Sync packet acknowledging P.seqno * Drop packet and return */ if ((dp->dccps_role != DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_RESPONSE) || (dp->dccps_role == DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_REQUEST) || (sk->sk_state == DCCP_RESPOND && dh->dccph_type == DCCP_PKT_DATA)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNC); goto discard; } /* Step 8: Process options */ if (dccp_parse_options(sk, NULL, skb)) return 1; /* * Step 9: Process Reset * If P.type == Reset, * Tear down connection * S.state := TIMEWAIT * Set TIMEWAIT timer * Drop packet and return */ if (dh->dccph_type == DCCP_PKT_RESET) { dccp_rcv_reset(sk, skb); return 0; } else if (dh->dccph_type == DCCP_PKT_CLOSEREQ) { /* Step 13 */ if (dccp_rcv_closereq(sk, skb)) return 0; goto discard; } else if (dh->dccph_type == DCCP_PKT_CLOSE) { /* Step 14 */ if (dccp_rcv_close(sk, skb)) return 0; goto discard; } switch (sk->sk_state) { case DCCP_REQUESTING: queued = dccp_rcv_request_sent_state_process(sk, skb, dh, len); if (queued >= 0) return queued; __kfree_skb(skb); return 0; case DCCP_PARTOPEN: /* Step 8: if using Ack Vectors, mark packet acknowledgeable */ dccp_handle_ackvec_processing(sk, skb); dccp_deliver_input_to_ccids(sk, skb); /* fall through */ case DCCP_RESPOND: queued = dccp_rcv_respond_partopen_state_process(sk, skb, dh, len); break; } if (dh->dccph_type == DCCP_PKT_ACK || dh->dccph_type == DCCP_PKT_DATAACK) { switch (old_state) { case DCCP_PARTOPEN: sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); break; } } else if (unlikely(dh->dccph_type == DCCP_PKT_SYNC)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNCACK); goto discard; } if (!queued) { discard: __kfree_skb(skb); } return 0; } EXPORT_SYMBOL_GPL(dccp_rcv_state_process); /** * dccp_sample_rtt - Validate and finalise computation of RTT sample * @delta: number of microseconds between packet and acknowledgment * * The routine is kept generic to work in different contexts. It should be * called immediately when the ACK used for the RTT sample arrives. */ u32 dccp_sample_rtt(struct sock *sk, long delta) { /* dccpor_elapsed_time is either zeroed out or set and > 0 */ delta -= dccp_sk(sk)->dccps_options_received.dccpor_elapsed_time * 10; if (unlikely(delta <= 0)) { DCCP_WARN("unusable RTT sample %ld, using min\n", delta); return DCCP_SANE_RTT_MIN; } if (unlikely(delta > DCCP_SANE_RTT_MAX)) { DCCP_WARN("RTT sample %ld too large, using max\n", delta); return DCCP_SANE_RTT_MAX; } return delta; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_3161_0
crossvul-cpp_data_good_2579_5
/* #pragma ident "@(#)g_init_sec_context.c 1.20 03/10/24 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_init_sec_context */ #include "mglueP.h" #include <stdio.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> static OM_uint32 val_init_sec_ctx_args( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID req_mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (actual_mech_type != NULL) *actual_mech_type = GSS_C_NO_OID; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE | GSS_S_NO_CONTEXT); if (target_name == NULL) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_BAD_NAME); if (output_token == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_init_sec_context (minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec) OM_uint32 * minor_status; gss_cred_id_t claimant_cred_handle; gss_ctx_id_t * context_handle; gss_name_t target_name; gss_OID req_mech_type; OM_uint32 req_flags; OM_uint32 time_req; gss_channel_bindings_t input_chan_bindings; gss_buffer_t input_token; gss_OID * actual_mech_type; gss_buffer_t output_token; OM_uint32 * ret_flags; OM_uint32 * time_rec; { OM_uint32 status, temp_minor_status; gss_union_name_t union_name; gss_union_cred_t union_cred; gss_name_t internal_name; gss_union_ctx_id_t union_ctx_id; gss_OID selected_mech; gss_mechanism mech; gss_cred_id_t input_cred_handle; status = val_init_sec_ctx_args(minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE) return (status); status = gssint_select_mech_type(minor_status, req_mech_type, &selected_mech); if (status != GSS_S_COMPLETE) return (status); union_name = (gss_union_name_t)target_name; /* * obtain the gss mechanism information for the requested * mechanism. If mech_type is NULL, set it to the resultant * mechanism */ mech = gssint_get_mechanism(selected_mech); if (mech == NULL) return (GSS_S_BAD_MECH); if (mech->gss_init_sec_context == NULL) return (GSS_S_UNAVAILABLE); /* * If target_name is mechanism_specific, then it must match the * mech_type that we're about to use. Otherwise, do an import on * the external_name form of the target name. */ if (union_name->mech_type && g_OID_equal(union_name->mech_type, selected_mech)) { internal_name = union_name->mech_name; } else { if ((status = gssint_import_internal_name(minor_status, selected_mech, union_name, &internal_name)) != GSS_S_COMPLETE) return (status); } /* * if context_handle is GSS_C_NO_CONTEXT, allocate a union context * descriptor to hold the mech type information as well as the * underlying mechanism context handle. Otherwise, cast the * value of *context_handle to the union context variable. */ if(*context_handle == GSS_C_NO_CONTEXT) { status = GSS_S_FAILURE; union_ctx_id = (gss_union_ctx_id_t) malloc(sizeof(gss_union_ctx_id_desc)); if (union_ctx_id == NULL) goto end; if (generic_gss_copy_oid(&temp_minor_status, selected_mech, &union_ctx_id->mech_type) != GSS_S_COMPLETE) { free(union_ctx_id); goto end; } /* copy the supplied context handle */ union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT; } else { union_ctx_id = (gss_union_ctx_id_t)*context_handle; if (union_ctx_id->internal_ctx_id == GSS_C_NO_CONTEXT) { status = GSS_S_NO_CONTEXT; goto end; } } /* * get the appropriate cred handle from the union cred struct. * defaults to GSS_C_NO_CREDENTIAL if there is no cred, which will * use the default credential. */ union_cred = (gss_union_cred_t) claimant_cred_handle; input_cred_handle = gssint_get_mechanism_cred(union_cred, selected_mech); /* * now call the approprate underlying mechanism routine */ status = mech->gss_init_sec_context( minor_status, input_cred_handle, &union_ctx_id->internal_ctx_id, internal_name, gssint_get_public_oid(selected_mech), req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE && status != GSS_S_CONTINUE_NEEDED) { /* * RFC 2744 5.19 requires that we not create a context on a failed * first call to init, and recommends that on a failed subsequent call * we make the caller responsible for calling gss_delete_sec_context. * Even if the mech deleted its context, keep the union context around * for the caller to delete. */ map_error(minor_status, mech); if (*context_handle == GSS_C_NO_CONTEXT) { free(union_ctx_id->mech_type->elements); free(union_ctx_id->mech_type); free(union_ctx_id); } } else if (*context_handle == GSS_C_NO_CONTEXT) { union_ctx_id->loopback = union_ctx_id; *context_handle = (gss_ctx_id_t)union_ctx_id; } end: if (union_name->mech_name == NULL || union_name->mech_name != internal_name) { (void) gssint_release_internal_name(&temp_minor_status, selected_mech, &internal_name); } return(status); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_5
crossvul-cpp_data_good_349_5
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Initially written by David Mattes <david.mattes@boeing.com> */ /* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #define MANU_ID "Gemplus" #define APPLET_NAME "GemSAFE V1" #define DRIVER_SERIAL_NUMBER "v0.9" #define GEMSAFE_APP_PATH "3F001600" #define GEMSAFE_PATH "3F0016000004" /* Apparently, the Applet max read "quanta" is 248 bytes * Gemalto ClassicClient reads files in chunks of 238 bytes */ #define GEMSAFE_READ_QUANTUM 248 #define GEMSAFE_MAX_OBJLEN 28672 int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *); static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags); static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags); static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags); typedef struct cdata_st { char *label; int authority; const char *path; size_t index; size_t count; const char *id; int obj_flags; } cdata; const unsigned int gemsafe_cert_max = 12; cdata gemsafe_cert[] = { {"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE}, }; typedef struct pdata_st { const u8 atr[SC_MAX_ATR_SIZE]; const size_t atr_len; const char *id; const char *label; const char *path; const int ref; const int type; const unsigned int maxlen; const unsigned int minlen; const int flags; const int tries_left; const char pad_char; const int obj_flags; } pindata; const unsigned int gemsafe_pin_max = 2; const pindata gemsafe_pin[] = { /* ATR-specific PIN policies, first match found is used: */ { {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65, 0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC, 8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }, /* default PIN policy comes last: */ { { 0 }, 0, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD, 16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE } }; typedef struct prdata_st { const char *id; char *label; unsigned int modulus_len; int usage; const char *path; int ref; const char *auth_id; int obj_flags; } prdata; #define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION #define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP #define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP | \ SC_PKCS15_PRKEY_USAGE_SIGN prdata gemsafe_prkeys[] = { { "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE}, }; static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01 && i < gemsafe_cert_max) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } static int gemsafe_detect_card( sc_pkcs15_card_t *p15card) { if (strcmp(p15card->card->name, "GemSAFE V1")) return SC_ERROR_WRONG_CARD; return SC_SUCCESS; } static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card) { int r; unsigned int i; struct sc_path path; struct sc_file *file = NULL; struct sc_card *card = p15card->card; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_log(p15card->card->ctx, "Setting pkcs15 parameters"); if (p15card->tokeninfo->label) free(p15card->tokeninfo->label); p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1); if (!p15card->tokeninfo->label) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->label, APPLET_NAME); if (p15card->tokeninfo->serial_number) free(p15card->tokeninfo->serial_number); p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1); if (!p15card->tokeninfo->serial_number) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER); /* the GemSAFE applet version number */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); /* Manual says Le=0x05, but should be 0x08 to return full version number */ apdu.le = 0x08; apdu.lc = 0; apdu.datalen = 0; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* the manufacturer ID, in this case GemPlus */ if (p15card->tokeninfo->manufacturer_id) free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1); if (!p15card->tokeninfo->manufacturer_id) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID); /* determine allocated key containers and length of certificates */ r = gemsafe_get_cert_len(card); if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* set certs */ sc_log(p15card->card->ctx, "Setting certificates"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; if (gemsafe_cert[i].label == NULL) continue; sc_format_path(gemsafe_cert[i].path, &path); sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id); path.index = gemsafe_cert[i].index; path.count = gemsafe_cert[i].count; sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, gemsafe_cert[i].authority, &path, &p15Id, gemsafe_cert[i].label, gemsafe_cert[i].obj_flags); } /* set gemsafe_pin */ sc_log(p15card->card->ctx, "Setting PIN"); for (i=0; i < gemsafe_pin_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id); sc_format_path(gemsafe_pin[i].path, &path); if (gemsafe_pin[i].atr_len == 0 || (gemsafe_pin[i].atr_len == p15card->card->atr.len && memcmp(p15card->card->atr.value, gemsafe_pin[i].atr, p15card->card->atr.len) == 0)) { sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label, &path, gemsafe_pin[i].ref, gemsafe_pin[i].type, gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen, gemsafe_pin[i].flags, gemsafe_pin[i].tries_left, gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags); break; } }; /* set private keys */ sc_log(p15card->card->ctx, "Setting private keys"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id, authId, *pauthId; struct sc_path path; int key_ref = 0x03; if (gemsafe_prkeys[i].label == NULL) continue; sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id); if (gemsafe_prkeys[i].auth_id) { sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId); pauthId = &authId; } else pauthId = NULL; sc_format_path(gemsafe_prkeys[i].path, &path); /* * The key ref may be different for different sites; * by adding flags=n where the low order 4 bits can be * the key ref we can force it. */ if ( p15card->card->flags & 0x0F) { key_ref = p15card->card->flags & 0x0F; sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Overriding key_ref %d with %d\n", gemsafe_prkeys[i].ref, key_ref); } else key_ref = gemsafe_prkeys[i].ref; sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label, SC_PKCS15_TYPE_PRKEY_RSA, gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage, &path, key_ref, pauthId, gemsafe_prkeys[i].obj_flags); } /* select the application DF */ sc_log(p15card->card->ctx, "Selecting application DF"); sc_format_path(GEMSAFE_APP_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* set the application DF */ if (p15card->file_app) free(p15card->file_app); p15card->file_app = file; return SC_SUCCESS; } int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_gemsafeV1_init(p15card); else { int r = gemsafe_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_gemsafeV1_init(p15card); } } static sc_pkcs15_df_t * sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type) { sc_pkcs15_df_t *df; sc_file_t *file; int created = 0; while (1) { for (df = p15card->df_list; df; df = df->next) { if (df->type == type) { if (created) df->enumerated = 1; return df; } } assert(created == 0); file = sc_file_new(); if (!file) return NULL; sc_format_path("11001101", &file->path); sc_pkcs15_add_df(p15card, type, &file->path); sc_file_free(file); created++; } } static int sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type, const char *label, void *data, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_object_t *obj; int df_type; obj = calloc(1, sizeof(*obj)); obj->type = type; obj->data = data; if (label) strncpy(obj->label, label, sizeof(obj->label)-1); obj->flags = obj_flags; if (auth_id) obj->auth_id = *auth_id; switch (type & SC_PKCS15_TYPE_CLASS_MASK) { case SC_PKCS15_TYPE_AUTH: df_type = SC_PKCS15_AODF; break; case SC_PKCS15_TYPE_PRKEY: df_type = SC_PKCS15_PRKDF; break; case SC_PKCS15_TYPE_PUBKEY: df_type = SC_PKCS15_PUKDF; break; case SC_PKCS15_TYPE_CERT: df_type = SC_PKCS15_CDF; break; default: sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type); free(obj); return SC_ERROR_INVALID_ARGUMENTS; } obj->df = sc_pkcs15emu_get_df(p15card, df_type); sc_pkcs15_add_object(p15card, obj); return 0; } static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags) { sc_pkcs15_auth_info_t *info; info = calloc(1, sizeof(*info)); if (!info) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; info->auth_method = SC_AC_CHV; info->auth_id = *id; info->attrs.pin.min_length = min_length; info->attrs.pin.max_length = max_length; info->attrs.pin.stored_length = max_length; info->attrs.pin.type = type; info->attrs.pin.reference = ref; info->attrs.pin.flags = flags; info->attrs.pin.pad_char = pad_char; info->tries_left = tries_left; info->logged_in = SC_PIN_STATE_UNKNOWN; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags) { sc_pkcs15_cert_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->authority = authority; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_prkey_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->modulus_length = modulus_length; info->usage = usage; info->native = 1; info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE | SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE | SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE | SC_PKCS15_PRKEY_ACCESS_LOCAL; info->key_reference = ref; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, auth_id, obj_flags); } /* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_5
crossvul-cpp_data_bad_694_0
/* * OpenVPN -- An application to securely tunnel IP networks * over a single TCP/UDP port, with support for SSL/TLS-based * session authentication and key exchange, * packet encryption, packet authentication, and * packet compression. * * Copyright (C) 2012-2018 Heiko Hund <heiko.hund@sophos.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "service.h" #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #include <userenv.h> #include <accctrl.h> #include <aclapi.h> #include <stdio.h> #include <sddl.h> #include <shellapi.h> #include <mstcpip.h> #ifdef HAVE_VERSIONHELPERS_H #include <versionhelpers.h> #else #include "compat-versionhelpers.h" #endif #include "openvpn-msg.h" #include "validate.h" #include "block_dns.h" #define IO_TIMEOUT 2000 /*ms*/ #define ERROR_OPENVPN_STARTUP 0x20000000 #define ERROR_STARTUP_DATA 0x20000001 #define ERROR_MESSAGE_DATA 0x20000002 #define ERROR_MESSAGE_TYPE 0x20000003 static SERVICE_STATUS_HANDLE service; static SERVICE_STATUS status = { .dwServiceType = SERVICE_WIN32_SHARE_PROCESS }; static HANDLE exit_event = NULL; static settings_t settings; static HANDLE rdns_semaphore = NULL; #define RDNS_TIMEOUT 600 /* seconds to wait for the semaphore */ openvpn_service_t interactive_service = { interactive, TEXT(PACKAGE_NAME "ServiceInteractive"), TEXT(PACKAGE_NAME " Interactive Service"), TEXT(SERVICE_DEPENDENCIES), SERVICE_AUTO_START }; typedef struct { WCHAR *directory; WCHAR *options; WCHAR *std_input; } STARTUP_DATA; /* Datatype for linked lists */ typedef struct _list_item { struct _list_item *next; LPVOID data; } list_item_t; /* Datatypes for undo information */ typedef enum { address, route, block_dns, undo_dns4, undo_dns6, _undo_type_max } undo_type_t; typedef list_item_t *undo_lists_t[_undo_type_max]; typedef struct { HANDLE engine; int index; int metric_v4; int metric_v6; } block_dns_data_t; static DWORD AddListItem(list_item_t **pfirst, LPVOID data) { list_item_t *new_item = malloc(sizeof(list_item_t)); if (new_item == NULL) { return ERROR_OUTOFMEMORY; } new_item->next = *pfirst; new_item->data = data; *pfirst = new_item; return NO_ERROR; } typedef BOOL (*match_fn_t) (LPVOID item, LPVOID ctx); static LPVOID RemoveListItem(list_item_t **pfirst, match_fn_t match, LPVOID ctx) { LPVOID data = NULL; list_item_t **pnext; for (pnext = pfirst; *pnext; pnext = &(*pnext)->next) { list_item_t *item = *pnext; if (!match(item->data, ctx)) { continue; } /* Found item, remove from the list and free memory */ *pnext = item->next; data = item->data; free(item); break; } return data; } static HANDLE CloseHandleEx(LPHANDLE handle) { if (handle && *handle && *handle != INVALID_HANDLE_VALUE) { CloseHandle(*handle); *handle = INVALID_HANDLE_VALUE; } return INVALID_HANDLE_VALUE; } static HANDLE InitOverlapped(LPOVERLAPPED overlapped) { ZeroMemory(overlapped, sizeof(OVERLAPPED)); overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); return overlapped->hEvent; } static BOOL ResetOverlapped(LPOVERLAPPED overlapped) { HANDLE io_event = overlapped->hEvent; if (!ResetEvent(io_event)) { return FALSE; } ZeroMemory(overlapped, sizeof(OVERLAPPED)); overlapped->hEvent = io_event; return TRUE; } typedef enum { peek, read, write } async_op_t; static DWORD AsyncPipeOp(async_op_t op, HANDLE pipe, LPVOID buffer, DWORD size, DWORD count, LPHANDLE events) { int i; BOOL success; HANDLE io_event; DWORD res, bytes = 0; OVERLAPPED overlapped; LPHANDLE handles = NULL; io_event = InitOverlapped(&overlapped); if (!io_event) { goto out; } handles = malloc((count + 1) * sizeof(HANDLE)); if (!handles) { goto out; } if (op == write) { success = WriteFile(pipe, buffer, size, NULL, &overlapped); } else { success = ReadFile(pipe, buffer, size, NULL, &overlapped); } if (!success && GetLastError() != ERROR_IO_PENDING && GetLastError() != ERROR_MORE_DATA) { goto out; } handles[0] = io_event; for (i = 0; i < count; i++) { handles[i + 1] = events[i]; } res = WaitForMultipleObjects(count + 1, handles, FALSE, op == peek ? INFINITE : IO_TIMEOUT); if (res != WAIT_OBJECT_0) { CancelIo(pipe); goto out; } if (op == peek) { PeekNamedPipe(pipe, NULL, 0, NULL, &bytes, NULL); } else { GetOverlappedResult(pipe, &overlapped, &bytes, TRUE); } out: CloseHandleEx(&io_event); free(handles); return bytes; } static DWORD PeekNamedPipeAsync(HANDLE pipe, DWORD count, LPHANDLE events) { return AsyncPipeOp(peek, pipe, NULL, 0, count, events); } static DWORD ReadPipeAsync(HANDLE pipe, LPVOID buffer, DWORD size, DWORD count, LPHANDLE events) { return AsyncPipeOp(read, pipe, buffer, size, count, events); } static DWORD WritePipeAsync(HANDLE pipe, LPVOID data, DWORD size, DWORD count, LPHANDLE events) { return AsyncPipeOp(write, pipe, data, size, count, events); } static VOID ReturnProcessId(HANDLE pipe, DWORD pid, DWORD count, LPHANDLE events) { const WCHAR msg[] = L"Process ID"; WCHAR buf[22 + _countof(msg)]; /* 10 chars each for error and PID and 2 for line breaks */ /* * Same format as error messages (3 line string) with error = 0 in * 0x%08x format, PID on line 2 and a description "Process ID" on line 3 */ swprintf(buf, _countof(buf), L"0x%08x\n0x%08x\n%s", 0, pid, msg); buf[_countof(buf) - 1] = '\0'; WritePipeAsync(pipe, buf, (DWORD)(wcslen(buf) * 2), count, events); } static VOID ReturnError(HANDLE pipe, DWORD error, LPCWSTR func, DWORD count, LPHANDLE events) { DWORD result_len; LPWSTR result = L"0xffffffff\nFormatMessage failed\nCould not return result"; DWORD_PTR args[] = { (DWORD_PTR) error, (DWORD_PTR) func, (DWORD_PTR) "" }; if (error != ERROR_OPENVPN_STARTUP) { FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, (LPWSTR) &args[2], 0, NULL); } result_len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING |FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_ARGUMENT_ARRAY, L"0x%1!08x!\n%2!s!\n%3!s!", 0, 0, (LPWSTR) &result, 0, (va_list *) args); WritePipeAsync(pipe, result, (DWORD)(wcslen(result) * 2), count, events); #ifdef UNICODE MsgToEventLog(MSG_FLAGS_ERROR, result); #else MsgToEventLog(MSG_FLAGS_ERROR, "%S", result); #endif if (error != ERROR_OPENVPN_STARTUP) { LocalFree((LPVOID) args[2]); } if (result_len) { LocalFree(result); } } static VOID ReturnLastError(HANDLE pipe, LPCWSTR func) { ReturnError(pipe, GetLastError(), func, 1, &exit_event); } static VOID ReturnOpenvpnOutput(HANDLE pipe, HANDLE ovpn_output, DWORD count, LPHANDLE events) { WCHAR *wide_output = NULL; CHAR output[512]; DWORD size; ReadFile(ovpn_output, output, sizeof(output), &size, NULL); if (size == 0) { return; } wide_output = malloc((size) * sizeof(WCHAR)); if (wide_output) { MultiByteToWideChar(CP_UTF8, 0, output, size, wide_output, size); wide_output[size - 1] = 0; } ReturnError(pipe, ERROR_OPENVPN_STARTUP, wide_output, count, events); free(wide_output); } /* * Validate options against a white list. Also check the config_file is * inside the config_dir. The white list is defined in validate.c * Returns true on success */ static BOOL ValidateOptions(HANDLE pipe, const WCHAR *workdir, const WCHAR *options) { WCHAR **argv; int argc; WCHAR buf[256]; BOOL ret = FALSE; int i; const WCHAR *msg1 = L"You have specified a config file location (%s relative to %s)" L" that requires admin approval. This error may be avoided" L" by adding your account to the \"%s\" group"; const WCHAR *msg2 = L"You have specified an option (%s) that may be used" L" only with admin approval. This error may be avoided" L" by adding your account to the \"%s\" group"; argv = CommandLineToArgvW(options, &argc); if (!argv) { ReturnLastError(pipe, L"CommandLineToArgvW"); ReturnError(pipe, ERROR_STARTUP_DATA, L"Cannot validate options", 1, &exit_event); goto out; } /* Note: argv[0] is the first option */ if (argc < 1) /* no options */ { ret = TRUE; goto out; } /* * If only one argument, it is the config file */ if (argc == 1) { WCHAR *argv_tmp[2] = { L"--config", argv[0] }; if (!CheckOption(workdir, 2, argv_tmp, &settings)) { swprintf(buf, _countof(buf), msg1, argv[0], workdir, settings.ovpn_admin_group); buf[_countof(buf) - 1] = L'\0'; ReturnError(pipe, ERROR_STARTUP_DATA, buf, 1, &exit_event); } goto out; } for (i = 0; i < argc; ++i) { if (!IsOption(argv[i])) { continue; } if (!CheckOption(workdir, argc-i, &argv[i], &settings)) { if (wcscmp(L"--config", argv[i]) == 0 && argc-i > 1) { swprintf(buf, _countof(buf), msg1, argv[i+1], workdir, settings.ovpn_admin_group); buf[_countof(buf) - 1] = L'\0'; ReturnError(pipe, ERROR_STARTUP_DATA, buf, 1, &exit_event); } else { swprintf(buf, _countof(buf), msg2, argv[i], settings.ovpn_admin_group); buf[_countof(buf) - 1] = L'\0'; ReturnError(pipe, ERROR_STARTUP_DATA, buf, 1, &exit_event); } goto out; } } /* all options passed */ ret = TRUE; out: if (argv) { LocalFree(argv); } return ret; } static BOOL GetStartupData(HANDLE pipe, STARTUP_DATA *sud) { size_t size, len; BOOL ret = FALSE; WCHAR *data = NULL; DWORD bytes, read; bytes = PeekNamedPipeAsync(pipe, 1, &exit_event); if (bytes == 0) { MsgToEventLog(M_SYSERR, TEXT("PeekNamedPipeAsync failed")); ReturnLastError(pipe, L"PeekNamedPipeAsync"); goto out; } size = bytes / sizeof(*data); if (size == 0) { MsgToEventLog(M_SYSERR, TEXT("malformed startup data: 1 byte received")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } data = malloc(bytes); if (data == NULL) { MsgToEventLog(M_SYSERR, TEXT("malloc failed")); ReturnLastError(pipe, L"malloc"); goto out; } read = ReadPipeAsync(pipe, data, bytes, 1, &exit_event); if (bytes != read) { MsgToEventLog(M_SYSERR, TEXT("ReadPipeAsync failed")); ReturnLastError(pipe, L"ReadPipeAsync"); goto out; } if (data[size - 1] != 0) { MsgToEventLog(M_ERR, TEXT("Startup data is not NULL terminated")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } sud->directory = data; len = wcslen(sud->directory) + 1; size -= len; if (size <= 0) { MsgToEventLog(M_ERR, TEXT("Startup data ends at working directory")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } sud->options = sud->directory + len; len = wcslen(sud->options) + 1; size -= len; if (size <= 0) { MsgToEventLog(M_ERR, TEXT("Startup data ends at command line options")); ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event); goto out; } sud->std_input = sud->options + len; data = NULL; /* don't free data */ ret = TRUE; out: free(data); return ret; } static VOID FreeStartupData(STARTUP_DATA *sud) { free(sud->directory); } static SOCKADDR_INET sockaddr_inet(short family, inet_address_t *addr) { SOCKADDR_INET sa_inet; ZeroMemory(&sa_inet, sizeof(sa_inet)); sa_inet.si_family = family; if (family == AF_INET) { sa_inet.Ipv4.sin_addr = addr->ipv4; } else if (family == AF_INET6) { sa_inet.Ipv6.sin6_addr = addr->ipv6; } return sa_inet; } static DWORD InterfaceLuid(const char *iface_name, PNET_LUID luid) { NETIO_STATUS status; LPWSTR wide_name = utf8to16(iface_name); if (wide_name) { status = ConvertInterfaceAliasToLuid(wide_name, luid); free(wide_name); } else { status = ERROR_OUTOFMEMORY; } return status; } static BOOL CmpAddress(LPVOID item, LPVOID address) { return memcmp(item, address, sizeof(MIB_UNICASTIPADDRESS_ROW)) == 0 ? TRUE : FALSE; } static DWORD DeleteAddress(PMIB_UNICASTIPADDRESS_ROW addr_row) { return DeleteUnicastIpAddressEntry(addr_row); } static DWORD HandleAddressMessage(address_message_t *msg, undo_lists_t *lists) { DWORD err; PMIB_UNICASTIPADDRESS_ROW addr_row; BOOL add = msg->header.type == msg_add_address; addr_row = malloc(sizeof(*addr_row)); if (addr_row == NULL) { return ERROR_OUTOFMEMORY; } InitializeUnicastIpAddressEntry(addr_row); addr_row->Address = sockaddr_inet(msg->family, &msg->address); addr_row->OnLinkPrefixLength = (UINT8) msg->prefix_len; if (msg->iface.index != -1) { addr_row->InterfaceIndex = msg->iface.index; } else { NET_LUID luid; err = InterfaceLuid(msg->iface.name, &luid); if (err) { goto out; } addr_row->InterfaceLuid = luid; } if (add) { err = CreateUnicastIpAddressEntry(addr_row); if (err) { goto out; } err = AddListItem(&(*lists)[address], addr_row); if (err) { DeleteAddress(addr_row); } } else { err = DeleteAddress(addr_row); if (err) { goto out; } free(RemoveListItem(&(*lists)[address], CmpAddress, addr_row)); } out: if (!add || err) { free(addr_row); } return err; } static BOOL CmpRoute(LPVOID item, LPVOID route) { return memcmp(item, route, sizeof(MIB_IPFORWARD_ROW2)) == 0 ? TRUE : FALSE; } static DWORD DeleteRoute(PMIB_IPFORWARD_ROW2 fwd_row) { return DeleteIpForwardEntry2(fwd_row); } static DWORD HandleRouteMessage(route_message_t *msg, undo_lists_t *lists) { DWORD err; PMIB_IPFORWARD_ROW2 fwd_row; BOOL add = msg->header.type == msg_add_route; fwd_row = malloc(sizeof(*fwd_row)); if (fwd_row == NULL) { return ERROR_OUTOFMEMORY; } ZeroMemory(fwd_row, sizeof(*fwd_row)); fwd_row->ValidLifetime = 0xffffffff; fwd_row->PreferredLifetime = 0xffffffff; fwd_row->Protocol = MIB_IPPROTO_NETMGMT; fwd_row->Metric = msg->metric; fwd_row->DestinationPrefix.Prefix = sockaddr_inet(msg->family, &msg->prefix); fwd_row->DestinationPrefix.PrefixLength = (UINT8) msg->prefix_len; fwd_row->NextHop = sockaddr_inet(msg->family, &msg->gateway); if (msg->iface.index != -1) { fwd_row->InterfaceIndex = msg->iface.index; } else if (strlen(msg->iface.name)) { NET_LUID luid; err = InterfaceLuid(msg->iface.name, &luid); if (err) { goto out; } fwd_row->InterfaceLuid = luid; } if (add) { err = CreateIpForwardEntry2(fwd_row); if (err) { goto out; } err = AddListItem(&(*lists)[route], fwd_row); if (err) { DeleteRoute(fwd_row); } } else { err = DeleteRoute(fwd_row); if (err) { goto out; } free(RemoveListItem(&(*lists)[route], CmpRoute, fwd_row)); } out: if (!add || err) { free(fwd_row); } return err; } static DWORD HandleFlushNeighborsMessage(flush_neighbors_message_t *msg) { if (msg->family == AF_INET) { return FlushIpNetTable(msg->iface.index); } return FlushIpNetTable2(msg->family, msg->iface.index); } static void BlockDNSErrHandler(DWORD err, const char *msg) { TCHAR buf[256]; LPCTSTR err_str; if (!err) { return; } err_str = TEXT("Unknown Win32 Error"); if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, err, 0, buf, sizeof(buf), NULL)) { err_str = buf; } #ifdef UNICODE MsgToEventLog(M_ERR, L"%S (status = %lu): %s", msg, err, err_str); #else MsgToEventLog(M_ERR, "%s (status = %lu): %s", msg, err, err_str); #endif } /* Use an always-true match_fn to get the head of the list */ static BOOL CmpEngine(LPVOID item, LPVOID any) { return TRUE; } static DWORD HandleBlockDNSMessage(const block_dns_message_t *msg, undo_lists_t *lists) { DWORD err = 0; block_dns_data_t *interface_data; HANDLE engine = NULL; LPCWSTR exe_path; #ifdef UNICODE exe_path = settings.exe_path; #else WCHAR wide_path[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, settings.exe_path, MAX_PATH, wide_path, MAX_PATH); exe_path = wide_path; #endif if (msg->header.type == msg_add_block_dns) { err = add_block_dns_filters(&engine, msg->iface.index, exe_path, BlockDNSErrHandler); if (!err) { interface_data = malloc(sizeof(block_dns_data_t)); if (!interface_data) { return ERROR_OUTOFMEMORY; } interface_data->engine = engine; interface_data->index = msg->iface.index; int is_auto = 0; interface_data->metric_v4 = get_interface_metric(msg->iface.index, AF_INET, &is_auto); if (is_auto) { interface_data->metric_v4 = 0; } interface_data->metric_v6 = get_interface_metric(msg->iface.index, AF_INET6, &is_auto); if (is_auto) { interface_data->metric_v6 = 0; } err = AddListItem(&(*lists)[block_dns], interface_data); if (!err) { err = set_interface_metric(msg->iface.index, AF_INET, BLOCK_DNS_IFACE_METRIC); if (!err) { set_interface_metric(msg->iface.index, AF_INET6, BLOCK_DNS_IFACE_METRIC); } } } } else { interface_data = RemoveListItem(&(*lists)[block_dns], CmpEngine, NULL); if (interface_data) { engine = interface_data->engine; err = delete_block_dns_filters(engine); engine = NULL; if (interface_data->metric_v4 >= 0) { set_interface_metric(msg->iface.index, AF_INET, interface_data->metric_v4); } if (interface_data->metric_v6 >= 0) { set_interface_metric(msg->iface.index, AF_INET6, interface_data->metric_v6); } free(interface_data); } else { MsgToEventLog(M_ERR, TEXT("No previous block DNS filters to delete")); } } if (err && engine) { delete_block_dns_filters(engine); } return err; } /* * Execute a command and return its exit code. If timeout > 0, terminate * the process if still running after timeout milliseconds. In that case * the return value is the windows error code WAIT_TIMEOUT = 0x102 */ static DWORD ExecCommand(const WCHAR *argv0, const WCHAR *cmdline, DWORD timeout) { DWORD exit_code; STARTUPINFOW si; PROCESS_INFORMATION pi; DWORD proc_flags = CREATE_NO_WINDOW|CREATE_UNICODE_ENVIRONMENT; WCHAR *cmdline_dup = NULL; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); /* CreateProcess needs a modifiable cmdline: make a copy */ cmdline_dup = wcsdup(cmdline); if (cmdline_dup && CreateProcessW(argv0, cmdline_dup, NULL, NULL, FALSE, proc_flags, NULL, NULL, &si, &pi) ) { WaitForSingleObject(pi.hProcess, timeout ? timeout : INFINITE); if (!GetExitCodeProcess(pi.hProcess, &exit_code)) { MsgToEventLog(M_SYSERR, TEXT("ExecCommand: Error getting exit_code:")); exit_code = GetLastError(); } else if (exit_code == STILL_ACTIVE) { exit_code = WAIT_TIMEOUT; /* Windows error code 0x102 */ /* kill without impunity */ TerminateProcess(pi.hProcess, exit_code); MsgToEventLog(M_ERR, TEXT("ExecCommand: \"%s %s\" killed after timeout"), argv0, cmdline); } else if (exit_code) { MsgToEventLog(M_ERR, TEXT("ExecCommand: \"%s %s\" exited with status = %lu"), argv0, cmdline, exit_code); } else { MsgToEventLog(M_INFO, TEXT("ExecCommand: \"%s %s\" completed"), argv0, cmdline); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } else { exit_code = GetLastError(); MsgToEventLog(M_SYSERR, TEXT("ExecCommand: could not run \"%s %s\" :"), argv0, cmdline); } free(cmdline_dup); return exit_code; } /* * Entry point for register-dns thread. */ static DWORD WINAPI RegisterDNS(LPVOID unused) { DWORD err; DWORD i; WCHAR sys_path[MAX_PATH]; DWORD timeout = RDNS_TIMEOUT * 1000; /* in milliseconds */ /* default path of ipconfig command */ WCHAR ipcfg[MAX_PATH] = L"C:\\Windows\\system32\\ipconfig.exe"; struct { WCHAR *argv0; WCHAR *cmdline; DWORD timeout; } cmds [] = { { ipcfg, L"ipconfig /flushdns", timeout }, { ipcfg, L"ipconfig /registerdns", timeout }, }; int ncmds = sizeof(cmds) / sizeof(cmds[0]); HANDLE wait_handles[2] = {rdns_semaphore, exit_event}; if (GetSystemDirectory(sys_path, MAX_PATH)) { swprintf(ipcfg, MAX_PATH, L"%s\\%s", sys_path, L"ipconfig.exe"); ipcfg[MAX_PATH-1] = L'\0'; } if (WaitForMultipleObjects(2, wait_handles, FALSE, timeout) == WAIT_OBJECT_0) { /* Semaphore locked */ for (i = 0; i < ncmds; ++i) { ExecCommand(cmds[i].argv0, cmds[i].cmdline, cmds[i].timeout); } err = 0; if (!ReleaseSemaphore(rdns_semaphore, 1, NULL) ) { err = MsgToEventLog(M_SYSERR, TEXT("RegisterDNS: Failed to release regsiter-dns semaphore:")); } } else { MsgToEventLog(M_ERR, TEXT("RegisterDNS: Failed to lock register-dns semaphore")); err = ERROR_SEM_TIMEOUT; /* Windows error code 0x79 */ } return err; } static DWORD HandleRegisterDNSMessage(void) { DWORD err; HANDLE thread = NULL; /* Delegate this job to a sub-thread */ thread = CreateThread(NULL, 0, RegisterDNS, NULL, 0, NULL); /* * We don't add these thread handles to the undo list -- the thread and * processes it spawns are all supposed to terminate or timeout by themselves. */ if (thread) { err = 0; CloseHandle(thread); } else { err = GetLastError(); } return err; } /** * Run the command: netsh interface $proto $action dns $if_name $addr [validate=no] * @param action "delete" or "add" * @param proto "ipv6" or "ip" * @param if_name "name_of_interface" * @param addr IPv4 (for proto = ip) or IPv6 address as a string * * If addr is null and action = "delete" all addresses are deleted. */ static DWORD netsh_dns_cmd(const wchar_t *action, const wchar_t *proto, const wchar_t *if_name, const wchar_t *addr) { DWORD err = 0; int timeout = 30000; /* in msec */ wchar_t argv0[MAX_PATH]; if (!addr) { if (wcscmp(action, L"delete") == 0) { addr = L"all"; } else /* nothing to do -- return success*/ { goto out; } } /* Path of netsh */ int n = GetSystemDirectory(argv0, MAX_PATH); if (n > 0 && n < MAX_PATH) /* got system directory */ { wcsncat(argv0, L"\\netsh.exe", MAX_PATH - n - 1); } else { wcsncpy(argv0, L"C:\\Windows\\system32\\netsh.exe", MAX_PATH); } /* cmd template: * netsh interface $proto $action dns $if_name $addr [validate=no] */ const wchar_t *fmt = L"netsh interface %s %s dns \"%s\" %s"; /* max cmdline length in wchars -- include room for worst case and some */ size_t ncmdline = wcslen(fmt) + wcslen(if_name) + wcslen(addr) + 32 + 1; wchar_t *cmdline = malloc(ncmdline*sizeof(wchar_t)); if (!cmdline) { err = ERROR_OUTOFMEMORY; goto out; } openvpn_sntprintf(cmdline, ncmdline, fmt, proto, action, if_name, addr); if (IsWindows7OrGreater()) { wcsncat(cmdline, L" validate=no", ncmdline - wcslen(cmdline) - 1); } err = ExecCommand(argv0, cmdline, timeout); out: free(cmdline); return err; } /* Delete all IPv4 or IPv6 dns servers for an interface */ static DWORD DeleteDNS(short family, wchar_t *if_name) { wchar_t *proto = (family == AF_INET6) ? L"ipv6" : L"ip"; return netsh_dns_cmd(L"delete", proto, if_name, NULL); } /* Add an IPv4 or IPv6 dns server to an interface */ static DWORD AddDNS(short family, wchar_t *if_name, wchar_t *addr) { wchar_t *proto = (family == AF_INET6) ? L"ipv6" : L"ip"; return netsh_dns_cmd(L"add", proto, if_name, addr); } static BOOL CmpWString(LPVOID item, LPVOID str) { return (wcscmp(item, str) == 0) ? TRUE : FALSE; } static DWORD HandleDNSConfigMessage(const dns_cfg_message_t *msg, undo_lists_t *lists) { DWORD err = 0; wchar_t addr[46]; /* large enough to hold string representation of an ipv4 / ipv6 address */ undo_type_t undo_type = (msg->family == AF_INET6) ? undo_dns4 : undo_dns6; int addr_len = msg->addr_len; /* sanity check */ if (addr_len > _countof(msg->addr)) { addr_len = _countof(msg->addr); } if (!msg->iface.name[0]) /* interface name is required */ { return ERROR_MESSAGE_DATA; } wchar_t *wide_name = utf8to16(msg->iface.name); /* utf8 to wide-char */ if (!wide_name) { return ERROR_OUTOFMEMORY; } /* We delete all current addresses before adding any * OR if the message type is del_dns_cfg */ if (addr_len > 0 || msg->header.type == msg_del_dns_cfg) { err = DeleteDNS(msg->family, wide_name); if (err) { goto out; } free(RemoveListItem(&(*lists)[undo_type], CmpWString, wide_name)); } if (msg->header.type == msg_del_dns_cfg) /* job done */ { goto out; } for (int i = 0; i < addr_len; ++i) { if (msg->family == AF_INET6) { RtlIpv6AddressToStringW(&msg->addr[i].ipv6, addr); } else { RtlIpv4AddressToStringW(&msg->addr[i].ipv4, addr); } err = AddDNS(msg->family, wide_name, addr); if (i == 0 && err) { goto out; } /* We do not check for duplicate addresses, so any error in adding * additional addresses is ignored. */ } if (msg->addr_len > 0) { wchar_t *tmp_name = wcsdup(wide_name); if (!tmp_name || AddListItem(&(*lists)[undo_type], tmp_name)) { free(tmp_name); DeleteDNS(msg->family, wide_name); err = ERROR_OUTOFMEMORY; goto out; } } err = 0; out: free(wide_name); return err; } static VOID HandleMessage(HANDLE pipe, DWORD bytes, DWORD count, LPHANDLE events, undo_lists_t *lists) { DWORD read; union { message_header_t header; address_message_t address; route_message_t route; flush_neighbors_message_t flush_neighbors; block_dns_message_t block_dns; dns_cfg_message_t dns; } msg; ack_message_t ack = { .header = { .type = msg_acknowledgement, .size = sizeof(ack), .message_id = -1 }, .error_number = ERROR_MESSAGE_DATA }; read = ReadPipeAsync(pipe, &msg, bytes, count, events); if (read != bytes || read < sizeof(msg.header) || read != msg.header.size) { goto out; } ack.header.message_id = msg.header.message_id; switch (msg.header.type) { case msg_add_address: case msg_del_address: if (msg.header.size == sizeof(msg.address)) { ack.error_number = HandleAddressMessage(&msg.address, lists); } break; case msg_add_route: case msg_del_route: if (msg.header.size == sizeof(msg.route)) { ack.error_number = HandleRouteMessage(&msg.route, lists); } break; case msg_flush_neighbors: if (msg.header.size == sizeof(msg.flush_neighbors)) { ack.error_number = HandleFlushNeighborsMessage(&msg.flush_neighbors); } break; case msg_add_block_dns: case msg_del_block_dns: if (msg.header.size == sizeof(msg.block_dns)) { ack.error_number = HandleBlockDNSMessage(&msg.block_dns, lists); } break; case msg_register_dns: ack.error_number = HandleRegisterDNSMessage(); break; case msg_add_dns_cfg: case msg_del_dns_cfg: ack.error_number = HandleDNSConfigMessage(&msg.dns, lists); break; default: ack.error_number = ERROR_MESSAGE_TYPE; MsgToEventLog(MSG_FLAGS_ERROR, TEXT("Unknown message type %d"), msg.header.type); break; } out: WritePipeAsync(pipe, &ack, sizeof(ack), count, events); } static VOID Undo(undo_lists_t *lists) { undo_type_t type; block_dns_data_t *interface_data; for (type = 0; type < _undo_type_max; type++) { list_item_t **pnext = &(*lists)[type]; while (*pnext) { list_item_t *item = *pnext; switch (type) { case address: DeleteAddress(item->data); break; case route: DeleteRoute(item->data); break; case undo_dns4: DeleteDNS(AF_INET, item->data); break; case undo_dns6: DeleteDNS(AF_INET6, item->data); break; case block_dns: interface_data = (block_dns_data_t*)(item->data); delete_block_dns_filters(interface_data->engine); if (interface_data->metric_v4 >= 0) { set_interface_metric(interface_data->index, AF_INET, interface_data->metric_v4); } if (interface_data->metric_v6 >= 0) { set_interface_metric(interface_data->index, AF_INET6, interface_data->metric_v6); } break; } /* Remove from the list and free memory */ *pnext = item->next; free(item->data); free(item); } } } static DWORD WINAPI RunOpenvpn(LPVOID p) { HANDLE pipe = p; HANDLE ovpn_pipe, svc_pipe; PTOKEN_USER svc_user, ovpn_user; HANDLE svc_token = NULL, imp_token = NULL, pri_token = NULL; HANDLE stdin_read = NULL, stdin_write = NULL; HANDLE stdout_write = NULL; DWORD pipe_mode, len, exit_code = 0; STARTUP_DATA sud = { 0, 0, 0 }; STARTUPINFOW startup_info; PROCESS_INFORMATION proc_info; LPVOID user_env = NULL; TCHAR ovpn_pipe_name[256]; /* The entire pipe name string can be up to 256 characters long according to MSDN. */ LPCWSTR exe_path; WCHAR *cmdline = NULL; size_t cmdline_size; undo_lists_t undo_lists; SECURITY_ATTRIBUTES inheritable = { .nLength = sizeof(inheritable), .lpSecurityDescriptor = NULL, .bInheritHandle = TRUE }; PACL ovpn_dacl; EXPLICIT_ACCESS ea[2]; SECURITY_DESCRIPTOR ovpn_sd; SECURITY_ATTRIBUTES ovpn_sa = { .nLength = sizeof(ovpn_sa), .lpSecurityDescriptor = &ovpn_sd, .bInheritHandle = FALSE }; ZeroMemory(&ea, sizeof(ea)); ZeroMemory(&startup_info, sizeof(startup_info)); ZeroMemory(&undo_lists, sizeof(undo_lists)); ZeroMemory(&proc_info, sizeof(proc_info)); if (!GetStartupData(pipe, &sud)) { goto out; } if (!InitializeSecurityDescriptor(&ovpn_sd, SECURITY_DESCRIPTOR_REVISION)) { ReturnLastError(pipe, L"InitializeSecurityDescriptor"); goto out; } /* Get SID of user the service is running under */ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &svc_token)) { ReturnLastError(pipe, L"OpenProcessToken"); goto out; } len = 0; svc_user = NULL; while (!GetTokenInformation(svc_token, TokenUser, svc_user, len, &len)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { ReturnLastError(pipe, L"GetTokenInformation (service token)"); goto out; } free(svc_user); svc_user = malloc(len); if (svc_user == NULL) { ReturnLastError(pipe, L"malloc (service token user)"); goto out; } } if (!IsValidSid(svc_user->User.Sid)) { ReturnLastError(pipe, L"IsValidSid (service token user)"); goto out; } if (!ImpersonateNamedPipeClient(pipe)) { ReturnLastError(pipe, L"ImpersonateNamedPipeClient"); goto out; } if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &imp_token)) { ReturnLastError(pipe, L"OpenThreadToken"); goto out; } len = 0; ovpn_user = NULL; while (!GetTokenInformation(imp_token, TokenUser, ovpn_user, len, &len)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { ReturnLastError(pipe, L"GetTokenInformation (impersonation token)"); goto out; } free(ovpn_user); ovpn_user = malloc(len); if (ovpn_user == NULL) { ReturnLastError(pipe, L"malloc (impersonation token user)"); goto out; } } if (!IsValidSid(ovpn_user->User.Sid)) { ReturnLastError(pipe, L"IsValidSid (impersonation token user)"); goto out; } /* Check user is authorized or options are white-listed */ if (!IsAuthorizedUser(ovpn_user->User.Sid, imp_token, settings.ovpn_admin_group) && !ValidateOptions(pipe, sud.directory, sud.options)) { goto out; } /* OpenVPN process DACL entry for access by service and user */ ea[0].grfAccessPermissions = SPECIFIC_RIGHTS_ALL | STANDARD_RIGHTS_ALL; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance = NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN; ea[0].Trustee.ptstrName = (LPTSTR) svc_user->User.Sid; ea[1].grfAccessPermissions = READ_CONTROL | SYNCHRONIZE | PROCESS_VM_READ |SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION; ea[1].grfAccessMode = SET_ACCESS; ea[1].grfInheritance = NO_INHERITANCE; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN; ea[1].Trustee.ptstrName = (LPTSTR) ovpn_user->User.Sid; /* Set owner and DACL of OpenVPN security descriptor */ if (!SetSecurityDescriptorOwner(&ovpn_sd, svc_user->User.Sid, FALSE)) { ReturnLastError(pipe, L"SetSecurityDescriptorOwner"); goto out; } if (SetEntriesInAcl(2, ea, NULL, &ovpn_dacl) != ERROR_SUCCESS) { ReturnLastError(pipe, L"SetEntriesInAcl"); goto out; } if (!SetSecurityDescriptorDacl(&ovpn_sd, TRUE, ovpn_dacl, FALSE)) { ReturnLastError(pipe, L"SetSecurityDescriptorDacl"); goto out; } /* Create primary token from impersonation token */ if (!DuplicateTokenEx(imp_token, TOKEN_ALL_ACCESS, NULL, 0, TokenPrimary, &pri_token)) { ReturnLastError(pipe, L"DuplicateTokenEx"); goto out; } /* use /dev/null for stdout of openvpn (client should use --log for output) */ stdout_write = CreateFile(_T("NUL"), GENERIC_WRITE, FILE_SHARE_WRITE, &inheritable, OPEN_EXISTING, 0, NULL); if (stdout_write == INVALID_HANDLE_VALUE) { ReturnLastError(pipe, L"CreateFile for stdout"); goto out; } if (!CreatePipe(&stdin_read, &stdin_write, &inheritable, 0) || !SetHandleInformation(stdin_write, HANDLE_FLAG_INHERIT, 0)) { ReturnLastError(pipe, L"CreatePipe"); goto out; } openvpn_sntprintf(ovpn_pipe_name, _countof(ovpn_pipe_name), TEXT("\\\\.\\pipe\\" PACKAGE "%s\\service_%lu"), service_instance, GetCurrentThreadId()); ovpn_pipe = CreateNamedPipe(ovpn_pipe_name, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 128, 128, 0, NULL); if (ovpn_pipe == INVALID_HANDLE_VALUE) { ReturnLastError(pipe, L"CreateNamedPipe"); goto out; } svc_pipe = CreateFile(ovpn_pipe_name, GENERIC_READ | GENERIC_WRITE, 0, &inheritable, OPEN_EXISTING, 0, NULL); if (svc_pipe == INVALID_HANDLE_VALUE) { ReturnLastError(pipe, L"CreateFile"); goto out; } pipe_mode = PIPE_READMODE_MESSAGE; if (!SetNamedPipeHandleState(svc_pipe, &pipe_mode, NULL, NULL)) { ReturnLastError(pipe, L"SetNamedPipeHandleState"); goto out; } cmdline_size = wcslen(sud.options) + 128; cmdline = malloc(cmdline_size * sizeof(*cmdline)); if (cmdline == NULL) { ReturnLastError(pipe, L"malloc"); goto out; } openvpn_sntprintf(cmdline, cmdline_size, L"openvpn %s --msg-channel %lu", sud.options, svc_pipe); if (!CreateEnvironmentBlock(&user_env, imp_token, FALSE)) { ReturnLastError(pipe, L"CreateEnvironmentBlock"); goto out; } startup_info.cb = sizeof(startup_info); startup_info.lpDesktop = L"winsta0\\default"; startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = stdin_read; startup_info.hStdOutput = stdout_write; startup_info.hStdError = stdout_write; #ifdef UNICODE exe_path = settings.exe_path; #else WCHAR wide_path[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, settings.exe_path, MAX_PATH, wide_path, MAX_PATH); exe_path = wide_path; #endif /* TODO: make sure HKCU is correct or call LoadUserProfile() */ if (!CreateProcessAsUserW(pri_token, exe_path, cmdline, &ovpn_sa, NULL, TRUE, settings.priority | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, user_env, sud.directory, &startup_info, &proc_info)) { ReturnLastError(pipe, L"CreateProcessAsUser"); goto out; } if (!RevertToSelf()) { TerminateProcess(proc_info.hProcess, 1); ReturnLastError(pipe, L"RevertToSelf"); goto out; } ReturnProcessId(pipe, proc_info.dwProcessId, 1, &exit_event); CloseHandleEx(&stdout_write); CloseHandleEx(&stdin_read); CloseHandleEx(&svc_pipe); DWORD input_size = WideCharToMultiByte(CP_UTF8, 0, sud.std_input, -1, NULL, 0, NULL, NULL); LPSTR input = NULL; if (input_size && (input = malloc(input_size))) { DWORD written; WideCharToMultiByte(CP_UTF8, 0, sud.std_input, -1, input, input_size, NULL, NULL); WriteFile(stdin_write, input, (DWORD)strlen(input), &written, NULL); free(input); } while (TRUE) { DWORD bytes = PeekNamedPipeAsync(ovpn_pipe, 1, &exit_event); if (bytes == 0) { break; } HandleMessage(ovpn_pipe, bytes, 1, &exit_event, &undo_lists); } WaitForSingleObject(proc_info.hProcess, IO_TIMEOUT); GetExitCodeProcess(proc_info.hProcess, &exit_code); if (exit_code == STILL_ACTIVE) { TerminateProcess(proc_info.hProcess, 1); } else if (exit_code != 0) { WCHAR buf[256]; swprintf(buf, _countof(buf), L"OpenVPN exited with error: exit code = %lu", exit_code); buf[_countof(buf) - 1] = L'\0'; ReturnError(pipe, ERROR_OPENVPN_STARTUP, buf, 1, &exit_event); } Undo(&undo_lists); out: FlushFileBuffers(pipe); DisconnectNamedPipe(pipe); free(ovpn_user); free(svc_user); free(cmdline); DestroyEnvironmentBlock(user_env); FreeStartupData(&sud); CloseHandleEx(&proc_info.hProcess); CloseHandleEx(&proc_info.hThread); CloseHandleEx(&stdin_read); CloseHandleEx(&stdin_write); CloseHandleEx(&stdout_write); CloseHandleEx(&svc_token); CloseHandleEx(&imp_token); CloseHandleEx(&pri_token); CloseHandleEx(&ovpn_pipe); CloseHandleEx(&svc_pipe); CloseHandleEx(&pipe); return 0; } static DWORD WINAPI ServiceCtrlInteractive(DWORD ctrl_code, DWORD event, LPVOID data, LPVOID ctx) { SERVICE_STATUS *status = ctx; switch (ctrl_code) { case SERVICE_CONTROL_STOP: status->dwCurrentState = SERVICE_STOP_PENDING; ReportStatusToSCMgr(service, status); if (exit_event) { SetEvent(exit_event); } return NO_ERROR; case SERVICE_CONTROL_INTERROGATE: return NO_ERROR; default: return ERROR_CALL_NOT_IMPLEMENTED; } } static HANDLE CreateClientPipeInstance(VOID) { TCHAR pipe_name[256]; /* The entire pipe name string can be up to 256 characters long according to MSDN. */ HANDLE pipe = NULL; PACL old_dacl, new_dacl; PSECURITY_DESCRIPTOR sd; static EXPLICIT_ACCESS ea[2]; static BOOL initialized = FALSE; DWORD flags = PIPE_ACCESS_DUPLEX | WRITE_DAC | FILE_FLAG_OVERLAPPED; if (!initialized) { PSID everyone, anonymous; ConvertStringSidToSid(TEXT("S-1-1-0"), &everyone); ConvertStringSidToSid(TEXT("S-1-5-7"), &anonymous); ea[0].grfAccessPermissions = FILE_GENERIC_WRITE; ea[0].grfAccessMode = GRANT_ACCESS; ea[0].grfInheritance = NO_INHERITANCE; ea[0].Trustee.pMultipleTrustee = NULL; ea[0].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN; ea[0].Trustee.ptstrName = (LPTSTR) everyone; ea[1].grfAccessPermissions = 0; ea[1].grfAccessMode = REVOKE_ACCESS; ea[1].grfInheritance = NO_INHERITANCE; ea[1].Trustee.pMultipleTrustee = NULL; ea[1].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN; ea[1].Trustee.ptstrName = (LPTSTR) anonymous; flags |= FILE_FLAG_FIRST_PIPE_INSTANCE; initialized = TRUE; } openvpn_sntprintf(pipe_name, _countof(pipe_name), TEXT("\\\\.\\pipe\\" PACKAGE "%s\\service"), service_instance); pipe = CreateNamedPipe(pipe_name, flags, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, NULL); if (pipe == INVALID_HANDLE_VALUE) { MsgToEventLog(M_SYSERR, TEXT("Could not create named pipe")); return INVALID_HANDLE_VALUE; } if (GetSecurityInfo(pipe, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &old_dacl, NULL, &sd) != ERROR_SUCCESS) { MsgToEventLog(M_SYSERR, TEXT("Could not get pipe security info")); return CloseHandleEx(&pipe); } if (SetEntriesInAcl(2, ea, old_dacl, &new_dacl) != ERROR_SUCCESS) { MsgToEventLog(M_SYSERR, TEXT("Could not set entries in new acl")); return CloseHandleEx(&pipe); } if (SetSecurityInfo(pipe, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, new_dacl, NULL) != ERROR_SUCCESS) { MsgToEventLog(M_SYSERR, TEXT("Could not set pipe security info")); return CloseHandleEx(&pipe); } return pipe; } static DWORD UpdateWaitHandles(LPHANDLE *handles_ptr, LPDWORD count, HANDLE io_event, HANDLE exit_event, list_item_t *threads) { static DWORD size = 10; static LPHANDLE handles = NULL; DWORD pos = 0; if (handles == NULL) { handles = malloc(size * sizeof(HANDLE)); *handles_ptr = handles; if (handles == NULL) { return ERROR_OUTOFMEMORY; } } handles[pos++] = io_event; if (!threads) { handles[pos++] = exit_event; } while (threads) { if (pos == size) { LPHANDLE tmp; size += 10; tmp = realloc(handles, size * sizeof(HANDLE)); if (tmp == NULL) { size -= 10; *count = pos; return ERROR_OUTOFMEMORY; } handles = tmp; *handles_ptr = handles; } handles[pos++] = threads->data; threads = threads->next; } *count = pos; return NO_ERROR; } static VOID FreeWaitHandles(LPHANDLE h) { free(h); } static BOOL CmpHandle(LPVOID item, LPVOID hnd) { return item == hnd; } VOID WINAPI ServiceStartInteractiveOwn(DWORD dwArgc, LPTSTR *lpszArgv) { status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; ServiceStartInteractive(dwArgc, lpszArgv); } VOID WINAPI ServiceStartInteractive(DWORD dwArgc, LPTSTR *lpszArgv) { HANDLE pipe, io_event = NULL; OVERLAPPED overlapped; DWORD error = NO_ERROR; list_item_t *threads = NULL; PHANDLE handles = NULL; DWORD handle_count; service = RegisterServiceCtrlHandlerEx(interactive_service.name, ServiceCtrlInteractive, &status); if (!service) { return; } status.dwCurrentState = SERVICE_START_PENDING; status.dwServiceSpecificExitCode = NO_ERROR; status.dwWin32ExitCode = NO_ERROR; status.dwWaitHint = 3000; ReportStatusToSCMgr(service, &status); /* Read info from registry in key HKLM\SOFTWARE\OpenVPN */ error = GetOpenvpnSettings(&settings); if (error != ERROR_SUCCESS) { goto out; } io_event = InitOverlapped(&overlapped); exit_event = CreateEvent(NULL, TRUE, FALSE, NULL); if (!exit_event || !io_event) { error = MsgToEventLog(M_SYSERR, TEXT("Could not create event")); goto out; } rdns_semaphore = CreateSemaphoreW(NULL, 1, 1, NULL); if (!rdns_semaphore) { error = MsgToEventLog(M_SYSERR, TEXT("Could not create semaphore for register-dns")); goto out; } error = UpdateWaitHandles(&handles, &handle_count, io_event, exit_event, threads); if (error != NO_ERROR) { goto out; } pipe = CreateClientPipeInstance(); if (pipe == INVALID_HANDLE_VALUE) { goto out; } status.dwCurrentState = SERVICE_RUNNING; status.dwWaitHint = 0; ReportStatusToSCMgr(service, &status); while (TRUE) { if (ConnectNamedPipe(pipe, &overlapped) == FALSE && GetLastError() != ERROR_PIPE_CONNECTED && GetLastError() != ERROR_IO_PENDING) { MsgToEventLog(M_SYSERR, TEXT("Could not connect pipe")); break; } error = WaitForMultipleObjects(handle_count, handles, FALSE, INFINITE); if (error == WAIT_OBJECT_0) { /* Client connected, spawn a worker thread for it */ HANDLE next_pipe = CreateClientPipeInstance(); HANDLE thread = CreateThread(NULL, 0, RunOpenvpn, pipe, CREATE_SUSPENDED, NULL); if (thread) { error = AddListItem(&threads, thread); if (!error) { error = UpdateWaitHandles(&handles, &handle_count, io_event, exit_event, threads); } if (error) { ReturnError(pipe, error, L"Insufficient resources to service new clients", 1, &exit_event); /* Update wait handles again after removing the last worker thread */ RemoveListItem(&threads, CmpHandle, thread); UpdateWaitHandles(&handles, &handle_count, io_event, exit_event, threads); TerminateThread(thread, 1); CloseHandleEx(&thread); CloseHandleEx(&pipe); } else { ResumeThread(thread); } } else { CloseHandleEx(&pipe); } ResetOverlapped(&overlapped); pipe = next_pipe; } else { CancelIo(pipe); if (error == WAIT_FAILED) { MsgToEventLog(M_SYSERR, TEXT("WaitForMultipleObjects failed")); SetEvent(exit_event); /* Give some time for worker threads to exit and then terminate */ Sleep(1000); break; } if (!threads) { /* exit event signaled */ CloseHandleEx(&pipe); ResetEvent(exit_event); error = NO_ERROR; break; } /* Worker thread ended */ HANDLE thread = RemoveListItem(&threads, CmpHandle, handles[error]); UpdateWaitHandles(&handles, &handle_count, io_event, exit_event, threads); CloseHandleEx(&thread); } } out: FreeWaitHandles(handles); CloseHandleEx(&io_event); CloseHandleEx(&exit_event); CloseHandleEx(&rdns_semaphore); status.dwCurrentState = SERVICE_STOPPED; status.dwWin32ExitCode = error; ReportStatusToSCMgr(service, &status); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_694_0
crossvul-cpp_data_good_2579_4
/* #pragma ident "@(#)g_exp_sec_context.c 1.14 04/02/23 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_export_sec_context */ #ifndef LEAN_CLIENT #include "mglueP.h" #include <stdio.h> #include <errno.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> static OM_uint32 val_exp_sec_ctx_args( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (interprocess_token != GSS_C_NO_BUFFER) { interprocess_token->length = 0; interprocess_token->value = NULL; } /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (interprocess_token == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_buffer_t interprocess_token; { OM_uint32 status; OM_uint32 length; gss_union_ctx_id_t ctx = NULL; gss_mechanism mech; gss_buffer_desc token = GSS_C_EMPTY_BUFFER; char *buf; status = val_exp_sec_ctx_args(minor_status, context_handle, interprocess_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) *context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return GSS_S_BAD_MECH; if (!mech->gss_export_sec_context) return (GSS_S_UNAVAILABLE); status = mech->gss_export_sec_context(minor_status, &ctx->internal_ctx_id, &token); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); goto cleanup; } length = token.length + 4 + ctx->mech_type->length; interprocess_token->length = length; interprocess_token->value = malloc(length); if (interprocess_token->value == 0) { *minor_status = ENOMEM; status = GSS_S_FAILURE; goto cleanup; } buf = interprocess_token->value; length = ctx->mech_type->length; buf[3] = (unsigned char) (length & 0xFF); length >>= 8; buf[2] = (unsigned char) (length & 0xFF); length >>= 8; buf[1] = (unsigned char) (length & 0xFF); length >>= 8; buf[0] = (unsigned char) (length & 0xFF); memcpy(buf+4, ctx->mech_type->elements, (size_t) ctx->mech_type->length); memcpy(buf+4+ctx->mech_type->length, token.value, token.length); status = GSS_S_COMPLETE; cleanup: (void) gss_release_buffer(minor_status, &token); if (ctx != NULL && ctx->internal_ctx_id == GSS_C_NO_CONTEXT) { /* If the mech deleted its context, delete the union context. */ free(ctx->mech_type->elements); free(ctx->mech_type); free(ctx); *context_handle = GSS_C_NO_CONTEXT; } return status; } #endif /*LEAN_CLIENT */
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_4
crossvul-cpp_data_bad_349_3
/* * card-tcos.c: Support for TCOS cards * * Copyright (C) 2011 Peter Koch <pk@opensc-project.org> * Copyright (C) 2002 g10 Code GmbH * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <ctype.h> #include <time.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table tcos_atrs[] = { /* Infineon SLE44 */ { "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66S */ { "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX320P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX322P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Philips P5CT072 */ { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, /* Philips P5CT080 */ { "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_card_operations tcos_ops; static struct sc_card_driver tcos_drv = { "TCOS 3.0", "tcos", &tcos_ops, NULL, 0, NULL }; static const struct sc_card_operations *iso_ops = NULL; typedef struct tcos_data_st { unsigned int pad_flags; unsigned int next_sign; } tcos_data; static int tcos_finish(sc_card_t *card) { free(card->drv_data); return 0; } static int tcos_match_card(sc_card_t *card) { int i; i = _sc_match_atr(card, tcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int tcos_init(sc_card_t *card) { unsigned long flags; tcos_data *data = malloc(sizeof(tcos_data)); if (!data) return SC_ERROR_OUT_OF_MEMORY; card->name = "TCOS"; card->drv_data = (void *)data; card->cla = 0x00; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); if (card->type == SC_CARD_TYPE_TCOS_V3) { card->caps |= SC_CARD_CAP_APDU_EXT; _sc_card_add_rsa_alg(card, 1280, flags, 0); _sc_card_add_rsa_alg(card, 1536, flags, 0); _sc_card_add_rsa_alg(card, 1792, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return 0; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static int tcos_construct_fci(const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; size_t n; /* FIXME: possible buffer overflow */ *p++ = 0x6F; /* FCI */ p++; /* File size */ buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x81, buf, 2, p, 16, &p); /* File descriptor */ n = 0; buf[n] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_WORKING_EF: break; case SC_FILE_TYPE_DF: buf[0] |= 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } buf[n++] |= file->ef_structure & 7; if ( (file->ef_structure & 7) > 1) { /* record structured file */ buf[n++] = 0x41; /* indicate 3rd byte */ buf[n++] = file->record_length; } sc_asn1_put_tag(0x82, buf, n, p, 8, &p); /* File identifier */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, 16, &p); /* Directory name */ if (file->type == SC_FILE_TYPE_DF) { if (file->namelen) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, 16, &p); } else { /* TCOS needs one, so we use a faked one */ snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu", (unsigned long) time (NULL)); sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p); } } /* File descriptor extension */ if (file->prop_attr_len && file->prop_attr) { n = file->prop_attr_len; memcpy(buf, file->prop_attr, n); } else { n = 0; buf[n++] = 0x01; /* not invalidated, permanent */ if (file->type == SC_FILE_TYPE_WORKING_EF) buf[n++] = 0x00; /* generic data file */ } sc_asn1_put_tag(0x85, buf, n, p, 16, &p); /* Security attributes */ if (file->sec_attr_len && file->sec_attr) { memcpy(buf, file->sec_attr, file->sec_attr_len); n = file->sec_attr_len; } else { /* no attributes given - fall back to default one */ memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */ memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */ memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */ memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/ n = 24; } sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p); /* fixup length of FCI */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int tcos_create_file(sc_card_t *card, sc_file_t *file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; len = SC_MAX_APDU_BUFFER_SIZE; r = tcos_construct_fci(file, sbuf, &len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.cla |= 0x80; /* this is an proprietary extension */ apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static unsigned int map_operations (int commandbyte ) { unsigned int op = (unsigned int)-1; switch ( (commandbyte & 0xfe) ) { case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break; case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break; case 0xe0: /* create */ op = SC_AC_OP_CREATE; break; case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break; case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break; case 0x82: /* external auth */ op = SC_AC_OP_READ; break; case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break; case 0x88: /* internal auth */ op = SC_AC_OP_READ; break; case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break; case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break; case 0xb0: /* read binary */ op = SC_AC_OP_READ; break; case 0xb2: /* read record */ op = SC_AC_OP_READ; break; case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break; case 0xa4: /* select */ op = SC_AC_OP_SELECT; break; case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break; case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break; case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break; case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break; case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break; case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break; } return op; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static void parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { unsigned int op; /* list directory is not covered by ACLs - so always add an entry */ sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES, SC_AC_NONE, SC_AC_KEY_REF_NONE); /* FIXME: check for what LOCK is used */ sc_file_add_acl_entry (file, SC_AC_OP_LOCK, SC_AC_NONE, SC_AC_KEY_REF_NONE); for (; len >= 6; len -= 6, buf += 6) { /* FIXME: temporary hacks */ if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */ sc_file_add_acl_entry (file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/ sc_file_add_acl_entry (file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/ sc_file_add_acl_entry (file, SC_AC_OP_UPDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */ sc_file_add_acl_entry (file, SC_AC_OP_WRITE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_CREATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else { /* the first byte tells use the command or the command group. We have to mask bit 0 because this one distinguish between AND/OR combination of PINs*/ op = map_operations (buf[0]); if (op == (unsigned int)-1) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown security command byte %02x\n", buf[0]); continue; } if (!buf[1]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_CHV, buf[1]); if (!buf[2] && !buf[3]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_TERM, (buf[2]<<8)|buf[3]); } } } static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1; int r, count = 0; assert(card != NULL); ctx = card->ctx; for (p1=1; p1<=2; p1++) { sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n", apdu.resplen / 2, p1 == 1 ? "DF" : "EF"); memcpy(buf, apdu.resp, apdu.resplen); buf += apdu.resplen; buflen -= apdu.resplen; count += apdu.resplen; } return count; } static int tcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r; u8 sbuf[2]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } sbuf[0] = path->value[0]; sbuf[1] = path->value[1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_context_t *ctx; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p; int r, default_key, tcos3; tcos_data *data; assert(card != NULL && env != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "No Key-Reference in SecEnvironment\n"); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n", env->key_ref[0], env->key_ref_len); /* Key-Reference 0x80 ?? */ default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n", tcos3, !!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); data->pad_flags = env->algorithm_flags; data->next_sign = default_key; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8); p = sbuf; *p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10; if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { *p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } apdu.data = sbuf; apdu.lc = apdu.datalen = (p - sbuf); r=sc_transmit_apdu(card, &apdu); if (r) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Detected Signature-Only key\n"); if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS; } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_restore_security_env(sc_card_t *card, int se_num) { return 0; } static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { size_t i, dlen=datalen; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int tcos3, r; assert(card != NULL && data != NULL && out != NULL); tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); if(((tcos_data *)card->drv_data)->next_sign){ if(datalen>48){ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A); memcpy(sbuf, data, datalen); dlen=datalen; } else { int keylen= tcos3 ? 256 : 128; sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = tcos3 ? 256 : 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) { int keylen=128; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); } if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len = apdu.resplen>outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){ offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset; offset=(offset<len-1) ? offset+1 : 0; } memcpy(out, apdu.resp+offset, len-offset); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the NullPIN method will be activated, otherwise the permanent operation will be done on the active file. */ static int tcos_setperm(sc_card_t *card, int enable_nullpin) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 0; apdu.datalen = 0; apdu.data = NULL; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; if (!serial) return SC_ERROR_INVALID_ARGUMENTS; /* see if we have cached serial number */ if (card->serialnr.len) { memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } card->serialnr.len = sizeof card->serialnr.value; r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0); if (r < 0) { card->serialnr.len = 0; return r; } /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_TCOS_SETPERM: return tcos_setperm(card, !!ptr); case SC_CARDCTL_GET_SERIALNR: return tcos_get_serialnr(card, (sc_serial_number_t *)ptr); } return SC_ERROR_NOT_SUPPORTED; } struct sc_card_driver * sc_get_tcos_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; tcos_ops = *iso_drv->ops; tcos_ops.match_card = tcos_match_card; tcos_ops.init = tcos_init; tcos_ops.finish = tcos_finish; tcos_ops.create_file = tcos_create_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.select_file = tcos_select_file; tcos_ops.list_files = tcos_list_files; tcos_ops.delete_file = tcos_delete_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.compute_signature = tcos_compute_signature; tcos_ops.decipher = tcos_decipher; tcos_ops.restore_security_env = tcos_restore_security_env; tcos_ops.card_ctl = tcos_card_ctl; return &tcos_drv; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_349_3
crossvul-cpp_data_good_348_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid = fs->cache.array[x].objectId.id; if (bufLen < 2) break; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count += 2; bufLen -= 2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_2
crossvul-cpp_data_good_2579_13
/* #pragma ident "@(#)g_seal.c 1.19 98/04/21 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_unwrap_iov */ #include "mglueP.h" static OM_uint32 val_unwrap_iov_args( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (iov == GSS_C_NO_IOV_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_unwrap_iov (minor_status, context_handle, conf_state, qop_state, iov, iov_count) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int * conf_state; gss_qop_t *qop_state; gss_iov_buffer_desc * iov; int iov_count; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_unwrap_iov_args(minor_status, context_handle, conf_state, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_unwrap_iov) { status = mech->gss_unwrap_iov( minor_status, ctx->internal_ctx_id, conf_state, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_unwrap_iov_args(minor_status, context_handle, NULL, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) return status; /* Select the approprate underlying mechanism routine and call it. */ ctx = (gss_union_ctx_id_t)context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; mech = gssint_get_mechanism(ctx->mech_type); if (mech == NULL) return GSS_S_BAD_MECH; if (mech->gss_verify_mic_iov == NULL) return GSS_S_UNAVAILABLE; status = mech->gss_verify_mic_iov(minor_status, ctx->internal_ctx_id, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); return status; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_13
crossvul-cpp_data_good_347_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL || sec_attr_len) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_7
crossvul-cpp_data_bad_349_5
/* * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Initially written by David Mattes <david.mattes@boeing.com> */ /* Support for multiple key containers by Lukas Wunner <lukas@wunner.de> */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #define MANU_ID "Gemplus" #define APPLET_NAME "GemSAFE V1" #define DRIVER_SERIAL_NUMBER "v0.9" #define GEMSAFE_APP_PATH "3F001600" #define GEMSAFE_PATH "3F0016000004" /* Apparently, the Applet max read "quanta" is 248 bytes * Gemalto ClassicClient reads files in chunks of 238 bytes */ #define GEMSAFE_READ_QUANTUM 248 #define GEMSAFE_MAX_OBJLEN 28672 int sc_pkcs15emu_gemsafeV1_init_ex(sc_pkcs15_card_t *, struct sc_aid *,sc_pkcs15emu_opt_t *); static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags); static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags); static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags); typedef struct cdata_st { char *label; int authority; const char *path; size_t index; size_t count; const char *id; int obj_flags; } cdata; const unsigned int gemsafe_cert_max = 12; cdata gemsafe_cert[] = { {"DS certificate #1", 0, GEMSAFE_PATH, 0, 0, "45", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #2", 0, GEMSAFE_PATH, 0, 0, "46", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #3", 0, GEMSAFE_PATH, 0, 0, "47", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #4", 0, GEMSAFE_PATH, 0, 0, "48", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #5", 0, GEMSAFE_PATH, 0, 0, "49", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #6", 0, GEMSAFE_PATH, 0, 0, "50", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #7", 0, GEMSAFE_PATH, 0, 0, "51", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #8", 0, GEMSAFE_PATH, 0, 0, "52", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #9", 0, GEMSAFE_PATH, 0, 0, "53", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #10", 0, GEMSAFE_PATH, 0, 0, "54", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #11", 0, GEMSAFE_PATH, 0, 0, "55", SC_PKCS15_CO_FLAG_MODIFIABLE}, {"DS certificate #12", 0, GEMSAFE_PATH, 0, 0, "56", SC_PKCS15_CO_FLAG_MODIFIABLE}, }; typedef struct pdata_st { const u8 atr[SC_MAX_ATR_SIZE]; const size_t atr_len; const char *id; const char *label; const char *path; const int ref; const int type; const unsigned int maxlen; const unsigned int minlen; const int flags; const int tries_left; const char pad_char; const int obj_flags; } pindata; const unsigned int gemsafe_pin_max = 2; const pindata gemsafe_pin[] = { /* ATR-specific PIN policies, first match found is used: */ { {0x3B, 0x7D, 0x96, 0x00, 0x00, 0x80, 0x31, 0x80, 0x65, 0xB0, 0x83, 0x11, 0x48, 0xC8, 0x83, 0x00, 0x90, 0x00}, 18, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_ASCII_NUMERIC, 8, 4, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0x00, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE }, /* default PIN policy comes last: */ { { 0 }, 0, "01", "DS pin", GEMSAFE_PATH, 0x01, SC_PKCS15_PIN_TYPE_BCD, 16, 6, SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL, 3, 0xFF, SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE } }; typedef struct prdata_st { const char *id; char *label; unsigned int modulus_len; int usage; const char *path; int ref; const char *auth_id; int obj_flags; } prdata; #define USAGE_NONREP SC_PKCS15_PRKEY_USAGE_NONREPUDIATION #define USAGE_KE SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP #define USAGE_AUT SC_PKCS15_PRKEY_USAGE_ENCRYPT | \ SC_PKCS15_PRKEY_USAGE_DECRYPT | \ SC_PKCS15_PRKEY_USAGE_WRAP | \ SC_PKCS15_PRKEY_USAGE_UNWRAP | \ SC_PKCS15_PRKEY_USAGE_SIGN prdata gemsafe_prkeys[] = { { "45", "DS key #1", 1024, USAGE_AUT, GEMSAFE_PATH, 0x03, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "46", "DS key #2", 1024, USAGE_AUT, GEMSAFE_PATH, 0x04, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "47", "DS key #3", 1024, USAGE_AUT, GEMSAFE_PATH, 0x05, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "48", "DS key #4", 1024, USAGE_AUT, GEMSAFE_PATH, 0x06, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "49", "DS key #5", 1024, USAGE_AUT, GEMSAFE_PATH, 0x07, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "50", "DS key #6", 1024, USAGE_AUT, GEMSAFE_PATH, 0x08, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "51", "DS key #7", 1024, USAGE_AUT, GEMSAFE_PATH, 0x09, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "52", "DS key #8", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0a, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "53", "DS key #9", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0b, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "54", "DS key #10", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0c, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "55", "DS key #11", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0d, "01", SC_PKCS15_CO_FLAG_PRIVATE}, { "56", "DS key #12", 1024, USAGE_AUT, GEMSAFE_PATH, 0x0e, "01", SC_PKCS15_CO_FLAG_PRIVATE}, }; static int gemsafe_get_cert_len(sc_card_t *card) { int r; u8 ibuf[GEMSAFE_MAX_OBJLEN]; u8 *iptr; struct sc_path path; struct sc_file *file; size_t objlen, certlen; unsigned int ind, i=0; sc_format_path(GEMSAFE_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* Initial read */ r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0); if (r < 0) return SC_ERROR_INTERNAL; /* Actual stored object size is encoded in first 2 bytes * (allocated EF space is much greater!) */ objlen = (((size_t) ibuf[0]) << 8) | ibuf[1]; sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) { sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u", objlen); return SC_ERROR_INTERNAL; } /* It looks like the first thing in the block is a table of * which keys are allocated. The table is small and is in the * first 248 bytes. Example for a card with 10 key containers: * 01 f0 00 03 03 b0 00 03 <= 1st key unallocated * 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated * 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated * 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated * 01 f0 00 07 03 b0 00 07 <= 5th key unallocated * ... * 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated * For allocated keys, the fourth byte seems to indicate the * default key and the fifth byte indicates the key_ref of * the private key. */ ind = 2; /* skip length */ while (ibuf[ind] == 0x01) { if (ibuf[ind+1] == 0xFE) { gemsafe_prkeys[i].ref = ibuf[ind+4]; sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d", i+1, gemsafe_prkeys[i].ref); ind += 9; } else { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; sc_log(card->ctx, "Key container %d is unallocated", i+1); ind += 8; } i++; } /* Delete additional key containers from the data structures if * this card can't accommodate them. */ for (; i < gemsafe_cert_max; i++) { gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } /* Read entire file, then dissect in memory. * Gemalto ClassicClient seems to do it the same way. */ iptr = ibuf + GEMSAFE_READ_QUANTUM; while ((size_t)(iptr - ibuf) < objlen) { r = sc_read_binary(card, iptr - ibuf, iptr, MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0); if (r < 0) { sc_log(card->ctx, "Could not read cert object"); return SC_ERROR_INTERNAL; } iptr += GEMSAFE_READ_QUANTUM; } /* Search buffer for certificates, they start with 0x3082. */ i = 0; while (ind < objlen - 1) { if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) { /* Find next allocated key container */ while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL) i++; if (i == gemsafe_cert_max) { sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind); return SC_SUCCESS; } /* DER cert len is encoded this way */ if (ind+3 >= sizeof ibuf) return SC_ERROR_INVALID_DATA; certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4; sc_log(card->ctx, "Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u", i+1, ind, certlen); gemsafe_cert[i].index = ind; gemsafe_cert[i].count = certlen; ind += certlen; i++; } else ind++; } /* Delete additional key containers from the data structures if * they're missing on the card. */ for (; i < gemsafe_cert_max; i++) { if (gemsafe_cert[i].label) { sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1); gemsafe_prkeys[i].label = NULL; gemsafe_cert[i].label = NULL; } } return SC_SUCCESS; } static int gemsafe_detect_card( sc_pkcs15_card_t *p15card) { if (strcmp(p15card->card->name, "GemSAFE V1")) return SC_ERROR_WRONG_CARD; return SC_SUCCESS; } static int sc_pkcs15emu_gemsafeV1_init( sc_pkcs15_card_t *p15card) { int r; unsigned int i; struct sc_path path; struct sc_file *file = NULL; struct sc_card *card = p15card->card; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_log(p15card->card->ctx, "Setting pkcs15 parameters"); if (p15card->tokeninfo->label) free(p15card->tokeninfo->label); p15card->tokeninfo->label = malloc(strlen(APPLET_NAME) + 1); if (!p15card->tokeninfo->label) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->label, APPLET_NAME); if (p15card->tokeninfo->serial_number) free(p15card->tokeninfo->serial_number); p15card->tokeninfo->serial_number = malloc(strlen(DRIVER_SERIAL_NUMBER) + 1); if (!p15card->tokeninfo->serial_number) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->serial_number, DRIVER_SERIAL_NUMBER); /* the GemSAFE applet version number */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0xdf, 0x03); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); /* Manual says Le=0x05, but should be 0x08 to return full version number */ apdu.le = 0x08; apdu.lc = 0; apdu.datalen = 0; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) return SC_ERROR_INTERNAL; if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* the manufacturer ID, in this case GemPlus */ if (p15card->tokeninfo->manufacturer_id) free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = malloc(strlen(MANU_ID) + 1); if (!p15card->tokeninfo->manufacturer_id) return SC_ERROR_INTERNAL; strcpy(p15card->tokeninfo->manufacturer_id, MANU_ID); /* determine allocated key containers and length of certificates */ r = gemsafe_get_cert_len(card); if (r != SC_SUCCESS) return SC_ERROR_INTERNAL; /* set certs */ sc_log(p15card->card->ctx, "Setting certificates"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; if (gemsafe_cert[i].label == NULL) continue; sc_format_path(gemsafe_cert[i].path, &path); sc_pkcs15_format_id(gemsafe_cert[i].id, &p15Id); path.index = gemsafe_cert[i].index; path.count = gemsafe_cert[i].count; sc_pkcs15emu_add_cert(p15card, SC_PKCS15_TYPE_CERT_X509, gemsafe_cert[i].authority, &path, &p15Id, gemsafe_cert[i].label, gemsafe_cert[i].obj_flags); } /* set gemsafe_pin */ sc_log(p15card->card->ctx, "Setting PIN"); for (i=0; i < gemsafe_pin_max; i++) { struct sc_pkcs15_id p15Id; struct sc_path path; sc_pkcs15_format_id(gemsafe_pin[i].id, &p15Id); sc_format_path(gemsafe_pin[i].path, &path); if (gemsafe_pin[i].atr_len == 0 || (gemsafe_pin[i].atr_len == p15card->card->atr.len && memcmp(p15card->card->atr.value, gemsafe_pin[i].atr, p15card->card->atr.len) == 0)) { sc_pkcs15emu_add_pin(p15card, &p15Id, gemsafe_pin[i].label, &path, gemsafe_pin[i].ref, gemsafe_pin[i].type, gemsafe_pin[i].minlen, gemsafe_pin[i].maxlen, gemsafe_pin[i].flags, gemsafe_pin[i].tries_left, gemsafe_pin[i].pad_char, gemsafe_pin[i].obj_flags); break; } }; /* set private keys */ sc_log(p15card->card->ctx, "Setting private keys"); for (i = 0; i < gemsafe_cert_max; i++) { struct sc_pkcs15_id p15Id, authId, *pauthId; struct sc_path path; int key_ref = 0x03; if (gemsafe_prkeys[i].label == NULL) continue; sc_pkcs15_format_id(gemsafe_prkeys[i].id, &p15Id); if (gemsafe_prkeys[i].auth_id) { sc_pkcs15_format_id(gemsafe_prkeys[i].auth_id, &authId); pauthId = &authId; } else pauthId = NULL; sc_format_path(gemsafe_prkeys[i].path, &path); /* * The key ref may be different for different sites; * by adding flags=n where the low order 4 bits can be * the key ref we can force it. */ if ( p15card->card->flags & 0x0F) { key_ref = p15card->card->flags & 0x0F; sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Overriding key_ref %d with %d\n", gemsafe_prkeys[i].ref, key_ref); } else key_ref = gemsafe_prkeys[i].ref; sc_pkcs15emu_add_prkey(p15card, &p15Id, gemsafe_prkeys[i].label, SC_PKCS15_TYPE_PRKEY_RSA, gemsafe_prkeys[i].modulus_len, gemsafe_prkeys[i].usage, &path, key_ref, pauthId, gemsafe_prkeys[i].obj_flags); } /* select the application DF */ sc_log(p15card->card->ctx, "Selecting application DF"); sc_format_path(GEMSAFE_APP_PATH, &path); r = sc_select_file(card, &path, &file); if (r != SC_SUCCESS || !file) return SC_ERROR_INTERNAL; /* set the application DF */ if (p15card->file_app) free(p15card->file_app); p15card->file_app = file; return SC_SUCCESS; } int sc_pkcs15emu_gemsafeV1_init_ex( sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_gemsafeV1_init(p15card); else { int r = gemsafe_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_gemsafeV1_init(p15card); } } static sc_pkcs15_df_t * sc_pkcs15emu_get_df(sc_pkcs15_card_t *p15card, unsigned int type) { sc_pkcs15_df_t *df; sc_file_t *file; int created = 0; while (1) { for (df = p15card->df_list; df; df = df->next) { if (df->type == type) { if (created) df->enumerated = 1; return df; } } assert(created == 0); file = sc_file_new(); if (!file) return NULL; sc_format_path("11001101", &file->path); sc_pkcs15_add_df(p15card, type, &file->path); sc_file_free(file); created++; } } static int sc_pkcs15emu_add_object(sc_pkcs15_card_t *p15card, int type, const char *label, void *data, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_object_t *obj; int df_type; obj = calloc(1, sizeof(*obj)); obj->type = type; obj->data = data; if (label) strncpy(obj->label, label, sizeof(obj->label)-1); obj->flags = obj_flags; if (auth_id) obj->auth_id = *auth_id; switch (type & SC_PKCS15_TYPE_CLASS_MASK) { case SC_PKCS15_TYPE_AUTH: df_type = SC_PKCS15_AODF; break; case SC_PKCS15_TYPE_PRKEY: df_type = SC_PKCS15_PRKDF; break; case SC_PKCS15_TYPE_PUBKEY: df_type = SC_PKCS15_PUKDF; break; case SC_PKCS15_TYPE_CERT: df_type = SC_PKCS15_CDF; break; default: sc_log(p15card->card->ctx, "Unknown PKCS15 object type %d", type); free(obj); return SC_ERROR_INVALID_ARGUMENTS; } obj->df = sc_pkcs15emu_get_df(p15card, df_type); sc_pkcs15_add_object(p15card, obj); return 0; } static int sc_pkcs15emu_add_pin(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, const sc_path_t *path, int ref, int type, unsigned int min_length, unsigned int max_length, int flags, int tries_left, const char pad_char, int obj_flags) { sc_pkcs15_auth_info_t *info; info = calloc(1, sizeof(*info)); if (!info) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); info->auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; info->auth_method = SC_AC_CHV; info->auth_id = *id; info->attrs.pin.min_length = min_length; info->attrs.pin.max_length = max_length; info->attrs.pin.stored_length = max_length; info->attrs.pin.type = type; info->attrs.pin.reference = ref; info->attrs.pin.flags = flags; info->attrs.pin.pad_char = pad_char; info->tries_left = tries_left; info->logged_in = SC_PIN_STATE_UNKNOWN; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, SC_PKCS15_TYPE_AUTH_PIN, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_cert(sc_pkcs15_card_t *p15card, int type, int authority, const sc_path_t *path, const sc_pkcs15_id_t *id, const char *label, int obj_flags) { sc_pkcs15_cert_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->authority = authority; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, NULL, obj_flags); } static int sc_pkcs15emu_add_prkey(sc_pkcs15_card_t *p15card, const sc_pkcs15_id_t *id, const char *label, int type, unsigned int modulus_length, int usage, const sc_path_t *path, int ref, const sc_pkcs15_id_t *auth_id, int obj_flags) { sc_pkcs15_prkey_info_t *info; info = calloc(1, sizeof(*info)); if (!info) { LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_OUT_OF_MEMORY); } info->id = *id; info->modulus_length = modulus_length; info->usage = usage; info->native = 1; info->access_flags = SC_PKCS15_PRKEY_ACCESS_SENSITIVE | SC_PKCS15_PRKEY_ACCESS_ALWAYSSENSITIVE | SC_PKCS15_PRKEY_ACCESS_NEVEREXTRACTABLE | SC_PKCS15_PRKEY_ACCESS_LOCAL; info->key_reference = ref; if (path) info->path = *path; return sc_pkcs15emu_add_object(p15card, type, label, info, auth_id, obj_flags); } /* SC_IMPLEMENT_DRIVER_VERSION("0.9.4") */
./CrossVul/dataset_final_sorted/CWE-415/c/bad_349_5
crossvul-cpp_data_good_1361_0
/* A Bison parser, made by GNU Bison 3.2.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.2.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 2 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "libyang.h" #include "common.h" #include "context.h" #include "resolve.h" #include "parser_yang.h" #include "parser_yang_lex.h" #include "parser.h" #define YANG_ADDELEM(current_ptr, size, array_name) \ if ((size) == LY_ARRAY_MAX(size)) { \ LOGERR(trg->ctx, LY_EINT, "Reached limit (%"PRIu64") for storing %s.", LY_ARRAY_MAX(size), array_name); \ free(s); \ YYABORT; \ } else if (!((size) % LY_YANG_ARRAY_SIZE)) { \ void *tmp; \ \ tmp = realloc((current_ptr), (sizeof *(current_ptr)) * ((size) + LY_YANG_ARRAY_SIZE)); \ if (!tmp) { \ LOGMEM(trg->ctx); \ free(s); \ YYABORT; \ } \ memset(tmp + (sizeof *(current_ptr)) * (size), 0, (sizeof *(current_ptr)) * LY_YANG_ARRAY_SIZE); \ (current_ptr) = tmp; \ } \ actual = &(current_ptr)[(size)++]; \ void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...); /* pointer on the current parsed element 'actual' */ # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "parser_yang_bis.h". */ #ifndef YY_YY_PARSER_YANG_BIS_H_INCLUDED # define YY_YY_PARSER_YANG_BIS_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { UNION_KEYWORD = 258, ANYXML_KEYWORD = 259, WHITESPACE = 260, ERROR = 261, EOL = 262, STRING = 263, STRINGS = 264, IDENTIFIER = 265, IDENTIFIERPREFIX = 266, REVISION_DATE = 267, TAB = 268, DOUBLEDOT = 269, URI = 270, INTEGER = 271, NON_NEGATIVE_INTEGER = 272, ZERO = 273, DECIMAL = 274, ARGUMENT_KEYWORD = 275, AUGMENT_KEYWORD = 276, BASE_KEYWORD = 277, BELONGS_TO_KEYWORD = 278, BIT_KEYWORD = 279, CASE_KEYWORD = 280, CHOICE_KEYWORD = 281, CONFIG_KEYWORD = 282, CONTACT_KEYWORD = 283, CONTAINER_KEYWORD = 284, DEFAULT_KEYWORD = 285, DESCRIPTION_KEYWORD = 286, ENUM_KEYWORD = 287, ERROR_APP_TAG_KEYWORD = 288, ERROR_MESSAGE_KEYWORD = 289, EXTENSION_KEYWORD = 290, DEVIATION_KEYWORD = 291, DEVIATE_KEYWORD = 292, FEATURE_KEYWORD = 293, FRACTION_DIGITS_KEYWORD = 294, GROUPING_KEYWORD = 295, IDENTITY_KEYWORD = 296, IF_FEATURE_KEYWORD = 297, IMPORT_KEYWORD = 298, INCLUDE_KEYWORD = 299, INPUT_KEYWORD = 300, KEY_KEYWORD = 301, LEAF_KEYWORD = 302, LEAF_LIST_KEYWORD = 303, LENGTH_KEYWORD = 304, LIST_KEYWORD = 305, MANDATORY_KEYWORD = 306, MAX_ELEMENTS_KEYWORD = 307, MIN_ELEMENTS_KEYWORD = 308, MODULE_KEYWORD = 309, MUST_KEYWORD = 310, NAMESPACE_KEYWORD = 311, NOTIFICATION_KEYWORD = 312, ORDERED_BY_KEYWORD = 313, ORGANIZATION_KEYWORD = 314, OUTPUT_KEYWORD = 315, PATH_KEYWORD = 316, PATTERN_KEYWORD = 317, POSITION_KEYWORD = 318, PREFIX_KEYWORD = 319, PRESENCE_KEYWORD = 320, RANGE_KEYWORD = 321, REFERENCE_KEYWORD = 322, REFINE_KEYWORD = 323, REQUIRE_INSTANCE_KEYWORD = 324, REVISION_KEYWORD = 325, REVISION_DATE_KEYWORD = 326, RPC_KEYWORD = 327, STATUS_KEYWORD = 328, SUBMODULE_KEYWORD = 329, TYPE_KEYWORD = 330, TYPEDEF_KEYWORD = 331, UNIQUE_KEYWORD = 332, UNITS_KEYWORD = 333, USES_KEYWORD = 334, VALUE_KEYWORD = 335, WHEN_KEYWORD = 336, YANG_VERSION_KEYWORD = 337, YIN_ELEMENT_KEYWORD = 338, ADD_KEYWORD = 339, CURRENT_KEYWORD = 340, DELETE_KEYWORD = 341, DEPRECATED_KEYWORD = 342, FALSE_KEYWORD = 343, NOT_SUPPORTED_KEYWORD = 344, OBSOLETE_KEYWORD = 345, REPLACE_KEYWORD = 346, SYSTEM_KEYWORD = 347, TRUE_KEYWORD = 348, UNBOUNDED_KEYWORD = 349, USER_KEYWORD = 350, ACTION_KEYWORD = 351, MODIFIER_KEYWORD = 352, ANYDATA_KEYWORD = 353, NODE = 354, NODE_PRINT = 355, EXTENSION_INSTANCE = 356, SUBMODULE_EXT_KEYWORD = 357 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { int32_t i; uint32_t uint; char *str; char **p_str; void *v; char ch; struct yang_type *type; struct lys_deviation *dev; struct lys_deviate *deviate; union { uint32_t index; struct lys_node_container *container; struct lys_node_anydata *anydata; struct type_node node; struct lys_node_case *cs; struct lys_node_grp *grouping; struct lys_refine *refine; struct lys_node_notif *notif; struct lys_node_uses *uses; struct lys_node_inout *inout; struct lys_node_augment *augment; } nodes; enum yytokentype token; struct { void *actual; enum yytokentype token; } backup_token; struct { struct lys_revision **revision; int index; } revisions; }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif int yyparse (void *scanner, struct yang_parameter *param); #endif /* !YY_YY_PARSER_YANG_BIS_H_INCLUDED */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 6 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 3466 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 113 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 329 /* YYNRULES -- Number of rules. */ #define YYNRULES 827 /* YYNSTATES -- Number of states. */ #define YYNSTATES 1318 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 357 #define YYTRANSLATE(YYX) \ ((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 111, 112, 2, 103, 2, 2, 2, 107, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 106, 2, 110, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 108, 2, 109, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 104, 2, 105, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 338, 338, 339, 340, 342, 365, 368, 370, 369, 393, 404, 414, 424, 425, 431, 436, 442, 453, 463, 476, 477, 483, 485, 489, 491, 495, 497, 498, 499, 501, 509, 517, 518, 523, 534, 545, 556, 564, 569, 570, 574, 575, 586, 597, 608, 612, 614, 637, 654, 658, 660, 661, 666, 671, 676, 682, 686, 688, 692, 694, 698, 700, 704, 706, 719, 730, 731, 743, 747, 748, 752, 753, 758, 765, 765, 776, 782, 830, 849, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 864, 879, 886, 887, 891, 892, 893, 899, 904, 910, 928, 930, 931, 935, 940, 941, 963, 964, 965, 978, 983, 985, 986, 987, 988, 1003, 1017, 1022, 1023, 1038, 1039, 1040, 1046, 1051, 1057, 1114, 1119, 1120, 1122, 1138, 1143, 1144, 1169, 1170, 1184, 1185, 1191, 1196, 1202, 1206, 1208, 1261, 1272, 1275, 1278, 1283, 1288, 1294, 1299, 1305, 1310, 1319, 1320, 1324, 1371, 1372, 1374, 1375, 1379, 1385, 1398, 1399, 1400, 1404, 1405, 1407, 1411, 1429, 1434, 1436, 1437, 1453, 1458, 1467, 1468, 1472, 1488, 1493, 1498, 1503, 1509, 1513, 1529, 1544, 1545, 1549, 1550, 1560, 1565, 1570, 1575, 1581, 1585, 1596, 1608, 1609, 1612, 1620, 1631, 1632, 1647, 1648, 1649, 1661, 1667, 1672, 1678, 1683, 1685, 1686, 1701, 1706, 1707, 1712, 1716, 1718, 1723, 1725, 1726, 1727, 1740, 1752, 1753, 1755, 1763, 1775, 1776, 1791, 1792, 1793, 1805, 1811, 1816, 1822, 1827, 1829, 1830, 1846, 1850, 1852, 1856, 1858, 1862, 1864, 1868, 1870, 1880, 1887, 1888, 1892, 1893, 1899, 1904, 1909, 1910, 1911, 1912, 1913, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1929, 1939, 1946, 1947, 1970, 1971, 1972, 1973, 1974, 1979, 1985, 1991, 1996, 2001, 2002, 2003, 2008, 2009, 2011, 2051, 2061, 2064, 2065, 2066, 2069, 2074, 2075, 2080, 2086, 2092, 2098, 2103, 2109, 2119, 2174, 2177, 2178, 2179, 2182, 2193, 2198, 2199, 2205, 2218, 2231, 2241, 2247, 2252, 2258, 2268, 2315, 2318, 2319, 2320, 2321, 2330, 2336, 2342, 2355, 2368, 2378, 2384, 2389, 2394, 2395, 2396, 2397, 2402, 2404, 2414, 2421, 2422, 2442, 2445, 2446, 2447, 2457, 2464, 2471, 2478, 2484, 2490, 2492, 2493, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2507, 2517, 2524, 2525, 2539, 2540, 2541, 2542, 2548, 2553, 2558, 2561, 2571, 2578, 2588, 2595, 2596, 2619, 2622, 2623, 2624, 2625, 2632, 2639, 2646, 2651, 2657, 2667, 2674, 2675, 2707, 2708, 2709, 2710, 2716, 2721, 2726, 2727, 2729, 2730, 2732, 2745, 2750, 2751, 2783, 2786, 2800, 2816, 2838, 2889, 2908, 2927, 2948, 2969, 2974, 2980, 2981, 2984, 2999, 3008, 3009, 3011, 3022, 3031, 3032, 3033, 3034, 3040, 3045, 3050, 3051, 3052, 3057, 3059, 3074, 3081, 3091, 3098, 3099, 3123, 3126, 3127, 3133, 3138, 3143, 3144, 3145, 3152, 3160, 3175, 3205, 3206, 3207, 3208, 3209, 3211, 3226, 3256, 3265, 3272, 3273, 3305, 3306, 3307, 3308, 3314, 3319, 3324, 3325, 3326, 3328, 3340, 3360, 3361, 3367, 3373, 3375, 3376, 3378, 3379, 3382, 3390, 3395, 3396, 3398, 3399, 3400, 3402, 3410, 3415, 3416, 3448, 3449, 3455, 3456, 3462, 3468, 3475, 3482, 3490, 3499, 3507, 3512, 3513, 3545, 3546, 3552, 3553, 3559, 3566, 3574, 3579, 3580, 3594, 3595, 3596, 3602, 3608, 3615, 3622, 3630, 3639, 3648, 3653, 3654, 3658, 3659, 3664, 3670, 3675, 3677, 3678, 3679, 3692, 3697, 3699, 3700, 3701, 3714, 3718, 3720, 3725, 3727, 3728, 3748, 3753, 3755, 3756, 3757, 3777, 3782, 3784, 3785, 3786, 3798, 3867, 3872, 3873, 3877, 3881, 3883, 3884, 3886, 3890, 3892, 3892, 3899, 3902, 3911, 3930, 3932, 3933, 3936, 3936, 3953, 3953, 3960, 3960, 3967, 3970, 3972, 3974, 3975, 3977, 3979, 3981, 3982, 3984, 3986, 3987, 3989, 3990, 3992, 3994, 3997, 4000, 4002, 4003, 4005, 4006, 4008, 4010, 4021, 4022, 4025, 4026, 4038, 4039, 4041, 4042, 4044, 4045, 4051, 4052, 4055, 4056, 4057, 4081, 4082, 4085, 4091, 4095, 4100, 4101, 4102, 4105, 4110, 4120, 4122, 4123, 4125, 4126, 4128, 4129, 4130, 4132, 4133, 4135, 4136, 4138, 4139, 4143, 4144, 4171, 4209, 4210, 4212, 4214, 4216, 4217, 4219, 4220, 4222, 4223, 4226, 4227, 4230, 4232, 4233, 4236, 4236, 4243, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4253, 4254, 4255, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301, 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, 4320, 4321, 4322, 4323, 4324, 4325, 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340, 4347, 4354, 4374, 4392, 4408, 4435, 4442, 4460, 4500, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4531, 4532, 4533, 4534, 4536, 4544, 4545, 4550, 4555, 4560, 4565, 4570, 4575, 4580, 4585, 4590, 4595, 4600, 4605, 4610, 4615, 4620, 4634, 4654, 4659, 4664, 4669, 4682, 4687, 4691, 4701, 4716, 4731, 4746, 4761, 4781, 4796, 4797, 4803, 4810, 4825, 4828 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "UNION_KEYWORD", "ANYXML_KEYWORD", "WHITESPACE", "ERROR", "EOL", "STRING", "STRINGS", "IDENTIFIER", "IDENTIFIERPREFIX", "REVISION_DATE", "TAB", "DOUBLEDOT", "URI", "INTEGER", "NON_NEGATIVE_INTEGER", "ZERO", "DECIMAL", "ARGUMENT_KEYWORD", "AUGMENT_KEYWORD", "BASE_KEYWORD", "BELONGS_TO_KEYWORD", "BIT_KEYWORD", "CASE_KEYWORD", "CHOICE_KEYWORD", "CONFIG_KEYWORD", "CONTACT_KEYWORD", "CONTAINER_KEYWORD", "DEFAULT_KEYWORD", "DESCRIPTION_KEYWORD", "ENUM_KEYWORD", "ERROR_APP_TAG_KEYWORD", "ERROR_MESSAGE_KEYWORD", "EXTENSION_KEYWORD", "DEVIATION_KEYWORD", "DEVIATE_KEYWORD", "FEATURE_KEYWORD", "FRACTION_DIGITS_KEYWORD", "GROUPING_KEYWORD", "IDENTITY_KEYWORD", "IF_FEATURE_KEYWORD", "IMPORT_KEYWORD", "INCLUDE_KEYWORD", "INPUT_KEYWORD", "KEY_KEYWORD", "LEAF_KEYWORD", "LEAF_LIST_KEYWORD", "LENGTH_KEYWORD", "LIST_KEYWORD", "MANDATORY_KEYWORD", "MAX_ELEMENTS_KEYWORD", "MIN_ELEMENTS_KEYWORD", "MODULE_KEYWORD", "MUST_KEYWORD", "NAMESPACE_KEYWORD", "NOTIFICATION_KEYWORD", "ORDERED_BY_KEYWORD", "ORGANIZATION_KEYWORD", "OUTPUT_KEYWORD", "PATH_KEYWORD", "PATTERN_KEYWORD", "POSITION_KEYWORD", "PREFIX_KEYWORD", "PRESENCE_KEYWORD", "RANGE_KEYWORD", "REFERENCE_KEYWORD", "REFINE_KEYWORD", "REQUIRE_INSTANCE_KEYWORD", "REVISION_KEYWORD", "REVISION_DATE_KEYWORD", "RPC_KEYWORD", "STATUS_KEYWORD", "SUBMODULE_KEYWORD", "TYPE_KEYWORD", "TYPEDEF_KEYWORD", "UNIQUE_KEYWORD", "UNITS_KEYWORD", "USES_KEYWORD", "VALUE_KEYWORD", "WHEN_KEYWORD", "YANG_VERSION_KEYWORD", "YIN_ELEMENT_KEYWORD", "ADD_KEYWORD", "CURRENT_KEYWORD", "DELETE_KEYWORD", "DEPRECATED_KEYWORD", "FALSE_KEYWORD", "NOT_SUPPORTED_KEYWORD", "OBSOLETE_KEYWORD", "REPLACE_KEYWORD", "SYSTEM_KEYWORD", "TRUE_KEYWORD", "UNBOUNDED_KEYWORD", "USER_KEYWORD", "ACTION_KEYWORD", "MODIFIER_KEYWORD", "ANYDATA_KEYWORD", "NODE", "NODE_PRINT", "EXTENSION_INSTANCE", "SUBMODULE_EXT_KEYWORD", "'+'", "'{'", "'}'", "';'", "'/'", "'['", "']'", "'='", "'('", "')'", "$accept", "start", "tmp_string", "string_1", "string_2", "$@1", "module_arg_str", "module_stmt", "module_header_stmts", "module_header_stmt", "submodule_arg_str", "submodule_stmt", "submodule_header_stmts", "submodule_header_stmt", "yang_version_arg", "yang_version_stmt", "namespace_arg_str", "namespace_stmt", "linkage_stmts", "import_stmt", "import_arg_str", "import_opt_stmt", "include_arg_str", "include_stmt", "include_end", "include_opt_stmt", "revision_date_arg", "revision_date_stmt", "belongs_to_arg_str", "belongs_to_stmt", "prefix_arg", "prefix_stmt", "meta_stmts", "organization_arg", "organization_stmt", "contact_arg", "contact_stmt", "description_arg", "description_stmt", "reference_arg", "reference_stmt", "revision_stmts", "revision_arg_stmt", "revision_stmts_opt", "revision_stmt", "revision_end", "revision_opt_stmt", "date_arg_str", "$@2", "body_stmts_end", "body_stmts", "body_stmt", "extension_arg_str", "extension_stmt", "extension_end", "extension_opt_stmt", "argument_str", "argument_stmt", "argument_end", "yin_element_arg", "yin_element_stmt", "yin_element_arg_str", "status_arg", "status_stmt", "status_arg_str", "feature_arg_str", "feature_stmt", "feature_end", "feature_opt_stmt", "if_feature_arg", "if_feature_stmt", "if_feature_end", "identity_arg_str", "identity_stmt", "identity_end", "identity_opt_stmt", "base_arg", "base_stmt", "typedef_arg_str", "typedef_stmt", "type_opt_stmt", "type_stmt", "type_arg_str", "type_end", "type_body_stmts", "some_restrictions", "union_stmt", "union_spec", "fraction_digits_arg", "fraction_digits_stmt", "fraction_digits_arg_str", "length_stmt", "length_arg_str", "length_end", "message_opt_stmt", "pattern_sep", "pattern_stmt", "pattern_arg_str", "pattern_end", "pattern_opt_stmt", "modifier_arg", "modifier_stmt", "enum_specification", "enum_stmts", "enum_stmt", "enum_arg_str", "enum_end", "enum_opt_stmt", "value_arg", "value_stmt", "integer_value_arg_str", "range_stmt", "range_end", "path_arg", "path_stmt", "require_instance_arg", "require_instance_stmt", "require_instance_arg_str", "bits_specification", "bit_stmts", "bit_stmt", "bit_arg_str", "bit_end", "bit_opt_stmt", "position_value_arg", "position_stmt", "position_value_arg_str", "error_message_arg", "error_message_stmt", "error_app_tag_arg", "error_app_tag_stmt", "units_arg", "units_stmt", "default_arg", "default_stmt", "grouping_arg_str", "grouping_stmt", "grouping_end", "grouping_opt_stmt", "data_def_stmt", "container_arg_str", "container_stmt", "container_end", "container_opt_stmt", "leaf_stmt", "leaf_arg_str", "leaf_opt_stmt", "leaf_list_arg_str", "leaf_list_stmt", "leaf_list_opt_stmt", "list_arg_str", "list_stmt", "list_opt_stmt", "choice_arg_str", "choice_stmt", "choice_end", "choice_opt_stmt", "short_case_case_stmt", "short_case_stmt", "case_arg_str", "case_stmt", "case_end", "case_opt_stmt", "anyxml_arg_str", "anyxml_stmt", "anydata_arg_str", "anydata_stmt", "anyxml_end", "anyxml_opt_stmt", "uses_arg_str", "uses_stmt", "uses_end", "uses_opt_stmt", "refine_args_str", "refine_arg_str", "refine_stmt", "refine_end", "refine_body_opt_stmts", "uses_augment_arg_str", "uses_augment_arg", "uses_augment_stmt", "augment_arg_str", "augment_arg", "augment_stmt", "augment_opt_stmt", "action_arg_str", "action_stmt", "rpc_arg_str", "rpc_stmt", "rpc_end", "rpc_opt_stmt", "input_arg", "input_stmt", "input_output_opt_stmt", "output_arg", "output_stmt", "notification_arg_str", "notification_stmt", "notification_end", "notification_opt_stmt", "deviation_arg", "deviation_stmt", "deviation_opt_stmt", "deviation_arg_str", "deviate_body_stmt", "deviate_not_supported", "deviate_not_supported_stmt", "deviate_not_supported_end", "deviate_stmts", "deviate_add", "deviate_add_stmt", "deviate_add_end", "deviate_add_opt_stmt", "deviate_delete", "deviate_delete_stmt", "deviate_delete_end", "deviate_delete_opt_stmt", "deviate_replace", "deviate_replace_stmt", "deviate_replace_end", "deviate_replace_opt_stmt", "when_arg_str", "when_stmt", "when_end", "when_opt_stmt", "config_arg", "config_stmt", "config_arg_str", "mandatory_arg", "mandatory_stmt", "mandatory_arg_str", "presence_arg", "presence_stmt", "min_value_arg", "min_elements_stmt", "min_value_arg_str", "max_value_arg", "max_elements_stmt", "max_value_arg_str", "ordered_by_arg", "ordered_by_stmt", "ordered_by_arg_str", "must_agr_str", "must_stmt", "must_end", "unique_arg", "unique_stmt", "unique_arg_str", "key_arg", "key_stmt", "key_arg_str", "$@3", "range_arg_str", "absolute_schema_nodeid", "absolute_schema_nodeids", "absolute_schema_nodeid_opt", "descendant_schema_nodeid", "$@4", "path_arg_str", "$@5", "$@6", "absolute_path", "absolute_paths", "absolute_path_opt", "relative_path", "relative_path_part1", "relative_path_part1_opt", "descendant_path", "descendant_path_opt", "path_predicate", "path_equality_expr", "path_key_expr", "rel_path_keyexpr", "rel_path_keyexpr_part1", "rel_path_keyexpr_part1_opt", "rel_path_keyexpr_part2", "current_function_invocation", "positive_integer_value", "non_negative_integer_value", "integer_value", "integer_value_convert", "prefix_arg_str", "identifier_arg_str", "node_identifier", "identifier_ref_arg_str", "stmtend", "semicolom", "curly_bracket_close", "curly_bracket_open", "stmtsep", "unknown_statement", "string_opt", "string_opt_part1", "string_opt_part2", "unknown_string", "unknown_string_part1", "unknown_string_part2", "unknown_statement_end", "unknown_statement2_opt", "unknown_statement2", "unknown_statement2_end", "unknown_statement2_yang_stmt", "unknown_statement2_module_stmt", "unknown_statement3_opt", "unknown_statement3_opt_end", "sep_stmt", "optsep", "sep", "whitespace_opt", "string", "$@7", "strings", "identifier", "identifier1", "yang_stmt", "identifiers", "identifiers_ref", "type_ext_alloc", "typedef_ext_alloc", "iffeature_ext_alloc", "restriction_ext_alloc", "when_ext_alloc", "revision_ext_alloc", "datadef_ext_check", "not_supported_ext_check", "not_supported_ext", "datadef_ext_stmt", "restriction_ext_stmt", "ext_substatements", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 43, 123, 125, 59, 47, 91, 93, 61, 40, 41 }; # endif #define YYPACT_NINF -1012 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-1012))) #define YYTABLE_NINF -757 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 440, 100, -1012, -1012, 566, 1894, -1012, -1012, -1012, 266, 266, -1012, 266, -1012, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -8, 31, 79, 868, 70, 125, 481, 266, -1012, -1012, 3273, 3273, 3273, 2893, 3273, 71, 2703, 2703, 2703, 2703, 2703, 98, 2988, 94, 52, 287, 2703, 77, 2703, 104, 287, 3273, 2703, 2703, 182, 58, 246, 2988, 2703, 321, 2703, 279, 279, 266, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 29, -1012, 134, -1012, -1012, -1012, -22, 2798, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 151, -1012, -1012, -1012, -1012, -1012, 156, -1012, 67, -1012, -1012, -1012, 224, -1012, -1012, -1012, 161, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, 224, -1012, 224, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, 224, -1012, -1012, 224, -1012, 262, 202, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 2893, 279, 3273, 279, 2703, 279, 2703, 2703, 2703, -1012, 2703, 279, 2703, 279, 58, 279, 3273, 3273, 3273, 3273, 3273, 266, 3273, 3273, 3273, 3273, 266, 2893, 3273, 3273, -1012, -1012, 279, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, 266, 266, -1012, 266, -1012, 266, -1012, 266, -1012, 266, 266, -1012, -1012, -1012, 3368, -1012, -1012, 291, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, 266, 266, -1012, -1012, -1012, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, 266, -1012, 228, 2703, 266, 274, -1012, 189, -1012, 288, -1012, 298, -1012, 303, -1012, 370, -1012, 380, -1012, 389, -1012, 393, -1012, 407, -1012, 411, -1012, 419, -1012, 426, -1012, 463, -1012, 238, -1012, 314, -1012, 317, -1012, 505, -1012, 506, -1012, 521, -1012, 407, -1012, 279, 279, 266, 266, 266, 266, 326, 279, 279, 109, 279, 112, 608, 266, 266, -1012, 262, -1012, 3083, 266, 332, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 1964, 1994, 2191, 347, -1012, -1012, 19, -1012, 54, 266, 355, -1012, -1012, 368, 373, -1012, -1012, -1012, 48, 3368, -1012, 266, 831, 279, 186, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 127, 515, 266, -1012, -1012, -1012, 515, -1012, -1012, 188, -1012, 279, -1012, 473, -1012, 306, -1012, 2552, 266, 266, 397, 1000, -1012, -1012, -1012, -1012, 783, -1012, 230, 503, 404, 887, 359, 438, 929, 1958, 1645, 817, 947, 344, 2074, 1547, 1768, 235, 852, 279, 279, 279, 279, 266, -22, 280, -1012, 266, 266, -1012, -1012, 375, 2703, 375, 279, -1012, -1012, -1012, 224, -1012, -1012, 3368, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 3273, 2703, -1012, -1012, -1012, -8, -1012, -1012, -1012, -1012, -1012, -1012, 279, 474, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 3273, 3273, 279, 279, -1012, -1012, -1012, -1012, -1012, 125, 224, -1012, -1012, 266, 266, -1012, 399, 473, 266, 528, 528, 545, -1012, 567, -1012, 279, -1012, 279, 279, 279, 480, -1012, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 2988, 2988, 279, 279, 279, 279, 279, 279, 279, 279, 279, 266, 266, 423, -1012, 570, -1012, 428, 2046, -1012, -1012, 434, -1012, 465, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 479, -1012, -1012, -1012, 571, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, -1012, 473, 266, 279, 279, 279, 279, -1012, 266, -1012, -1012, -1012, 266, 279, 279, 266, 51, 3273, 51, 3273, 3273, 3273, 279, 266, 459, 2367, 385, 509, 279, 279, 341, 365, -1012, -1012, 483, -1012, -1012, 574, -1012, -1012, 486, -1012, -1012, 591, -1012, 592, -1012, 521, -1012, 473, -1012, 473, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 885, 1126, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 332, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 467, 492, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279, 279, 279, 473, 473, 279, 279, 279, 279, 279, 279, 279, 279, 1460, 205, 524, 216, 201, 493, 579, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 293, 279, 279, 497, 3178, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 73, 120, 133, 163, -1012, 50, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 510, 222, 279, 279, 279, 473, -1012, 824, 346, 985, 3368, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 790, 0, 2, 3, 0, 757, 1, 649, 650, 0, 0, 652, 0, 763, 0, 0, 761, 0, 0, 0, 0, 762, 0, 0, 766, 764, 765, 767, 0, 768, 769, 770, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 759, 760, 0, 771, 802, 806, 619, 792, 803, 797, 793, 794, 619, 809, 796, 815, 814, 819, 804, 813, 818, 799, 800, 795, 798, 810, 811, 805, 816, 817, 812, 820, 801, 0, 0, 0, 0, 0, 0, 0, 627, 758, 651, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 791, 822, 0, 619, 0, 619, 0, 619, 0, 0, 0, 0, 789, 787, 788, 786, 619, 0, 619, 0, 619, 0, 0, 0, 0, 0, 651, 0, 0, 0, 0, 651, 0, 0, 0, 778, 777, 780, 781, 782, 776, 775, 774, 773, 785, 772, 0, 779, 0, 784, 783, 619, 0, 629, 653, 679, 5, 669, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 666, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 670, 744, 671, 672, 673, 674, 745, 675, 676, 677, 678, 746, 747, 748, 651, 608, 0, 10, 749, 667, 668, 651, 0, 17, 0, 99, 750, 613, 0, 138, 651, 651, 0, 47, 651, 651, 529, 0, 525, 659, 662, 660, 664, 665, 663, 658, 0, 58, 656, 661, 0, 243, 0, 60, 0, 239, 0, 237, 598, 170, 0, 167, 651, 610, 563, 0, 559, 561, 609, 651, 651, 534, 0, 530, 651, 545, 0, 541, 651, 599, 540, 0, 537, 600, 651, 0, 25, 651, 651, 550, 0, 546, 0, 56, 575, 0, 213, 0, 0, 236, 0, 233, 651, 605, 0, 49, 651, 0, 535, 0, 62, 651, 651, 219, 0, 215, 74, 76, 0, 45, 651, 651, 651, 114, 0, 109, 558, 0, 555, 651, 569, 0, 241, 603, 604, 601, 209, 0, 206, 651, 602, 0, 191, 621, 620, 651, 0, 807, 0, 808, 0, 821, 0, 0, 0, 180, 0, 823, 0, 824, 0, 825, 0, 0, 0, 0, 0, 445, 0, 0, 0, 0, 452, 0, 0, 0, 619, 619, 826, 651, 651, 827, 651, 628, 651, 7, 619, 607, 619, 619, 101, 100, 618, 616, 139, 619, 619, 611, 612, 619, 528, 527, 526, 59, 651, 244, 61, 240, 238, 168, 169, 560, 651, 533, 532, 531, 543, 542, 544, 538, 539, 26, 549, 548, 547, 57, 214, 0, 578, 572, 0, 574, 582, 234, 235, 50, 606, 536, 63, 218, 217, 216, 651, 46, 111, 113, 112, 110, 556, 557, 567, 242, 207, 208, 192, 0, 625, 624, 0, 150, 0, 140, 0, 124, 0, 172, 0, 551, 0, 182, 0, 564, 0, 518, 0, 65, 0, 368, 0, 357, 0, 334, 0, 266, 0, 245, 0, 285, 0, 298, 0, 314, 0, 454, 0, 383, 0, 430, 0, 370, 447, 447, 645, 647, 632, 630, 6, 13, 20, 104, 614, 0, 0, 657, 562, 587, 577, 581, 0, 75, 570, 651, 634, 622, 623, 626, 619, 151, 149, 619, 619, 126, 125, 619, 173, 171, 619, 553, 552, 619, 183, 181, 619, 211, 210, 619, 520, 519, 619, 69, 68, 619, 372, 369, 619, 359, 358, 619, 336, 335, 619, 268, 267, 619, 247, 246, 619, 619, 619, 619, 456, 455, 619, 385, 384, 619, 434, 431, 371, 0, 0, 0, 631, 651, 27, 12, 27, 19, 0, 0, 617, 619, 0, 576, 579, 583, 580, 585, 0, 568, 636, 156, 142, 0, 175, 175, 185, 175, 522, 71, 374, 361, 338, 270, 249, 286, 300, 316, 458, 387, 436, 446, 619, 619, 619, 258, 259, 260, 261, 262, 263, 264, 265, 619, 453, 651, 627, 651, 0, 51, 0, 14, 15, 16, 51, 21, 619, 0, 102, 615, 48, 654, 584, 0, 565, 0, 0, 0, 0, 153, 154, 619, 155, 221, 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 449, 450, 451, 448, 648, 0, 0, 8, 0, 0, 619, 619, 66, 0, 66, 22, 651, 651, 108, 0, 103, 655, 0, 586, 644, 635, 638, 651, 627, 627, 643, 0, 0, 152, 159, 619, 0, 162, 619, 619, 619, 158, 157, 194, 220, 141, 147, 148, 146, 619, 144, 145, 174, 178, 179, 176, 177, 554, 184, 189, 190, 186, 187, 188, 212, 521, 523, 524, 70, 72, 73, 373, 381, 382, 380, 619, 619, 378, 379, 619, 360, 365, 366, 364, 619, 619, 619, 337, 345, 346, 344, 619, 341, 350, 351, 352, 353, 356, 619, 348, 349, 354, 355, 619, 342, 343, 269, 277, 278, 276, 619, 619, 619, 619, 619, 619, 619, 275, 274, 619, 248, 251, 252, 250, 619, 619, 619, 619, 619, 284, 296, 297, 295, 619, 619, 290, 292, 619, 293, 294, 619, 299, 312, 313, 311, 619, 619, 305, 304, 619, 307, 308, 309, 310, 619, 315, 327, 328, 326, 619, 619, 619, 619, 619, 619, 619, 322, 323, 324, 325, 619, 321, 320, 457, 462, 463, 461, 619, 619, 619, 619, 619, 0, 0, 386, 391, 392, 390, 619, 619, 619, 619, 435, 439, 440, 438, 619, 619, 619, 619, 619, 646, 651, 651, 0, 0, 28, 29, 52, 53, 54, 55, 78, 64, 0, 23, 78, 107, 106, 105, 0, 654, 637, 0, 0, 0, 224, 0, 197, 164, 165, 160, 161, 163, 193, 222, 143, 376, 375, 377, 363, 367, 362, 340, 347, 339, 272, 282, 279, 283, 280, 281, 271, 273, 254, 253, 255, 256, 257, 288, 289, 287, 291, 302, 303, 301, 306, 318, 329, 330, 333, 331, 332, 317, 319, 460, 464, 465, 466, 459, 0, 0, 389, 393, 394, 388, 437, 441, 442, 443, 444, 633, 9, 0, 31, 0, 37, 0, 77, 619, 24, 0, 588, 0, 651, 641, 639, 640, 619, 225, 619, 619, 198, 196, 619, 413, 414, 0, 651, 396, 397, 0, 651, 619, 619, 39, 38, 651, 0, 0, 0, 0, 0, 0, 619, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 67, 651, 654, 645, 227, 223, 200, 195, 619, 412, 619, 399, 398, 395, 32, 41, 11, 0, 0, 0, 0, 0, 0, 79, 18, 0, 0, 0, 0, 420, 401, 0, 0, 417, 418, 0, 567, 651, 0, 90, 474, 0, 467, 651, 0, 115, 0, 128, 0, 432, 654, 589, 654, 642, 226, 231, 232, 230, 619, 229, 199, 204, 205, 203, 619, 202, 0, 0, 30, 36, 33, 34, 35, 40, 44, 42, 43, 619, 566, 416, 619, 92, 91, 619, 473, 619, 117, 116, 619, 130, 129, 433, 0, 0, 228, 201, 415, 424, 425, 423, 619, 619, 619, 619, 619, 619, 400, 410, 411, 619, 405, 406, 407, 404, 408, 409, 619, 420, 94, 469, 119, 132, 654, 654, 422, 426, 429, 427, 428, 421, 403, 402, 0, 0, 0, 0, 0, 0, 0, 419, 93, 97, 98, 619, 96, 0, 468, 470, 471, 118, 122, 123, 121, 619, 131, 136, 137, 135, 619, 133, 597, 654, 590, 593, 95, 0, 120, 134, 0, 0, 484, 497, 477, 506, 619, 651, 475, 476, 651, 481, 651, 483, 651, 482, 654, 594, 595, 472, 0, 0, 0, 0, 592, 591, 619, 479, 478, 619, 486, 485, 619, 499, 498, 619, 508, 507, 0, 0, 488, 501, 510, 654, 480, 0, 0, 0, 0, 487, 489, 492, 493, 494, 495, 496, 619, 491, 500, 502, 505, 619, 504, 509, 619, 512, 513, 514, 515, 516, 517, 596, 490, 503, 511 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -1012, -1012, -1012, 245, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -16, -1012, -2, -9, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1011, -1012, 22, -1012, -534, -24, -1012, 658, -1012, 681, -1012, 63, -1012, 105, -41, -1012, -1012, -237, -1012, -1012, 305, -1012, -225, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -486, -1012, -1012, -1012, -1012, -1012, 41, -1012, -1012, -1012, -1012, -1012, -1012, -11, -1012, -1012, -1012, -1012, -1012, -1012, -657, -1012, -3, -1012, -653, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 23, -1012, 30, -1012, -1012, 53, -1012, 35, -1012, -1012, -1012, -1012, 10, -1012, -1012, -236, -1012, -1012, -1012, -1012, -366, -1012, 38, -1012, -1012, 40, -1012, 43, -1012, -1012, -1012, -21, -1012, -1012, -1012, -1012, -355, -1012, -1012, 12, -1012, 18, -1012, -704, -1012, -480, -1012, 16, -1012, -1012, -560, -1012, -80, -1012, -1012, -67, -1012, -1012, -1012, -63, -1012, -1012, -39, -1012, -1012, -36, -1012, -1012, -1012, -1012, -1012, -33, -1012, -1012, -1012, -28, -1012, -27, 206, -1012, -1012, 667, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -435, -1012, -62, -1012, -1012, -365, -1012, -1012, 42, 211, -1012, 44, -1012, -87, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 74, -1012, -1012, -1012, -473, -1012, -1012, -667, -1012, -1012, -675, -1012, -722, -1012, -1012, -662, -1012, -1012, -271, -1012, -1012, -35, -1012, -1012, -725, -1012, -1012, 46, -1012, -1012, -1012, -390, -319, -335, -461, -1012, -1012, -1012, -1012, 214, 97, -1012, -1012, 239, -1012, -1012, -1012, 135, -1012, -1012, -1012, -441, -1012, -1012, -1012, 155, 693, -1012, -1012, -1012, 185, -93, -328, 1164, -1012, -1012, -1012, 526, 110, -1012, -1012, -1012, -433, -1012, -1012, -1012, -1012, -1012, -143, -1012, -1012, -260, 84, -4, 1453, 166, -694, 119, -1012, 660, -12, -1012, 137, -20, -23, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 1, 261, 262, 553, 933, 263, 2, 631, 632, 269, 3, 633, 634, 944, 688, 332, 54, 686, 740, 1023, 1106, 1025, 741, 1056, 1107, 365, 55, 279, 56, 351, 57, 742, 339, 938, 293, 939, 299, 783, 356, 784, 942, 521, 943, 144, 597, 718, 366, 489, 1027, 1028, 1064, 1113, 1065, 1157, 1208, 271, 62, 438, 749, 636, 750, 371, 1174, 372, 1119, 1066, 1162, 1210, 509, 1175, 579, 1121, 1067, 1165, 1211, 275, 64, 507, 669, 711, 127, 505, 575, 705, 706, 765, 766, 307, 65, 308, 136, 511, 582, 713, 401, 137, 515, 588, 715, 388, 66, 707, 964, 708, 957, 1043, 1103, 384, 67, 385, 138, 591, 342, 68, 361, 69, 362, 709, 774, 710, 955, 1040, 1102, 347, 70, 348, 303, 785, 301, 786, 378, 73, 297, 74, 531, 670, 612, 723, 671, 529, 672, 609, 722, 673, 533, 724, 535, 674, 725, 537, 675, 726, 527, 676, 606, 721, 828, 829, 525, 1177, 603, 720, 523, 677, 545, 678, 600, 719, 541, 679, 621, 728, 1050, 1051, 919, 1087, 1142, 1046, 1047, 920, 1109, 1110, 1071, 1141, 543, 1178, 1123, 1072, 624, 729, 170, 171, 626, 172, 173, 539, 1179, 618, 727, 1116, 1074, 1209, 1117, 1249, 1250, 1251, 1271, 1252, 1253, 1254, 1274, 1288, 1255, 1256, 1277, 1289, 1257, 1258, 1280, 1290, 519, 1180, 594, 717, 284, 75, 285, 319, 76, 320, 354, 77, 328, 78, 329, 323, 79, 324, 337, 80, 338, 513, 680, 585, 374, 81, 375, 312, 82, 313, 459, 517, 646, 1112, 567, 376, 497, 343, 344, 345, 475, 476, 563, 478, 479, 565, 643, 699, 640, 950, 1126, 1237, 1238, 1244, 1268, 1127, 330, 331, 386, 387, 352, 264, 377, 276, 441, 442, 638, 443, 124, 390, 502, 503, 571, 176, 430, 629, 570, 702, 757, 1036, 758, 759, 628, 428, 391, 4, 177, 752, 294, 451, 295, 265, 266, 267, 268, 392, 83, 84, 85, 86, 87, 88, 89, 90, 91, 175, 140, 5 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 11, 901, 174, 881, 897, 92, 92, 780, 92, 160, 92, 92, 314, 92, 92, 92, 92, 71, 92, 92, 865, 877, 161, 72, 92, 639, 162, 169, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 63, 848, 92, 764, 163, 139, 808, 164, 835, 751, 165, 869, 779, 180, 180, 166, 167, 882, 898, 506, 180, 126, 60, 305, 363, 864, 876, 278, 131, 36, 277, 15, 7, 180, 8, 129, 426, 41, 427, 180, 92, 296, 296, 296, 296, 296, 542, 315, 353, 1144, 1149, 296, 690, 296, 6, 687, 180, 296, 296, 159, 180, 128, 315, 296, 61, 296, 180, 960, 7, 305, 8, 7, -573, 8, 273, 130, 92, 273, 92, 7, 92, 8, 92, 92, 92, 92, 7, 423, 8, 737, 687, 92, 7, 92, 8, 92, 92, 92, 92, 92, 321, 92, 92, 92, 92, 141, 92, 92, 92, -587, -587, -654, 645, 281, 815, 142, 843, 856, 282, 296, 892, 910, 7, 334, 8, 436, 335, 437, 11, 93, 94, 1269, 95, 1270, 96, 97, 316, 98, 99, 100, 101, 317, 102, 103, 180, 7, 635, 8, 104, 143, 180, 273, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 477, 637, 123, 298, 300, 302, 304, 14, 1272, 12, 1273, 7, 333, 8, 340, 781, 20, 273, 355, 357, 20, 1275, 424, 1276, 379, 822, 389, 130, 866, 878, 807, 20, 834, 847, 735, 868, 880, 896, 180, 433, 912, 1033, 130, 309, 435, 20, 325, 22, 23, 446, 20, 1278, 43, 1279, 358, 7, 43, 8, 46, 359, 746, 130, 46, 270, 272, 747, 280, 43, 7, 7, 8, 8, 932, 46, 273, 712, 393, 576, 395, 180, 397, 43, 399, 400, 402, 403, 43, 913, 305, 326, 1229, 405, 46, 407, 1215, 409, 410, 411, 412, 413, 141, 415, 416, 417, 418, 1224, 420, 421, 422, 953, 954, 1287, 439, 180, 440, 367, 568, 368, 569, 782, 369, 380, 381, 382, 914, 274, 613, 283, 292, 292, 292, 292, 292, 306, 311, 318, 322, 327, 292, 336, 292, 341, 346, 350, 292, 292, 360, 364, 370, 373, 292, 383, 292, 474, 278, 17, 20, 277, 19, 20, 19, 1245, 573, 1246, 574, 562, 1247, 1100, 1248, 296, 130, 296, 296, 296, 20, 296, 577, 296, 578, 33, 20, 278, 564, 133, 277, 133, 580, 18, 581, 41, 20, 583, 43, 584, 11, 43, 45, 474, 698, 11, 20, 46, 614, 126, 1189, 615, 48, 47, 48, 141, 43, 130, 11, 630, 11, 1167, 43, 1168, 38, 20, 45, 22, 23, 645, 11, 11, 43, 11, 11, -651, 1143, -651, 40, 859, 684, 1301, 43, 11, 883, 899, 11, 11, 46, 11, 695, 11, 315, 11, 795, 11, 11, 1188, 1070, 20, 1148, 43, 644, 697, 586, 1187, 587, 11, 751, 11, 1190, 698, 11, 11, 589, 145, 590, 11, 11, 11, 1129, 296, 11, 592, -651, 593, 11, 595, 703, 596, 11, 52, 763, 1212, 1213, 43, 146, 147, 1032, 788, 148, 598, 704, 599, -651, 601, 510, 602, 512, 514, 516, 149, 518, 604, 520, 605, 150, 1053, 151, 152, 607, 153, 608, 1057, 20, 683, 22, 23, 154, 1076, 20, 155, 1243, 798, 1125, 11, 11, 11, 11, 1048, 1052, 130, 701, 315, 1234, 20, 11, 11, 738, 739, 156, 1220, 11, 1300, 1305, 1267, 1297, 610, 1312, 611, 43, 7, 1145, 8, 1281, 1077, 43, 157, 1197, 158, 508, 1176, 46, 1083, 1293, 1302, 1308, 1152, 125, 49, 1158, 43, 1291, 1236, 524, 526, 528, 530, 532, 1198, 534, 536, 538, 540, 1259, 1235, 544, 546, 787, 616, 619, 617, 620, 7, 1135, 8, 315, 1286, 692, 273, 9, 1296, 572, 1311, 691, 622, 1298, 623, 1313, 1221, 689, 92, 1034, 315, 1035, 845, 858, 1307, 274, 894, 10, 823, 292, 11, 292, 292, 292, 1176, 292, 1038, 292, 1039, 364, 394, 824, 396, 693, 398, 825, 951, 844, 857, 1185, 58, 893, 274, 404, 744, 406, 1186, 408, 1041, 41, 1042, 1054, 1085, 1055, 1086, 1155, 92, 1156, 11, 826, 92, 809, 827, 59, 849, 830, 870, 884, 900, 911, 831, 832, 1160, 1163, 1161, 1164, 92, 92, 425, 1111, 946, 1111, 714, 1029, 716, 805, 814, 821, 840, 522, 863, 875, 889, 907, 918, 926, 841, 854, 1031, 1218, 890, 908, 791, 927, 792, 1044, 767, 11, 296, 11, 793, 92, 92, 768, 1140, 842, 855, 315, 769, 891, 909, 770, 928, 771, 1134, 292, 772, 296, 625, 778, 965, 92, 92, 168, 1207, 1166, 627, 804, 813, 820, 839, 853, 862, 874, 888, 906, 917, 925, 929, 902, 930, 776, 1118, 1153, 641, 789, 700, 796, 799, 802, 811, 818, 837, 851, 860, 872, 886, 904, 915, 923, 806, 816, 833, 846, 753, 867, 879, 895, 694, 921, 1260, 642, 940, 349, 940, 1294, 1303, 1309, 1037, 756, 19, 20, 1295, 777, 1310, 1101, 931, 790, 145, 797, 800, 803, 812, 819, 838, 852, 861, 873, 887, 905, 916, 924, 0, 7, 431, 8, 760, 0, 0, 273, 147, 17, 0, 148, 941, 20, 941, 43, 17, 0, 743, 19, 703, 46, 149, 126, 130, 0, 48, 945, 704, 151, 152, 0, 153, 0, 761, 762, 0, 133, 0, 154, 33, 34, 35, 0, 133, 0, 958, 42, 20, 43, 0, 0, 0, 775, 145, 46, 0, 149, 128, 130, 0, 156, 150, 141, 0, 0, 47, 48, 0, 934, 935, 0, 0, 92, 92, 146, 147, 155, 157, 148, 158, 20, 132, 20, 43, 22, 23, 836, 133, 0, 46, 0, 130, 128, 1292, 134, 0, 151, 152, 135, 153, 0, 0, 0, 748, 0, 1073, 154, 11, 11, 0, 956, 0, 11, 547, 548, 145, 43, 0, 43, 0, 17, 922, 46, 554, 20, 555, 556, 0, 156, 0, 141, 0, 557, 558, 0, 130, 559, 147, 0, 0, 148, 0, 20, 0, 33, 157, 0, 158, 133, 0, 0, 149, 292, 0, 1171, 0, 794, 0, 151, 152, 43, 153, 315, 315, 0, 0, 46, 0, 154, 0, 0, 292, 683, 0, 141, 0, 17, 0, 43, 19, 0, 11, 11, 0, 46, 0, 14, 128, 0, 1068, 156, 0, 0, 0, 0, 0, 0, 0, 801, 0, 33, 34, 35, 28, 0, 0, 0, 157, 1069, 158, 0, 0, 0, 132, 0, 0, 850, 0, 92, 92, 92, 92, 92, 92, 126, 39, 134, 48, 0, 0, 135, 0, 0, 44, 0, 0, 0, 0, 11, -166, 0, 0, 1010, 1011, 11, 0, 0, 0, 11, 0, 0, 11, 0, 315, 1306, 1133, 1139, 0, 0, 11, 0, 0, 0, 648, 0, 0, 649, 650, 0, 0, 651, 1191, 0, 652, 0, 0, 653, 0, 0, 654, 0, 0, 655, 1024, 1026, 656, 0, 0, 657, 0, 0, 658, 0, 0, 659, 1184, 0, 660, 0, 0, 661, 0, 0, 662, 663, 664, 665, 1132, 1138, 666, 0, 0, 667, 0, 11, 1261, 0, 17, 0, 11, 19, 20, 0, 0, 0, 0, 0, 0, 696, 1130, 1136, 0, 130, 1146, 1150, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 43, 0, 730, 731, 732, 1314, 1228, 1233, 0, 0, 0, 1172, 1182, 733, 1131, 1137, 0, 0, 1147, 1151, 0, 0, 0, 92, 0, 0, 745, 0, 0, 0, 0, 1092, 1093, 1094, 1095, 1096, 1097, 0, 1181, 315, 0, 773, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1173, 1183, 0, 1219, 0, 1227, 1232, 1299, 1304, 1045, 1049, 0, 0, 11, 11, 11, 11, 0, 0, 0, 936, 937, 0, 0, 1172, 1216, 1222, 1225, 1230, 0, 0, 0, 1114, 315, 1120, 1122, 1124, 0, 0, 0, 0, 0, 0, 0, 0, 959, 0, 0, 961, 962, 963, 0, 0, 0, 0, 0, 0, 0, 0, 966, 0, 0, 0, 0, 0, 0, 1173, 1217, 1223, 1226, 1231, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 967, 968, 0, 0, 969, 0, 1108, 0, 1115, 970, 971, 972, 0, 0, 0, 0, 973, 0, 0, 0, 0, 0, 0, 974, 0, 0, 0, 0, 975, 0, 0, 0, 0, 0, 0, 976, 977, 978, 979, 980, 981, 982, 0, 0, 983, 0, 0, 0, 0, 984, 985, 986, 987, 988, 0, 1240, 0, 0, 989, 990, 0, 0, 991, 0, 0, 992, 0, 0, 0, 0, 993, 994, 0, 0, 995, 0, 0, 0, 0, 996, 0, 0, 0, 0, 997, 998, 999, 1000, 1001, 1002, 1003, 0, 0, 0, 0, 1004, 0, 0, 0, 0, 0, 0, 1005, 1006, 1007, 1008, 1009, 0, 0, 0, 0, 0, 0, 1012, 1013, 1014, 1015, 449, 0, 0, 0, 1016, 1017, 1018, 1019, 1020, 450, 0, 0, 0, 452, 0, 453, 145, 454, 0, 455, 0, 0, 0, 456, 0, 0, 0, 0, 458, 0, 0, 0, 0, 0, 0, 462, 0, 146, 147, 464, 0, 148, 0, 20, 466, 0, 0, 0, 468, 0, 0, 0, 0, 471, 130, 472, 0, 0, 473, 151, 152, 0, 153, 480, 0, 0, 0, 482, 0, 154, 484, 0, 485, 0, 0, 0, 0, 488, 0, 43, 0, 490, 0, 0, 0, 46, 0, 494, 0, 0, 495, 156, 0, 141, 498, 0, 0, 178, 0, 0, 499, 0, 0, 145, 501, 0, 0, 1075, 157, 0, 158, 0, 0, 0, 0, 0, 1079, 1214, 1080, 1081, 0, 0, 1082, 0, 0, 147, 17, 0, 148, 0, 20, 1089, 1090, 0, 0, 0, 0, 0, 0, 149, 0, 130, 1098, 0, 0, 32, 151, 152, 0, 153, 0, 34, 35, 0, 133, 414, 154, 37, 0, 0, 419, 1104, 0, 1105, 0, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 128, 47, 0, 156, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 157, 0, 158, 0, 0, 0, 145, 0, 0, 885, 0, 0, 0, 0, 0, 0, 1169, 0, 0, 0, 0, 0, 1170, 0, 0, 0, 0, 146, 147, 17, 0, 148, 19, 20, 0, 1192, 0, 0, 1193, 0, 0, 1194, 0, 1195, 130, 0, 1196, 0, 0, 151, 152, 0, 153, 33, 0, 0, 0, 0, 1199, 1200, 1201, 1202, 1203, 1204, 0, 0, 0, 1205, 0, 43, 0, 432, 0, 0, 1206, 46, 0, 0, 434, 0, 0, 0, 0, 141, 0, 0, 0, 444, 445, 0, 0, 447, 448, 0, 0, 0, 0, 0, 0, 0, 158, 1239, 0, 0, 0, 0, 0, 817, 0, 0, 0, 1241, 0, 0, 0, 0, 1242, 0, 0, 457, 0, 0, 0, 0, 0, 0, 460, 461, 0, 145, 0, 463, 1262, 0, 0, 465, 0, 0, 0, 0, 0, 467, 0, 0, 469, 470, 0, 0, 0, 0, 0, 147, 1282, 0, 148, 1283, 20, 0, 1284, 481, 0, 1285, 0, 483, 0, 149, 0, 130, 486, 487, 0, 0, 151, 152, 0, 153, 0, 491, 492, 493, 133, 0, 1315, 0, 0, 0, 496, 1316, 0, 0, 1317, 0, 43, 0, 0, 0, 500, 0, 46, 0, 0, 128, 504, 0, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 0, 903, 0, 0, 0, 0, 0, 549, 550, 0, 551, 0, 552, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 560, 0, 0, 0, 0, 0, 0, 0, 561, 949, 12, 13, 14, 15, 16, 0, 0, 17, 18, 0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 29, -753, 30, 31, 0, 32, 0, 566, -754, 0, 33, 34, 35, 0, -754, 36, 0, 37, 38, 0, 39, -754, 40, 41, 42, -754, 43, 145, 44, -756, 45, 0, 46, 145, -751, -752, 47, 48, 0, 49, -755, 50, 51, 0, 0, 0, 0, 0, 0, 147, 0, 0, 148, 0, 20, 147, 52, 0, 148, 0, 0, 53, 0, 145, 0, 130, 0, 0, 0, 149, 151, 152, 0, 153, 0, 0, 151, 152, 0, 153, 0, 0, 0, 0, 133, 147, 647, 0, 148, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 149, 0, 0, 156, 0, 141, 128, 151, 152, 156, 153, 0, 0, 0, 0, 133, 145, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 158, 810, 0, 0, 0, 1058, 0, 668, 128, 0, 147, 156, 0, 148, 0, 0, 0, 0, 0, 1059, 1060, 685, 1061, 0, 149, 1062, 0, 0, 0, 0, 158, 151, 152, 0, 153, 0, 0, 681, 0, 17, 0, 154, 19, 20, 0, 0, 1030, 0, 0, 0, 0, 0, 0, 0, 130, 0, 1063, 0, 0, 0, 128, 0, 0, 156, 34, 35, 0, 133, 0, 0, 37, 0, 0, 734, 0, 736, 0, 0, 0, 43, 0, 0, 158, 0, 0, 46, 0, 126, 0, 0, 48, 0, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 871, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 947, 948, 181, 310, 0, 0, 0, 0, 0, 0, 0, 952, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 1021, 1022, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 1128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1078, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1084, 0, 0, 0, 1088, 0, 0, 0, 0, 1091, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1099, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 0, 273, 0, 1154, 0, 0, 0, 0, 0, 1159, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 754, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 0, 248, 0, 0, 0, 0, 253, 0, 0, 0, 0, 258, 259, 260, 0, 0, 0, 0, 0, 0, 755, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1263, 0, 0, 1264, 179, 1265, 0, 1266, 180, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 429, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 273, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 477, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 1236, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 0, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260 }; static const yytype_int16 yycheck[] = { 4, 726, 89, 725, 726, 9, 10, 711, 12, 89, 14, 15, 105, 17, 18, 19, 20, 5, 22, 23, 724, 725, 89, 5, 28, 559, 89, 89, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 722, 52, 706, 89, 86, 719, 89, 721, 5, 89, 724, 711, 8, 8, 89, 89, 725, 726, 393, 8, 75, 5, 17, 12, 724, 725, 96, 85, 56, 96, 23, 5, 8, 7, 84, 104, 64, 106, 8, 90, 99, 100, 101, 102, 103, 420, 105, 114, 1106, 1107, 109, 632, 111, 0, 82, 8, 115, 116, 89, 8, 76, 120, 121, 5, 123, 8, 766, 5, 17, 7, 5, 14, 7, 11, 42, 126, 11, 128, 5, 130, 7, 132, 133, 134, 135, 5, 104, 7, 8, 82, 141, 5, 143, 7, 145, 146, 147, 148, 149, 94, 151, 152, 153, 154, 81, 156, 157, 158, 107, 108, 107, 107, 88, 720, 87, 722, 723, 93, 177, 726, 727, 5, 92, 7, 104, 95, 106, 178, 9, 10, 104, 12, 106, 14, 15, 88, 17, 18, 19, 20, 93, 22, 23, 8, 5, 83, 7, 28, 70, 8, 11, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 14, 105, 52, 100, 101, 102, 103, 22, 104, 20, 106, 5, 109, 7, 111, 711, 31, 11, 115, 116, 31, 104, 104, 106, 121, 721, 123, 42, 724, 725, 719, 31, 721, 722, 683, 724, 725, 726, 8, 104, 21, 951, 42, 104, 104, 31, 107, 33, 34, 104, 31, 104, 67, 106, 88, 5, 67, 7, 73, 93, 88, 42, 73, 94, 95, 93, 97, 67, 5, 5, 7, 7, 8, 73, 11, 105, 126, 104, 128, 8, 130, 67, 132, 133, 134, 135, 67, 68, 17, 18, 105, 141, 73, 143, 105, 145, 146, 147, 148, 149, 81, 151, 152, 153, 154, 105, 156, 157, 158, 758, 759, 105, 104, 8, 106, 85, 104, 87, 106, 105, 90, 16, 17, 18, 105, 96, 104, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 107, 393, 27, 31, 393, 30, 31, 30, 84, 104, 86, 106, 474, 89, 1077, 91, 397, 42, 399, 400, 401, 31, 403, 104, 405, 106, 51, 31, 420, 107, 55, 420, 55, 104, 28, 106, 64, 31, 104, 67, 106, 414, 67, 71, 107, 108, 419, 31, 73, 104, 75, 1142, 104, 78, 77, 78, 81, 67, 42, 432, 103, 434, 1125, 67, 1127, 59, 31, 71, 33, 34, 107, 444, 445, 67, 447, 448, 5, 105, 7, 63, 105, 103, 105, 67, 457, 725, 726, 460, 461, 73, 463, 105, 465, 474, 467, 105, 469, 470, 1142, 1028, 31, 105, 67, 565, 105, 104, 1142, 106, 481, 5, 483, 1142, 108, 486, 487, 104, 4, 106, 491, 492, 493, 105, 503, 496, 104, 54, 106, 500, 104, 24, 106, 504, 97, 105, 1197, 1198, 67, 25, 26, 109, 105, 29, 104, 32, 106, 74, 104, 397, 106, 399, 400, 401, 40, 403, 104, 405, 106, 45, 104, 47, 48, 104, 50, 106, 105, 31, 628, 33, 34, 57, 105, 31, 60, 1236, 105, 85, 549, 550, 551, 552, 1010, 1011, 42, 645, 565, 1211, 31, 560, 561, 43, 44, 79, 37, 566, 1288, 1289, 1259, 1288, 104, 1290, 106, 67, 5, 1106, 7, 1268, 110, 67, 96, 111, 98, 395, 1141, 73, 104, 1288, 1289, 1290, 104, 62, 80, 104, 67, 1286, 14, 409, 410, 411, 412, 413, 107, 415, 416, 417, 418, 107, 112, 421, 422, 105, 104, 104, 106, 106, 5, 105, 7, 628, 107, 634, 11, 54, 1288, 503, 1290, 633, 104, 1288, 106, 1290, 105, 632, 635, 104, 645, 106, 722, 723, 1290, 393, 726, 74, 721, 397, 647, 399, 400, 401, 1207, 403, 104, 405, 106, 407, 127, 721, 129, 634, 131, 721, 752, 722, 723, 1142, 5, 726, 420, 140, 691, 142, 1142, 144, 104, 64, 106, 104, 104, 106, 106, 104, 683, 106, 685, 721, 687, 719, 721, 5, 722, 721, 724, 725, 726, 727, 721, 721, 104, 104, 106, 106, 703, 704, 175, 1092, 744, 1094, 652, 943, 654, 719, 720, 721, 722, 407, 724, 725, 726, 727, 728, 729, 722, 723, 946, 1208, 726, 727, 715, 729, 715, 964, 706, 734, 743, 736, 715, 738, 739, 706, 1103, 722, 723, 752, 706, 726, 727, 706, 729, 706, 1102, 503, 706, 762, 545, 711, 774, 758, 759, 89, 1192, 1123, 548, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 729, 726, 729, 711, 1094, 1111, 563, 715, 644, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 719, 720, 721, 722, 700, 724, 725, 726, 635, 728, 1244, 565, 742, 113, 744, 1288, 1289, 1290, 954, 702, 30, 31, 1288, 711, 1290, 1078, 735, 715, 4, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, -1, 5, 177, 7, 702, -1, -1, 11, 26, 27, -1, 29, 742, 31, 744, 67, 27, -1, 687, 30, 24, 73, 40, 75, 42, -1, 78, 743, 32, 47, 48, -1, 50, -1, 703, 704, -1, 55, -1, 57, 51, 52, 53, -1, 55, -1, 762, 65, 31, 67, -1, -1, -1, 105, 4, 73, -1, 40, 76, 42, -1, 79, 45, 81, -1, -1, 77, 78, -1, 738, 739, -1, -1, 912, 913, 25, 26, 60, 96, 29, 98, 31, 49, 31, 67, 33, 34, 105, 55, -1, 73, -1, 42, 76, 105, 62, -1, 47, 48, 66, 50, -1, -1, -1, 694, -1, 1028, 57, 947, 948, -1, 761, -1, 952, 423, 424, 4, 67, -1, 67, -1, 27, 105, 73, 433, 31, 435, 436, -1, 79, -1, 81, -1, 442, 443, -1, 42, 446, 26, -1, -1, 29, -1, 31, -1, 51, 96, -1, 98, 55, -1, -1, 40, 743, -1, 105, -1, 105, -1, 47, 48, 67, 50, 1010, 1011, -1, -1, 73, -1, 57, -1, -1, 762, 1101, -1, 81, -1, 27, -1, 67, 30, -1, 1021, 1022, -1, 73, -1, 22, 76, -1, 1028, 79, -1, -1, -1, -1, -1, -1, -1, 105, -1, 51, 52, 53, 39, -1, -1, -1, 96, 1028, 98, -1, -1, -1, 49, -1, -1, 105, -1, 1058, 1059, 1060, 1061, 1062, 1063, 75, 61, 62, 78, -1, -1, 66, -1, -1, 69, -1, -1, -1, -1, 1078, 75, -1, -1, 912, 913, 1084, -1, -1, -1, 1088, -1, -1, 1091, -1, 1101, 105, 1102, 1103, -1, -1, 1099, -1, -1, -1, 573, -1, -1, 576, 577, -1, -1, 580, 1142, -1, 583, -1, -1, 586, -1, -1, 589, -1, -1, 592, 934, 935, 595, -1, -1, 598, -1, -1, 601, -1, -1, 604, 1142, -1, 607, -1, -1, 610, -1, -1, 613, 614, 615, 616, 1102, 1103, 619, -1, -1, 622, -1, 1154, 1244, -1, 27, -1, 1159, 30, 31, -1, -1, -1, -1, -1, -1, 638, 1102, 1103, -1, 42, 1106, 1107, -1, -1, -1, -1, -1, -1, 51, 52, 53, -1, 55, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, -1, 67, -1, 669, 670, 671, 1291, 1210, 1211, -1, -1, -1, 1141, 1142, 680, 1102, 1103, -1, -1, 1106, 1107, -1, -1, -1, 1220, -1, -1, 693, -1, -1, -1, -1, 1058, 1059, 1060, 1061, 1062, 1063, -1, 105, 1244, -1, 708, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1141, 1142, -1, 1208, -1, 1210, 1211, 1288, 1289, 1010, 1011, -1, -1, 1263, 1264, 1265, 1266, -1, -1, -1, 740, 741, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, 1093, 1291, 1095, 1096, 1097, -1, -1, -1, -1, -1, -1, -1, -1, 765, -1, -1, 768, 769, 770, -1, -1, -1, -1, -1, -1, -1, -1, 779, -1, -1, -1, -1, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 805, 806, -1, -1, 809, -1, 1092, -1, 1094, 814, 815, 816, -1, -1, -1, -1, 821, -1, -1, -1, -1, -1, -1, 828, -1, -1, -1, -1, 833, -1, -1, -1, -1, -1, -1, 840, 841, 842, 843, 844, 845, 846, -1, -1, 849, -1, -1, -1, -1, 854, 855, 856, 857, 858, -1, 1220, -1, -1, 863, 864, -1, -1, 867, -1, -1, 870, -1, -1, -1, -1, 875, 876, -1, -1, 879, -1, -1, -1, -1, 884, -1, -1, -1, -1, 889, 890, 891, 892, 893, 894, 895, -1, -1, -1, -1, 900, -1, -1, -1, -1, -1, -1, 907, 908, 909, 910, 911, -1, -1, -1, -1, -1, -1, 918, 919, 920, 921, 284, -1, -1, -1, 926, 927, 928, 929, 930, 293, -1, -1, -1, 297, -1, 299, 4, 301, -1, 303, -1, -1, -1, 307, -1, -1, -1, -1, 312, -1, -1, -1, -1, -1, -1, 319, -1, 25, 26, 323, -1, 29, -1, 31, 328, -1, -1, -1, 332, -1, -1, -1, -1, 337, 42, 339, -1, -1, 342, 47, 48, -1, 50, 347, -1, -1, -1, 351, -1, 57, 354, -1, 356, -1, -1, -1, -1, 361, -1, 67, -1, 365, -1, -1, -1, 73, -1, 371, -1, -1, 374, 79, -1, 81, 378, -1, -1, 92, -1, -1, 384, -1, -1, 4, 388, -1, -1, 1029, 96, -1, 98, -1, -1, -1, -1, -1, 1038, 105, 1040, 1041, -1, -1, 1044, -1, -1, 26, 27, -1, 29, -1, 31, 1053, 1054, -1, -1, -1, -1, -1, -1, 40, -1, 42, 1064, -1, -1, 46, 47, 48, -1, 50, -1, 52, 53, -1, 55, 150, 57, 58, -1, -1, 155, 1083, -1, 1085, -1, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 76, 77, -1, 79, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, 98, -1, -1, -1, 4, -1, -1, 105, -1, -1, -1, -1, -1, -1, 1133, -1, -1, -1, -1, -1, 1139, -1, -1, -1, -1, 25, 26, 27, -1, 29, 30, 31, -1, 1152, -1, -1, 1155, -1, -1, 1158, -1, 1160, 42, -1, 1163, -1, -1, 47, 48, -1, 50, 51, -1, -1, -1, -1, 1175, 1176, 1177, 1178, 1179, 1180, -1, -1, -1, 1184, -1, 67, -1, 261, -1, -1, 1191, 73, -1, -1, 268, -1, -1, -1, -1, 81, -1, -1, -1, 277, 278, -1, -1, 281, 282, -1, -1, -1, -1, -1, -1, -1, 98, 1218, -1, -1, -1, -1, -1, 105, -1, -1, -1, 1228, -1, -1, -1, -1, 1233, -1, -1, 309, -1, -1, -1, -1, -1, -1, 316, 317, -1, 4, -1, 321, 1249, -1, -1, 325, -1, -1, -1, -1, -1, 331, -1, -1, 334, 335, -1, -1, -1, -1, -1, 26, 1269, -1, 29, 1272, 31, -1, 1275, 349, -1, 1278, -1, 353, -1, 40, -1, 42, 358, 359, -1, -1, 47, 48, -1, 50, -1, 367, 368, 369, 55, -1, 1299, -1, -1, -1, 376, 1304, -1, -1, 1307, -1, 67, -1, -1, -1, 386, -1, 73, -1, -1, 76, 392, -1, 79, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, 426, 427, -1, 429, -1, 431, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 451, -1, -1, -1, -1, -1, -1, -1, 459, 749, 20, 21, 22, 23, 24, -1, -1, 27, 28, -1, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, -1, 46, -1, 489, 49, -1, 51, 52, 53, -1, 55, 56, -1, 58, 59, -1, 61, 62, 63, 64, 65, 66, 67, 4, 69, 70, 71, -1, 73, 4, 75, 76, 77, 78, -1, 80, 81, 82, 83, -1, -1, -1, -1, -1, -1, 26, -1, -1, 29, -1, 31, 26, 97, -1, 29, -1, -1, 102, -1, 4, -1, 42, -1, -1, -1, 40, 47, 48, -1, 50, -1, -1, 47, 48, -1, 50, -1, -1, -1, -1, 55, 26, 568, -1, 29, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 40, -1, -1, 79, -1, 81, 76, 47, 48, 79, 50, -1, -1, -1, -1, 55, 4, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, 98, 105, -1, -1, -1, 21, -1, 105, 76, -1, 26, 79, -1, 29, -1, -1, -1, -1, -1, 35, 36, 630, 38, -1, 40, 41, -1, -1, -1, -1, 98, 47, 48, -1, 50, -1, -1, 105, -1, 27, -1, 57, 30, 31, -1, -1, 944, -1, -1, -1, -1, -1, -1, -1, 42, -1, 72, -1, -1, -1, 76, -1, -1, 79, 52, 53, -1, 55, -1, -1, 58, -1, -1, 682, -1, 684, -1, -1, -1, 67, -1, -1, 98, -1, -1, 73, -1, 75, -1, -1, 78, -1, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, 746, 747, 10, 11, -1, -1, -1, -1, -1, -1, -1, 757, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, 932, 933, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1034, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1048, -1, -1, -1, 1052, -1, -1, -1, -1, 1057, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1076, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, 11, -1, 1112, -1, -1, -1, -1, -1, 1118, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, -1, -1, -1, -1, 91, -1, -1, -1, -1, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1250, -1, -1, 1253, 4, 1255, -1, 1257, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 114, 120, 124, 419, 441, 0, 5, 7, 54, 74, 418, 20, 21, 22, 23, 24, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 43, 44, 46, 51, 52, 53, 56, 58, 59, 61, 63, 64, 65, 67, 69, 71, 73, 77, 78, 80, 82, 83, 97, 102, 130, 140, 142, 144, 147, 149, 151, 153, 170, 176, 190, 202, 214, 222, 227, 229, 238, 241, 243, 245, 247, 339, 342, 345, 347, 350, 353, 359, 362, 430, 431, 432, 433, 434, 435, 436, 437, 438, 418, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 402, 402, 75, 194, 76, 192, 42, 183, 49, 55, 62, 66, 204, 209, 224, 356, 440, 81, 335, 70, 157, 4, 25, 26, 29, 40, 45, 47, 48, 50, 57, 60, 79, 96, 98, 249, 254, 257, 261, 264, 267, 273, 277, 279, 283, 299, 304, 305, 307, 308, 310, 439, 407, 420, 419, 4, 8, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 115, 116, 119, 395, 425, 426, 427, 428, 123, 395, 169, 395, 11, 116, 189, 397, 428, 429, 141, 395, 88, 93, 116, 338, 340, 9, 11, 12, 16, 17, 18, 116, 148, 422, 424, 425, 246, 422, 150, 422, 242, 422, 240, 422, 17, 116, 201, 203, 390, 11, 116, 361, 363, 396, 425, 88, 93, 116, 341, 343, 94, 116, 349, 351, 390, 18, 116, 346, 348, 390, 391, 129, 422, 92, 95, 116, 352, 354, 146, 422, 116, 226, 371, 372, 373, 116, 237, 239, 391, 116, 143, 394, 428, 344, 422, 152, 422, 88, 93, 116, 228, 230, 12, 116, 139, 160, 85, 87, 90, 116, 175, 177, 116, 358, 360, 369, 396, 244, 422, 16, 17, 18, 116, 221, 223, 392, 393, 213, 422, 403, 418, 429, 420, 402, 420, 402, 420, 402, 420, 420, 208, 420, 420, 402, 420, 402, 420, 402, 420, 420, 420, 420, 420, 419, 420, 420, 420, 420, 419, 420, 420, 420, 104, 104, 402, 104, 106, 417, 8, 408, 424, 419, 104, 419, 104, 104, 106, 171, 104, 106, 398, 399, 401, 419, 419, 104, 419, 419, 398, 398, 423, 398, 398, 398, 398, 398, 419, 398, 364, 419, 419, 398, 419, 398, 419, 398, 419, 398, 419, 419, 398, 398, 398, 107, 374, 375, 14, 377, 378, 398, 419, 398, 419, 398, 398, 419, 419, 398, 161, 398, 419, 419, 419, 398, 398, 419, 370, 398, 398, 419, 398, 404, 405, 419, 195, 397, 191, 395, 182, 422, 205, 422, 355, 422, 210, 422, 365, 422, 334, 422, 155, 160, 276, 395, 272, 395, 266, 395, 253, 395, 248, 395, 258, 395, 260, 395, 263, 395, 309, 395, 282, 397, 298, 395, 278, 395, 402, 402, 419, 419, 419, 419, 117, 402, 402, 402, 402, 402, 402, 419, 419, 396, 376, 107, 379, 419, 368, 104, 106, 410, 406, 422, 104, 106, 196, 104, 104, 106, 184, 104, 106, 206, 104, 106, 357, 104, 106, 211, 104, 106, 225, 104, 106, 336, 104, 106, 158, 104, 106, 280, 104, 106, 274, 104, 106, 268, 104, 106, 255, 104, 106, 250, 104, 104, 104, 104, 106, 311, 104, 106, 284, 104, 106, 302, 280, 306, 306, 416, 409, 103, 121, 122, 125, 126, 83, 173, 105, 400, 144, 382, 374, 378, 380, 396, 107, 366, 419, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 105, 192, 249, 252, 254, 257, 261, 264, 267, 277, 279, 283, 356, 105, 105, 396, 103, 419, 131, 82, 128, 130, 144, 131, 128, 142, 420, 105, 402, 105, 108, 381, 382, 396, 411, 24, 32, 197, 198, 215, 217, 231, 233, 193, 105, 207, 207, 212, 207, 337, 159, 281, 275, 269, 256, 251, 259, 262, 265, 312, 285, 303, 402, 402, 402, 402, 419, 407, 419, 8, 43, 44, 132, 136, 145, 420, 145, 402, 88, 93, 116, 172, 174, 5, 421, 375, 54, 105, 403, 412, 414, 415, 427, 420, 420, 105, 190, 199, 200, 202, 204, 209, 224, 227, 229, 402, 232, 105, 151, 153, 176, 194, 245, 247, 105, 151, 153, 241, 243, 105, 105, 151, 153, 214, 241, 243, 105, 105, 151, 153, 105, 151, 153, 105, 151, 153, 176, 183, 335, 339, 342, 356, 105, 151, 153, 176, 183, 252, 335, 105, 151, 153, 176, 183, 247, 254, 257, 261, 264, 267, 270, 271, 273, 277, 279, 335, 339, 342, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 345, 356, 105, 151, 153, 176, 192, 249, 252, 299, 310, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 342, 356, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 347, 350, 353, 356, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 347, 350, 353, 356, 359, 362, 105, 151, 153, 176, 183, 192, 249, 252, 356, 21, 68, 105, 151, 153, 176, 183, 288, 293, 335, 105, 151, 153, 176, 183, 192, 249, 305, 308, 417, 8, 118, 420, 420, 402, 402, 147, 149, 151, 153, 154, 156, 127, 422, 154, 419, 419, 398, 383, 396, 419, 407, 407, 234, 395, 218, 422, 402, 194, 402, 402, 402, 216, 233, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 420, 420, 402, 402, 402, 402, 402, 402, 402, 402, 402, 419, 419, 133, 395, 135, 395, 162, 163, 157, 398, 162, 109, 421, 104, 106, 413, 413, 104, 106, 235, 104, 106, 219, 217, 116, 291, 292, 369, 116, 286, 287, 369, 104, 104, 106, 137, 105, 21, 35, 36, 38, 41, 72, 164, 166, 179, 186, 192, 249, 252, 296, 301, 310, 314, 402, 105, 110, 419, 402, 402, 402, 402, 104, 419, 104, 106, 289, 419, 402, 402, 419, 420, 420, 420, 420, 420, 420, 402, 419, 421, 416, 236, 220, 402, 402, 134, 138, 116, 294, 295, 366, 367, 165, 395, 116, 313, 316, 367, 178, 395, 185, 395, 300, 395, 85, 384, 389, 105, 105, 151, 153, 176, 183, 238, 105, 151, 153, 176, 183, 222, 297, 290, 105, 140, 144, 151, 153, 105, 140, 151, 153, 104, 368, 419, 104, 106, 167, 104, 419, 104, 106, 180, 104, 106, 187, 302, 421, 421, 402, 402, 105, 151, 153, 176, 183, 252, 273, 299, 310, 335, 105, 151, 153, 183, 247, 339, 342, 345, 347, 350, 356, 402, 402, 402, 402, 402, 111, 107, 402, 402, 402, 402, 402, 402, 402, 402, 297, 168, 315, 181, 188, 421, 421, 105, 105, 151, 153, 170, 176, 37, 105, 151, 153, 105, 151, 153, 176, 183, 105, 151, 153, 176, 183, 190, 112, 14, 385, 386, 402, 420, 402, 402, 421, 387, 84, 86, 89, 91, 317, 318, 319, 321, 322, 323, 326, 327, 330, 331, 107, 386, 396, 402, 419, 419, 419, 419, 421, 388, 104, 106, 320, 104, 106, 324, 104, 106, 328, 104, 106, 332, 421, 402, 402, 402, 402, 107, 105, 325, 329, 333, 421, 105, 245, 247, 339, 342, 347, 350, 356, 359, 105, 245, 247, 356, 359, 105, 194, 245, 247, 339, 342, 347, 350, 396, 402, 402, 402 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 113, 114, 114, 114, 115, 116, 117, 118, 117, 119, 120, 121, 122, 122, 122, 122, 123, 124, 125, 126, 126, 126, 127, 128, 129, 130, 131, 131, 131, 132, 133, 134, 134, 134, 134, 134, 135, 136, 137, 137, 138, 138, 138, 138, 139, 140, 141, 142, 143, 144, 145, 145, 145, 145, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 156, 157, 158, 158, 159, 159, 159, 161, 160, 160, 162, 163, 163, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 165, 166, 167, 167, 168, 168, 168, 168, 168, 169, 170, 171, 171, 172, 173, 173, 174, 174, 174, 175, 176, 177, 177, 177, 177, 178, 179, 180, 180, 181, 181, 181, 181, 181, 182, 183, 184, 184, 185, 186, 187, 187, 188, 188, 188, 188, 188, 188, 189, 190, 191, 192, 193, 193, 193, 193, 193, 193, 193, 194, 195, 196, 196, 197, 197, 197, 198, 198, 198, 198, 198, 198, 198, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, 206, 207, 207, 207, 207, 207, 208, 209, 210, 211, 211, 212, 212, 212, 212, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 219, 220, 220, 220, 220, 220, 220, 221, 222, 223, 223, 224, 225, 225, 226, 227, 228, 229, 230, 230, 230, 231, 232, 232, 233, 234, 235, 235, 236, 236, 236, 236, 236, 236, 237, 238, 239, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 253, 254, 255, 255, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 257, 258, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 260, 261, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 263, 264, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 266, 267, 268, 268, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 270, 270, 271, 271, 271, 271, 271, 271, 271, 272, 273, 274, 274, 275, 275, 275, 275, 275, 275, 275, 276, 277, 278, 279, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 283, 284, 284, 285, 285, 285, 285, 285, 285, 285, 285, 286, 286, 287, 288, 289, 289, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 291, 291, 292, 293, 294, 294, 295, 296, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 298, 299, 300, 301, 302, 302, 303, 303, 303, 303, 303, 303, 303, 303, 303, 304, 305, 306, 306, 306, 306, 306, 307, 308, 309, 310, 311, 311, 312, 312, 312, 312, 312, 312, 312, 312, 312, 313, 314, 315, 315, 315, 315, 316, 316, 317, 317, 318, 319, 320, 320, 321, 321, 321, 322, 323, 324, 324, 325, 325, 325, 325, 325, 325, 325, 325, 325, 326, 327, 328, 328, 329, 329, 329, 329, 329, 330, 331, 332, 332, 333, 333, 333, 333, 333, 333, 333, 333, 334, 335, 336, 336, 337, 337, 337, 338, 339, 340, 340, 340, 341, 342, 343, 343, 343, 344, 345, 346, 347, 348, 348, 349, 350, 351, 351, 351, 352, 353, 354, 354, 354, 355, 356, 357, 357, 358, 359, 360, 360, 361, 362, 364, 363, 363, 365, 366, 367, 368, 368, 370, 369, 372, 371, 373, 371, 371, 374, 375, 376, 376, 377, 378, 379, 379, 380, 381, 381, 382, 382, 383, 384, 385, 386, 387, 387, 388, 388, 389, 390, 391, 391, 392, 392, 393, 393, 394, 394, 395, 395, 396, 396, 397, 397, 397, 398, 398, 399, 400, 401, 402, 402, 402, 403, 404, 405, 406, 406, 407, 407, 408, 408, 408, 409, 409, 410, 410, 411, 411, 412, 412, 412, 413, 413, 414, 415, 416, 416, 417, 417, 418, 418, 419, 419, 420, 421, 421, 423, 422, 422, 424, 424, 424, 424, 424, 424, 424, 425, 425, 425, 426, 426, 426, 426, 426, 426, 426, 426, 426, 426, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 440, 440, 440, 440, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 1, 3, 0, 0, 6, 1, 13, 1, 0, 2, 2, 2, 1, 13, 1, 0, 2, 3, 1, 4, 1, 4, 0, 3, 3, 7, 1, 0, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 2, 1, 4, 1, 7, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 4, 1, 4, 1, 4, 1, 1, 0, 3, 4, 1, 4, 0, 2, 2, 0, 3, 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 4, 1, 0, 4, 2, 2, 1, 1, 4, 2, 2, 2, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 3, 1, 4, 1, 4, 0, 2, 3, 2, 2, 2, 1, 4, 1, 7, 0, 3, 2, 2, 2, 2, 2, 4, 1, 1, 4, 1, 1, 1, 0, 2, 2, 2, 3, 3, 2, 3, 3, 2, 0, 1, 4, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 2, 1, 4, 3, 0, 3, 4, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 4, 1, 4, 1, 4, 1, 4, 2, 2, 1, 2, 0, 2, 5, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 0, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 1, 0, 3, 3, 3, 2, 3, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 1, 4, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 2, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 7, 2, 1, 1, 7, 0, 3, 3, 2, 2, 2, 3, 3, 3, 3, 1, 4, 1, 4, 1, 4, 0, 3, 2, 2, 2, 3, 3, 3, 3, 2, 5, 0, 3, 3, 3, 3, 2, 5, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 3, 1, 7, 0, 2, 2, 5, 2, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 3, 1, 4, 0, 2, 3, 2, 2, 2, 2, 2, 2, 1, 3, 1, 4, 0, 2, 3, 2, 2, 1, 3, 1, 4, 0, 3, 2, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 2, 1, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 1, 4, 2, 1, 1, 4, 0, 3, 1, 1, 2, 2, 0, 2, 0, 3, 0, 2, 0, 2, 1, 3, 2, 0, 2, 3, 2, 0, 2, 2, 0, 2, 0, 5, 5, 5, 4, 4, 0, 2, 0, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 2, 4, 1, 1, 1, 0, 2, 2, 3, 2, 1, 0, 1, 0, 2, 0, 2, 3, 0, 5, 1, 4, 0, 3, 1, 3, 3, 1, 4, 1, 1, 0, 4, 2, 5, 1, 1, 0, 2, 2, 0, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 4, 4, 4, 4, 4 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, scanner, param, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (0) #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Print *YYLOCP on YYO. Private, do not rely on its existence. */ YY_ATTRIBUTE_UNUSED static int yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp) { int res = 0; int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0; if (0 <= yylocp->first_line) { res += YYFPRINTF (yyo, "%d", yylocp->first_line); if (0 <= yylocp->first_column) res += YYFPRINTF (yyo, ".%d", yylocp->first_column); } if (0 <= yylocp->last_line) { if (yylocp->first_line < yylocp->last_line) { res += YYFPRINTF (yyo, "-%d", yylocp->last_line); if (0 <= end_col) res += YYFPRINTF (yyo, ".%d", end_col); } else if (0 <= end_col && yylocp->first_column < end_col) res += YYFPRINTF (yyo, "-%d", end_col); } return res; } # define YY_LOCATION_PRINT(File, Loc) \ yy_location_print_ (File, &(Loc)) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, scanner, param); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { FILE *yyoutput = yyo; YYUSE (yyoutput); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyo, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { YYFPRINTF (yyo, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); YY_LOCATION_PRINT (yyo, *yylocationp); YYFPRINTF (yyo, ": "); yy_symbol_value_print (yyo, yytype, yyvaluep, yylocationp, scanner, param); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, void *scanner, struct yang_parameter *param) { unsigned long yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , scanner, param); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, yylsp, Rule, scanner, param); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return (YYSIZE_T) (yystpcpy (yyres, yystr) - yyres); } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, void *scanner, struct yang_parameter *param) { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 115: /* tmp_string */ { free((((*yyvaluep).p_str)) ? *((*yyvaluep).p_str) : NULL); } break; case 210: /* pattern_arg_str */ { free(((*yyvaluep).str)); } break; case 399: /* semicolom */ { free(((*yyvaluep).str)); } break; case 401: /* curly_bracket_open */ { free(((*yyvaluep).str)); } break; case 405: /* string_opt_part1 */ { free(((*yyvaluep).str)); } break; case 430: /* type_ext_alloc */ { yang_type_free(param->module->ctx, ((*yyvaluep).v)); } break; case 431: /* typedef_ext_alloc */ { yang_type_free(param->module->ctx, &((struct lys_tpdf *)((*yyvaluep).v))->type); } break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, &s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", &s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, &s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++c; YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)]; } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; s = NULL; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, &s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, &s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, &s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, &s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, &s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, &s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, &s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, &s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, &s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, &s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, &s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, &s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, &s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, &s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, &s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...) { free(*param->value); *param->value = NULL; if (yylloc->first_line != -1) { if (*param->data_node && (*param->data_node) == (*param->actual_node)) { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner)); } else { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); } } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_1361_0
crossvul-cpp_data_good_2938_0
/** * collectd - src/snmp.c * Copyright (C) 2007-2012 Florian octo Forster * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: * Florian octo Forster <octo at collectd.org> **/ #include "collectd.h" #include "common.h" #include "plugin.h" #include "utils_complain.h" #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> #include <fnmatch.h> /* * Private data structes */ struct oid_s { oid oid[MAX_OID_LEN]; size_t oid_len; }; typedef struct oid_s oid_t; union instance_u { char string[DATA_MAX_NAME_LEN]; oid_t oid; }; typedef union instance_u instance_t; struct data_definition_s { char *name; /* used to reference this from the `Collect' option */ char *type; /* used to find the data_set */ _Bool is_table; instance_t instance; char *instance_prefix; oid_t *values; size_t values_len; double scale; double shift; struct data_definition_s *next; char **ignores; size_t ignores_len; int invert_match; }; typedef struct data_definition_s data_definition_t; struct host_definition_s { char *name; char *address; int version; /* snmpv1/2 options */ char *community; /* snmpv3 security options */ char *username; oid *auth_protocol; size_t auth_protocol_len; char *auth_passphrase; oid *priv_protocol; size_t priv_protocol_len; char *priv_passphrase; int security_level; char *context; void *sess_handle; c_complain_t complaint; cdtime_t interval; data_definition_t **data_list; int data_list_len; }; typedef struct host_definition_s host_definition_t; /* These two types are used to cache values in `csnmp_read_table' to handle * gaps in tables. */ struct csnmp_list_instances_s { oid_t suffix; char instance[DATA_MAX_NAME_LEN]; struct csnmp_list_instances_s *next; }; typedef struct csnmp_list_instances_s csnmp_list_instances_t; struct csnmp_table_values_s { oid_t suffix; value_t value; struct csnmp_table_values_s *next; }; typedef struct csnmp_table_values_s csnmp_table_values_t; /* * Private variables */ static data_definition_t *data_head = NULL; /* * Prototypes */ static int csnmp_read_host(user_data_t *ud); /* * Private functions */ static void csnmp_oid_init(oid_t *dst, oid const *src, size_t n) { assert(n <= STATIC_ARRAY_SIZE(dst->oid)); memcpy(dst->oid, src, sizeof(*src) * n); dst->oid_len = n; } static int csnmp_oid_compare(oid_t const *left, oid_t const *right) { return ( snmp_oid_compare(left->oid, left->oid_len, right->oid, right->oid_len)); } static int csnmp_oid_suffix(oid_t *dst, oid_t const *src, oid_t const *root) { /* Make sure "src" is in "root"s subtree. */ if (src->oid_len <= root->oid_len) return (EINVAL); if (snmp_oid_ncompare(root->oid, root->oid_len, src->oid, src->oid_len, /* n = */ root->oid_len) != 0) return (EINVAL); memset(dst, 0, sizeof(*dst)); dst->oid_len = src->oid_len - root->oid_len; memcpy(dst->oid, &src->oid[root->oid_len], dst->oid_len * sizeof(dst->oid[0])); return (0); } static int csnmp_oid_to_string(char *buffer, size_t buffer_size, oid_t const *o) { char oid_str[MAX_OID_LEN][16]; char *oid_str_ptr[MAX_OID_LEN]; for (size_t i = 0; i < o->oid_len; i++) { ssnprintf(oid_str[i], sizeof(oid_str[i]), "%lu", (unsigned long)o->oid[i]); oid_str_ptr[i] = oid_str[i]; } return (strjoin(buffer, buffer_size, oid_str_ptr, o->oid_len, /* separator = */ ".")); } static void csnmp_host_close_session(host_definition_t *host) /* {{{ */ { if (host->sess_handle == NULL) return; snmp_sess_close(host->sess_handle); host->sess_handle = NULL; } /* }}} void csnmp_host_close_session */ static void csnmp_host_definition_destroy(void *arg) /* {{{ */ { host_definition_t *hd; hd = arg; if (hd == NULL) return; if (hd->name != NULL) { DEBUG("snmp plugin: Destroying host definition for host `%s'.", hd->name); } csnmp_host_close_session(hd); sfree(hd->name); sfree(hd->address); sfree(hd->community); sfree(hd->username); sfree(hd->auth_passphrase); sfree(hd->priv_passphrase); sfree(hd->context); sfree(hd->data_list); sfree(hd); } /* }}} void csnmp_host_definition_destroy */ /* Many functions to handle the configuration. {{{ */ /* First there are many functions which do configuration stuff. It's a big * bloated and messy, I'm afraid. */ /* * Callgraph for the config stuff: * csnmp_config * +-> call_snmp_init_once * +-> csnmp_config_add_data * ! +-> csnmp_config_add_data_instance * ! +-> csnmp_config_add_data_instance_prefix * ! +-> csnmp_config_add_data_values * +-> csnmp_config_add_host * +-> csnmp_config_add_host_version * +-> csnmp_config_add_host_collect * +-> csnmp_config_add_host_auth_protocol * +-> csnmp_config_add_host_priv_protocol * +-> csnmp_config_add_host_security_level */ static void call_snmp_init_once(void) { static int have_init = 0; if (have_init == 0) init_snmp(PACKAGE_NAME); have_init = 1; } /* void call_snmp_init_once */ static int csnmp_config_add_data_instance(data_definition_t *dd, oconfig_item_t *ci) { char buffer[DATA_MAX_NAME_LEN]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (dd->is_table) { /* Instance is an OID */ dd->instance.oid.oid_len = MAX_OID_LEN; if (!read_objid(buffer, dd->instance.oid.oid, &dd->instance.oid.oid_len)) { ERROR("snmp plugin: read_objid (%s) failed.", buffer); return (-1); } } else { /* Instance is a simple string */ sstrncpy(dd->instance.string, buffer, sizeof(dd->instance.string)); } return (0); } /* int csnmp_config_add_data_instance */ static int csnmp_config_add_data_instance_prefix(data_definition_t *dd, oconfig_item_t *ci) { int status; if (!dd->is_table) { WARNING("snmp plugin: data %s: InstancePrefix is ignored when `Table' " "is set to `false'.", dd->name); return (-1); } status = cf_util_get_string(ci, &dd->instance_prefix); return status; } /* int csnmp_config_add_data_instance_prefix */ static int csnmp_config_add_data_values(data_definition_t *dd, oconfig_item_t *ci) { if (ci->values_num < 1) { WARNING("snmp plugin: `Values' needs at least one argument."); return (-1); } for (int i = 0; i < ci->values_num; i++) if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: `Values' needs only string argument."); return (-1); } sfree(dd->values); dd->values_len = 0; dd->values = malloc(sizeof(*dd->values) * ci->values_num); if (dd->values == NULL) return (-1); dd->values_len = (size_t)ci->values_num; for (int i = 0; i < ci->values_num; i++) { dd->values[i].oid_len = MAX_OID_LEN; if (NULL == snmp_parse_oid(ci->values[i].value.string, dd->values[i].oid, &dd->values[i].oid_len)) { ERROR("snmp plugin: snmp_parse_oid (%s) failed.", ci->values[i].value.string); free(dd->values); dd->values = NULL; dd->values_len = 0; return (-1); } } return (0); } /* int csnmp_config_add_data_instance */ static int csnmp_config_add_data_blacklist(data_definition_t *dd, oconfig_item_t *ci) { if (ci->values_num < 1) return (0); for (int i = 0; i < ci->values_num; i++) { if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: `Ignore' needs only string argument."); return (-1); } } dd->ignores_len = 0; dd->ignores = NULL; for (int i = 0; i < ci->values_num; ++i) { if (strarray_add(&(dd->ignores), &(dd->ignores_len), ci->values[i].value.string) != 0) { ERROR("snmp plugin: Can't allocate memory"); strarray_free(dd->ignores, dd->ignores_len); return (ENOMEM); } } return 0; } /* int csnmp_config_add_data_blacklist */ static int csnmp_config_add_data_blacklist_match_inverted(data_definition_t *dd, oconfig_item_t *ci) { if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN)) { WARNING("snmp plugin: `InvertMatch' needs exactly one boolean argument."); return (-1); } dd->invert_match = ci->values[0].value.boolean ? 1 : 0; return (0); } /* int csnmp_config_add_data_blacklist_match_inverted */ static int csnmp_config_add_data(oconfig_item_t *ci) { data_definition_t *dd; int status = 0; dd = calloc(1, sizeof(*dd)); if (dd == NULL) return (-1); status = cf_util_get_string(ci, &dd->name); if (status != 0) { free(dd); return (-1); } dd->scale = 1.0; dd->shift = 0.0; for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *option = ci->children + i; if (strcasecmp("Type", option->key) == 0) status = cf_util_get_string(option, &dd->type); else if (strcasecmp("Table", option->key) == 0) status = cf_util_get_boolean(option, &dd->is_table); else if (strcasecmp("Instance", option->key) == 0) status = csnmp_config_add_data_instance(dd, option); else if (strcasecmp("InstancePrefix", option->key) == 0) status = csnmp_config_add_data_instance_prefix(dd, option); else if (strcasecmp("Values", option->key) == 0) status = csnmp_config_add_data_values(dd, option); else if (strcasecmp("Shift", option->key) == 0) status = cf_util_get_double(option, &dd->shift); else if (strcasecmp("Scale", option->key) == 0) status = cf_util_get_double(option, &dd->scale); else if (strcasecmp("Ignore", option->key) == 0) status = csnmp_config_add_data_blacklist(dd, option); else if (strcasecmp("InvertMatch", option->key) == 0) status = csnmp_config_add_data_blacklist_match_inverted(dd, option); else { WARNING("snmp plugin: Option `%s' not allowed here.", option->key); status = -1; } if (status != 0) break; } /* for (ci->children) */ while (status == 0) { if (dd->type == NULL) { WARNING("snmp plugin: `Type' not given for data `%s'", dd->name); status = -1; break; } if (dd->values == NULL) { WARNING("snmp plugin: No `Value' given for data `%s'", dd->name); status = -1; break; } break; } /* while (status == 0) */ if (status != 0) { sfree(dd->name); sfree(dd->instance_prefix); sfree(dd->values); sfree(dd->ignores); sfree(dd); return (-1); } DEBUG("snmp plugin: dd = { name = %s, type = %s, is_table = %s, values_len = " "%zu }", dd->name, dd->type, (dd->is_table != 0) ? "true" : "false", dd->values_len); if (data_head == NULL) data_head = dd; else { data_definition_t *last; last = data_head; while (last->next != NULL) last = last->next; last->next = dd; } return (0); } /* int csnmp_config_add_data */ static int csnmp_config_add_host_version(host_definition_t *hd, oconfig_item_t *ci) { int version; if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) { WARNING("snmp plugin: The `Version' config option needs exactly one number " "argument."); return (-1); } version = (int)ci->values[0].value.number; if ((version < 1) || (version > 3)) { WARNING("snmp plugin: `Version' must either be `1', `2', or `3'."); return (-1); } hd->version = version; return (0); } /* int csnmp_config_add_host_address */ static int csnmp_config_add_host_collect(host_definition_t *host, oconfig_item_t *ci) { data_definition_t *data; data_definition_t **data_list; int data_list_len; if (ci->values_num < 1) { WARNING("snmp plugin: `Collect' needs at least one argument."); return (-1); } for (int i = 0; i < ci->values_num; i++) if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: All arguments to `Collect' must be strings."); return (-1); } data_list_len = host->data_list_len + ci->values_num; data_list = realloc(host->data_list, sizeof(data_definition_t *) * data_list_len); if (data_list == NULL) return (-1); host->data_list = data_list; for (int i = 0; i < ci->values_num; i++) { for (data = data_head; data != NULL; data = data->next) if (strcasecmp(ci->values[i].value.string, data->name) == 0) break; if (data == NULL) { WARNING("snmp plugin: No such data configured: `%s'", ci->values[i].value.string); continue; } DEBUG("snmp plugin: Collect: host = %s, data[%i] = %s;", host->name, host->data_list_len, data->name); host->data_list[host->data_list_len] = data; host->data_list_len++; } /* for (values_num) */ return (0); } /* int csnmp_config_add_host_collect */ static int csnmp_config_add_host_auth_protocol(host_definition_t *hd, oconfig_item_t *ci) { char buffer[4]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("MD5", buffer) == 0) { hd->auth_protocol = usmHMACMD5AuthProtocol; hd->auth_protocol_len = sizeof(usmHMACMD5AuthProtocol) / sizeof(oid); } else if (strcasecmp("SHA", buffer) == 0) { hd->auth_protocol = usmHMACSHA1AuthProtocol; hd->auth_protocol_len = sizeof(usmHMACSHA1AuthProtocol) / sizeof(oid); } else { WARNING("snmp plugin: The `AuthProtocol' config option must be `MD5' or " "`SHA'."); return (-1); } DEBUG("snmp plugin: host = %s; host->auth_protocol = %s;", hd->name, hd->auth_protocol == usmHMACMD5AuthProtocol ? "MD5" : "SHA"); return (0); } /* int csnmp_config_add_host_auth_protocol */ static int csnmp_config_add_host_priv_protocol(host_definition_t *hd, oconfig_item_t *ci) { char buffer[4]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("AES", buffer) == 0) { hd->priv_protocol = usmAESPrivProtocol; hd->priv_protocol_len = sizeof(usmAESPrivProtocol) / sizeof(oid); } else if (strcasecmp("DES", buffer) == 0) { hd->priv_protocol = usmDESPrivProtocol; hd->priv_protocol_len = sizeof(usmDESPrivProtocol) / sizeof(oid); } else { WARNING("snmp plugin: The `PrivProtocol' config option must be `AES' or " "`DES'."); return (-1); } DEBUG("snmp plugin: host = %s; host->priv_protocol = %s;", hd->name, hd->priv_protocol == usmAESPrivProtocol ? "AES" : "DES"); return (0); } /* int csnmp_config_add_host_priv_protocol */ static int csnmp_config_add_host_security_level(host_definition_t *hd, oconfig_item_t *ci) { char buffer[16]; int status; status = cf_util_get_string_buffer(ci, buffer, sizeof(buffer)); if (status != 0) return status; if (strcasecmp("noAuthNoPriv", buffer) == 0) hd->security_level = SNMP_SEC_LEVEL_NOAUTH; else if (strcasecmp("authNoPriv", buffer) == 0) hd->security_level = SNMP_SEC_LEVEL_AUTHNOPRIV; else if (strcasecmp("authPriv", buffer) == 0) hd->security_level = SNMP_SEC_LEVEL_AUTHPRIV; else { WARNING("snmp plugin: The `SecurityLevel' config option must be " "`noAuthNoPriv', `authNoPriv', or `authPriv'."); return (-1); } DEBUG("snmp plugin: host = %s; host->security_level = %d;", hd->name, hd->security_level); return (0); } /* int csnmp_config_add_host_security_level */ static int csnmp_config_add_host(oconfig_item_t *ci) { host_definition_t *hd; int status = 0; /* Registration stuff. */ char cb_name[DATA_MAX_NAME_LEN]; hd = calloc(1, sizeof(*hd)); if (hd == NULL) return (-1); hd->version = 2; C_COMPLAIN_INIT(&hd->complaint); status = cf_util_get_string(ci, &hd->name); if (status != 0) { sfree(hd); return status; } hd->sess_handle = NULL; hd->interval = 0; for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *option = ci->children + i; status = 0; if (strcasecmp("Address", option->key) == 0) status = cf_util_get_string(option, &hd->address); else if (strcasecmp("Community", option->key) == 0) status = cf_util_get_string(option, &hd->community); else if (strcasecmp("Version", option->key) == 0) status = csnmp_config_add_host_version(hd, option); else if (strcasecmp("Collect", option->key) == 0) csnmp_config_add_host_collect(hd, option); else if (strcasecmp("Interval", option->key) == 0) cf_util_get_cdtime(option, &hd->interval); else if (strcasecmp("Username", option->key) == 0) status = cf_util_get_string(option, &hd->username); else if (strcasecmp("AuthProtocol", option->key) == 0) status = csnmp_config_add_host_auth_protocol(hd, option); else if (strcasecmp("PrivacyProtocol", option->key) == 0) status = csnmp_config_add_host_priv_protocol(hd, option); else if (strcasecmp("AuthPassphrase", option->key) == 0) status = cf_util_get_string(option, &hd->auth_passphrase); else if (strcasecmp("PrivacyPassphrase", option->key) == 0) status = cf_util_get_string(option, &hd->priv_passphrase); else if (strcasecmp("SecurityLevel", option->key) == 0) status = csnmp_config_add_host_security_level(hd, option); else if (strcasecmp("Context", option->key) == 0) status = cf_util_get_string(option, &hd->context); else { WARNING( "snmp plugin: csnmp_config_add_host: Option `%s' not allowed here.", option->key); status = -1; } if (status != 0) break; } /* for (ci->children) */ while (status == 0) { if (hd->address == NULL) { WARNING("snmp plugin: `Address' not given for host `%s'", hd->name); status = -1; break; } if (hd->community == NULL && hd->version < 3) { WARNING("snmp plugin: `Community' not given for host `%s'", hd->name); status = -1; break; } if (hd->version == 3) { if (hd->username == NULL) { WARNING("snmp plugin: `Username' not given for host `%s'", hd->name); status = -1; break; } if (hd->security_level == 0) { WARNING("snmp plugin: `SecurityLevel' not given for host `%s'", hd->name); status = -1; break; } if (hd->security_level == SNMP_SEC_LEVEL_AUTHNOPRIV || hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) { if (hd->auth_protocol == NULL) { WARNING("snmp plugin: `AuthProtocol' not given for host `%s'", hd->name); status = -1; break; } if (hd->auth_passphrase == NULL) { WARNING("snmp plugin: `AuthPassphrase' not given for host `%s'", hd->name); status = -1; break; } } if (hd->security_level == SNMP_SEC_LEVEL_AUTHPRIV) { if (hd->priv_protocol == NULL) { WARNING("snmp plugin: `PrivacyProtocol' not given for host `%s'", hd->name); status = -1; break; } if (hd->priv_passphrase == NULL) { WARNING("snmp plugin: `PrivacyPassphrase' not given for host `%s'", hd->name); status = -1; break; } } } break; } /* while (status == 0) */ if (status != 0) { csnmp_host_definition_destroy(hd); return (-1); } DEBUG("snmp plugin: hd = { name = %s, address = %s, community = %s, version " "= %i }", hd->name, hd->address, hd->community, hd->version); ssnprintf(cb_name, sizeof(cb_name), "snmp-%s", hd->name); user_data_t ud = {.data = hd, .free_func = csnmp_host_definition_destroy}; status = plugin_register_complex_read(/* group = */ NULL, cb_name, csnmp_read_host, hd->interval, /* user_data = */ &ud); if (status != 0) { ERROR("snmp plugin: Registering complex read function failed."); csnmp_host_definition_destroy(hd); return (-1); } return (0); } /* int csnmp_config_add_host */ static int csnmp_config(oconfig_item_t *ci) { call_snmp_init_once(); for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; if (strcasecmp("Data", child->key) == 0) csnmp_config_add_data(child); else if (strcasecmp("Host", child->key) == 0) csnmp_config_add_host(child); else { WARNING("snmp plugin: Ignoring unknown config option `%s'.", child->key); } } /* for (ci->children) */ return (0); } /* int csnmp_config */ /* }}} End of the config stuff. Now the interesting part begins */ static void csnmp_host_open_session(host_definition_t *host) { struct snmp_session sess; int error; if (host->sess_handle != NULL) csnmp_host_close_session(host); snmp_sess_init(&sess); sess.peername = host->address; switch (host->version) { case 1: sess.version = SNMP_VERSION_1; break; case 3: sess.version = SNMP_VERSION_3; break; default: sess.version = SNMP_VERSION_2c; break; } if (host->version == 3) { sess.securityName = host->username; sess.securityNameLen = strlen(host->username); sess.securityLevel = host->security_level; if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) { sess.securityAuthProto = host->auth_protocol; sess.securityAuthProtoLen = host->auth_protocol_len; sess.securityAuthKeyLen = USM_AUTH_KU_LEN; error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen, (u_char *)host->auth_passphrase, strlen(host->auth_passphrase), sess.securityAuthKey, &sess.securityAuthKeyLen); if (error != SNMPERR_SUCCESS) { ERROR("snmp plugin: host %s: Error generating Ku from auth_passphrase. " "(Error %d)", host->name, error); } } if (sess.securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) { sess.securityPrivProto = host->priv_protocol; sess.securityPrivProtoLen = host->priv_protocol_len; sess.securityPrivKeyLen = USM_PRIV_KU_LEN; error = generate_Ku(sess.securityAuthProto, sess.securityAuthProtoLen, (u_char *)host->priv_passphrase, strlen(host->priv_passphrase), sess.securityPrivKey, &sess.securityPrivKeyLen); if (error != SNMPERR_SUCCESS) { ERROR("snmp plugin: host %s: Error generating Ku from priv_passphrase. " "(Error %d)", host->name, error); } } if (host->context != NULL) { sess.contextName = host->context; sess.contextNameLen = strlen(host->context); } } else /* SNMPv1/2 "authenticates" with community string */ { sess.community = (u_char *)host->community; sess.community_len = strlen(host->community); } /* snmp_sess_open will copy the `struct snmp_session *'. */ host->sess_handle = snmp_sess_open(&sess); if (host->sess_handle == NULL) { char *errstr = NULL; snmp_error(&sess, NULL, NULL, &errstr); ERROR("snmp plugin: host %s: snmp_sess_open failed: %s", host->name, (errstr == NULL) ? "Unknown problem" : errstr); sfree(errstr); } } /* void csnmp_host_open_session */ /* TODO: Check if negative values wrap around. Problem: negative temperatures. */ static value_t csnmp_value_list_to_value(struct variable_list *vl, int type, double scale, double shift, const char *host_name, const char *data_name) { value_t ret; uint64_t tmp_unsigned = 0; int64_t tmp_signed = 0; _Bool defined = 1; /* Set to true when the original SNMP type appears to have been signed. */ _Bool prefer_signed = 0; if ((vl->type == ASN_INTEGER) || (vl->type == ASN_UINTEGER) || (vl->type == ASN_COUNTER) #ifdef ASN_TIMETICKS || (vl->type == ASN_TIMETICKS) #endif || (vl->type == ASN_GAUGE)) { tmp_unsigned = (uint32_t)*vl->val.integer; tmp_signed = (int32_t)*vl->val.integer; if (vl->type == ASN_INTEGER) prefer_signed = 1; DEBUG("snmp plugin: Parsed int32 value is %" PRIu64 ".", tmp_unsigned); } else if (vl->type == ASN_COUNTER64) { tmp_unsigned = (uint32_t)vl->val.counter64->high; tmp_unsigned = tmp_unsigned << 32; tmp_unsigned += (uint32_t)vl->val.counter64->low; tmp_signed = (int64_t)tmp_unsigned; DEBUG("snmp plugin: Parsed int64 value is %" PRIu64 ".", tmp_unsigned); } else if (vl->type == ASN_OCTET_STR) { /* We'll handle this later.. */ } else { char oid_buffer[1024] = {0}; snprint_objid(oid_buffer, sizeof(oid_buffer) - 1, vl->name, vl->name_length); #ifdef ASN_NULL if (vl->type == ASN_NULL) INFO("snmp plugin: OID \"%s\" is undefined (type ASN_NULL)", oid_buffer); else #endif WARNING("snmp plugin: I don't know the ASN type #%i " "(OID: \"%s\", data block \"%s\", host block \"%s\")", (int)vl->type, oid_buffer, (data_name != NULL) ? data_name : "UNKNOWN", (host_name != NULL) ? host_name : "UNKNOWN"); defined = 0; } if (vl->type == ASN_OCTET_STR) { int status = -1; if (vl->val.string != NULL) { char string[64]; size_t string_length; string_length = sizeof(string) - 1; if (vl->val_len < string_length) string_length = vl->val_len; /* The strings we get from the Net-SNMP library may not be null * terminated. That is why we're using `memcpy' here and not `strcpy'. * `string_length' is set to `vl->val_len' which holds the length of the * string. -octo */ memcpy(string, vl->val.string, string_length); string[string_length] = 0; status = parse_value(string, &ret, type); if (status != 0) { ERROR("snmp plugin: host %s: csnmp_value_list_to_value: Parsing string " "as %s failed: %s", (host_name != NULL) ? host_name : "UNKNOWN", DS_TYPE_TO_STRING(type), string); } } if (status != 0) { switch (type) { case DS_TYPE_COUNTER: case DS_TYPE_DERIVE: case DS_TYPE_ABSOLUTE: memset(&ret, 0, sizeof(ret)); break; case DS_TYPE_GAUGE: ret.gauge = NAN; break; default: ERROR("snmp plugin: csnmp_value_list_to_value: Unknown " "data source type: %i.", type); ret.gauge = NAN; } } } /* if (vl->type == ASN_OCTET_STR) */ else if (type == DS_TYPE_COUNTER) { ret.counter = tmp_unsigned; } else if (type == DS_TYPE_GAUGE) { if (!defined) ret.gauge = NAN; else if (prefer_signed) ret.gauge = (scale * tmp_signed) + shift; else ret.gauge = (scale * tmp_unsigned) + shift; } else if (type == DS_TYPE_DERIVE) { if (prefer_signed) ret.derive = (derive_t)tmp_signed; else ret.derive = (derive_t)tmp_unsigned; } else if (type == DS_TYPE_ABSOLUTE) { ret.absolute = (absolute_t)tmp_unsigned; } else { ERROR("snmp plugin: csnmp_value_list_to_value: Unknown data source " "type: %i.", type); ret.gauge = NAN; } return (ret); } /* value_t csnmp_value_list_to_value */ /* csnmp_strvbcopy_hexstring converts the bit string contained in "vb" to a hex * representation and writes it to dst. Returns zero on success and ENOMEM if * dst is not large enough to hold the string. dst is guaranteed to be * nul-terminated. */ static int csnmp_strvbcopy_hexstring(char *dst, /* {{{ */ const struct variable_list *vb, size_t dst_size) { char *buffer_ptr; size_t buffer_free; dst[0] = 0; buffer_ptr = dst; buffer_free = dst_size; for (size_t i = 0; i < vb->val_len; i++) { int status; status = snprintf(buffer_ptr, buffer_free, (i == 0) ? "%02x" : ":%02x", (unsigned int)vb->val.bitstring[i]); assert(status >= 0); if (((size_t)status) >= buffer_free) /* truncated */ { dst[dst_size - 1] = 0; return ENOMEM; } else /* if (status < buffer_free) */ { buffer_ptr += (size_t)status; buffer_free -= (size_t)status; } } return 0; } /* }}} int csnmp_strvbcopy_hexstring */ /* csnmp_strvbcopy copies the octet string or bit string contained in vb to * dst. If non-printable characters are detected, it will switch to a hex * representation of the string. Returns zero on success, EINVAL if vb does not * contain a string and ENOMEM if dst is not large enough to contain the * string. */ static int csnmp_strvbcopy(char *dst, /* {{{ */ const struct variable_list *vb, size_t dst_size) { char *src; size_t num_chars; if (vb->type == ASN_OCTET_STR) src = (char *)vb->val.string; else if (vb->type == ASN_BIT_STR) src = (char *)vb->val.bitstring; else if (vb->type == ASN_IPADDRESS) { return ssnprintf(dst, dst_size, "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8 "", (uint8_t)vb->val.string[0], (uint8_t)vb->val.string[1], (uint8_t)vb->val.string[2], (uint8_t)vb->val.string[3]); } else { dst[0] = 0; return (EINVAL); } num_chars = dst_size - 1; if (num_chars > vb->val_len) num_chars = vb->val_len; for (size_t i = 0; i < num_chars; i++) { /* Check for control characters. */ if ((unsigned char)src[i] < 32) return (csnmp_strvbcopy_hexstring(dst, vb, dst_size)); dst[i] = src[i]; } dst[num_chars] = 0; dst[dst_size - 1] = 0; if (dst_size <= vb->val_len) return ENOMEM; return 0; } /* }}} int csnmp_strvbcopy */ static int csnmp_instance_list_add(csnmp_list_instances_t **head, csnmp_list_instances_t **tail, const struct snmp_pdu *res, const host_definition_t *hd, const data_definition_t *dd) { csnmp_list_instances_t *il; struct variable_list *vb; oid_t vb_name; int status; uint32_t is_matched; /* Set vb on the last variable */ for (vb = res->variables; (vb != NULL) && (vb->next_variable != NULL); vb = vb->next_variable) /* do nothing */; if (vb == NULL) return (-1); csnmp_oid_init(&vb_name, vb->name, vb->name_length); il = calloc(1, sizeof(*il)); if (il == NULL) { ERROR("snmp plugin: calloc failed."); return (-1); } il->next = NULL; status = csnmp_oid_suffix(&il->suffix, &vb_name, &dd->instance.oid); if (status != 0) { sfree(il); return (status); } /* Get instance name */ if ((vb->type == ASN_OCTET_STR) || (vb->type == ASN_BIT_STR) || (vb->type == ASN_IPADDRESS)) { char *ptr; csnmp_strvbcopy(il->instance, vb, sizeof(il->instance)); is_matched = 0; for (uint32_t i = 0; i < dd->ignores_len; i++) { status = fnmatch(dd->ignores[i], il->instance, 0); if (status == 0) { if (dd->invert_match == 0) { sfree(il); return 0; } else { is_matched = 1; break; } } } if (dd->invert_match != 0 && is_matched == 0) { sfree(il); return 0; } for (ptr = il->instance; *ptr != '\0'; ptr++) { if ((*ptr > 0) && (*ptr < 32)) *ptr = ' '; else if (*ptr == '/') *ptr = '_'; } DEBUG("snmp plugin: il->instance = `%s';", il->instance); } else { value_t val = csnmp_value_list_to_value( vb, DS_TYPE_COUNTER, /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name); ssnprintf(il->instance, sizeof(il->instance), "%llu", val.counter); } /* TODO: Debugging output */ if (*head == NULL) *head = il; else (*tail)->next = il; *tail = il; return (0); } /* int csnmp_instance_list_add */ static int csnmp_dispatch_table(host_definition_t *host, data_definition_t *data, csnmp_list_instances_t *instance_list, csnmp_table_values_t **value_table) { const data_set_t *ds; value_list_t vl = VALUE_LIST_INIT; csnmp_list_instances_t *instance_list_ptr; csnmp_table_values_t **value_table_ptr; size_t i; _Bool have_more; oid_t current_suffix; ds = plugin_get_ds(data->type); if (!ds) { ERROR("snmp plugin: DataSet `%s' not defined.", data->type); return (-1); } assert(ds->ds_num == data->values_len); assert(data->values_len > 0); instance_list_ptr = instance_list; value_table_ptr = calloc(data->values_len, sizeof(*value_table_ptr)); if (value_table_ptr == NULL) return (-1); for (i = 0; i < data->values_len; i++) value_table_ptr[i] = value_table[i]; vl.values_len = data->values_len; vl.values = malloc(sizeof(*vl.values) * vl.values_len); if (vl.values == NULL) { ERROR("snmp plugin: malloc failed."); sfree(value_table_ptr); return (-1); } sstrncpy(vl.host, host->name, sizeof(vl.host)); sstrncpy(vl.plugin, "snmp", sizeof(vl.plugin)); vl.interval = host->interval; have_more = 1; while (have_more) { _Bool suffix_skipped = 0; /* Determine next suffix to handle. */ if (instance_list != NULL) { if (instance_list_ptr == NULL) { have_more = 0; continue; } memcpy(&current_suffix, &instance_list_ptr->suffix, sizeof(current_suffix)); } else /* no instance configured */ { csnmp_table_values_t *ptr = value_table_ptr[0]; if (ptr == NULL) { have_more = 0; continue; } memcpy(&current_suffix, &ptr->suffix, sizeof(current_suffix)); } /* Update all the value_table_ptr to point at the entry with the same * trailing partial OID */ for (i = 0; i < data->values_len; i++) { while ( (value_table_ptr[i] != NULL) && (csnmp_oid_compare(&value_table_ptr[i]->suffix, &current_suffix) < 0)) value_table_ptr[i] = value_table_ptr[i]->next; if (value_table_ptr[i] == NULL) { have_more = 0; break; } else if (csnmp_oid_compare(&value_table_ptr[i]->suffix, &current_suffix) > 0) { /* This suffix is missing in the subtree. Indicate this with the * "suffix_skipped" flag and try the next instance / suffix. */ suffix_skipped = 1; break; } } /* for (i = 0; i < columns; i++) */ if (!have_more) break; /* Matching the values failed. Start from the beginning again. */ if (suffix_skipped) { if (instance_list != NULL) instance_list_ptr = instance_list_ptr->next; else value_table_ptr[0] = value_table_ptr[0]->next; continue; } /* if we reach this line, all value_table_ptr[i] are non-NULL and are set * to the same subid. instance_list_ptr is either NULL or points to the * same subid, too. */ #if COLLECT_DEBUG for (i = 1; i < data->values_len; i++) { assert(value_table_ptr[i] != NULL); assert(csnmp_oid_compare(&value_table_ptr[i - 1]->suffix, &value_table_ptr[i]->suffix) == 0); } assert((instance_list_ptr == NULL) || (csnmp_oid_compare(&instance_list_ptr->suffix, &value_table_ptr[0]->suffix) == 0)); #endif sstrncpy(vl.type, data->type, sizeof(vl.type)); { char temp[DATA_MAX_NAME_LEN]; if (instance_list_ptr == NULL) csnmp_oid_to_string(temp, sizeof(temp), &current_suffix); else sstrncpy(temp, instance_list_ptr->instance, sizeof(temp)); if (data->instance_prefix == NULL) sstrncpy(vl.type_instance, temp, sizeof(vl.type_instance)); else ssnprintf(vl.type_instance, sizeof(vl.type_instance), "%s%s", data->instance_prefix, temp); } for (i = 0; i < data->values_len; i++) vl.values[i] = value_table_ptr[i]->value; /* If we get here `vl.type_instance' and all `vl.values' have been set * vl.type_instance can be empty, i.e. a blank port description on a * switch if you're using IF-MIB::ifDescr as Instance. */ if (vl.type_instance[0] != '\0') plugin_dispatch_values(&vl); if (instance_list != NULL) instance_list_ptr = instance_list_ptr->next; else value_table_ptr[0] = value_table_ptr[0]->next; } /* while (have_more) */ sfree(vl.values); sfree(value_table_ptr); return (0); } /* int csnmp_dispatch_table */ static int csnmp_read_table(host_definition_t *host, data_definition_t *data) { struct snmp_pdu *req; struct snmp_pdu *res = NULL; struct variable_list *vb; const data_set_t *ds; size_t oid_list_len = data->values_len + 1; /* Holds the last OID returned by the device. We use this in the GETNEXT * request to proceed. */ oid_t oid_list[oid_list_len]; /* Set to false when an OID has left its subtree so we don't re-request it * again. */ _Bool oid_list_todo[oid_list_len]; int status; size_t i; /* `value_list_head' and `value_list_tail' implement a linked list for each * value. `instance_list_head' and `instance_list_tail' implement a linked * list of * instance names. This is used to jump gaps in the table. */ csnmp_list_instances_t *instance_list_head; csnmp_list_instances_t *instance_list_tail; csnmp_table_values_t **value_list_head; csnmp_table_values_t **value_list_tail; DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name, data->name); if (host->sess_handle == NULL) { DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL"); return (-1); } ds = plugin_get_ds(data->type); if (!ds) { ERROR("snmp plugin: DataSet `%s' not defined.", data->type); return (-1); } if (ds->ds_num != data->values_len) { ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks " "about %zu", data->type, ds->ds_num, data->values_len); return (-1); } assert(data->values_len > 0); /* We need a copy of all the OIDs, because GETNEXT will destroy them. */ memcpy(oid_list, data->values, data->values_len * sizeof(oid_t)); if (data->instance.oid.oid_len > 0) memcpy(oid_list + data->values_len, &data->instance.oid, sizeof(oid_t)); else /* no InstanceFrom option specified. */ oid_list_len--; for (i = 0; i < oid_list_len; i++) oid_list_todo[i] = 1; /* We're going to construct n linked lists, one for each "value". * value_list_head will contain pointers to the heads of these linked lists, * value_list_tail will contain pointers to the tail of the lists. */ value_list_head = calloc(data->values_len, sizeof(*value_list_head)); value_list_tail = calloc(data->values_len, sizeof(*value_list_tail)); if ((value_list_head == NULL) || (value_list_tail == NULL)) { ERROR("snmp plugin: csnmp_read_table: calloc failed."); sfree(value_list_head); sfree(value_list_tail); return (-1); } instance_list_head = NULL; instance_list_tail = NULL; status = 0; while (status == 0) { int oid_list_todo_num; req = snmp_pdu_create(SNMP_MSG_GETNEXT); if (req == NULL) { ERROR("snmp plugin: snmp_pdu_create failed."); status = -1; break; } oid_list_todo_num = 0; for (i = 0; i < oid_list_len; i++) { /* Do not rerequest already finished OIDs */ if (!oid_list_todo[i]) continue; oid_list_todo_num++; snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len); } if (oid_list_todo_num == 0) { /* The request is still empty - so we are finished */ DEBUG("snmp plugin: all variables have left their subtree"); snmp_free_pdu(req); status = 0; break; } res = NULL; /* snmp_sess_synch_response always frees our req PDU */ status = snmp_sess_synch_response(host->sess_handle, req, &res); if ((status != STAT_SUCCESS) || (res == NULL)) { char *errstr = NULL; snmp_sess_error(host->sess_handle, NULL, NULL, &errstr); c_complain(LOG_ERR, &host->complaint, "snmp plugin: host %s: snmp_sess_synch_response failed: %s", host->name, (errstr == NULL) ? "Unknown problem" : errstr); if (res != NULL) snmp_free_pdu(res); res = NULL; sfree(errstr); csnmp_host_close_session(host); status = -1; break; } status = 0; assert(res != NULL); c_release(LOG_INFO, &host->complaint, "snmp plugin: host %s: snmp_sess_synch_response successful.", host->name); vb = res->variables; if (vb == NULL) { status = -1; break; } for (vb = res->variables, i = 0; (vb != NULL); vb = vb->next_variable, i++) { /* Calculate value index from todo list */ while ((i < oid_list_len) && !oid_list_todo[i]) i++; /* An instance is configured and the res variable we process is the * instance value (last index) */ if ((data->instance.oid.oid_len > 0) && (i == data->values_len)) { if ((vb->type == SNMP_ENDOFMIBVIEW) || (snmp_oid_ncompare( data->instance.oid.oid, data->instance.oid.oid_len, vb->name, vb->name_length, data->instance.oid.oid_len) != 0)) { DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.", host->name, data->name); oid_list_todo[i] = 0; continue; } /* Allocate a new `csnmp_list_instances_t', insert the instance name and * add it to the list */ if (csnmp_instance_list_add(&instance_list_head, &instance_list_tail, res, host, data) != 0) { ERROR("snmp plugin: host %s: csnmp_instance_list_add failed.", host->name); status = -1; break; } } else /* The variable we are processing is a normal value */ { csnmp_table_values_t *vt; oid_t vb_name; oid_t suffix; int ret; csnmp_oid_init(&vb_name, vb->name, vb->name_length); /* Calculate the current suffix. This is later used to check that the * suffix is increasing. This also checks if we left the subtree */ ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i); if (ret != 0) { DEBUG("snmp plugin: host = %s; data = %s; i = %zu; " "Value probably left its subtree.", host->name, data->name, i); oid_list_todo[i] = 0; continue; } /* Make sure the OIDs returned by the agent are increasing. Otherwise * our * table matching algorithm will get confused. */ if ((value_list_tail[i] != NULL) && (csnmp_oid_compare(&suffix, &value_list_tail[i]->suffix) <= 0)) { DEBUG("snmp plugin: host = %s; data = %s; i = %zu; " "Suffix is not increasing.", host->name, data->name, i); oid_list_todo[i] = 0; continue; } vt = calloc(1, sizeof(*vt)); if (vt == NULL) { ERROR("snmp plugin: calloc failed."); status = -1; break; } vt->value = csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale, data->shift, host->name, data->name); memcpy(&vt->suffix, &suffix, sizeof(vt->suffix)); vt->next = NULL; if (value_list_tail[i] == NULL) value_list_head[i] = vt; else value_list_tail[i]->next = vt; value_list_tail[i] = vt; } /* Copy OID to oid_list[i] */ memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length); oid_list[i].oid_len = vb->name_length; } /* for (vb = res->variables ...) */ if (res != NULL) snmp_free_pdu(res); res = NULL; } /* while (status == 0) */ if (res != NULL) snmp_free_pdu(res); res = NULL; if (status == 0) csnmp_dispatch_table(host, data, instance_list_head, value_list_head); /* Free all allocated variables here */ while (instance_list_head != NULL) { csnmp_list_instances_t *next = instance_list_head->next; sfree(instance_list_head); instance_list_head = next; } for (i = 0; i < data->values_len; i++) { while (value_list_head[i] != NULL) { csnmp_table_values_t *next = value_list_head[i]->next; sfree(value_list_head[i]); value_list_head[i] = next; } } sfree(value_list_head); sfree(value_list_tail); return (0); } /* int csnmp_read_table */ static int csnmp_read_value(host_definition_t *host, data_definition_t *data) { struct snmp_pdu *req; struct snmp_pdu *res = NULL; struct variable_list *vb; const data_set_t *ds; value_list_t vl = VALUE_LIST_INIT; int status; size_t i; DEBUG("snmp plugin: csnmp_read_value (host = %s, data = %s)", host->name, data->name); if (host->sess_handle == NULL) { DEBUG("snmp plugin: csnmp_read_value: host->sess_handle == NULL"); return (-1); } ds = plugin_get_ds(data->type); if (!ds) { ERROR("snmp plugin: DataSet `%s' not defined.", data->type); return (-1); } if (ds->ds_num != data->values_len) { ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks " "about %zu", data->type, ds->ds_num, data->values_len); return (-1); } vl.values_len = ds->ds_num; vl.values = malloc(sizeof(*vl.values) * vl.values_len); if (vl.values == NULL) return (-1); for (i = 0; i < vl.values_len; i++) { if (ds->ds[i].type == DS_TYPE_COUNTER) vl.values[i].counter = 0; else vl.values[i].gauge = NAN; } sstrncpy(vl.host, host->name, sizeof(vl.host)); sstrncpy(vl.plugin, "snmp", sizeof(vl.plugin)); sstrncpy(vl.type, data->type, sizeof(vl.type)); sstrncpy(vl.type_instance, data->instance.string, sizeof(vl.type_instance)); vl.interval = host->interval; req = snmp_pdu_create(SNMP_MSG_GET); if (req == NULL) { ERROR("snmp plugin: snmp_pdu_create failed."); sfree(vl.values); return (-1); } for (i = 0; i < data->values_len; i++) snmp_add_null_var(req, data->values[i].oid, data->values[i].oid_len); status = snmp_sess_synch_response(host->sess_handle, req, &res); if ((status != STAT_SUCCESS) || (res == NULL)) { char *errstr = NULL; snmp_sess_error(host->sess_handle, NULL, NULL, &errstr); ERROR("snmp plugin: host %s: snmp_sess_synch_response failed: %s", host->name, (errstr == NULL) ? "Unknown problem" : errstr); if (res != NULL) snmp_free_pdu(res); sfree(errstr); sfree(vl.values); csnmp_host_close_session(host); return (-1); } for (vb = res->variables; vb != NULL; vb = vb->next_variable) { #if COLLECT_DEBUG char buffer[1024]; snprint_variable(buffer, sizeof(buffer), vb->name, vb->name_length, vb); DEBUG("snmp plugin: Got this variable: %s", buffer); #endif /* COLLECT_DEBUG */ for (i = 0; i < data->values_len; i++) if (snmp_oid_compare(data->values[i].oid, data->values[i].oid_len, vb->name, vb->name_length) == 0) vl.values[i] = csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale, data->shift, host->name, data->name); } /* for (res->variables) */ snmp_free_pdu(res); DEBUG("snmp plugin: -> plugin_dispatch_values (&vl);"); plugin_dispatch_values(&vl); sfree(vl.values); return (0); } /* int csnmp_read_value */ static int csnmp_read_host(user_data_t *ud) { host_definition_t *host; int status; int success; int i; host = ud->data; if (host->interval == 0) host->interval = plugin_get_interval(); if (host->sess_handle == NULL) csnmp_host_open_session(host); if (host->sess_handle == NULL) return (-1); success = 0; for (i = 0; i < host->data_list_len; i++) { data_definition_t *data = host->data_list[i]; if (data->is_table) status = csnmp_read_table(host, data); else status = csnmp_read_value(host, data); if (status == 0) success++; } if (success == 0) return (-1); return (0); } /* int csnmp_read_host */ static int csnmp_init(void) { call_snmp_init_once(); return (0); } /* int csnmp_init */ static int csnmp_shutdown(void) { data_definition_t *data_this; data_definition_t *data_next; /* When we get here, the read threads have been stopped and all the * `host_definition_t' will be freed. */ DEBUG("snmp plugin: Destroying all data definitions."); data_this = data_head; data_head = NULL; while (data_this != NULL) { data_next = data_this->next; sfree(data_this->name); sfree(data_this->type); sfree(data_this->values); sfree(data_this->ignores); sfree(data_this); data_this = data_next; } return (0); } /* int csnmp_shutdown */ void module_register(void) { plugin_register_complex_config("snmp", csnmp_config); plugin_register_init("snmp", csnmp_init); plugin_register_shutdown("snmp", csnmp_shutdown); } /* void module_register */ /* * vim: shiftwidth=2 softtabstop=2 tabstop=8 fdm=marker */
./CrossVul/dataset_final_sorted/CWE-415/c/good_2938_0
crossvul-cpp_data_good_2579_1
/* #ident "@(#)gss_seal.c 1.10 95/08/07 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_complete_auth_token */ #include "mglueP.h" #include <stdio.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> #include <errno.h> OM_uint32 KRB5_CALLCONV gss_complete_auth_token (OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; mech = gssint_get_mechanism (ctx->mech_type); if (mech != NULL) { if (mech->gss_complete_auth_token != NULL) { status = mech->gss_complete_auth_token(minor_status, ctx->internal_ctx_id, input_message_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_COMPLETE; } else status = GSS_S_BAD_MECH; return status; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_1
crossvul-cpp_data_good_349_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include "libopensc/internal.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = MIN(file->size, sizeof buf); sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = MIN(file->size, sizeof buf); sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_8
crossvul-cpp_data_bad_1364_0
/* A Bison parser, made by GNU Bison 3.2.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.2.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 2 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "libyang.h" #include "common.h" #include "context.h" #include "resolve.h" #include "parser_yang.h" #include "parser_yang_lex.h" #include "parser.h" #define YANG_ADDELEM(current_ptr, size, array_name) \ if ((size) == LY_ARRAY_MAX(size)) { \ LOGERR(trg->ctx, LY_EINT, "Reached limit (%"PRIu64") for storing %s.", LY_ARRAY_MAX(size), array_name); \ free(s); \ YYABORT; \ } else if (!((size) % LY_YANG_ARRAY_SIZE)) { \ void *tmp; \ \ tmp = realloc((current_ptr), (sizeof *(current_ptr)) * ((size) + LY_YANG_ARRAY_SIZE)); \ if (!tmp) { \ LOGMEM(trg->ctx); \ free(s); \ YYABORT; \ } \ memset(tmp + (sizeof *(current_ptr)) * (size), 0, (sizeof *(current_ptr)) * LY_YANG_ARRAY_SIZE); \ (current_ptr) = tmp; \ } \ actual = &(current_ptr)[(size)++]; \ void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...); /* pointer on the current parsed element 'actual' */ # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "parser_yang_bis.h". */ #ifndef YY_YY_PARSER_YANG_BIS_H_INCLUDED # define YY_YY_PARSER_YANG_BIS_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { UNION_KEYWORD = 258, ANYXML_KEYWORD = 259, WHITESPACE = 260, ERROR = 261, EOL = 262, STRING = 263, STRINGS = 264, IDENTIFIER = 265, IDENTIFIERPREFIX = 266, REVISION_DATE = 267, TAB = 268, DOUBLEDOT = 269, URI = 270, INTEGER = 271, NON_NEGATIVE_INTEGER = 272, ZERO = 273, DECIMAL = 274, ARGUMENT_KEYWORD = 275, AUGMENT_KEYWORD = 276, BASE_KEYWORD = 277, BELONGS_TO_KEYWORD = 278, BIT_KEYWORD = 279, CASE_KEYWORD = 280, CHOICE_KEYWORD = 281, CONFIG_KEYWORD = 282, CONTACT_KEYWORD = 283, CONTAINER_KEYWORD = 284, DEFAULT_KEYWORD = 285, DESCRIPTION_KEYWORD = 286, ENUM_KEYWORD = 287, ERROR_APP_TAG_KEYWORD = 288, ERROR_MESSAGE_KEYWORD = 289, EXTENSION_KEYWORD = 290, DEVIATION_KEYWORD = 291, DEVIATE_KEYWORD = 292, FEATURE_KEYWORD = 293, FRACTION_DIGITS_KEYWORD = 294, GROUPING_KEYWORD = 295, IDENTITY_KEYWORD = 296, IF_FEATURE_KEYWORD = 297, IMPORT_KEYWORD = 298, INCLUDE_KEYWORD = 299, INPUT_KEYWORD = 300, KEY_KEYWORD = 301, LEAF_KEYWORD = 302, LEAF_LIST_KEYWORD = 303, LENGTH_KEYWORD = 304, LIST_KEYWORD = 305, MANDATORY_KEYWORD = 306, MAX_ELEMENTS_KEYWORD = 307, MIN_ELEMENTS_KEYWORD = 308, MODULE_KEYWORD = 309, MUST_KEYWORD = 310, NAMESPACE_KEYWORD = 311, NOTIFICATION_KEYWORD = 312, ORDERED_BY_KEYWORD = 313, ORGANIZATION_KEYWORD = 314, OUTPUT_KEYWORD = 315, PATH_KEYWORD = 316, PATTERN_KEYWORD = 317, POSITION_KEYWORD = 318, PREFIX_KEYWORD = 319, PRESENCE_KEYWORD = 320, RANGE_KEYWORD = 321, REFERENCE_KEYWORD = 322, REFINE_KEYWORD = 323, REQUIRE_INSTANCE_KEYWORD = 324, REVISION_KEYWORD = 325, REVISION_DATE_KEYWORD = 326, RPC_KEYWORD = 327, STATUS_KEYWORD = 328, SUBMODULE_KEYWORD = 329, TYPE_KEYWORD = 330, TYPEDEF_KEYWORD = 331, UNIQUE_KEYWORD = 332, UNITS_KEYWORD = 333, USES_KEYWORD = 334, VALUE_KEYWORD = 335, WHEN_KEYWORD = 336, YANG_VERSION_KEYWORD = 337, YIN_ELEMENT_KEYWORD = 338, ADD_KEYWORD = 339, CURRENT_KEYWORD = 340, DELETE_KEYWORD = 341, DEPRECATED_KEYWORD = 342, FALSE_KEYWORD = 343, NOT_SUPPORTED_KEYWORD = 344, OBSOLETE_KEYWORD = 345, REPLACE_KEYWORD = 346, SYSTEM_KEYWORD = 347, TRUE_KEYWORD = 348, UNBOUNDED_KEYWORD = 349, USER_KEYWORD = 350, ACTION_KEYWORD = 351, MODIFIER_KEYWORD = 352, ANYDATA_KEYWORD = 353, NODE = 354, NODE_PRINT = 355, EXTENSION_INSTANCE = 356, SUBMODULE_EXT_KEYWORD = 357 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { int32_t i; uint32_t uint; char *str; char **p_str; void *v; char ch; struct yang_type *type; struct lys_deviation *dev; struct lys_deviate *deviate; union { uint32_t index; struct lys_node_container *container; struct lys_node_anydata *anydata; struct type_node node; struct lys_node_case *cs; struct lys_node_grp *grouping; struct lys_refine *refine; struct lys_node_notif *notif; struct lys_node_uses *uses; struct lys_node_inout *inout; struct lys_node_augment *augment; } nodes; enum yytokentype token; struct { void *actual; enum yytokentype token; } backup_token; struct { struct lys_revision **revision; int index; } revisions; }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif int yyparse (void *scanner, struct yang_parameter *param); #endif /* !YY_YY_PARSER_YANG_BIS_H_INCLUDED */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 6 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 3466 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 113 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 329 /* YYNRULES -- Number of rules. */ #define YYNRULES 827 /* YYNSTATES -- Number of states. */ #define YYNSTATES 1318 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 357 #define YYTRANSLATE(YYX) \ ((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 111, 112, 2, 103, 2, 2, 2, 107, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 106, 2, 110, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 108, 2, 109, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 104, 2, 105, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 338, 338, 339, 340, 342, 365, 368, 370, 369, 393, 404, 414, 424, 425, 431, 436, 442, 453, 463, 476, 477, 483, 485, 489, 491, 495, 497, 498, 499, 501, 509, 517, 518, 523, 534, 545, 556, 564, 569, 570, 574, 575, 586, 597, 608, 612, 614, 637, 654, 658, 660, 661, 666, 671, 676, 682, 686, 688, 692, 694, 698, 700, 704, 706, 719, 730, 731, 743, 747, 748, 752, 753, 758, 765, 765, 776, 782, 830, 849, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 864, 879, 886, 887, 891, 892, 893, 899, 904, 910, 928, 930, 931, 935, 940, 941, 963, 964, 965, 978, 983, 985, 986, 987, 988, 1003, 1017, 1022, 1023, 1038, 1039, 1040, 1046, 1051, 1057, 1114, 1119, 1120, 1122, 1138, 1143, 1144, 1169, 1170, 1184, 1185, 1191, 1196, 1202, 1206, 1208, 1261, 1272, 1275, 1278, 1283, 1288, 1294, 1299, 1305, 1310, 1319, 1320, 1324, 1371, 1372, 1374, 1375, 1379, 1385, 1398, 1399, 1400, 1404, 1405, 1407, 1411, 1429, 1434, 1436, 1437, 1453, 1458, 1467, 1468, 1472, 1488, 1493, 1498, 1503, 1509, 1513, 1529, 1544, 1545, 1549, 1550, 1560, 1565, 1570, 1575, 1581, 1585, 1596, 1608, 1609, 1612, 1620, 1631, 1632, 1647, 1648, 1649, 1661, 1667, 1672, 1678, 1683, 1685, 1686, 1701, 1706, 1707, 1712, 1716, 1718, 1723, 1725, 1726, 1727, 1740, 1752, 1753, 1755, 1763, 1775, 1776, 1791, 1792, 1793, 1805, 1811, 1816, 1822, 1827, 1829, 1830, 1846, 1850, 1852, 1856, 1858, 1862, 1864, 1868, 1870, 1880, 1887, 1888, 1892, 1893, 1899, 1904, 1909, 1910, 1911, 1912, 1913, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1929, 1939, 1946, 1947, 1970, 1971, 1972, 1973, 1974, 1979, 1985, 1991, 1996, 2001, 2002, 2003, 2008, 2009, 2011, 2051, 2061, 2064, 2065, 2066, 2069, 2074, 2075, 2080, 2086, 2092, 2098, 2103, 2109, 2119, 2174, 2177, 2178, 2179, 2182, 2193, 2198, 2199, 2205, 2218, 2231, 2241, 2247, 2252, 2258, 2268, 2315, 2318, 2319, 2320, 2321, 2330, 2336, 2342, 2355, 2368, 2378, 2384, 2389, 2394, 2395, 2396, 2397, 2402, 2404, 2414, 2421, 2422, 2442, 2445, 2446, 2447, 2457, 2464, 2471, 2478, 2484, 2490, 2492, 2493, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2507, 2517, 2524, 2525, 2539, 2540, 2541, 2542, 2548, 2553, 2558, 2561, 2571, 2578, 2588, 2595, 2596, 2619, 2622, 2623, 2624, 2625, 2632, 2639, 2646, 2651, 2657, 2667, 2674, 2675, 2707, 2708, 2709, 2710, 2716, 2721, 2726, 2727, 2729, 2730, 2732, 2745, 2750, 2751, 2783, 2786, 2800, 2816, 2838, 2889, 2908, 2927, 2948, 2969, 2974, 2980, 2981, 2984, 2999, 3008, 3009, 3011, 3022, 3031, 3032, 3033, 3034, 3040, 3045, 3050, 3051, 3052, 3057, 3059, 3074, 3081, 3091, 3098, 3099, 3123, 3126, 3127, 3133, 3138, 3143, 3144, 3145, 3152, 3160, 3175, 3205, 3206, 3207, 3208, 3209, 3211, 3226, 3256, 3265, 3272, 3273, 3305, 3306, 3307, 3308, 3314, 3319, 3324, 3325, 3326, 3328, 3340, 3360, 3361, 3367, 3373, 3375, 3376, 3378, 3379, 3382, 3390, 3395, 3396, 3398, 3399, 3400, 3402, 3410, 3415, 3416, 3448, 3449, 3455, 3456, 3462, 3468, 3475, 3482, 3490, 3499, 3507, 3512, 3513, 3545, 3546, 3552, 3553, 3559, 3566, 3574, 3579, 3580, 3594, 3595, 3596, 3602, 3608, 3615, 3622, 3630, 3639, 3648, 3653, 3654, 3658, 3659, 3664, 3670, 3675, 3677, 3678, 3679, 3692, 3697, 3699, 3700, 3701, 3714, 3718, 3720, 3725, 3727, 3728, 3748, 3753, 3755, 3756, 3757, 3777, 3782, 3784, 3785, 3786, 3798, 3867, 3872, 3873, 3877, 3881, 3883, 3884, 3886, 3890, 3892, 3892, 3899, 3902, 3911, 3930, 3932, 3933, 3936, 3936, 3953, 3953, 3960, 3960, 3967, 3970, 3972, 3974, 3975, 3977, 3979, 3981, 3982, 3984, 3986, 3987, 3989, 3990, 3992, 3994, 3997, 4000, 4002, 4003, 4005, 4006, 4008, 4010, 4021, 4022, 4025, 4026, 4038, 4039, 4041, 4042, 4044, 4045, 4051, 4052, 4055, 4056, 4057, 4081, 4082, 4085, 4091, 4095, 4100, 4101, 4102, 4105, 4110, 4120, 4122, 4123, 4125, 4126, 4128, 4129, 4130, 4132, 4133, 4135, 4136, 4138, 4139, 4143, 4144, 4171, 4209, 4210, 4212, 4214, 4216, 4217, 4219, 4220, 4222, 4223, 4226, 4227, 4230, 4232, 4233, 4236, 4236, 4243, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4253, 4254, 4255, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301, 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, 4320, 4321, 4322, 4323, 4324, 4325, 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340, 4347, 4354, 4374, 4392, 4408, 4435, 4442, 4460, 4500, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4531, 4532, 4533, 4534, 4536, 4544, 4545, 4550, 4555, 4560, 4565, 4570, 4575, 4580, 4585, 4590, 4595, 4600, 4605, 4610, 4615, 4620, 4634, 4654, 4659, 4664, 4669, 4682, 4687, 4691, 4701, 4716, 4731, 4746, 4761, 4781, 4796, 4797, 4803, 4810, 4825, 4828 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "UNION_KEYWORD", "ANYXML_KEYWORD", "WHITESPACE", "ERROR", "EOL", "STRING", "STRINGS", "IDENTIFIER", "IDENTIFIERPREFIX", "REVISION_DATE", "TAB", "DOUBLEDOT", "URI", "INTEGER", "NON_NEGATIVE_INTEGER", "ZERO", "DECIMAL", "ARGUMENT_KEYWORD", "AUGMENT_KEYWORD", "BASE_KEYWORD", "BELONGS_TO_KEYWORD", "BIT_KEYWORD", "CASE_KEYWORD", "CHOICE_KEYWORD", "CONFIG_KEYWORD", "CONTACT_KEYWORD", "CONTAINER_KEYWORD", "DEFAULT_KEYWORD", "DESCRIPTION_KEYWORD", "ENUM_KEYWORD", "ERROR_APP_TAG_KEYWORD", "ERROR_MESSAGE_KEYWORD", "EXTENSION_KEYWORD", "DEVIATION_KEYWORD", "DEVIATE_KEYWORD", "FEATURE_KEYWORD", "FRACTION_DIGITS_KEYWORD", "GROUPING_KEYWORD", "IDENTITY_KEYWORD", "IF_FEATURE_KEYWORD", "IMPORT_KEYWORD", "INCLUDE_KEYWORD", "INPUT_KEYWORD", "KEY_KEYWORD", "LEAF_KEYWORD", "LEAF_LIST_KEYWORD", "LENGTH_KEYWORD", "LIST_KEYWORD", "MANDATORY_KEYWORD", "MAX_ELEMENTS_KEYWORD", "MIN_ELEMENTS_KEYWORD", "MODULE_KEYWORD", "MUST_KEYWORD", "NAMESPACE_KEYWORD", "NOTIFICATION_KEYWORD", "ORDERED_BY_KEYWORD", "ORGANIZATION_KEYWORD", "OUTPUT_KEYWORD", "PATH_KEYWORD", "PATTERN_KEYWORD", "POSITION_KEYWORD", "PREFIX_KEYWORD", "PRESENCE_KEYWORD", "RANGE_KEYWORD", "REFERENCE_KEYWORD", "REFINE_KEYWORD", "REQUIRE_INSTANCE_KEYWORD", "REVISION_KEYWORD", "REVISION_DATE_KEYWORD", "RPC_KEYWORD", "STATUS_KEYWORD", "SUBMODULE_KEYWORD", "TYPE_KEYWORD", "TYPEDEF_KEYWORD", "UNIQUE_KEYWORD", "UNITS_KEYWORD", "USES_KEYWORD", "VALUE_KEYWORD", "WHEN_KEYWORD", "YANG_VERSION_KEYWORD", "YIN_ELEMENT_KEYWORD", "ADD_KEYWORD", "CURRENT_KEYWORD", "DELETE_KEYWORD", "DEPRECATED_KEYWORD", "FALSE_KEYWORD", "NOT_SUPPORTED_KEYWORD", "OBSOLETE_KEYWORD", "REPLACE_KEYWORD", "SYSTEM_KEYWORD", "TRUE_KEYWORD", "UNBOUNDED_KEYWORD", "USER_KEYWORD", "ACTION_KEYWORD", "MODIFIER_KEYWORD", "ANYDATA_KEYWORD", "NODE", "NODE_PRINT", "EXTENSION_INSTANCE", "SUBMODULE_EXT_KEYWORD", "'+'", "'{'", "'}'", "';'", "'/'", "'['", "']'", "'='", "'('", "')'", "$accept", "start", "tmp_string", "string_1", "string_2", "$@1", "module_arg_str", "module_stmt", "module_header_stmts", "module_header_stmt", "submodule_arg_str", "submodule_stmt", "submodule_header_stmts", "submodule_header_stmt", "yang_version_arg", "yang_version_stmt", "namespace_arg_str", "namespace_stmt", "linkage_stmts", "import_stmt", "import_arg_str", "import_opt_stmt", "include_arg_str", "include_stmt", "include_end", "include_opt_stmt", "revision_date_arg", "revision_date_stmt", "belongs_to_arg_str", "belongs_to_stmt", "prefix_arg", "prefix_stmt", "meta_stmts", "organization_arg", "organization_stmt", "contact_arg", "contact_stmt", "description_arg", "description_stmt", "reference_arg", "reference_stmt", "revision_stmts", "revision_arg_stmt", "revision_stmts_opt", "revision_stmt", "revision_end", "revision_opt_stmt", "date_arg_str", "$@2", "body_stmts_end", "body_stmts", "body_stmt", "extension_arg_str", "extension_stmt", "extension_end", "extension_opt_stmt", "argument_str", "argument_stmt", "argument_end", "yin_element_arg", "yin_element_stmt", "yin_element_arg_str", "status_arg", "status_stmt", "status_arg_str", "feature_arg_str", "feature_stmt", "feature_end", "feature_opt_stmt", "if_feature_arg", "if_feature_stmt", "if_feature_end", "identity_arg_str", "identity_stmt", "identity_end", "identity_opt_stmt", "base_arg", "base_stmt", "typedef_arg_str", "typedef_stmt", "type_opt_stmt", "type_stmt", "type_arg_str", "type_end", "type_body_stmts", "some_restrictions", "union_stmt", "union_spec", "fraction_digits_arg", "fraction_digits_stmt", "fraction_digits_arg_str", "length_stmt", "length_arg_str", "length_end", "message_opt_stmt", "pattern_sep", "pattern_stmt", "pattern_arg_str", "pattern_end", "pattern_opt_stmt", "modifier_arg", "modifier_stmt", "enum_specification", "enum_stmts", "enum_stmt", "enum_arg_str", "enum_end", "enum_opt_stmt", "value_arg", "value_stmt", "integer_value_arg_str", "range_stmt", "range_end", "path_arg", "path_stmt", "require_instance_arg", "require_instance_stmt", "require_instance_arg_str", "bits_specification", "bit_stmts", "bit_stmt", "bit_arg_str", "bit_end", "bit_opt_stmt", "position_value_arg", "position_stmt", "position_value_arg_str", "error_message_arg", "error_message_stmt", "error_app_tag_arg", "error_app_tag_stmt", "units_arg", "units_stmt", "default_arg", "default_stmt", "grouping_arg_str", "grouping_stmt", "grouping_end", "grouping_opt_stmt", "data_def_stmt", "container_arg_str", "container_stmt", "container_end", "container_opt_stmt", "leaf_stmt", "leaf_arg_str", "leaf_opt_stmt", "leaf_list_arg_str", "leaf_list_stmt", "leaf_list_opt_stmt", "list_arg_str", "list_stmt", "list_opt_stmt", "choice_arg_str", "choice_stmt", "choice_end", "choice_opt_stmt", "short_case_case_stmt", "short_case_stmt", "case_arg_str", "case_stmt", "case_end", "case_opt_stmt", "anyxml_arg_str", "anyxml_stmt", "anydata_arg_str", "anydata_stmt", "anyxml_end", "anyxml_opt_stmt", "uses_arg_str", "uses_stmt", "uses_end", "uses_opt_stmt", "refine_args_str", "refine_arg_str", "refine_stmt", "refine_end", "refine_body_opt_stmts", "uses_augment_arg_str", "uses_augment_arg", "uses_augment_stmt", "augment_arg_str", "augment_arg", "augment_stmt", "augment_opt_stmt", "action_arg_str", "action_stmt", "rpc_arg_str", "rpc_stmt", "rpc_end", "rpc_opt_stmt", "input_arg", "input_stmt", "input_output_opt_stmt", "output_arg", "output_stmt", "notification_arg_str", "notification_stmt", "notification_end", "notification_opt_stmt", "deviation_arg", "deviation_stmt", "deviation_opt_stmt", "deviation_arg_str", "deviate_body_stmt", "deviate_not_supported", "deviate_not_supported_stmt", "deviate_not_supported_end", "deviate_stmts", "deviate_add", "deviate_add_stmt", "deviate_add_end", "deviate_add_opt_stmt", "deviate_delete", "deviate_delete_stmt", "deviate_delete_end", "deviate_delete_opt_stmt", "deviate_replace", "deviate_replace_stmt", "deviate_replace_end", "deviate_replace_opt_stmt", "when_arg_str", "when_stmt", "when_end", "when_opt_stmt", "config_arg", "config_stmt", "config_arg_str", "mandatory_arg", "mandatory_stmt", "mandatory_arg_str", "presence_arg", "presence_stmt", "min_value_arg", "min_elements_stmt", "min_value_arg_str", "max_value_arg", "max_elements_stmt", "max_value_arg_str", "ordered_by_arg", "ordered_by_stmt", "ordered_by_arg_str", "must_agr_str", "must_stmt", "must_end", "unique_arg", "unique_stmt", "unique_arg_str", "key_arg", "key_stmt", "key_arg_str", "$@3", "range_arg_str", "absolute_schema_nodeid", "absolute_schema_nodeids", "absolute_schema_nodeid_opt", "descendant_schema_nodeid", "$@4", "path_arg_str", "$@5", "$@6", "absolute_path", "absolute_paths", "absolute_path_opt", "relative_path", "relative_path_part1", "relative_path_part1_opt", "descendant_path", "descendant_path_opt", "path_predicate", "path_equality_expr", "path_key_expr", "rel_path_keyexpr", "rel_path_keyexpr_part1", "rel_path_keyexpr_part1_opt", "rel_path_keyexpr_part2", "current_function_invocation", "positive_integer_value", "non_negative_integer_value", "integer_value", "integer_value_convert", "prefix_arg_str", "identifier_arg_str", "node_identifier", "identifier_ref_arg_str", "stmtend", "semicolom", "curly_bracket_close", "curly_bracket_open", "stmtsep", "unknown_statement", "string_opt", "string_opt_part1", "string_opt_part2", "unknown_string", "unknown_string_part1", "unknown_string_part2", "unknown_statement_end", "unknown_statement2_opt", "unknown_statement2", "unknown_statement2_end", "unknown_statement2_yang_stmt", "unknown_statement2_module_stmt", "unknown_statement3_opt", "unknown_statement3_opt_end", "sep_stmt", "optsep", "sep", "whitespace_opt", "string", "$@7", "strings", "identifier", "identifier1", "yang_stmt", "identifiers", "identifiers_ref", "type_ext_alloc", "typedef_ext_alloc", "iffeature_ext_alloc", "restriction_ext_alloc", "when_ext_alloc", "revision_ext_alloc", "datadef_ext_check", "not_supported_ext_check", "not_supported_ext", "datadef_ext_stmt", "restriction_ext_stmt", "ext_substatements", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 43, 123, 125, 59, 47, 91, 93, 61, 40, 41 }; # endif #define YYPACT_NINF -1012 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-1012))) #define YYTABLE_NINF -757 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 440, 100, -1012, -1012, 566, 1894, -1012, -1012, -1012, 266, 266, -1012, 266, -1012, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -8, 31, 79, 868, 70, 125, 481, 266, -1012, -1012, 3273, 3273, 3273, 2893, 3273, 71, 2703, 2703, 2703, 2703, 2703, 98, 2988, 94, 52, 287, 2703, 77, 2703, 104, 287, 3273, 2703, 2703, 182, 58, 246, 2988, 2703, 321, 2703, 279, 279, 266, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 29, -1012, 134, -1012, -1012, -1012, -22, 2798, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 151, -1012, -1012, -1012, -1012, -1012, 156, -1012, 67, -1012, -1012, -1012, 224, -1012, -1012, -1012, 161, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, 224, -1012, 224, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, 224, -1012, -1012, 224, -1012, 262, 202, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 2893, 279, 3273, 279, 2703, 279, 2703, 2703, 2703, -1012, 2703, 279, 2703, 279, 58, 279, 3273, 3273, 3273, 3273, 3273, 266, 3273, 3273, 3273, 3273, 266, 2893, 3273, 3273, -1012, -1012, 279, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, 266, 266, -1012, 266, -1012, 266, -1012, 266, -1012, 266, 266, -1012, -1012, -1012, 3368, -1012, -1012, 291, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, 266, 266, -1012, -1012, -1012, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, 266, -1012, 228, 2703, 266, 274, -1012, 189, -1012, 288, -1012, 298, -1012, 303, -1012, 370, -1012, 380, -1012, 389, -1012, 393, -1012, 407, -1012, 411, -1012, 419, -1012, 426, -1012, 463, -1012, 238, -1012, 314, -1012, 317, -1012, 505, -1012, 506, -1012, 521, -1012, 407, -1012, 279, 279, 266, 266, 266, 266, 326, 279, 279, 109, 279, 112, 608, 266, 266, -1012, 262, -1012, 3083, 266, 332, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 1964, 1994, 2191, 347, -1012, -1012, 19, -1012, 54, 266, 355, -1012, -1012, 368, 373, -1012, -1012, -1012, 48, 3368, -1012, 266, 831, 279, 186, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 127, 515, 266, -1012, -1012, -1012, 515, -1012, -1012, 188, -1012, 279, -1012, 473, -1012, 306, -1012, 2552, 266, 266, 397, 1000, -1012, -1012, -1012, -1012, 783, -1012, 230, 503, 404, 887, 359, 438, 929, 1958, 1645, 817, 947, 344, 2074, 1547, 1768, 235, 852, 279, 279, 279, 279, 266, -22, 280, -1012, 266, 266, -1012, -1012, 375, 2703, 375, 279, -1012, -1012, -1012, 224, -1012, -1012, 3368, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 3273, 2703, -1012, -1012, -1012, -8, -1012, -1012, -1012, -1012, -1012, -1012, 279, 474, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 3273, 3273, 279, 279, -1012, -1012, -1012, -1012, -1012, 125, 224, -1012, -1012, 266, 266, -1012, 399, 473, 266, 528, 528, 545, -1012, 567, -1012, 279, -1012, 279, 279, 279, 480, -1012, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 2988, 2988, 279, 279, 279, 279, 279, 279, 279, 279, 279, 266, 266, 423, -1012, 570, -1012, 428, 2046, -1012, -1012, 434, -1012, 465, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 479, -1012, -1012, -1012, 571, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, -1012, 473, 266, 279, 279, 279, 279, -1012, 266, -1012, -1012, -1012, 266, 279, 279, 266, 51, 3273, 51, 3273, 3273, 3273, 279, 266, 459, 2367, 385, 509, 279, 279, 341, 365, -1012, -1012, 483, -1012, -1012, 574, -1012, -1012, 486, -1012, -1012, 591, -1012, 592, -1012, 521, -1012, 473, -1012, 473, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 885, 1126, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 332, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 467, 492, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279, 279, 279, 473, 473, 279, 279, 279, 279, 279, 279, 279, 279, 1460, 205, 524, 216, 201, 493, 579, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 293, 279, 279, 497, 3178, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 73, 120, 133, 163, -1012, 50, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 510, 222, 279, 279, 279, 473, -1012, 824, 346, 985, 3368, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 790, 0, 2, 3, 0, 757, 1, 649, 650, 0, 0, 652, 0, 763, 0, 0, 761, 0, 0, 0, 0, 762, 0, 0, 766, 764, 765, 767, 0, 768, 769, 770, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 759, 760, 0, 771, 802, 806, 619, 792, 803, 797, 793, 794, 619, 809, 796, 815, 814, 819, 804, 813, 818, 799, 800, 795, 798, 810, 811, 805, 816, 817, 812, 820, 801, 0, 0, 0, 0, 0, 0, 0, 627, 758, 651, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 791, 822, 0, 619, 0, 619, 0, 619, 0, 0, 0, 0, 789, 787, 788, 786, 619, 0, 619, 0, 619, 0, 0, 0, 0, 0, 651, 0, 0, 0, 0, 651, 0, 0, 0, 778, 777, 780, 781, 782, 776, 775, 774, 773, 785, 772, 0, 779, 0, 784, 783, 619, 0, 629, 653, 679, 5, 669, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 666, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 670, 744, 671, 672, 673, 674, 745, 675, 676, 677, 678, 746, 747, 748, 651, 608, 0, 10, 749, 667, 668, 651, 0, 17, 0, 99, 750, 613, 0, 138, 651, 651, 0, 47, 651, 651, 529, 0, 525, 659, 662, 660, 664, 665, 663, 658, 0, 58, 656, 661, 0, 243, 0, 60, 0, 239, 0, 237, 598, 170, 0, 167, 651, 610, 563, 0, 559, 561, 609, 651, 651, 534, 0, 530, 651, 545, 0, 541, 651, 599, 540, 0, 537, 600, 651, 0, 25, 651, 651, 550, 0, 546, 0, 56, 575, 0, 213, 0, 0, 236, 0, 233, 651, 605, 0, 49, 651, 0, 535, 0, 62, 651, 651, 219, 0, 215, 74, 76, 0, 45, 651, 651, 651, 114, 0, 109, 558, 0, 555, 651, 569, 0, 241, 603, 604, 601, 209, 0, 206, 651, 602, 0, 191, 621, 620, 651, 0, 807, 0, 808, 0, 821, 0, 0, 0, 180, 0, 823, 0, 824, 0, 825, 0, 0, 0, 0, 0, 445, 0, 0, 0, 0, 452, 0, 0, 0, 619, 619, 826, 651, 651, 827, 651, 628, 651, 7, 619, 607, 619, 619, 101, 100, 618, 616, 139, 619, 619, 611, 612, 619, 528, 527, 526, 59, 651, 244, 61, 240, 238, 168, 169, 560, 651, 533, 532, 531, 543, 542, 544, 538, 539, 26, 549, 548, 547, 57, 214, 0, 578, 572, 0, 574, 582, 234, 235, 50, 606, 536, 63, 218, 217, 216, 651, 46, 111, 113, 112, 110, 556, 557, 567, 242, 207, 208, 192, 0, 625, 624, 0, 150, 0, 140, 0, 124, 0, 172, 0, 551, 0, 182, 0, 564, 0, 518, 0, 65, 0, 368, 0, 357, 0, 334, 0, 266, 0, 245, 0, 285, 0, 298, 0, 314, 0, 454, 0, 383, 0, 430, 0, 370, 447, 447, 645, 647, 632, 630, 6, 13, 20, 104, 614, 0, 0, 657, 562, 587, 577, 581, 0, 75, 570, 651, 634, 622, 623, 626, 619, 151, 149, 619, 619, 126, 125, 619, 173, 171, 619, 553, 552, 619, 183, 181, 619, 211, 210, 619, 520, 519, 619, 69, 68, 619, 372, 369, 619, 359, 358, 619, 336, 335, 619, 268, 267, 619, 247, 246, 619, 619, 619, 619, 456, 455, 619, 385, 384, 619, 434, 431, 371, 0, 0, 0, 631, 651, 27, 12, 27, 19, 0, 0, 617, 619, 0, 576, 579, 583, 580, 585, 0, 568, 636, 156, 142, 0, 175, 175, 185, 175, 522, 71, 374, 361, 338, 270, 249, 286, 300, 316, 458, 387, 436, 446, 619, 619, 619, 258, 259, 260, 261, 262, 263, 264, 265, 619, 453, 651, 627, 651, 0, 51, 0, 14, 15, 16, 51, 21, 619, 0, 102, 615, 48, 654, 584, 0, 565, 0, 0, 0, 0, 153, 154, 619, 155, 221, 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 449, 450, 451, 448, 648, 0, 0, 8, 0, 0, 619, 619, 66, 0, 66, 22, 651, 651, 108, 0, 103, 655, 0, 586, 644, 635, 638, 651, 627, 627, 643, 0, 0, 152, 159, 619, 0, 162, 619, 619, 619, 158, 157, 194, 220, 141, 147, 148, 146, 619, 144, 145, 174, 178, 179, 176, 177, 554, 184, 189, 190, 186, 187, 188, 212, 521, 523, 524, 70, 72, 73, 373, 381, 382, 380, 619, 619, 378, 379, 619, 360, 365, 366, 364, 619, 619, 619, 337, 345, 346, 344, 619, 341, 350, 351, 352, 353, 356, 619, 348, 349, 354, 355, 619, 342, 343, 269, 277, 278, 276, 619, 619, 619, 619, 619, 619, 619, 275, 274, 619, 248, 251, 252, 250, 619, 619, 619, 619, 619, 284, 296, 297, 295, 619, 619, 290, 292, 619, 293, 294, 619, 299, 312, 313, 311, 619, 619, 305, 304, 619, 307, 308, 309, 310, 619, 315, 327, 328, 326, 619, 619, 619, 619, 619, 619, 619, 322, 323, 324, 325, 619, 321, 320, 457, 462, 463, 461, 619, 619, 619, 619, 619, 0, 0, 386, 391, 392, 390, 619, 619, 619, 619, 435, 439, 440, 438, 619, 619, 619, 619, 619, 646, 651, 651, 0, 0, 28, 29, 52, 53, 54, 55, 78, 64, 0, 23, 78, 107, 106, 105, 0, 654, 637, 0, 0, 0, 224, 0, 197, 164, 165, 160, 161, 163, 193, 222, 143, 376, 375, 377, 363, 367, 362, 340, 347, 339, 272, 282, 279, 283, 280, 281, 271, 273, 254, 253, 255, 256, 257, 288, 289, 287, 291, 302, 303, 301, 306, 318, 329, 330, 333, 331, 332, 317, 319, 460, 464, 465, 466, 459, 0, 0, 389, 393, 394, 388, 437, 441, 442, 443, 444, 633, 9, 0, 31, 0, 37, 0, 77, 619, 24, 0, 588, 0, 651, 641, 639, 640, 619, 225, 619, 619, 198, 196, 619, 413, 414, 0, 651, 396, 397, 0, 651, 619, 619, 39, 38, 651, 0, 0, 0, 0, 0, 0, 619, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 67, 651, 654, 645, 227, 223, 200, 195, 619, 412, 619, 399, 398, 395, 32, 41, 11, 0, 0, 0, 0, 0, 0, 79, 18, 0, 0, 0, 0, 420, 401, 0, 0, 417, 418, 0, 567, 651, 0, 90, 474, 0, 467, 651, 0, 115, 0, 128, 0, 432, 654, 589, 654, 642, 226, 231, 232, 230, 619, 229, 199, 204, 205, 203, 619, 202, 0, 0, 30, 36, 33, 34, 35, 40, 44, 42, 43, 619, 566, 416, 619, 92, 91, 619, 473, 619, 117, 116, 619, 130, 129, 433, 0, 0, 228, 201, 415, 424, 425, 423, 619, 619, 619, 619, 619, 619, 400, 410, 411, 619, 405, 406, 407, 404, 408, 409, 619, 420, 94, 469, 119, 132, 654, 654, 422, 426, 429, 427, 428, 421, 403, 402, 0, 0, 0, 0, 0, 0, 0, 419, 93, 97, 98, 619, 96, 0, 468, 470, 471, 118, 122, 123, 121, 619, 131, 136, 137, 135, 619, 133, 597, 654, 590, 593, 95, 0, 120, 134, 0, 0, 484, 497, 477, 506, 619, 651, 475, 476, 651, 481, 651, 483, 651, 482, 654, 594, 595, 472, 0, 0, 0, 0, 592, 591, 619, 479, 478, 619, 486, 485, 619, 499, 498, 619, 508, 507, 0, 0, 488, 501, 510, 654, 480, 0, 0, 0, 0, 487, 489, 492, 493, 494, 495, 496, 619, 491, 500, 502, 505, 619, 504, 509, 619, 512, 513, 514, 515, 516, 517, 596, 490, 503, 511 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -1012, -1012, -1012, 245, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -16, -1012, -2, -9, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1011, -1012, 22, -1012, -534, -24, -1012, 658, -1012, 681, -1012, 63, -1012, 105, -41, -1012, -1012, -237, -1012, -1012, 305, -1012, -225, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -486, -1012, -1012, -1012, -1012, -1012, 41, -1012, -1012, -1012, -1012, -1012, -1012, -11, -1012, -1012, -1012, -1012, -1012, -1012, -657, -1012, -3, -1012, -653, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 23, -1012, 30, -1012, -1012, 53, -1012, 35, -1012, -1012, -1012, -1012, 10, -1012, -1012, -236, -1012, -1012, -1012, -1012, -366, -1012, 38, -1012, -1012, 40, -1012, 43, -1012, -1012, -1012, -21, -1012, -1012, -1012, -1012, -355, -1012, -1012, 12, -1012, 18, -1012, -704, -1012, -480, -1012, 16, -1012, -1012, -560, -1012, -80, -1012, -1012, -67, -1012, -1012, -1012, -63, -1012, -1012, -39, -1012, -1012, -36, -1012, -1012, -1012, -1012, -1012, -33, -1012, -1012, -1012, -28, -1012, -27, 206, -1012, -1012, 667, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -435, -1012, -62, -1012, -1012, -365, -1012, -1012, 42, 211, -1012, 44, -1012, -87, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 74, -1012, -1012, -1012, -473, -1012, -1012, -667, -1012, -1012, -675, -1012, -722, -1012, -1012, -662, -1012, -1012, -271, -1012, -1012, -35, -1012, -1012, -725, -1012, -1012, 46, -1012, -1012, -1012, -390, -319, -335, -461, -1012, -1012, -1012, -1012, 214, 97, -1012, -1012, 239, -1012, -1012, -1012, 135, -1012, -1012, -1012, -441, -1012, -1012, -1012, 155, 693, -1012, -1012, -1012, 185, -93, -328, 1164, -1012, -1012, -1012, 526, 110, -1012, -1012, -1012, -433, -1012, -1012, -1012, -1012, -1012, -143, -1012, -1012, -260, 84, -4, 1453, 166, -694, 119, -1012, 660, -12, -1012, 137, -20, -23, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 1, 261, 262, 553, 933, 263, 2, 631, 632, 269, 3, 633, 634, 944, 688, 332, 54, 686, 740, 1023, 1106, 1025, 741, 1056, 1107, 365, 55, 279, 56, 351, 57, 742, 339, 938, 293, 939, 299, 783, 356, 784, 942, 521, 943, 144, 597, 718, 366, 489, 1027, 1028, 1064, 1113, 1065, 1157, 1208, 271, 62, 438, 749, 636, 750, 371, 1174, 372, 1119, 1066, 1162, 1210, 509, 1175, 579, 1121, 1067, 1165, 1211, 275, 64, 507, 669, 711, 127, 505, 575, 705, 706, 765, 766, 307, 65, 308, 136, 511, 582, 713, 401, 137, 515, 588, 715, 388, 66, 707, 964, 708, 957, 1043, 1103, 384, 67, 385, 138, 591, 342, 68, 361, 69, 362, 709, 774, 710, 955, 1040, 1102, 347, 70, 348, 303, 785, 301, 786, 378, 73, 297, 74, 531, 670, 612, 723, 671, 529, 672, 609, 722, 673, 533, 724, 535, 674, 725, 537, 675, 726, 527, 676, 606, 721, 828, 829, 525, 1177, 603, 720, 523, 677, 545, 678, 600, 719, 541, 679, 621, 728, 1050, 1051, 919, 1087, 1142, 1046, 1047, 920, 1109, 1110, 1071, 1141, 543, 1178, 1123, 1072, 624, 729, 170, 171, 626, 172, 173, 539, 1179, 618, 727, 1116, 1074, 1209, 1117, 1249, 1250, 1251, 1271, 1252, 1253, 1254, 1274, 1288, 1255, 1256, 1277, 1289, 1257, 1258, 1280, 1290, 519, 1180, 594, 717, 284, 75, 285, 319, 76, 320, 354, 77, 328, 78, 329, 323, 79, 324, 337, 80, 338, 513, 680, 585, 374, 81, 375, 312, 82, 313, 459, 517, 646, 1112, 567, 376, 497, 343, 344, 345, 475, 476, 563, 478, 479, 565, 643, 699, 640, 950, 1126, 1237, 1238, 1244, 1268, 1127, 330, 331, 386, 387, 352, 264, 377, 276, 441, 442, 638, 443, 124, 390, 502, 503, 571, 176, 430, 629, 570, 702, 757, 1036, 758, 759, 628, 428, 391, 4, 177, 752, 294, 451, 295, 265, 266, 267, 268, 392, 83, 84, 85, 86, 87, 88, 89, 90, 91, 175, 140, 5 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 11, 901, 174, 881, 897, 92, 92, 780, 92, 160, 92, 92, 314, 92, 92, 92, 92, 71, 92, 92, 865, 877, 161, 72, 92, 639, 162, 169, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 63, 848, 92, 764, 163, 139, 808, 164, 835, 751, 165, 869, 779, 180, 180, 166, 167, 882, 898, 506, 180, 126, 60, 305, 363, 864, 876, 278, 131, 36, 277, 15, 7, 180, 8, 129, 426, 41, 427, 180, 92, 296, 296, 296, 296, 296, 542, 315, 353, 1144, 1149, 296, 690, 296, 6, 687, 180, 296, 296, 159, 180, 128, 315, 296, 61, 296, 180, 960, 7, 305, 8, 7, -573, 8, 273, 130, 92, 273, 92, 7, 92, 8, 92, 92, 92, 92, 7, 423, 8, 737, 687, 92, 7, 92, 8, 92, 92, 92, 92, 92, 321, 92, 92, 92, 92, 141, 92, 92, 92, -587, -587, -654, 645, 281, 815, 142, 843, 856, 282, 296, 892, 910, 7, 334, 8, 436, 335, 437, 11, 93, 94, 1269, 95, 1270, 96, 97, 316, 98, 99, 100, 101, 317, 102, 103, 180, 7, 635, 8, 104, 143, 180, 273, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 477, 637, 123, 298, 300, 302, 304, 14, 1272, 12, 1273, 7, 333, 8, 340, 781, 20, 273, 355, 357, 20, 1275, 424, 1276, 379, 822, 389, 130, 866, 878, 807, 20, 834, 847, 735, 868, 880, 896, 180, 433, 912, 1033, 130, 309, 435, 20, 325, 22, 23, 446, 20, 1278, 43, 1279, 358, 7, 43, 8, 46, 359, 746, 130, 46, 270, 272, 747, 280, 43, 7, 7, 8, 8, 932, 46, 273, 712, 393, 576, 395, 180, 397, 43, 399, 400, 402, 403, 43, 913, 305, 326, 1229, 405, 46, 407, 1215, 409, 410, 411, 412, 413, 141, 415, 416, 417, 418, 1224, 420, 421, 422, 953, 954, 1287, 439, 180, 440, 367, 568, 368, 569, 782, 369, 380, 381, 382, 914, 274, 613, 283, 292, 292, 292, 292, 292, 306, 311, 318, 322, 327, 292, 336, 292, 341, 346, 350, 292, 292, 360, 364, 370, 373, 292, 383, 292, 474, 278, 17, 20, 277, 19, 20, 19, 1245, 573, 1246, 574, 562, 1247, 1100, 1248, 296, 130, 296, 296, 296, 20, 296, 577, 296, 578, 33, 20, 278, 564, 133, 277, 133, 580, 18, 581, 41, 20, 583, 43, 584, 11, 43, 45, 474, 698, 11, 20, 46, 614, 126, 1189, 615, 48, 47, 48, 141, 43, 130, 11, 630, 11, 1167, 43, 1168, 38, 20, 45, 22, 23, 645, 11, 11, 43, 11, 11, -651, 1143, -651, 40, 859, 684, 1301, 43, 11, 883, 899, 11, 11, 46, 11, 695, 11, 315, 11, 795, 11, 11, 1188, 1070, 20, 1148, 43, 644, 697, 586, 1187, 587, 11, 751, 11, 1190, 698, 11, 11, 589, 145, 590, 11, 11, 11, 1129, 296, 11, 592, -651, 593, 11, 595, 703, 596, 11, 52, 763, 1212, 1213, 43, 146, 147, 1032, 788, 148, 598, 704, 599, -651, 601, 510, 602, 512, 514, 516, 149, 518, 604, 520, 605, 150, 1053, 151, 152, 607, 153, 608, 1057, 20, 683, 22, 23, 154, 1076, 20, 155, 1243, 798, 1125, 11, 11, 11, 11, 1048, 1052, 130, 701, 315, 1234, 20, 11, 11, 738, 739, 156, 1220, 11, 1300, 1305, 1267, 1297, 610, 1312, 611, 43, 7, 1145, 8, 1281, 1077, 43, 157, 1197, 158, 508, 1176, 46, 1083, 1293, 1302, 1308, 1152, 125, 49, 1158, 43, 1291, 1236, 524, 526, 528, 530, 532, 1198, 534, 536, 538, 540, 1259, 1235, 544, 546, 787, 616, 619, 617, 620, 7, 1135, 8, 315, 1286, 692, 273, 9, 1296, 572, 1311, 691, 622, 1298, 623, 1313, 1221, 689, 92, 1034, 315, 1035, 845, 858, 1307, 274, 894, 10, 823, 292, 11, 292, 292, 292, 1176, 292, 1038, 292, 1039, 364, 394, 824, 396, 693, 398, 825, 951, 844, 857, 1185, 58, 893, 274, 404, 744, 406, 1186, 408, 1041, 41, 1042, 1054, 1085, 1055, 1086, 1155, 92, 1156, 11, 826, 92, 809, 827, 59, 849, 830, 870, 884, 900, 911, 831, 832, 1160, 1163, 1161, 1164, 92, 92, 425, 1111, 946, 1111, 714, 1029, 716, 805, 814, 821, 840, 522, 863, 875, 889, 907, 918, 926, 841, 854, 1031, 1218, 890, 908, 791, 927, 792, 1044, 767, 11, 296, 11, 793, 92, 92, 768, 1140, 842, 855, 315, 769, 891, 909, 770, 928, 771, 1134, 292, 772, 296, 625, 778, 965, 92, 92, 168, 1207, 1166, 627, 804, 813, 820, 839, 853, 862, 874, 888, 906, 917, 925, 929, 902, 930, 776, 1118, 1153, 641, 789, 700, 796, 799, 802, 811, 818, 837, 851, 860, 872, 886, 904, 915, 923, 806, 816, 833, 846, 753, 867, 879, 895, 694, 921, 1260, 642, 940, 349, 940, 1294, 1303, 1309, 1037, 756, 19, 20, 1295, 777, 1310, 1101, 931, 790, 145, 797, 800, 803, 812, 819, 838, 852, 861, 873, 887, 905, 916, 924, 0, 7, 431, 8, 760, 0, 0, 273, 147, 17, 0, 148, 941, 20, 941, 43, 17, 0, 743, 19, 703, 46, 149, 126, 130, 0, 48, 945, 704, 151, 152, 0, 153, 0, 761, 762, 0, 133, 0, 154, 33, 34, 35, 0, 133, 0, 958, 42, 20, 43, 0, 0, 0, 775, 145, 46, 0, 149, 128, 130, 0, 156, 150, 141, 0, 0, 47, 48, 0, 934, 935, 0, 0, 92, 92, 146, 147, 155, 157, 148, 158, 20, 132, 20, 43, 22, 23, 836, 133, 0, 46, 0, 130, 128, 1292, 134, 0, 151, 152, 135, 153, 0, 0, 0, 748, 0, 1073, 154, 11, 11, 0, 956, 0, 11, 547, 548, 145, 43, 0, 43, 0, 17, 922, 46, 554, 20, 555, 556, 0, 156, 0, 141, 0, 557, 558, 0, 130, 559, 147, 0, 0, 148, 0, 20, 0, 33, 157, 0, 158, 133, 0, 0, 149, 292, 0, 1171, 0, 794, 0, 151, 152, 43, 153, 315, 315, 0, 0, 46, 0, 154, 0, 0, 292, 683, 0, 141, 0, 17, 0, 43, 19, 0, 11, 11, 0, 46, 0, 14, 128, 0, 1068, 156, 0, 0, 0, 0, 0, 0, 0, 801, 0, 33, 34, 35, 28, 0, 0, 0, 157, 1069, 158, 0, 0, 0, 132, 0, 0, 850, 0, 92, 92, 92, 92, 92, 92, 126, 39, 134, 48, 0, 0, 135, 0, 0, 44, 0, 0, 0, 0, 11, -166, 0, 0, 1010, 1011, 11, 0, 0, 0, 11, 0, 0, 11, 0, 315, 1306, 1133, 1139, 0, 0, 11, 0, 0, 0, 648, 0, 0, 649, 650, 0, 0, 651, 1191, 0, 652, 0, 0, 653, 0, 0, 654, 0, 0, 655, 1024, 1026, 656, 0, 0, 657, 0, 0, 658, 0, 0, 659, 1184, 0, 660, 0, 0, 661, 0, 0, 662, 663, 664, 665, 1132, 1138, 666, 0, 0, 667, 0, 11, 1261, 0, 17, 0, 11, 19, 20, 0, 0, 0, 0, 0, 0, 696, 1130, 1136, 0, 130, 1146, 1150, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 43, 0, 730, 731, 732, 1314, 1228, 1233, 0, 0, 0, 1172, 1182, 733, 1131, 1137, 0, 0, 1147, 1151, 0, 0, 0, 92, 0, 0, 745, 0, 0, 0, 0, 1092, 1093, 1094, 1095, 1096, 1097, 0, 1181, 315, 0, 773, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1173, 1183, 0, 1219, 0, 1227, 1232, 1299, 1304, 1045, 1049, 0, 0, 11, 11, 11, 11, 0, 0, 0, 936, 937, 0, 0, 1172, 1216, 1222, 1225, 1230, 0, 0, 0, 1114, 315, 1120, 1122, 1124, 0, 0, 0, 0, 0, 0, 0, 0, 959, 0, 0, 961, 962, 963, 0, 0, 0, 0, 0, 0, 0, 0, 966, 0, 0, 0, 0, 0, 0, 1173, 1217, 1223, 1226, 1231, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 967, 968, 0, 0, 969, 0, 1108, 0, 1115, 970, 971, 972, 0, 0, 0, 0, 973, 0, 0, 0, 0, 0, 0, 974, 0, 0, 0, 0, 975, 0, 0, 0, 0, 0, 0, 976, 977, 978, 979, 980, 981, 982, 0, 0, 983, 0, 0, 0, 0, 984, 985, 986, 987, 988, 0, 1240, 0, 0, 989, 990, 0, 0, 991, 0, 0, 992, 0, 0, 0, 0, 993, 994, 0, 0, 995, 0, 0, 0, 0, 996, 0, 0, 0, 0, 997, 998, 999, 1000, 1001, 1002, 1003, 0, 0, 0, 0, 1004, 0, 0, 0, 0, 0, 0, 1005, 1006, 1007, 1008, 1009, 0, 0, 0, 0, 0, 0, 1012, 1013, 1014, 1015, 449, 0, 0, 0, 1016, 1017, 1018, 1019, 1020, 450, 0, 0, 0, 452, 0, 453, 145, 454, 0, 455, 0, 0, 0, 456, 0, 0, 0, 0, 458, 0, 0, 0, 0, 0, 0, 462, 0, 146, 147, 464, 0, 148, 0, 20, 466, 0, 0, 0, 468, 0, 0, 0, 0, 471, 130, 472, 0, 0, 473, 151, 152, 0, 153, 480, 0, 0, 0, 482, 0, 154, 484, 0, 485, 0, 0, 0, 0, 488, 0, 43, 0, 490, 0, 0, 0, 46, 0, 494, 0, 0, 495, 156, 0, 141, 498, 0, 0, 178, 0, 0, 499, 0, 0, 145, 501, 0, 0, 1075, 157, 0, 158, 0, 0, 0, 0, 0, 1079, 1214, 1080, 1081, 0, 0, 1082, 0, 0, 147, 17, 0, 148, 0, 20, 1089, 1090, 0, 0, 0, 0, 0, 0, 149, 0, 130, 1098, 0, 0, 32, 151, 152, 0, 153, 0, 34, 35, 0, 133, 414, 154, 37, 0, 0, 419, 1104, 0, 1105, 0, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 128, 47, 0, 156, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 157, 0, 158, 0, 0, 0, 145, 0, 0, 885, 0, 0, 0, 0, 0, 0, 1169, 0, 0, 0, 0, 0, 1170, 0, 0, 0, 0, 146, 147, 17, 0, 148, 19, 20, 0, 1192, 0, 0, 1193, 0, 0, 1194, 0, 1195, 130, 0, 1196, 0, 0, 151, 152, 0, 153, 33, 0, 0, 0, 0, 1199, 1200, 1201, 1202, 1203, 1204, 0, 0, 0, 1205, 0, 43, 0, 432, 0, 0, 1206, 46, 0, 0, 434, 0, 0, 0, 0, 141, 0, 0, 0, 444, 445, 0, 0, 447, 448, 0, 0, 0, 0, 0, 0, 0, 158, 1239, 0, 0, 0, 0, 0, 817, 0, 0, 0, 1241, 0, 0, 0, 0, 1242, 0, 0, 457, 0, 0, 0, 0, 0, 0, 460, 461, 0, 145, 0, 463, 1262, 0, 0, 465, 0, 0, 0, 0, 0, 467, 0, 0, 469, 470, 0, 0, 0, 0, 0, 147, 1282, 0, 148, 1283, 20, 0, 1284, 481, 0, 1285, 0, 483, 0, 149, 0, 130, 486, 487, 0, 0, 151, 152, 0, 153, 0, 491, 492, 493, 133, 0, 1315, 0, 0, 0, 496, 1316, 0, 0, 1317, 0, 43, 0, 0, 0, 500, 0, 46, 0, 0, 128, 504, 0, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 0, 903, 0, 0, 0, 0, 0, 549, 550, 0, 551, 0, 552, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 560, 0, 0, 0, 0, 0, 0, 0, 561, 949, 12, 13, 14, 15, 16, 0, 0, 17, 18, 0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 29, -753, 30, 31, 0, 32, 0, 566, -754, 0, 33, 34, 35, 0, -754, 36, 0, 37, 38, 0, 39, -754, 40, 41, 42, -754, 43, 145, 44, -756, 45, 0, 46, 145, -751, -752, 47, 48, 0, 49, -755, 50, 51, 0, 0, 0, 0, 0, 0, 147, 0, 0, 148, 0, 20, 147, 52, 0, 148, 0, 0, 53, 0, 145, 0, 130, 0, 0, 0, 149, 151, 152, 0, 153, 0, 0, 151, 152, 0, 153, 0, 0, 0, 0, 133, 147, 647, 0, 148, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 149, 0, 0, 156, 0, 141, 128, 151, 152, 156, 153, 0, 0, 0, 0, 133, 145, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 158, 810, 0, 0, 0, 1058, 0, 668, 128, 0, 147, 156, 0, 148, 0, 0, 0, 0, 0, 1059, 1060, 685, 1061, 0, 149, 1062, 0, 0, 0, 0, 158, 151, 152, 0, 153, 0, 0, 681, 0, 17, 0, 154, 19, 20, 0, 0, 1030, 0, 0, 0, 0, 0, 0, 0, 130, 0, 1063, 0, 0, 0, 128, 0, 0, 156, 34, 35, 0, 133, 0, 0, 37, 0, 0, 734, 0, 736, 0, 0, 0, 43, 0, 0, 158, 0, 0, 46, 0, 126, 0, 0, 48, 0, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 871, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 947, 948, 181, 310, 0, 0, 0, 0, 0, 0, 0, 952, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 1021, 1022, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 1128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1078, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1084, 0, 0, 0, 1088, 0, 0, 0, 0, 1091, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1099, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 0, 273, 0, 1154, 0, 0, 0, 0, 0, 1159, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 754, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 0, 248, 0, 0, 0, 0, 253, 0, 0, 0, 0, 258, 259, 260, 0, 0, 0, 0, 0, 0, 755, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1263, 0, 0, 1264, 179, 1265, 0, 1266, 180, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 429, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 273, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 477, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 1236, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 0, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260 }; static const yytype_int16 yycheck[] = { 4, 726, 89, 725, 726, 9, 10, 711, 12, 89, 14, 15, 105, 17, 18, 19, 20, 5, 22, 23, 724, 725, 89, 5, 28, 559, 89, 89, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 722, 52, 706, 89, 86, 719, 89, 721, 5, 89, 724, 711, 8, 8, 89, 89, 725, 726, 393, 8, 75, 5, 17, 12, 724, 725, 96, 85, 56, 96, 23, 5, 8, 7, 84, 104, 64, 106, 8, 90, 99, 100, 101, 102, 103, 420, 105, 114, 1106, 1107, 109, 632, 111, 0, 82, 8, 115, 116, 89, 8, 76, 120, 121, 5, 123, 8, 766, 5, 17, 7, 5, 14, 7, 11, 42, 126, 11, 128, 5, 130, 7, 132, 133, 134, 135, 5, 104, 7, 8, 82, 141, 5, 143, 7, 145, 146, 147, 148, 149, 94, 151, 152, 153, 154, 81, 156, 157, 158, 107, 108, 107, 107, 88, 720, 87, 722, 723, 93, 177, 726, 727, 5, 92, 7, 104, 95, 106, 178, 9, 10, 104, 12, 106, 14, 15, 88, 17, 18, 19, 20, 93, 22, 23, 8, 5, 83, 7, 28, 70, 8, 11, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 14, 105, 52, 100, 101, 102, 103, 22, 104, 20, 106, 5, 109, 7, 111, 711, 31, 11, 115, 116, 31, 104, 104, 106, 121, 721, 123, 42, 724, 725, 719, 31, 721, 722, 683, 724, 725, 726, 8, 104, 21, 951, 42, 104, 104, 31, 107, 33, 34, 104, 31, 104, 67, 106, 88, 5, 67, 7, 73, 93, 88, 42, 73, 94, 95, 93, 97, 67, 5, 5, 7, 7, 8, 73, 11, 105, 126, 104, 128, 8, 130, 67, 132, 133, 134, 135, 67, 68, 17, 18, 105, 141, 73, 143, 105, 145, 146, 147, 148, 149, 81, 151, 152, 153, 154, 105, 156, 157, 158, 758, 759, 105, 104, 8, 106, 85, 104, 87, 106, 105, 90, 16, 17, 18, 105, 96, 104, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 107, 393, 27, 31, 393, 30, 31, 30, 84, 104, 86, 106, 474, 89, 1077, 91, 397, 42, 399, 400, 401, 31, 403, 104, 405, 106, 51, 31, 420, 107, 55, 420, 55, 104, 28, 106, 64, 31, 104, 67, 106, 414, 67, 71, 107, 108, 419, 31, 73, 104, 75, 1142, 104, 78, 77, 78, 81, 67, 42, 432, 103, 434, 1125, 67, 1127, 59, 31, 71, 33, 34, 107, 444, 445, 67, 447, 448, 5, 105, 7, 63, 105, 103, 105, 67, 457, 725, 726, 460, 461, 73, 463, 105, 465, 474, 467, 105, 469, 470, 1142, 1028, 31, 105, 67, 565, 105, 104, 1142, 106, 481, 5, 483, 1142, 108, 486, 487, 104, 4, 106, 491, 492, 493, 105, 503, 496, 104, 54, 106, 500, 104, 24, 106, 504, 97, 105, 1197, 1198, 67, 25, 26, 109, 105, 29, 104, 32, 106, 74, 104, 397, 106, 399, 400, 401, 40, 403, 104, 405, 106, 45, 104, 47, 48, 104, 50, 106, 105, 31, 628, 33, 34, 57, 105, 31, 60, 1236, 105, 85, 549, 550, 551, 552, 1010, 1011, 42, 645, 565, 1211, 31, 560, 561, 43, 44, 79, 37, 566, 1288, 1289, 1259, 1288, 104, 1290, 106, 67, 5, 1106, 7, 1268, 110, 67, 96, 111, 98, 395, 1141, 73, 104, 1288, 1289, 1290, 104, 62, 80, 104, 67, 1286, 14, 409, 410, 411, 412, 413, 107, 415, 416, 417, 418, 107, 112, 421, 422, 105, 104, 104, 106, 106, 5, 105, 7, 628, 107, 634, 11, 54, 1288, 503, 1290, 633, 104, 1288, 106, 1290, 105, 632, 635, 104, 645, 106, 722, 723, 1290, 393, 726, 74, 721, 397, 647, 399, 400, 401, 1207, 403, 104, 405, 106, 407, 127, 721, 129, 634, 131, 721, 752, 722, 723, 1142, 5, 726, 420, 140, 691, 142, 1142, 144, 104, 64, 106, 104, 104, 106, 106, 104, 683, 106, 685, 721, 687, 719, 721, 5, 722, 721, 724, 725, 726, 727, 721, 721, 104, 104, 106, 106, 703, 704, 175, 1092, 744, 1094, 652, 943, 654, 719, 720, 721, 722, 407, 724, 725, 726, 727, 728, 729, 722, 723, 946, 1208, 726, 727, 715, 729, 715, 964, 706, 734, 743, 736, 715, 738, 739, 706, 1103, 722, 723, 752, 706, 726, 727, 706, 729, 706, 1102, 503, 706, 762, 545, 711, 774, 758, 759, 89, 1192, 1123, 548, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 729, 726, 729, 711, 1094, 1111, 563, 715, 644, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 719, 720, 721, 722, 700, 724, 725, 726, 635, 728, 1244, 565, 742, 113, 744, 1288, 1289, 1290, 954, 702, 30, 31, 1288, 711, 1290, 1078, 735, 715, 4, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, -1, 5, 177, 7, 702, -1, -1, 11, 26, 27, -1, 29, 742, 31, 744, 67, 27, -1, 687, 30, 24, 73, 40, 75, 42, -1, 78, 743, 32, 47, 48, -1, 50, -1, 703, 704, -1, 55, -1, 57, 51, 52, 53, -1, 55, -1, 762, 65, 31, 67, -1, -1, -1, 105, 4, 73, -1, 40, 76, 42, -1, 79, 45, 81, -1, -1, 77, 78, -1, 738, 739, -1, -1, 912, 913, 25, 26, 60, 96, 29, 98, 31, 49, 31, 67, 33, 34, 105, 55, -1, 73, -1, 42, 76, 105, 62, -1, 47, 48, 66, 50, -1, -1, -1, 694, -1, 1028, 57, 947, 948, -1, 761, -1, 952, 423, 424, 4, 67, -1, 67, -1, 27, 105, 73, 433, 31, 435, 436, -1, 79, -1, 81, -1, 442, 443, -1, 42, 446, 26, -1, -1, 29, -1, 31, -1, 51, 96, -1, 98, 55, -1, -1, 40, 743, -1, 105, -1, 105, -1, 47, 48, 67, 50, 1010, 1011, -1, -1, 73, -1, 57, -1, -1, 762, 1101, -1, 81, -1, 27, -1, 67, 30, -1, 1021, 1022, -1, 73, -1, 22, 76, -1, 1028, 79, -1, -1, -1, -1, -1, -1, -1, 105, -1, 51, 52, 53, 39, -1, -1, -1, 96, 1028, 98, -1, -1, -1, 49, -1, -1, 105, -1, 1058, 1059, 1060, 1061, 1062, 1063, 75, 61, 62, 78, -1, -1, 66, -1, -1, 69, -1, -1, -1, -1, 1078, 75, -1, -1, 912, 913, 1084, -1, -1, -1, 1088, -1, -1, 1091, -1, 1101, 105, 1102, 1103, -1, -1, 1099, -1, -1, -1, 573, -1, -1, 576, 577, -1, -1, 580, 1142, -1, 583, -1, -1, 586, -1, -1, 589, -1, -1, 592, 934, 935, 595, -1, -1, 598, -1, -1, 601, -1, -1, 604, 1142, -1, 607, -1, -1, 610, -1, -1, 613, 614, 615, 616, 1102, 1103, 619, -1, -1, 622, -1, 1154, 1244, -1, 27, -1, 1159, 30, 31, -1, -1, -1, -1, -1, -1, 638, 1102, 1103, -1, 42, 1106, 1107, -1, -1, -1, -1, -1, -1, 51, 52, 53, -1, 55, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, -1, 67, -1, 669, 670, 671, 1291, 1210, 1211, -1, -1, -1, 1141, 1142, 680, 1102, 1103, -1, -1, 1106, 1107, -1, -1, -1, 1220, -1, -1, 693, -1, -1, -1, -1, 1058, 1059, 1060, 1061, 1062, 1063, -1, 105, 1244, -1, 708, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1141, 1142, -1, 1208, -1, 1210, 1211, 1288, 1289, 1010, 1011, -1, -1, 1263, 1264, 1265, 1266, -1, -1, -1, 740, 741, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, 1093, 1291, 1095, 1096, 1097, -1, -1, -1, -1, -1, -1, -1, -1, 765, -1, -1, 768, 769, 770, -1, -1, -1, -1, -1, -1, -1, -1, 779, -1, -1, -1, -1, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 805, 806, -1, -1, 809, -1, 1092, -1, 1094, 814, 815, 816, -1, -1, -1, -1, 821, -1, -1, -1, -1, -1, -1, 828, -1, -1, -1, -1, 833, -1, -1, -1, -1, -1, -1, 840, 841, 842, 843, 844, 845, 846, -1, -1, 849, -1, -1, -1, -1, 854, 855, 856, 857, 858, -1, 1220, -1, -1, 863, 864, -1, -1, 867, -1, -1, 870, -1, -1, -1, -1, 875, 876, -1, -1, 879, -1, -1, -1, -1, 884, -1, -1, -1, -1, 889, 890, 891, 892, 893, 894, 895, -1, -1, -1, -1, 900, -1, -1, -1, -1, -1, -1, 907, 908, 909, 910, 911, -1, -1, -1, -1, -1, -1, 918, 919, 920, 921, 284, -1, -1, -1, 926, 927, 928, 929, 930, 293, -1, -1, -1, 297, -1, 299, 4, 301, -1, 303, -1, -1, -1, 307, -1, -1, -1, -1, 312, -1, -1, -1, -1, -1, -1, 319, -1, 25, 26, 323, -1, 29, -1, 31, 328, -1, -1, -1, 332, -1, -1, -1, -1, 337, 42, 339, -1, -1, 342, 47, 48, -1, 50, 347, -1, -1, -1, 351, -1, 57, 354, -1, 356, -1, -1, -1, -1, 361, -1, 67, -1, 365, -1, -1, -1, 73, -1, 371, -1, -1, 374, 79, -1, 81, 378, -1, -1, 92, -1, -1, 384, -1, -1, 4, 388, -1, -1, 1029, 96, -1, 98, -1, -1, -1, -1, -1, 1038, 105, 1040, 1041, -1, -1, 1044, -1, -1, 26, 27, -1, 29, -1, 31, 1053, 1054, -1, -1, -1, -1, -1, -1, 40, -1, 42, 1064, -1, -1, 46, 47, 48, -1, 50, -1, 52, 53, -1, 55, 150, 57, 58, -1, -1, 155, 1083, -1, 1085, -1, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 76, 77, -1, 79, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, 98, -1, -1, -1, 4, -1, -1, 105, -1, -1, -1, -1, -1, -1, 1133, -1, -1, -1, -1, -1, 1139, -1, -1, -1, -1, 25, 26, 27, -1, 29, 30, 31, -1, 1152, -1, -1, 1155, -1, -1, 1158, -1, 1160, 42, -1, 1163, -1, -1, 47, 48, -1, 50, 51, -1, -1, -1, -1, 1175, 1176, 1177, 1178, 1179, 1180, -1, -1, -1, 1184, -1, 67, -1, 261, -1, -1, 1191, 73, -1, -1, 268, -1, -1, -1, -1, 81, -1, -1, -1, 277, 278, -1, -1, 281, 282, -1, -1, -1, -1, -1, -1, -1, 98, 1218, -1, -1, -1, -1, -1, 105, -1, -1, -1, 1228, -1, -1, -1, -1, 1233, -1, -1, 309, -1, -1, -1, -1, -1, -1, 316, 317, -1, 4, -1, 321, 1249, -1, -1, 325, -1, -1, -1, -1, -1, 331, -1, -1, 334, 335, -1, -1, -1, -1, -1, 26, 1269, -1, 29, 1272, 31, -1, 1275, 349, -1, 1278, -1, 353, -1, 40, -1, 42, 358, 359, -1, -1, 47, 48, -1, 50, -1, 367, 368, 369, 55, -1, 1299, -1, -1, -1, 376, 1304, -1, -1, 1307, -1, 67, -1, -1, -1, 386, -1, 73, -1, -1, 76, 392, -1, 79, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, 426, 427, -1, 429, -1, 431, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 451, -1, -1, -1, -1, -1, -1, -1, 459, 749, 20, 21, 22, 23, 24, -1, -1, 27, 28, -1, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, -1, 46, -1, 489, 49, -1, 51, 52, 53, -1, 55, 56, -1, 58, 59, -1, 61, 62, 63, 64, 65, 66, 67, 4, 69, 70, 71, -1, 73, 4, 75, 76, 77, 78, -1, 80, 81, 82, 83, -1, -1, -1, -1, -1, -1, 26, -1, -1, 29, -1, 31, 26, 97, -1, 29, -1, -1, 102, -1, 4, -1, 42, -1, -1, -1, 40, 47, 48, -1, 50, -1, -1, 47, 48, -1, 50, -1, -1, -1, -1, 55, 26, 568, -1, 29, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 40, -1, -1, 79, -1, 81, 76, 47, 48, 79, 50, -1, -1, -1, -1, 55, 4, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, 98, 105, -1, -1, -1, 21, -1, 105, 76, -1, 26, 79, -1, 29, -1, -1, -1, -1, -1, 35, 36, 630, 38, -1, 40, 41, -1, -1, -1, -1, 98, 47, 48, -1, 50, -1, -1, 105, -1, 27, -1, 57, 30, 31, -1, -1, 944, -1, -1, -1, -1, -1, -1, -1, 42, -1, 72, -1, -1, -1, 76, -1, -1, 79, 52, 53, -1, 55, -1, -1, 58, -1, -1, 682, -1, 684, -1, -1, -1, 67, -1, -1, 98, -1, -1, 73, -1, 75, -1, -1, 78, -1, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, 746, 747, 10, 11, -1, -1, -1, -1, -1, -1, -1, 757, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, 932, 933, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1034, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1048, -1, -1, -1, 1052, -1, -1, -1, -1, 1057, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1076, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, 11, -1, 1112, -1, -1, -1, -1, -1, 1118, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, -1, -1, -1, -1, 91, -1, -1, -1, -1, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1250, -1, -1, 1253, 4, 1255, -1, 1257, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 114, 120, 124, 419, 441, 0, 5, 7, 54, 74, 418, 20, 21, 22, 23, 24, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 43, 44, 46, 51, 52, 53, 56, 58, 59, 61, 63, 64, 65, 67, 69, 71, 73, 77, 78, 80, 82, 83, 97, 102, 130, 140, 142, 144, 147, 149, 151, 153, 170, 176, 190, 202, 214, 222, 227, 229, 238, 241, 243, 245, 247, 339, 342, 345, 347, 350, 353, 359, 362, 430, 431, 432, 433, 434, 435, 436, 437, 438, 418, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 402, 402, 75, 194, 76, 192, 42, 183, 49, 55, 62, 66, 204, 209, 224, 356, 440, 81, 335, 70, 157, 4, 25, 26, 29, 40, 45, 47, 48, 50, 57, 60, 79, 96, 98, 249, 254, 257, 261, 264, 267, 273, 277, 279, 283, 299, 304, 305, 307, 308, 310, 439, 407, 420, 419, 4, 8, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 115, 116, 119, 395, 425, 426, 427, 428, 123, 395, 169, 395, 11, 116, 189, 397, 428, 429, 141, 395, 88, 93, 116, 338, 340, 9, 11, 12, 16, 17, 18, 116, 148, 422, 424, 425, 246, 422, 150, 422, 242, 422, 240, 422, 17, 116, 201, 203, 390, 11, 116, 361, 363, 396, 425, 88, 93, 116, 341, 343, 94, 116, 349, 351, 390, 18, 116, 346, 348, 390, 391, 129, 422, 92, 95, 116, 352, 354, 146, 422, 116, 226, 371, 372, 373, 116, 237, 239, 391, 116, 143, 394, 428, 344, 422, 152, 422, 88, 93, 116, 228, 230, 12, 116, 139, 160, 85, 87, 90, 116, 175, 177, 116, 358, 360, 369, 396, 244, 422, 16, 17, 18, 116, 221, 223, 392, 393, 213, 422, 403, 418, 429, 420, 402, 420, 402, 420, 402, 420, 420, 208, 420, 420, 402, 420, 402, 420, 402, 420, 420, 420, 420, 420, 419, 420, 420, 420, 420, 419, 420, 420, 420, 104, 104, 402, 104, 106, 417, 8, 408, 424, 419, 104, 419, 104, 104, 106, 171, 104, 106, 398, 399, 401, 419, 419, 104, 419, 419, 398, 398, 423, 398, 398, 398, 398, 398, 419, 398, 364, 419, 419, 398, 419, 398, 419, 398, 419, 398, 419, 419, 398, 398, 398, 107, 374, 375, 14, 377, 378, 398, 419, 398, 419, 398, 398, 419, 419, 398, 161, 398, 419, 419, 419, 398, 398, 419, 370, 398, 398, 419, 398, 404, 405, 419, 195, 397, 191, 395, 182, 422, 205, 422, 355, 422, 210, 422, 365, 422, 334, 422, 155, 160, 276, 395, 272, 395, 266, 395, 253, 395, 248, 395, 258, 395, 260, 395, 263, 395, 309, 395, 282, 397, 298, 395, 278, 395, 402, 402, 419, 419, 419, 419, 117, 402, 402, 402, 402, 402, 402, 419, 419, 396, 376, 107, 379, 419, 368, 104, 106, 410, 406, 422, 104, 106, 196, 104, 104, 106, 184, 104, 106, 206, 104, 106, 357, 104, 106, 211, 104, 106, 225, 104, 106, 336, 104, 106, 158, 104, 106, 280, 104, 106, 274, 104, 106, 268, 104, 106, 255, 104, 106, 250, 104, 104, 104, 104, 106, 311, 104, 106, 284, 104, 106, 302, 280, 306, 306, 416, 409, 103, 121, 122, 125, 126, 83, 173, 105, 400, 144, 382, 374, 378, 380, 396, 107, 366, 419, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 105, 192, 249, 252, 254, 257, 261, 264, 267, 277, 279, 283, 356, 105, 105, 396, 103, 419, 131, 82, 128, 130, 144, 131, 128, 142, 420, 105, 402, 105, 108, 381, 382, 396, 411, 24, 32, 197, 198, 215, 217, 231, 233, 193, 105, 207, 207, 212, 207, 337, 159, 281, 275, 269, 256, 251, 259, 262, 265, 312, 285, 303, 402, 402, 402, 402, 419, 407, 419, 8, 43, 44, 132, 136, 145, 420, 145, 402, 88, 93, 116, 172, 174, 5, 421, 375, 54, 105, 403, 412, 414, 415, 427, 420, 420, 105, 190, 199, 200, 202, 204, 209, 224, 227, 229, 402, 232, 105, 151, 153, 176, 194, 245, 247, 105, 151, 153, 241, 243, 105, 105, 151, 153, 214, 241, 243, 105, 105, 151, 153, 105, 151, 153, 105, 151, 153, 176, 183, 335, 339, 342, 356, 105, 151, 153, 176, 183, 252, 335, 105, 151, 153, 176, 183, 247, 254, 257, 261, 264, 267, 270, 271, 273, 277, 279, 335, 339, 342, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 345, 356, 105, 151, 153, 176, 192, 249, 252, 299, 310, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 342, 356, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 347, 350, 353, 356, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 347, 350, 353, 356, 359, 362, 105, 151, 153, 176, 183, 192, 249, 252, 356, 21, 68, 105, 151, 153, 176, 183, 288, 293, 335, 105, 151, 153, 176, 183, 192, 249, 305, 308, 417, 8, 118, 420, 420, 402, 402, 147, 149, 151, 153, 154, 156, 127, 422, 154, 419, 419, 398, 383, 396, 419, 407, 407, 234, 395, 218, 422, 402, 194, 402, 402, 402, 216, 233, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 420, 420, 402, 402, 402, 402, 402, 402, 402, 402, 402, 419, 419, 133, 395, 135, 395, 162, 163, 157, 398, 162, 109, 421, 104, 106, 413, 413, 104, 106, 235, 104, 106, 219, 217, 116, 291, 292, 369, 116, 286, 287, 369, 104, 104, 106, 137, 105, 21, 35, 36, 38, 41, 72, 164, 166, 179, 186, 192, 249, 252, 296, 301, 310, 314, 402, 105, 110, 419, 402, 402, 402, 402, 104, 419, 104, 106, 289, 419, 402, 402, 419, 420, 420, 420, 420, 420, 420, 402, 419, 421, 416, 236, 220, 402, 402, 134, 138, 116, 294, 295, 366, 367, 165, 395, 116, 313, 316, 367, 178, 395, 185, 395, 300, 395, 85, 384, 389, 105, 105, 151, 153, 176, 183, 238, 105, 151, 153, 176, 183, 222, 297, 290, 105, 140, 144, 151, 153, 105, 140, 151, 153, 104, 368, 419, 104, 106, 167, 104, 419, 104, 106, 180, 104, 106, 187, 302, 421, 421, 402, 402, 105, 151, 153, 176, 183, 252, 273, 299, 310, 335, 105, 151, 153, 183, 247, 339, 342, 345, 347, 350, 356, 402, 402, 402, 402, 402, 111, 107, 402, 402, 402, 402, 402, 402, 402, 402, 297, 168, 315, 181, 188, 421, 421, 105, 105, 151, 153, 170, 176, 37, 105, 151, 153, 105, 151, 153, 176, 183, 105, 151, 153, 176, 183, 190, 112, 14, 385, 386, 402, 420, 402, 402, 421, 387, 84, 86, 89, 91, 317, 318, 319, 321, 322, 323, 326, 327, 330, 331, 107, 386, 396, 402, 419, 419, 419, 419, 421, 388, 104, 106, 320, 104, 106, 324, 104, 106, 328, 104, 106, 332, 421, 402, 402, 402, 402, 107, 105, 325, 329, 333, 421, 105, 245, 247, 339, 342, 347, 350, 356, 359, 105, 245, 247, 356, 359, 105, 194, 245, 247, 339, 342, 347, 350, 396, 402, 402, 402 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 113, 114, 114, 114, 115, 116, 117, 118, 117, 119, 120, 121, 122, 122, 122, 122, 123, 124, 125, 126, 126, 126, 127, 128, 129, 130, 131, 131, 131, 132, 133, 134, 134, 134, 134, 134, 135, 136, 137, 137, 138, 138, 138, 138, 139, 140, 141, 142, 143, 144, 145, 145, 145, 145, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 156, 157, 158, 158, 159, 159, 159, 161, 160, 160, 162, 163, 163, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 165, 166, 167, 167, 168, 168, 168, 168, 168, 169, 170, 171, 171, 172, 173, 173, 174, 174, 174, 175, 176, 177, 177, 177, 177, 178, 179, 180, 180, 181, 181, 181, 181, 181, 182, 183, 184, 184, 185, 186, 187, 187, 188, 188, 188, 188, 188, 188, 189, 190, 191, 192, 193, 193, 193, 193, 193, 193, 193, 194, 195, 196, 196, 197, 197, 197, 198, 198, 198, 198, 198, 198, 198, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, 206, 207, 207, 207, 207, 207, 208, 209, 210, 211, 211, 212, 212, 212, 212, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 219, 220, 220, 220, 220, 220, 220, 221, 222, 223, 223, 224, 225, 225, 226, 227, 228, 229, 230, 230, 230, 231, 232, 232, 233, 234, 235, 235, 236, 236, 236, 236, 236, 236, 237, 238, 239, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 253, 254, 255, 255, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 257, 258, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 260, 261, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 263, 264, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 266, 267, 268, 268, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 270, 270, 271, 271, 271, 271, 271, 271, 271, 272, 273, 274, 274, 275, 275, 275, 275, 275, 275, 275, 276, 277, 278, 279, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 283, 284, 284, 285, 285, 285, 285, 285, 285, 285, 285, 286, 286, 287, 288, 289, 289, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 291, 291, 292, 293, 294, 294, 295, 296, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 298, 299, 300, 301, 302, 302, 303, 303, 303, 303, 303, 303, 303, 303, 303, 304, 305, 306, 306, 306, 306, 306, 307, 308, 309, 310, 311, 311, 312, 312, 312, 312, 312, 312, 312, 312, 312, 313, 314, 315, 315, 315, 315, 316, 316, 317, 317, 318, 319, 320, 320, 321, 321, 321, 322, 323, 324, 324, 325, 325, 325, 325, 325, 325, 325, 325, 325, 326, 327, 328, 328, 329, 329, 329, 329, 329, 330, 331, 332, 332, 333, 333, 333, 333, 333, 333, 333, 333, 334, 335, 336, 336, 337, 337, 337, 338, 339, 340, 340, 340, 341, 342, 343, 343, 343, 344, 345, 346, 347, 348, 348, 349, 350, 351, 351, 351, 352, 353, 354, 354, 354, 355, 356, 357, 357, 358, 359, 360, 360, 361, 362, 364, 363, 363, 365, 366, 367, 368, 368, 370, 369, 372, 371, 373, 371, 371, 374, 375, 376, 376, 377, 378, 379, 379, 380, 381, 381, 382, 382, 383, 384, 385, 386, 387, 387, 388, 388, 389, 390, 391, 391, 392, 392, 393, 393, 394, 394, 395, 395, 396, 396, 397, 397, 397, 398, 398, 399, 400, 401, 402, 402, 402, 403, 404, 405, 406, 406, 407, 407, 408, 408, 408, 409, 409, 410, 410, 411, 411, 412, 412, 412, 413, 413, 414, 415, 416, 416, 417, 417, 418, 418, 419, 419, 420, 421, 421, 423, 422, 422, 424, 424, 424, 424, 424, 424, 424, 425, 425, 425, 426, 426, 426, 426, 426, 426, 426, 426, 426, 426, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 440, 440, 440, 440, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 1, 3, 0, 0, 6, 1, 13, 1, 0, 2, 2, 2, 1, 13, 1, 0, 2, 3, 1, 4, 1, 4, 0, 3, 3, 7, 1, 0, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 2, 1, 4, 1, 7, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 4, 1, 4, 1, 4, 1, 1, 0, 3, 4, 1, 4, 0, 2, 2, 0, 3, 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 4, 1, 0, 4, 2, 2, 1, 1, 4, 2, 2, 2, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 3, 1, 4, 1, 4, 0, 2, 3, 2, 2, 2, 1, 4, 1, 7, 0, 3, 2, 2, 2, 2, 2, 4, 1, 1, 4, 1, 1, 1, 0, 2, 2, 2, 3, 3, 2, 3, 3, 2, 0, 1, 4, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 2, 1, 4, 3, 0, 3, 4, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 4, 1, 4, 1, 4, 1, 4, 2, 2, 1, 2, 0, 2, 5, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 0, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 1, 0, 3, 3, 3, 2, 3, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 1, 4, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 2, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 7, 2, 1, 1, 7, 0, 3, 3, 2, 2, 2, 3, 3, 3, 3, 1, 4, 1, 4, 1, 4, 0, 3, 2, 2, 2, 3, 3, 3, 3, 2, 5, 0, 3, 3, 3, 3, 2, 5, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 3, 1, 7, 0, 2, 2, 5, 2, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 3, 1, 4, 0, 2, 3, 2, 2, 2, 2, 2, 2, 1, 3, 1, 4, 0, 2, 3, 2, 2, 1, 3, 1, 4, 0, 3, 2, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 2, 1, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 1, 4, 2, 1, 1, 4, 0, 3, 1, 1, 2, 2, 0, 2, 0, 3, 0, 2, 0, 2, 1, 3, 2, 0, 2, 3, 2, 0, 2, 2, 0, 2, 0, 5, 5, 5, 4, 4, 0, 2, 0, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 2, 4, 1, 1, 1, 0, 2, 2, 3, 2, 1, 0, 1, 0, 2, 0, 2, 3, 0, 5, 1, 4, 0, 3, 1, 3, 3, 1, 4, 1, 1, 0, 4, 2, 5, 1, 1, 0, 2, 2, 0, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 4, 4, 4, 4, 4 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, scanner, param, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (0) #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Print *YYLOCP on YYO. Private, do not rely on its existence. */ YY_ATTRIBUTE_UNUSED static int yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp) { int res = 0; int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0; if (0 <= yylocp->first_line) { res += YYFPRINTF (yyo, "%d", yylocp->first_line); if (0 <= yylocp->first_column) res += YYFPRINTF (yyo, ".%d", yylocp->first_column); } if (0 <= yylocp->last_line) { if (yylocp->first_line < yylocp->last_line) { res += YYFPRINTF (yyo, "-%d", yylocp->last_line); if (0 <= end_col) res += YYFPRINTF (yyo, ".%d", end_col); } else if (0 <= end_col && yylocp->first_column < end_col) res += YYFPRINTF (yyo, "-%d", end_col); } return res; } # define YY_LOCATION_PRINT(File, Loc) \ yy_location_print_ (File, &(Loc)) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, scanner, param); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { FILE *yyoutput = yyo; YYUSE (yyoutput); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyo, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { YYFPRINTF (yyo, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); YY_LOCATION_PRINT (yyo, *yylocationp); YYFPRINTF (yyo, ": "); yy_symbol_value_print (yyo, yytype, yyvaluep, yylocationp, scanner, param); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, void *scanner, struct yang_parameter *param) { unsigned long yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , scanner, param); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, yylsp, Rule, scanner, param); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return (YYSIZE_T) (yystpcpy (yyres, yystr) - yyres); } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, void *scanner, struct yang_parameter *param) { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 115: /* tmp_string */ { free((((*yyvaluep).p_str)) ? *((*yyvaluep).p_str) : NULL); } break; case 210: /* pattern_arg_str */ { free(((*yyvaluep).str)); } break; case 399: /* semicolom */ { free(((*yyvaluep).str)); } break; case 401: /* curly_bracket_open */ { free(((*yyvaluep).str)); } break; case 405: /* string_opt_part1 */ { free(((*yyvaluep).str)); } break; case 430: /* type_ext_alloc */ { yang_type_free(param->module->ctx, ((*yyvaluep).v)); } break; case 431: /* typedef_ext_alloc */ { yang_type_free(param->module->ctx, &((struct lys_tpdf *)((*yyvaluep).v))->type); } break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...) { free(*param->value); if (yylloc->first_line != -1) { if (*param->data_node && (*param->data_node) == (*param->actual_node)) { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner)); } else { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); } } }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1364_0
crossvul-cpp_data_good_2579_2
/* #pragma ident "@(#)g_context_time.c 1.12 98/01/22 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routines for gss_context_time */ #include "mglueP.h" OM_uint32 KRB5_CALLCONV gss_context_time (minor_status, context_handle, time_rec) OM_uint32 * minor_status; gss_ctx_id_t context_handle; OM_uint32 * time_rec; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (time_rec == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_context_time) { status = mech->gss_context_time( minor_status, ctx->internal_ctx_id, time_rec); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_2
crossvul-cpp_data_good_2579_8
/* #pragma ident "@(#)g_process_context.c 1.12 98/01/22 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine gss_process_context */ #include "mglueP.h" OM_uint32 KRB5_CALLCONV gss_process_context_token (minor_status, context_handle, token_buffer) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (GSS_EMPTY_BUFFER(token_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_process_context_token) { status = mech->gss_process_context_token( minor_status, ctx->internal_ctx_id, token_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_8
crossvul-cpp_data_good_349_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, serial->len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_0
crossvul-cpp_data_bad_348_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_0
crossvul-cpp_data_good_349_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL || sec_attr_len) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_7
crossvul-cpp_data_good_347_10
/* * util.c: utility functions used by OpenSC command line tools. * * Copyright (C) 2011 OpenSC Project developers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #ifndef _WIN32 #include <termios.h> #else #include <conio.h> #endif #include <ctype.h> #include "util.h" #include "ui/notify.h" int is_string_valid_atr(const char *atr_str) { unsigned char atr[SC_MAX_ATR_SIZE]; size_t atr_len = sizeof(atr); if (sc_hex_to_bin(atr_str, atr, &atr_len)) return 0; if (atr_len < 2) return 0; if (atr[0] != 0x3B && atr[0] != 0x3F) return 0; return 1; } int util_connect_card_ex(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int do_lock, int verbose) { struct sc_reader *reader = NULL, *found = NULL; struct sc_card *card = NULL; int r; sc_notify_init(); if (do_wait) { unsigned int event; if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "Waiting for a reader to be attached...\n"); r = sc_wait_for_event(ctx, SC_EVENT_READER_ATTACHED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a reader: %s\n", sc_strerror(r)); return 3; } r = sc_ctx_detect_readers(ctx); if (r < 0) { fprintf(stderr, "Error while refreshing readers: %s\n", sc_strerror(r)); return 3; } } fprintf(stderr, "Waiting for a card to be inserted...\n"); r = sc_wait_for_event(ctx, SC_EVENT_CARD_INSERTED, &found, &event, -1, NULL); if (r < 0) { fprintf(stderr, "Error while waiting for a card: %s\n", sc_strerror(r)); return 3; } reader = found; } else if (sc_ctx_get_reader_count(ctx) == 0) { fprintf(stderr, "No smart card readers found.\n"); return 1; } else { if (!reader_id) { unsigned int i; /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { reader = sc_ctx_get_reader(ctx, i); if (sc_detect_card_presence(reader) & SC_READER_CARD_PRESENT) { fprintf(stderr, "Using reader with a card: %s\n", reader->name); goto autofound; } } /* If no reader had a card, default to the first reader */ reader = sc_ctx_get_reader(ctx, 0); } else { /* If the reader identifier looks like an ATR, try to find the reader with that card */ if (is_string_valid_atr(reader_id)) { unsigned char atr_buf[SC_MAX_ATR_SIZE]; size_t atr_buf_len = sizeof(atr_buf); unsigned int i; sc_hex_to_bin(reader_id, atr_buf, &atr_buf_len); /* Loop readers, looking for a card with ATR */ for (i = 0; i < sc_ctx_get_reader_count(ctx); i++) { struct sc_reader *rdr = sc_ctx_get_reader(ctx, i); if (!(sc_detect_card_presence(rdr) & SC_READER_CARD_PRESENT)) continue; else if (rdr->atr.len != atr_buf_len) continue; else if (memcmp(rdr->atr.value, atr_buf, rdr->atr.len)) continue; fprintf(stderr, "Matched ATR in reader: %s\n", rdr->name); reader = rdr; goto autofound; } } else { char *endptr = NULL; unsigned int num; errno = 0; num = strtol(reader_id, &endptr, 0); if (!errno && endptr && *endptr == '\0') reader = sc_ctx_get_reader(ctx, num); else reader = sc_ctx_get_reader_by_name(ctx, reader_id); } } autofound: if (!reader) { fprintf(stderr, "Reader \"%s\" not found (%d reader(s) detected)\n", reader_id, sc_ctx_get_reader_count(ctx)); return 1; } if (sc_detect_card_presence(reader) <= 0) { fprintf(stderr, "Card not present.\n"); return 3; } } if (verbose) printf("Connecting to card in reader %s...\n", reader->name); r = sc_connect_card(reader, &card); if (r < 0) { fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Using card driver %s.\n", card->driver->name); if (do_lock) { r = sc_lock(card); if (r < 0) { fprintf(stderr, "Failed to lock card: %s\n", sc_strerror(r)); sc_disconnect_card(card); return 1; } } *cardp = card; return 0; } int util_connect_card(sc_context_t *ctx, sc_card_t **cardp, const char *reader_id, int do_wait, int verbose) { return util_connect_card_ex(ctx, cardp, reader_id, do_wait, 1, verbose); } void util_print_binary(FILE *f, const u8 *buf, int count) { int i; for (i = 0; i < count; i++) { unsigned char c = buf[i]; const char *format; if (!isprint(c)) format = "\\x%02X"; else format = "%c"; fprintf(f, format, c); } (void) fflush(f); } void util_hex_dump(FILE *f, const u8 *in, int len, const char *sep) { int i; for (i = 0; i < len; i++) { if (sep != NULL && i) fprintf(f, "%s", sep); fprintf(f, "%02X", in[i]); } } void util_hex_dump_asc(FILE *f, const u8 *in, size_t count, int addr) { int lines = 0; while (count) { char ascbuf[17]; size_t i; if (addr >= 0) { fprintf(f, "%08X: ", addr); addr += 16; } for (i = 0; i < count && i < 16; i++) { fprintf(f, "%02X ", *in); if (isprint(*in)) ascbuf[i] = *in; else ascbuf[i] = '.'; in++; } count -= i; ascbuf[i] = 0; for (; i < 16 && lines; i++) fprintf(f, " "); fprintf(f, "%s\n", ascbuf); lines++; } } NORETURN void util_print_usage_and_die(const char *app_name, const struct option options[], const char *option_help[], const char *args) { int i; int header_shown = 0; if (args) printf("Usage: %s [OPTIONS] %s\n", app_name, args); else printf("Usage: %s [OPTIONS]\n", app_name); for (i = 0; options[i].name; i++) { char buf[40]; const char *arg_str; /* Skip "hidden" options */ if (option_help[i] == NULL) continue; if (!header_shown++) printf("Options:\n"); switch (options[i].has_arg) { case 1: arg_str = " <arg>"; break; case 2: arg_str = " [arg]"; break; default: arg_str = ""; break; } if (isascii(options[i].val) && isprint(options[i].val) && !isspace(options[i].val)) sprintf(buf, "-%c, --%s%s", options[i].val, options[i].name, arg_str); else sprintf(buf, " --%s%s", options[i].name, arg_str); /* print the line - wrap if necessary */ if (strlen(buf) > 28) { printf(" %s\n", buf); buf[0] = '\0'; } printf(" %-28s %s\n", buf, option_help[i]); } exit(2); } const char * util_acl_to_str(const sc_acl_entry_t *e) { static char line[80], buf[20]; unsigned int acl; if (e == NULL) return "N/A"; line[0] = 0; while (e != NULL) { acl = e->method; switch (acl) { case SC_AC_UNKNOWN: return "N/A"; case SC_AC_NEVER: return "NEVR"; case SC_AC_NONE: return "NONE"; case SC_AC_CHV: strcpy(buf, "CHV"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "%d", e->key_ref); break; case SC_AC_TERM: strcpy(buf, "TERM"); break; case SC_AC_PRO: strcpy(buf, "PROT"); break; case SC_AC_AUT: strcpy(buf, "AUTH"); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 4, "%d", e->key_ref); break; case SC_AC_SEN: strcpy(buf, "Sec.Env. "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; case SC_AC_SCB: strcpy(buf, "Sec.ControlByte "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "Ox%X", e->key_ref); break; case SC_AC_IDA: strcpy(buf, "PKCS#15 AuthID "); if (e->key_ref != SC_AC_KEY_REF_NONE) sprintf(buf + 3, "#%d", e->key_ref); break; default: strcpy(buf, "????"); break; } strncat(line, buf, sizeof line); strncat(line, " ", sizeof line); e = e->next; } line[(sizeof line)-1] = '\0'; /* make sure it's NUL terminated */ line[strlen(line)-1] = 0; /* get rid of trailing space */ return line; } NORETURN void util_fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\nAborting.\n"); va_end(ap); sc_notify_close(); exit(1); } void util_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void util_warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "warning: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } int util_getpass (char **lineptr, size_t *len, FILE *stream) { #define MAX_PASS_SIZE 128 char *buf; size_t i; int ch = 0; #ifndef _WIN32 struct termios old, new; fflush(stdout); if (tcgetattr (fileno (stdout), &old) != 0) return -1; new = old; new.c_lflag &= ~ECHO; if (tcsetattr (fileno (stdout), TCSAFLUSH, &new) != 0) return -1; #endif buf = calloc(1, MAX_PASS_SIZE); if (!buf) return -1; for (i = 0; i < MAX_PASS_SIZE - 1; i++) { #ifndef _WIN32 ch = getchar(); #else ch = _getch(); #endif if (ch == 0 || ch == 3) break; if (ch == '\n' || ch == '\r') break; buf[i] = (char) ch; } #ifndef _WIN32 tcsetattr (fileno (stdout), TCSAFLUSH, &old); fputs("\n", stdout); #endif if (ch == 0 || ch == 3) { free(buf); return -1; } if (*lineptr && (!len || *len < i+1)) { free(*lineptr); *lineptr = NULL; } if (*lineptr) { memcpy(*lineptr,buf,i+1); memset(buf, 0, MAX_PASS_SIZE); free(buf); } else { *lineptr = buf; if (len) *len = MAX_PASS_SIZE; } return i; } size_t util_get_pin(const char *input, const char **pin) { size_t inputlen = strlen(input); size_t pinlen = 0; if(inputlen > 4 && strncasecmp(input, "env:", 4) == 0) { // Get a PIN from a environment variable *pin = getenv(input + 4); pinlen = *pin ? strlen(*pin) : 0; } else { //Just use the input *pin = input; pinlen = inputlen; } return pinlen; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_10
crossvul-cpp_data_good_5172_1
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_INFO(0, var_name) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_INFO(0, var_name) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; TSRMLS_FETCH(); MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i], strlen(atts[i])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { stack->varname = estrdup(atts[i]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) { zval *tmp; char *key; char *p1, *p2, *endp; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-415/c/good_5172_1
crossvul-cpp_data_bad_3102_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO FFFFF IIIII L EEEEE % % P P R R O O F I L E % % PPPP RRRR O O FFF I L EEE % % P R R O O F I L E % % P R R OOO F IIIII LLLLL EEEEE % % % % % % MagickCore Image Profile Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colorspace-private.h" #include "magick/configure.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/option-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/token.h" #include "magick/utility.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H) #include <wchar.h> #include <lcms/lcms2.h> #else #include <wchar.h> #include "lcms2.h" #endif #endif /* Forward declarations */ static MagickBooleanType SetImageProfileInternal(Image *,const char *,const StringInfo *, const MagickBooleanType); static void WriteTo8BimProfile(Image *,const char*,const StringInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProfiles() clones one or more image profiles. % % The format of the CloneImageProfiles method is: % % MagickBooleanType CloneImageProfiles(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickSignature); image->color_profile.length=clone_image->color_profile.length; image->color_profile.info=clone_image->color_profile.info; image->iptc_profile.length=clone_image->iptc_profile.length; image->iptc_profile.info=clone_image->iptc_profile.info; if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProfile() deletes a profile from the image by its name. % % The format of the DeleteImageProfile method is: % % MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); if (LocaleCompare(name,"icc") == 0) { /* Continue to support deprecated color profile for now. */ image->color_profile.length=0; image->color_profile.info=(unsigned char *) NULL; } if (LocaleCompare(name,"iptc") == 0) { /* Continue to support deprecated IPTC profile for now. */ image->iptc_profile.length=0; image->iptc_profile.info=(unsigned char *) NULL; } WriteTo8BimProfile(image,name,(StringInfo *) NULL); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProfiles() releases memory associated with an image profile map. % % The format of the DestroyProfiles method is: % % void DestroyImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProfiles(Image *image) { if (image->profiles != (SplayTreeInfo *) NULL) image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProfile() gets a profile associated with an image by name. % % The format of the GetImageProfile method is: % % const StringInfo *GetImageProfile(const Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport const StringInfo *GetImageProfile(const Image *image, const char *name) { const StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProfile() gets the next profile name for an image. % % The format of the GetNextImageProfile method is: % % char *GetNextImageProfile(const Image *image) % % A description of each parameter follows: % % o hash_info: the hash info. % */ MagickExport char *GetNextImageProfile(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((char *) NULL); return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProfileImage() associates, applies, or removes an ICM, IPTC, or generic % profile with / to / from an image. If the profile is NULL, it is removed % from the image otherwise added or applied. Use a name of '*' and a profile % of NULL to remove all profiles from the image. % % ICC and ICM profiles are handled as follows: If the image does not have % an associated color profile, the one you provide is associated with the % image and the image pixels are not transformed. Otherwise, the colorspace % transform defined by the existing and new profile are applied to the image % pixels and the new profile is associated with the image. % % The format of the ProfileImage method is: % % MagickBooleanType ProfileImage(Image *image,const char *name, % const void *datum,const size_t length,const MagickBooleanType clone) % % A description of each parameter follows: % % o image: the image. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o datum: the profile data. % % o length: the length of the profile. % % o clone: should be MagickFalse. % */ #if defined(MAGICKCORE_LCMS_DELEGATE) static unsigned short **DestroyPixelThreadSet(unsigned short **pixels) { register ssize_t i; assert(pixels != (unsigned short **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (unsigned short *) NULL) pixels[i]=(unsigned short *) RelinquishMagickMemory(pixels[i]); pixels=(unsigned short **) RelinquishMagickMemory(pixels); return(pixels); } static unsigned short **AcquirePixelThreadSet(const size_t columns, const size_t channels) { register ssize_t i; unsigned short **pixels; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(unsigned short **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (unsigned short **) NULL) return((unsigned short **) NULL); (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(unsigned short *) AcquireQuantumMemory(columns,channels* sizeof(**pixels)); if (pixels[i] == (unsigned short *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform) { register ssize_t i; assert(transform != (cmsHTRANSFORM *) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (transform[i] != (cmsHTRANSFORM) NULL) cmsDeleteTransform(transform[i]); transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform); return(transform); } static cmsHTRANSFORM *AcquireTransformThreadSet(Image *image, const cmsHPROFILE source_profile,const cmsUInt32Number source_type, const cmsHPROFILE target_profile,const cmsUInt32Number target_type, const int intent,const cmsUInt32Number flags) { cmsHTRANSFORM *transform; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads, sizeof(*transform)); if (transform == (cmsHTRANSFORM *) NULL) return((cmsHTRANSFORM *) NULL); (void) ResetMagickMemory(transform,0,number_threads*sizeof(*transform)); for (i=0; i < (ssize_t) number_threads; i++) { transform[i]=cmsCreateTransformTHR((cmsContext) image,source_profile, source_type,target_profile,target_type,intent,flags); if (transform[i] == (cmsHTRANSFORM) NULL) return(DestroyTransformThreadSet(transform)); } return(transform); } #endif #if defined(MAGICKCORE_LCMS_DELEGATE) static void LCMSExceptionHandler(cmsContext context,cmsUInt32Number severity, const char *message) { Image *image; (void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s", severity,message != (char *) NULL ? message : "no message"); image=(Image *) context; if (image != (Image *) NULL) (void) ThrowMagickException(&image->exception,GetMagickModule(), ImageWarning,"UnableToTransformColorspace","`%s'",image->filename); } #endif static MagickBooleanType SetsRGBImageProfile(Image *image) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (GetImageProfile(image,"icc") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); return(status); } MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, const void *datum,const size_t length, const MagickBooleanType magick_unused(clone)) { #define ProfileImageTag "Profile/Image" #define ThrowProfileException(severity,tag,context) \ { \ if (source_profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(source_profile); \ if (target_profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(target_profile); \ ThrowBinaryException(severity,tag,context); \ } MagickBooleanType status; StringInfo *profile; magick_unreferenced(clone); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(name != (const char *) NULL); if ((datum == (const void *) NULL) || (length == 0)) { char *next; /* Delete image profile(s). */ ResetImageProfileIterator(image); for (next=GetNextImageProfile(image); next != (const char *) NULL; ) { if (IsOptionMember(next,name) != MagickFalse) { (void) DeleteImageProfile(image,next); ResetImageProfileIterator(image); } next=GetNextImageProfile(image); } return(MagickTrue); } /* Add a ICC, IPTC, or generic profile to the image. */ status=MagickTrue; profile=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile,(unsigned char *) datum); if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) status=SetImageProfile(image,name,profile); else { const StringInfo *icc_profile; icc_profile=GetImageProfile(image,"icc"); if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { const char *value; value=GetImageProperty(image,"exif:ColorSpace"); (void) value; if (LocaleCompare(value,"1") != 0) (void) SetsRGBImageProfile(image); value=GetImageProperty(image,"exif:InteroperabilityIndex"); if (LocaleCompare(value,"R98.") != 0) (void) SetsRGBImageProfile(image); /* Future. value=GetImageProperty(image,"exif:InteroperabilityIndex"); if (LocaleCompare(value,"R03.") != 0) (void) SetAdobeRGB1998ImageProfile(image); */ icc_profile=GetImageProfile(image,"icc"); } if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { profile=DestroyStringInfo(profile); return(MagickTrue); } #if !defined(MAGICKCORE_LCMS_DELEGATE) (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (LCMS)", image->filename); #else { cmsHPROFILE source_profile; /* Transform pixel colors as defined by the color profiles. */ cmsSetLogErrorHandler(LCMSExceptionHandler); source_profile=cmsOpenProfileFromMemTHR((cmsContext) image, GetStringInfoDatum(profile),(cmsUInt32Number) GetStringInfoLength(profile)); if (source_profile == (cmsHPROFILE) NULL) ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) && (icc_profile == (StringInfo *) NULL)) status=SetImageProfile(image,name,profile); else { CacheView *image_view; ColorspaceType source_colorspace, target_colorspace; cmsColorSpaceSignature signature; cmsHPROFILE target_profile; cmsHTRANSFORM *magick_restrict transform; cmsUInt32Number flags, source_type, target_type; ExceptionInfo *exception; int intent; MagickOffsetType progress; size_t source_channels, target_channels; ssize_t y; unsigned short **magick_restrict source_pixels, **magick_restrict target_pixels; exception=(&image->exception); target_profile=(cmsHPROFILE) NULL; if (icc_profile != (StringInfo *) NULL) { target_profile=source_profile; source_profile=cmsOpenProfileFromMemTHR((cmsContext) image, GetStringInfoDatum(icc_profile),(cmsUInt32Number) GetStringInfoLength(icc_profile)); if (source_profile == (cmsHPROFILE) NULL) ThrowProfileException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } switch (cmsGetColorSpace(source_profile)) { case cmsSigCmykData: { source_colorspace=CMYKColorspace; source_type=(cmsUInt32Number) TYPE_CMYK_16; source_channels=4; break; } case cmsSigGrayData: { source_colorspace=GRAYColorspace; source_type=(cmsUInt32Number) TYPE_GRAY_16; source_channels=1; break; } case cmsSigLabData: { source_colorspace=LabColorspace; source_type=(cmsUInt32Number) TYPE_Lab_16; source_channels=3; break; } case cmsSigLuvData: { source_colorspace=YUVColorspace; source_type=(cmsUInt32Number) TYPE_YUV_16; source_channels=3; break; } case cmsSigRgbData: { source_colorspace=sRGBColorspace; source_type=(cmsUInt32Number) TYPE_RGB_16; source_channels=3; break; } case cmsSigXYZData: { source_colorspace=XYZColorspace; source_type=(cmsUInt32Number) TYPE_XYZ_16; source_channels=3; break; } case cmsSigYCbCrData: { source_colorspace=YCbCrColorspace; source_type=(cmsUInt32Number) TYPE_YCbCr_16; source_channels=3; break; } default: { source_colorspace=UndefinedColorspace; source_type=(cmsUInt32Number) TYPE_RGB_16; source_channels=3; break; } } signature=cmsGetPCS(source_profile); if (target_profile != (cmsHPROFILE) NULL) signature=cmsGetColorSpace(target_profile); switch (signature) { case cmsSigCmykData: { target_colorspace=CMYKColorspace; target_type=(cmsUInt32Number) TYPE_CMYK_16; target_channels=4; break; } case cmsSigLabData: { target_colorspace=LabColorspace; target_type=(cmsUInt32Number) TYPE_Lab_16; target_channels=3; break; } case cmsSigGrayData: { target_colorspace=GRAYColorspace; target_type=(cmsUInt32Number) TYPE_GRAY_16; target_channels=1; break; } case cmsSigLuvData: { target_colorspace=YUVColorspace; target_type=(cmsUInt32Number) TYPE_YUV_16; target_channels=3; break; } case cmsSigRgbData: { target_colorspace=sRGBColorspace; target_type=(cmsUInt32Number) TYPE_RGB_16; target_channels=3; break; } case cmsSigXYZData: { target_colorspace=XYZColorspace; target_type=(cmsUInt32Number) TYPE_XYZ_16; target_channels=3; break; } case cmsSigYCbCrData: { target_colorspace=YCbCrColorspace; target_type=(cmsUInt32Number) TYPE_YCbCr_16; target_channels=3; break; } default: { target_colorspace=UndefinedColorspace; target_type=(cmsUInt32Number) TYPE_RGB_16; target_channels=3; break; } } if ((source_colorspace == UndefinedColorspace) || (target_colorspace == UndefinedColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == GRAYColorspace) && (SetImageGray(image,exception) == MagickFalse)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == CMYKColorspace) && (image->colorspace != CMYKColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == XYZColorspace) && (image->colorspace != XYZColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace == YCbCrColorspace) && (image->colorspace != YCbCrColorspace)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); if ((source_colorspace != CMYKColorspace) && (source_colorspace != GRAYColorspace) && (source_colorspace != LabColorspace) && (source_colorspace != XYZColorspace) && (source_colorspace != YCbCrColorspace) && (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)) ThrowProfileException(ImageError,"ColorspaceColorProfileMismatch", name); switch (image->rendering_intent) { case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break; case PerceptualIntent: intent=INTENT_PERCEPTUAL; break; case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break; case SaturationIntent: intent=INTENT_SATURATION; break; default: intent=INTENT_PERCEPTUAL; break; } flags=cmsFLAGS_HIGHRESPRECALC; #if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) if (image->black_point_compensation != MagickFalse) flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; #endif transform=AcquireTransformThreadSet(image,source_profile, source_type,target_profile,target_type,intent,flags); if (transform == (cmsHTRANSFORM *) NULL) ThrowProfileException(ImageError,"UnableToCreateColorTransform", name); /* Transform image as dictated by the source & target image profiles. */ source_pixels=AcquirePixelThreadSet(image->columns,source_channels); target_pixels=AcquirePixelThreadSet(image->columns,target_channels); if ((source_pixels == (unsigned short **) NULL) || (target_pixels == (unsigned short **) NULL)) { transform=DestroyTransformThreadSet(transform); ThrowProfileException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { target_pixels=DestroyPixelThreadSet(target_pixels); source_pixels=DestroyPixelThreadSet(source_pixels); transform=DestroyTransformThreadSet(transform); if (source_profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(source_profile); if (target_profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_profile); return(MagickFalse); } if (target_colorspace == CMYKColorspace) (void) SetImageColorspace(image,target_colorspace); progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; register unsigned short *p; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); p=source_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=ScaleQuantumToShort(GetPixelRed(q)); if (source_channels > 1) { *p++=ScaleQuantumToShort(GetPixelGreen(q)); *p++=ScaleQuantumToShort(GetPixelBlue(q)); } if (source_channels > 3) *p++=ScaleQuantumToShort(GetPixelIndex(indexes+x)); q++; } cmsDoTransform(transform[id],source_pixels[id],target_pixels[id], (unsigned int) image->columns); p=target_pixels[id]; q-=image->columns; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum(*p)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); p++; if (target_channels > 1) { SetPixelGreen(q,ScaleShortToQuantum(*p)); p++; SetPixelBlue(q,ScaleShortToQuantum(*p)); p++; } if (target_channels > 3) { SetPixelIndex(indexes+x,ScaleShortToQuantum(*p)); p++; } q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ProfileImage) #endif proceed=SetImageProgress(image,ProfileImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) SetImageColorspace(image,target_colorspace); switch (signature) { case cmsSigRgbData: { image->type=image->matte == MagickFalse ? TrueColorType : TrueColorMatteType; break; } case cmsSigCmykData: { image->type=image->matte == MagickFalse ? ColorSeparationType : ColorSeparationMatteType; break; } case cmsSigGrayData: { image->type=image->matte == MagickFalse ? GrayscaleType : GrayscaleMatteType; break; } default: break; } target_pixels=DestroyPixelThreadSet(target_pixels); source_pixels=DestroyPixelThreadSet(source_pixels); transform=DestroyTransformThreadSet(transform); if ((status != MagickFalse) || (cmsGetDeviceClass(source_profile) != cmsSigLinkClass)) status=SetImageProfile(image,name,profile); if (target_profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_profile); } (void) cmsCloseProfile(source_profile); } #endif } profile=DestroyStringInfo(profile); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProfile() removes a named profile from the image and returns its % value. % % The format of the RemoveImageProfile method is: % % void *RemoveImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name) { StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); if (LocaleCompare(name,"icc") == 0) { /* Continue to support deprecated color profile for now. */ image->color_profile.length=0; image->color_profile.info=(unsigned char *) NULL; } if (LocaleCompare(name,"iptc") == 0) { /* Continue to support deprecated IPTC profile for now. */ image->iptc_profile.length=0; image->iptc_profile.info=(unsigned char *) NULL; } WriteTo8BimProfile(image,name,(StringInfo *) NULL); profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t P r o f i l e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageProfileIterator() resets the image profile iterator. Use it in % conjunction with GetNextImageProfile() to iterate over all the profiles % associated with an image. % % The format of the ResetImageProfileIterator method is: % % ResetImageProfileIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageProfileIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProfile() adds a named profile to the image. If a profile with the % same name already exists, it is replaced. This method differs from the % ProfileImage() method in that it does not apply CMS color profiles. % % The format of the SetImageProfile method is: % % MagickBooleanType SetImageProfile(Image *image,const char *name, % const StringInfo *profile) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name, for example icc, exif, and 8bim (8bim is the % Photoshop wrapper for iptc profiles). % % o profile: A StringInfo structure that contains the named profile. % */ static void *DestroyProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static inline const unsigned char *ReadResourceByte(const unsigned char *p, unsigned char *quantum) { *quantum=(*p++); return(p); } static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++); return(p); } static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p); } static inline void WriteResourceLong(unsigned char *p, const unsigned int quantum) { unsigned char buffer[4]; buffer[0]=(unsigned char) (quantum >> 24); buffer[1]=(unsigned char) (quantum >> 16); buffer[2]=(unsigned char) (quantum >> 8); buffer[3]=(unsigned char) quantum; (void) CopyMagickMemory(p,buffer,4); } static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; register const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) CopyMagickMemory(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) CopyMagickMemory(extract_profile->datum,datum,offset-4); (void) WriteResourceLong(extract_profile->datum+offset-4, (unsigned int) profile->length); (void) CopyMagickMemory(extract_profile->datum+offset, profile->datum,profile->length); } (void) CopyMagickMemory(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } static void GetProfilesFromResourceBlock(Image *image, const StringInfo *resource_block) { const unsigned char *datum; register const unsigned char *p; size_t length; ssize_t count; StringInfo *profile; unsigned char length_byte; unsigned int value; unsigned short id; datum=GetStringInfoDatum(resource_block); length=GetStringInfoLength(resource_block); for (p=datum; p < (datum+length-16); ) { if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0)) break; switch (id) { case 0x03ed: { unsigned int resolution; unsigned short units; /* Resolution. */ p=ReadResourceLong(p,&resolution); image->x_resolution=((double) resolution)/65536.0; p=ReadResourceShort(p,&units)+2; p=ReadResourceLong(p,&resolution)+4; image->y_resolution=((double) resolution)/65536.0; /* Values are always stored as pixels per inch. */ if ((ResolutionType) units != PixelsPerCentimeterResolution) image->units=PixelsPerInchResolution; else { image->units=PixelsPerCentimeterResolution; image->x_resolution/=2.54; image->y_resolution/=2.54; } break; } case 0x0404: { /* IPTC Profile */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"iptc",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } case 0x040c: { /* Thumbnail. */ p+=count; break; } case 0x040f: { /* ICC Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"icc",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0422: { /* EXIF Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"exif",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0424: { /* XMP Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"xmp",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } } static MagickBooleanType SetImageProfileInternal(Image *image,const char *name, const StringInfo *profile,const MagickBooleanType recursive) { char key[MaxTextExtent]; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MaxTextExtent); LocaleLower(key); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),CloneStringInfo(profile)); if ((status != MagickFalse) && ((LocaleCompare(name,"icc") == 0) || (LocaleCompare(name,"icm") == 0))) { const StringInfo *icc_profile; /* Continue to support deprecated color profile member. */ icc_profile=GetImageProfile(image,name); if (icc_profile != (const StringInfo *) NULL) { image->color_profile.length=GetStringInfoLength(icc_profile); image->color_profile.info=GetStringInfoDatum(icc_profile); } } if ((status != MagickFalse) && ((LocaleCompare(name,"iptc") == 0) || (LocaleCompare(name,"8bim") == 0))) { const StringInfo *iptc_profile; /* Continue to support deprecated IPTC profile member. */ iptc_profile=GetImageProfile(image,name); if (iptc_profile != (const StringInfo *) NULL) { image->iptc_profile.length=GetStringInfoLength(iptc_profile); image->iptc_profile.info=GetStringInfoDatum(iptc_profile); } } if (status != MagickFalse) { if (LocaleCompare(name,"8bim") == 0) GetProfilesFromResourceBlock(image,profile); else if (recursive == MagickFalse) WriteTo8BimProfile(image,name,profile); } return(status); } MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile) { return(SetImageProfileInternal(image,name,profile,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageProfiles() synchronizes image properties with the image profiles. % Currently we only support updating the EXIF resolution and orientation. % % The format of the SyncImageProfiles method is: % % MagickBooleanType SyncImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline int ReadProfileByte(unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length) { signed int value; if (*length < 4) return(0); value=ReadProfileLong(MSBEndian,*p); (*length)-=4; *p+=4; return(value); } static inline signed short ReadProfileMSBShort(unsigned char **p, size_t *length) { signed short value; if (*length < 2) return(0); value=ReadProfileShort(MSBEndian,*p); (*length)-=2; *p+=2; return(value); } static inline void WriteProfileLong(const EndianType endian, const size_t value,unsigned char *p) { unsigned char buffer[4]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); (void) CopyMagickMemory(p,buffer,4); return; } buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; (void) CopyMagickMemory(p,buffer,4); } static void WriteProfileShort(const EndianType endian, const unsigned short value,unsigned char *p) { unsigned char buffer[2]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); (void) CopyMagickMemory(p,buffer,2); return; } buffer[0]=(unsigned char) (value >> 8); buffer[1]=(unsigned char) value; (void) CopyMagickMemory(p,buffer,2); } static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile) { size_t length; ssize_t count; unsigned char *p; unsigned short id; length=GetStringInfoLength(profile); p=GetStringInfoDatum(profile); while (length != 0) { if (ReadProfileByte(&p,&length) != 0x38) continue; if (ReadProfileByte(&p,&length) != 0x42) continue; if (ReadProfileByte(&p,&length) != 0x49) continue; if (ReadProfileByte(&p,&length) != 0x4D) continue; if (length < 7) return(MagickFalse); id=ReadProfileMSBShort(&p,&length); count=(ssize_t) ReadProfileByte(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); p+=count; if ((*p & 0x01) == 0) (void) ReadProfileByte(&p,&length); count=(ssize_t) ReadProfileMSBLong(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); if ((id == 0x3ED) && (count == 16)) { if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian, (unsigned int) (image->x_resolution*2.54* 65536.0),p); else WriteProfileLong(MSBEndian, (unsigned int) (image->x_resolution* 65536.0),p); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4); if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian, (unsigned int) (image->y_resolution*2.54* 65536.0),p+8); else WriteProfileLong(MSBEndian, (unsigned int) (image->y_resolution* 65536.0),p+8); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12); } p+=count; length-=count; } return(MagickTrue); } static MagickBooleanType SyncExifProfile(Image *image, StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; SplayTreeInfo *exif_resources; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || ((size_t) offset >= length)) return(MagickFalse); directory=exif+offset; level=0; entry=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t number_bytes; ssize_t components, format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(ssize_t) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->x_resolution+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->y_resolution+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(MagickTrue); } MagickExport MagickBooleanType SyncImageProfiles(Image *image) { MagickBooleanType status; StringInfo *profile; status=MagickTrue; profile=(StringInfo *) GetImageProfile(image,"8BIM"); if (profile != (StringInfo *) NULL) if (Sync8BimProfile(image,profile) == MagickFalse) status=MagickFalse; profile=(StringInfo *) GetImageProfile(image,"EXIF"); if (profile != (StringInfo *) NULL) if (SyncExifProfile(image,profile) == MagickFalse) status=MagickFalse; return(status); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_3102_0
crossvul-cpp_data_bad_666_0
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "index.h" #include <stddef.h> #include "repository.h" #include "tree.h" #include "tree-cache.h" #include "hash.h" #include "iterator.h" #include "pathspec.h" #include "ignore.h" #include "blob.h" #include "idxmap.h" #include "diff.h" #include "varint.h" #include "git2/odb.h" #include "git2/oid.h" #include "git2/blob.h" #include "git2/config.h" #include "git2/sys/index.h" #define INSERT_IN_MAP_EX(idx, map, e, err) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_insert((khash_t(idxicase) *) (map), (e), (e), (err)); \ else \ git_idxmap_insert((map), (e), (e), (err)); \ } while (0) #define INSERT_IN_MAP(idx, e, err) INSERT_IN_MAP_EX(idx, (idx)->entries_map, e, err) #define LOOKUP_IN_MAP(p, idx, k) do { \ if ((idx)->ignore_case) \ (p) = git_idxmap_icase_lookup_index((khash_t(idxicase) *) index->entries_map, (k)); \ else \ (p) = git_idxmap_lookup_index(index->entries_map, (k)); \ } while (0) #define DELETE_IN_MAP(idx, e) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_delete((khash_t(idxicase) *) (idx)->entries_map, (e)); \ else \ git_idxmap_delete((idx)->entries_map, (e)); \ } while (0) static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload); #define minimal_entry_size (offsetof(struct entry_short, path)) static const size_t INDEX_FOOTER_SIZE = GIT_OID_RAWSZ; static const size_t INDEX_HEADER_SIZE = 12; static const unsigned int INDEX_VERSION_NUMBER_DEFAULT = 2; static const unsigned int INDEX_VERSION_NUMBER_LB = 2; static const unsigned int INDEX_VERSION_NUMBER_EXT = 3; static const unsigned int INDEX_VERSION_NUMBER_COMP = 4; static const unsigned int INDEX_VERSION_NUMBER_UB = 4; static const unsigned int INDEX_HEADER_SIG = 0x44495243; static const char INDEX_EXT_TREECACHE_SIG[] = {'T', 'R', 'E', 'E'}; static const char INDEX_EXT_UNMERGED_SIG[] = {'R', 'E', 'U', 'C'}; static const char INDEX_EXT_CONFLICT_NAME_SIG[] = {'N', 'A', 'M', 'E'}; #define INDEX_OWNER(idx) ((git_repository *)(GIT_REFCOUNT_OWNER(idx))) struct index_header { uint32_t signature; uint32_t version; uint32_t entry_count; }; struct index_extension { char signature[4]; uint32_t extension_size; }; struct entry_time { uint32_t seconds; uint32_t nanoseconds; }; struct entry_short { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; char path[1]; /* arbitrary length */ }; struct entry_long { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; uint16_t flags_extended; char path[1]; /* arbitrary length */ }; struct entry_srch_key { const char *path; size_t pathlen; int stage; }; struct entry_internal { git_index_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; struct reuc_entry_internal { git_index_reuc_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; /* local declarations */ static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size); static int read_header(struct index_header *dest, const void *buffer); static int parse_index(git_index *index, const char *buffer, size_t buffer_size); static bool is_index_extended(git_index *index); static int write_index(git_oid *checksum, git_index *index, git_filebuf *file); static void index_entry_free(git_index_entry *entry); static void index_entry_reuc_free(git_index_reuc_entry *reuc); int git_index_entry_srch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = memcmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } int git_index_entry_isrch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = strncasecmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } static int index_entry_srch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcmp((const char *)path, entry->path); } static int index_entry_isrch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcasecmp((const char *)path, entry->path); } int git_index_entry_cmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } int git_index_entry_icmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcasecmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } static int conflict_name_cmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcmp(name_a->ours, name_b->ours); } /** * TODO: enable this when resolving case insensitive conflicts */ #if 0 static int conflict_name_icmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcasecmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcasecmp(name_a->ours, name_b->ours); } #endif static int reuc_srch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcmp(key, reuc->path); } static int reuc_isrch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcasecmp(key, reuc->path); } static int reuc_cmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcmp(info_a->path, info_b->path); } static int reuc_icmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcasecmp(info_a->path, info_b->path); } static void index_entry_reuc_free(git_index_reuc_entry *reuc) { git__free(reuc); } static void index_entry_free(git_index_entry *entry) { if (!entry) return; memset(&entry->id, 0, sizeof(entry->id)); git__free(entry); } unsigned int git_index__create_mode(unsigned int mode) { if (S_ISLNK(mode)) return S_IFLNK; if (S_ISDIR(mode) || (mode & S_IFMT) == (S_IFLNK | S_IFDIR)) return (S_IFLNK | S_IFDIR); return S_IFREG | GIT_PERMS_CANONICAL(mode); } static unsigned int index_merge_mode( git_index *index, git_index_entry *existing, unsigned int mode) { if (index->no_symlinks && S_ISREG(mode) && existing && S_ISLNK(existing->mode)) return existing->mode; if (index->distrust_filemode && S_ISREG(mode)) return (existing && S_ISREG(existing->mode)) ? existing->mode : git_index__create_mode(0666); return git_index__create_mode(mode); } GIT_INLINE(int) index_find_in_entries( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { struct entry_srch_key srch_key; srch_key.path = path; srch_key.pathlen = !path_len ? strlen(path) : path_len; srch_key.stage = stage; return git_vector_bsearch2(out, entries, entry_srch, &srch_key); } GIT_INLINE(int) index_find( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { git_vector_sort(&index->entries); return index_find_in_entries( out, &index->entries, index->entries_search, path, path_len, stage); } void git_index__set_ignore_case(git_index *index, bool ignore_case) { index->ignore_case = ignore_case; if (ignore_case) { index->entries_cmp_path = git__strcasecmp_cb; index->entries_search = git_index_entry_isrch; index->entries_search_path = index_entry_isrch_path; index->reuc_search = reuc_isrch; } else { index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; } git_vector_set_cmp(&index->entries, ignore_case ? git_index_entry_icmp : git_index_entry_cmp); git_vector_sort(&index->entries); git_vector_set_cmp(&index->reuc, ignore_case ? reuc_icmp : reuc_cmp); git_vector_sort(&index->reuc); } int git_index_open(git_index **index_out, const char *index_path) { git_index *index; int error = -1; assert(index_out); index = git__calloc(1, sizeof(git_index)); GITERR_CHECK_ALLOC(index); git_pool_init(&index->tree_pool, 1); if (index_path != NULL) { index->index_file_path = git__strdup(index_path); if (!index->index_file_path) goto fail; /* Check if index file is stored on disk already */ if (git_path_exists(index->index_file_path) == true) index->on_disk = 1; } if (git_vector_init(&index->entries, 32, git_index_entry_cmp) < 0 || git_idxmap_alloc(&index->entries_map) < 0 || git_vector_init(&index->names, 8, conflict_name_cmp) < 0 || git_vector_init(&index->reuc, 8, reuc_cmp) < 0 || git_vector_init(&index->deleted, 8, git_index_entry_cmp) < 0) goto fail; index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; index->version = INDEX_VERSION_NUMBER_DEFAULT; if (index_path != NULL && (error = git_index_read(index, true)) < 0) goto fail; *index_out = index; GIT_REFCOUNT_INC(index); return 0; fail: git_pool_clear(&index->tree_pool); git_index_free(index); return error; } int git_index_new(git_index **out) { return git_index_open(out, NULL); } static void index_free(git_index *index) { /* index iterators increment the refcount of the index, so if we * get here then there should be no outstanding iterators. */ assert(!git_atomic_get(&index->readers)); git_index_clear(index); git_idxmap_free(index->entries_map); git_vector_free(&index->entries); git_vector_free(&index->names); git_vector_free(&index->reuc); git_vector_free(&index->deleted); git__free(index->index_file_path); git__memzero(index, sizeof(*index)); git__free(index); } void git_index_free(git_index *index) { if (index == NULL) return; GIT_REFCOUNT_DEC(index, index_free); } /* call with locked index */ static void index_free_deleted(git_index *index) { int readers = (int)git_atomic_get(&index->readers); size_t i; if (readers > 0 || !index->deleted.length) return; for (i = 0; i < index->deleted.length; ++i) { git_index_entry *ie = git__swap(index->deleted.contents[i], NULL); index_entry_free(ie); } git_vector_clear(&index->deleted); } /* call with locked index */ static int index_remove_entry(git_index *index, size_t pos) { int error = 0; git_index_entry *entry = git_vector_get(&index->entries, pos); if (entry != NULL) { git_tree_cache_invalidate_path(index->tree, entry->path); DELETE_IN_MAP(index, entry); } error = git_vector_remove(&index->entries, pos); if (!error) { if (git_atomic_get(&index->readers) > 0) { error = git_vector_insert(&index->deleted, entry); } else { index_entry_free(entry); } } return error; } int git_index_clear(git_index *index) { int error = 0; assert(index); index->tree = NULL; git_pool_clear(&index->tree_pool); git_idxmap_clear(index->entries_map); while (!error && index->entries.length > 0) error = index_remove_entry(index, index->entries.length - 1); index_free_deleted(index); git_index_reuc_clear(index); git_index_name_clear(index); git_futils_filestamp_set(&index->stamp, NULL); return error; } static int create_index_error(int error, const char *msg) { giterr_set_str(GITERR_INDEX, msg); return error; } int git_index_set_caps(git_index *index, int caps) { unsigned int old_ignore_case; assert(index); old_ignore_case = index->ignore_case; if (caps == GIT_INDEXCAP_FROM_OWNER) { git_repository *repo = INDEX_OWNER(index); int val; if (!repo) return create_index_error( -1, "cannot access repository to set index caps"); if (!git_repository__cvar(&val, repo, GIT_CVAR_IGNORECASE)) index->ignore_case = (val != 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_FILEMODE)) index->distrust_filemode = (val == 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_SYMLINKS)) index->no_symlinks = (val == 0); } else { index->ignore_case = ((caps & GIT_INDEXCAP_IGNORE_CASE) != 0); index->distrust_filemode = ((caps & GIT_INDEXCAP_NO_FILEMODE) != 0); index->no_symlinks = ((caps & GIT_INDEXCAP_NO_SYMLINKS) != 0); } if (old_ignore_case != index->ignore_case) { git_index__set_ignore_case(index, (bool)index->ignore_case); } return 0; } int git_index_caps(const git_index *index) { return ((index->ignore_case ? GIT_INDEXCAP_IGNORE_CASE : 0) | (index->distrust_filemode ? GIT_INDEXCAP_NO_FILEMODE : 0) | (index->no_symlinks ? GIT_INDEXCAP_NO_SYMLINKS : 0)); } const git_oid *git_index_checksum(git_index *index) { return &index->checksum; } /** * Returns 1 for changed, 0 for not changed and <0 for errors */ static int compare_checksum(git_index *index) { int fd; ssize_t bytes_read; git_oid checksum = {{ 0 }}; if ((fd = p_open(index->index_file_path, O_RDONLY)) < 0) return fd; if (p_lseek(fd, -20, SEEK_END) < 0) { p_close(fd); giterr_set(GITERR_OS, "failed to seek to end of file"); return -1; } bytes_read = p_read(fd, &checksum, GIT_OID_RAWSZ); p_close(fd); if (bytes_read < 0) return -1; return !!git_oid_cmp(&checksum, &index->checksum); } int git_index_read(git_index *index, int force) { int error = 0, updated; git_buf buffer = GIT_BUF_INIT; git_futils_filestamp stamp = index->stamp; if (!index->index_file_path) return create_index_error(-1, "failed to read index: The index is in-memory only"); index->on_disk = git_path_exists(index->index_file_path); if (!index->on_disk) { if (force) return git_index_clear(index); return 0; } if ((updated = git_futils_filestamp_check(&stamp, index->index_file_path) < 0) || ((updated = compare_checksum(index)) < 0)) { giterr_set( GITERR_INDEX, "failed to read index: '%s' no longer exists", index->index_file_path); return updated; } if (!updated && !force) return 0; error = git_futils_readbuffer(&buffer, index->index_file_path); if (error < 0) return error; index->tree = NULL; git_pool_clear(&index->tree_pool); error = git_index_clear(index); if (!error) error = parse_index(index, buffer.ptr, buffer.size); if (!error) git_futils_filestamp_set(&index->stamp, &stamp); git_buf_free(&buffer); return error; } int git_index__changed_relative_to( git_index *index, const git_oid *checksum) { /* attempt to update index (ignoring errors) */ if (git_index_read(index, false) < 0) giterr_clear(); return !!git_oid_cmp(&index->checksum, checksum); } static bool is_racy_entry(git_index *index, const git_index_entry *entry) { /* Git special-cases submodules in the check */ if (S_ISGITLINK(entry->mode)) return false; return git_index_entry_newer_than_index(entry, index); } /* * Force the next diff to take a look at those entries which have the * same timestamp as the current index. */ static int truncate_racily_clean(git_index *index) { size_t i; int error; git_index_entry *entry; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; git_diff *diff = NULL; git_vector paths = GIT_VECTOR_INIT; git_diff_delta *delta; /* Nothing to do if there's no repo to talk about */ if (!INDEX_OWNER(index)) return 0; /* If there's no workdir, we can't know where to even check */ if (!git_repository_workdir(INDEX_OWNER(index))) return 0; diff_opts.flags |= GIT_DIFF_INCLUDE_TYPECHANGE | GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_DISABLE_PATHSPEC_MATCH; git_vector_foreach(&index->entries, i, entry) { if ((entry->flags_extended & GIT_IDXENTRY_UPTODATE) == 0 && is_racy_entry(index, entry)) git_vector_insert(&paths, (char *)entry->path); } if (paths.length == 0) goto done; diff_opts.pathspec.count = paths.length; diff_opts.pathspec.strings = (char **)paths.contents; if ((error = git_diff_index_to_workdir(&diff, INDEX_OWNER(index), index, &diff_opts)) < 0) return error; git_vector_foreach(&diff->deltas, i, delta) { entry = (git_index_entry *)git_index_get_bypath(index, delta->old_file.path, 0); /* Ensure that we have a stage 0 for this file (ie, it's not a * conflict), otherwise smudging it is quite pointless. */ if (entry) entry->file_size = 0; } done: git_diff_free(diff); git_vector_free(&paths); return 0; } unsigned git_index_version(git_index *index) { assert(index); return index->version; } int git_index_set_version(git_index *index, unsigned int version) { assert(index); if (version < INDEX_VERSION_NUMBER_LB || version > INDEX_VERSION_NUMBER_UB) { giterr_set(GITERR_INDEX, "invalid version number"); return -1; } index->version = version; return 0; } int git_index_write(git_index *index) { git_indexwriter writer = GIT_INDEXWRITER_INIT; int error; truncate_racily_clean(index); if ((error = git_indexwriter_init(&writer, index)) == 0) error = git_indexwriter_commit(&writer); git_indexwriter_cleanup(&writer); return error; } const char * git_index_path(const git_index *index) { assert(index); return index->index_file_path; } int git_index_write_tree(git_oid *oid, git_index *index) { git_repository *repo; assert(oid && index); repo = INDEX_OWNER(index); if (repo == NULL) return create_index_error(-1, "Failed to write tree. " "the index file is not backed up by an existing repository"); return git_tree__write_index(oid, index, repo); } int git_index_write_tree_to( git_oid *oid, git_index *index, git_repository *repo) { assert(oid && index && repo); return git_tree__write_index(oid, index, repo); } size_t git_index_entrycount(const git_index *index) { assert(index); return index->entries.length; } const git_index_entry *git_index_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->entries); return git_vector_get(&index->entries, n); } const git_index_entry *git_index_get_bypath( git_index *index, const char *path, int stage) { khiter_t pos; git_index_entry key = {{ 0 }}; assert(index); key.path = path; GIT_IDXENTRY_STAGE_SET(&key, stage); LOOKUP_IN_MAP(pos, index, &key); if (git_idxmap_valid_index(index->entries_map, pos)) return git_idxmap_value_at(index->entries_map, pos); giterr_set(GITERR_INDEX, "index does not contain '%s'", path); return NULL; } void git_index_entry__init_from_stat( git_index_entry *entry, struct stat *st, bool trust_mode) { entry->ctime.seconds = (int32_t)st->st_ctime; entry->mtime.seconds = (int32_t)st->st_mtime; #if defined(GIT_USE_NSEC) entry->mtime.nanoseconds = st->st_mtime_nsec; entry->ctime.nanoseconds = st->st_ctime_nsec; #endif entry->dev = st->st_rdev; entry->ino = st->st_ino; entry->mode = (!trust_mode && S_ISREG(st->st_mode)) ? git_index__create_mode(0666) : git_index__create_mode(st->st_mode); entry->uid = st->st_uid; entry->gid = st->st_gid; entry->file_size = (uint32_t)st->st_size; } static void index_entry_adjust_namemask( git_index_entry *entry, size_t path_length) { entry->flags &= ~GIT_IDXENTRY_NAMEMASK; if (path_length < GIT_IDXENTRY_NAMEMASK) entry->flags |= path_length & GIT_IDXENTRY_NAMEMASK; else entry->flags |= GIT_IDXENTRY_NAMEMASK; } /* When `from_workdir` is true, we will validate the paths to avoid placing * paths that are invalid for the working directory on the current filesystem * (eg, on Windows, we will disallow `GIT~1`, `AUX`, `COM1`, etc). This * function will *always* prevent `.git` and directory traversal `../` from * being added to the index. */ static int index_entry_create( git_index_entry **out, git_repository *repo, const char *path, bool from_workdir) { size_t pathlen = strlen(path), alloclen; struct entry_internal *entry; unsigned int path_valid_flags = GIT_PATH_REJECT_INDEX_DEFAULTS; /* always reject placing `.git` in the index and directory traversal. * when requested, disallow platform-specific filenames and upgrade to * the platform-specific `.git` tests (eg, `git~1`, etc). */ if (from_workdir) path_valid_flags |= GIT_PATH_REJECT_WORKDIR_DEFAULTS; if (!git_path_isvalid(repo, path, path_valid_flags)) { giterr_set(GITERR_INDEX, "invalid path: '%s'", path); return -1; } GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(struct entry_internal), pathlen); GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); entry = git__calloc(1, alloclen); GITERR_CHECK_ALLOC(entry); entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; *out = (git_index_entry *)entry; return 0; } static int index_entry_init( git_index_entry **entry_out, git_index *index, const char *rel_path) { int error = 0; git_index_entry *entry = NULL; struct stat st; git_oid oid; if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (index_entry_create(&entry, INDEX_OWNER(index), rel_path, true) < 0) return -1; /* write the blob to disk and get the oid and stat info */ error = git_blob__create_from_paths( &oid, &st, INDEX_OWNER(index), NULL, rel_path, 0, true); if (error < 0) { index_entry_free(entry); return error; } entry->id = oid; git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); *entry_out = (git_index_entry *)entry; return 0; } static git_index_reuc_entry *reuc_entry_alloc(const char *path) { size_t pathlen = strlen(path), structlen = sizeof(struct reuc_entry_internal), alloclen; struct reuc_entry_internal *entry; if (GIT_ADD_SIZET_OVERFLOW(&alloclen, structlen, pathlen) || GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1)) return NULL; entry = git__calloc(1, alloclen); if (!entry) return NULL; entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; return (git_index_reuc_entry *)entry; } static int index_entry_reuc_init(git_index_reuc_entry **reuc_out, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; assert(reuc_out && path); *reuc_out = reuc = reuc_entry_alloc(path); GITERR_CHECK_ALLOC(reuc); if ((reuc->mode[0] = ancestor_mode) > 0) { assert(ancestor_oid); git_oid_cpy(&reuc->oid[0], ancestor_oid); } if ((reuc->mode[1] = our_mode) > 0) { assert(our_oid); git_oid_cpy(&reuc->oid[1], our_oid); } if ((reuc->mode[2] = their_mode) > 0) { assert(their_oid); git_oid_cpy(&reuc->oid[2], their_oid); } return 0; } static void index_entry_cpy( git_index_entry *tgt, const git_index_entry *src) { const char *tgt_path = tgt->path; memcpy(tgt, src, sizeof(*tgt)); tgt->path = tgt_path; } static int index_entry_dup( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy(*out, src); return 0; } static void index_entry_cpy_nocache( git_index_entry *tgt, const git_index_entry *src) { git_oid_cpy(&tgt->id, &src->id); tgt->mode = src->mode; tgt->flags = src->flags; tgt->flags_extended = (src->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); } static int index_entry_dup_nocache( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy_nocache(*out, src); return 0; } static int has_file_name(git_index *index, const git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = 0; size_t len = strlen(entry->path); int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; while (pos < index->entries.length) { struct entry_internal *p = index->entries.contents[pos++]; if (len >= p->pathlen) break; if (memcmp(name, p->path, len)) break; if (GIT_IDXENTRY_STAGE(&p->entry) != stage) continue; if (p->path[len] != '/') continue; retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, --pos) < 0) break; } return retval; } /* * Do we have another file with a pathname that is a proper * subset of the name we're trying to add? */ static int has_dir_name(git_index *index, const git_index_entry *entry, int ok_to_replace) { int retval = 0; int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; const char *slash = name + strlen(name); for (;;) { size_t len, pos; for (;;) { if (*--slash == '/') break; if (slash <= entry->path) return retval; } len = slash - name; if (!index_find(&pos, index, name, len, stage)) { retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, pos) < 0) break; continue; } /* * Trivial optimization: if we find an entry that * already matches the sub-directory, then we know * we're ok, and we can exit. */ for (; pos < index->entries.length; ++pos) { struct entry_internal *p = index->entries.contents[pos]; if (p->pathlen <= len || p->path[len] != '/' || memcmp(p->path, name, len)) break; /* not our subdirectory */ if (GIT_IDXENTRY_STAGE(&p->entry) == stage) return retval; } } return retval; } static int check_file_directory_collision(git_index *index, git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = has_file_name(index, entry, pos, ok_to_replace); retval = retval + has_dir_name(index, entry, ok_to_replace); if (retval) { giterr_set(GITERR_INDEX, "'%s' appears as both a file and a directory", entry->path); return -1; } return 0; } static int canonicalize_directory_path( git_index *index, git_index_entry *entry, git_index_entry *existing) { const git_index_entry *match, *best = NULL; char *search, *sep; size_t pos, search_len, best_len; if (!index->ignore_case) return 0; /* item already exists in the index, simply re-use the existing case */ if (existing) { memcpy((char *)entry->path, existing->path, strlen(existing->path)); return 0; } /* nothing to do */ if (strchr(entry->path, '/') == NULL) return 0; if ((search = git__strdup(entry->path)) == NULL) return -1; /* starting at the parent directory and descending to the root, find the * common parent directory. */ while (!best && (sep = strrchr(search, '/'))) { sep[1] = '\0'; search_len = strlen(search); git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, search); while ((match = git_vector_get(&index->entries, pos))) { if (GIT_IDXENTRY_STAGE(match) != 0) { /* conflicts do not contribute to canonical paths */ } else if (strncmp(search, match->path, search_len) == 0) { /* prefer an exact match to the input filename */ best = match; best_len = search_len; break; } else if (strncasecmp(search, match->path, search_len) == 0) { /* continue walking, there may be a path with an exact * (case sensitive) match later in the index, but use this * as the best match until that happens. */ if (!best) { best = match; best_len = search_len; } } else { break; } pos++; } sep[0] = '\0'; } if (best) memcpy((char *)entry->path, best->path, best_len); git__free(search); return 0; } static int index_no_dups(void **old, void *new) { const git_index_entry *entry = new; GIT_UNUSED(old); giterr_set(GITERR_INDEX, "'%s' appears multiple times at stage %d", entry->path, GIT_IDXENTRY_STAGE(entry)); return GIT_EEXISTS; } static void index_existing_and_best( git_index_entry **existing, size_t *existing_position, git_index_entry **best, git_index *index, const git_index_entry *entry) { git_index_entry *e; size_t pos; int error; error = index_find(&pos, index, entry->path, 0, GIT_IDXENTRY_STAGE(entry)); if (error == 0) { *existing = index->entries.contents[pos]; *existing_position = pos; *best = index->entries.contents[pos]; return; } *existing = NULL; *existing_position = 0; *best = NULL; if (GIT_IDXENTRY_STAGE(entry) == 0) { for (; pos < index->entries.length; pos++) { int (*strcomp)(const char *a, const char *b) = index->ignore_case ? git__strcasecmp : git__strcmp; e = index->entries.contents[pos]; if (strcomp(entry->path, e->path) != 0) break; if (GIT_IDXENTRY_STAGE(e) == GIT_INDEX_STAGE_ANCESTOR) { *best = e; continue; } else { *best = e; break; } } } } /* index_insert takes ownership of the new entry - if it can't insert * it, then it will return an error **and also free the entry**. When * it replaces an existing entry, it will update the entry_ptr with the * actual entry in the index (and free the passed in one). * * trust_path is whether we use the given path, or whether (on case * insensitive systems only) we try to canonicalize the given path to * be within an existing directory. * * trust_mode is whether we trust the mode in entry_ptr. * * trust_id is whether we trust the id or it should be validated. */ static int index_insert( git_index *index, git_index_entry **entry_ptr, int replace, bool trust_path, bool trust_mode, bool trust_id) { int error = 0; size_t path_length, position; git_index_entry *existing, *best, *entry; assert(index && entry_ptr); entry = *entry_ptr; /* make sure that the path length flag is correct */ path_length = ((struct entry_internal *)entry)->pathlen; index_entry_adjust_namemask(entry, path_length); /* this entry is now up-to-date and should not be checked for raciness */ entry->flags_extended |= GIT_IDXENTRY_UPTODATE; git_vector_sort(&index->entries); /* look if an entry with this path already exists, either staged, or (if * this entry is a regular staged item) as the "ours" side of a conflict. */ index_existing_and_best(&existing, &position, &best, index, entry); /* update the file mode */ entry->mode = trust_mode ? git_index__create_mode(entry->mode) : index_merge_mode(index, best, entry->mode); /* canonicalize the directory name */ if (!trust_path) error = canonicalize_directory_path(index, entry, best); /* ensure that the given id exists (unless it's a submodule) */ if (!error && !trust_id && INDEX_OWNER(index) && (entry->mode & GIT_FILEMODE_COMMIT) != GIT_FILEMODE_COMMIT) { if (!git_object__is_valid(INDEX_OWNER(index), &entry->id, git_object__type_from_filemode(entry->mode))) error = -1; } /* look for tree / blob name collisions, removing conflicts if requested */ if (!error) error = check_file_directory_collision(index, entry, position, replace); if (error < 0) /* skip changes */; /* if we are replacing an existing item, overwrite the existing entry * and return it in place of the passed in one. */ else if (existing) { if (replace) { index_entry_cpy(existing, entry); if (trust_path) memcpy((char *)existing->path, entry->path, strlen(entry->path)); } index_entry_free(entry); *entry_ptr = entry = existing; } else { /* if replace is not requested or no existing entry exists, insert * at the sorted position. (Since we re-sort after each insert to * check for dups, this is actually cheaper in the long run.) */ error = git_vector_insert_sorted(&index->entries, entry, index_no_dups); if (error == 0) { INSERT_IN_MAP(index, entry, &error); } } if (error < 0) { index_entry_free(*entry_ptr); *entry_ptr = NULL; } return error; } static int index_conflict_to_reuc(git_index *index, const char *path) { const git_index_entry *conflict_entries[3]; int ancestor_mode, our_mode, their_mode; git_oid const *ancestor_oid, *our_oid, *their_oid; int ret; if ((ret = git_index_conflict_get(&conflict_entries[0], &conflict_entries[1], &conflict_entries[2], index, path)) < 0) return ret; ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode; our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode; their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode; ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id; our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id; their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id; if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) >= 0) ret = git_index_conflict_remove(index, path); return ret; } GIT_INLINE(bool) is_file_or_link(const int filemode) { return (filemode == GIT_FILEMODE_BLOB || filemode == GIT_FILEMODE_BLOB_EXECUTABLE || filemode == GIT_FILEMODE_LINK); } GIT_INLINE(bool) valid_filemode(const int filemode) { return (is_file_or_link(filemode) || filemode == GIT_FILEMODE_COMMIT); } int git_index_add_frombuffer( git_index *index, const git_index_entry *source_entry, const void *buffer, size_t len) { git_index_entry *entry = NULL; int error = 0; git_oid id; assert(index && source_entry->path); if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (!is_file_or_link(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid filemode"); return -1; } if (index_entry_dup(&entry, index, source_entry) < 0) return -1; error = git_blob_create_frombuffer(&id, INDEX_OWNER(index), buffer, len); if (error < 0) { index_entry_free(entry); return error; } git_oid_cpy(&entry->id, &id); entry->file_size = len; if ((error = index_insert(index, &entry, 1, true, true, true)) < 0) return error; /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((error = index_conflict_to_reuc(index, entry->path)) < 0 && error != GIT_ENOTFOUND) return error; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } static int add_repo_as_submodule(git_index_entry **out, git_index *index, const char *path) { git_repository *sub; git_buf abspath = GIT_BUF_INIT; git_repository *repo = INDEX_OWNER(index); git_reference *head; git_index_entry *entry; struct stat st; int error; if (index_entry_create(&entry, INDEX_OWNER(index), path, true) < 0) return -1; if ((error = git_buf_joinpath(&abspath, git_repository_workdir(repo), path)) < 0) return error; if ((error = p_stat(abspath.ptr, &st)) < 0) { giterr_set(GITERR_OS, "failed to stat repository dir"); return -1; } git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); if ((error = git_repository_open(&sub, abspath.ptr)) < 0) return error; if ((error = git_repository_head(&head, sub)) < 0) return error; git_oid_cpy(&entry->id, git_reference_target(head)); entry->mode = GIT_FILEMODE_COMMIT; git_reference_free(head); git_repository_free(sub); git_buf_free(&abspath); *out = entry; return 0; } int git_index_add_bypath(git_index *index, const char *path) { git_index_entry *entry = NULL; int ret; assert(index && path); if ((ret = index_entry_init(&entry, index, path)) == 0) ret = index_insert(index, &entry, 1, false, false, true); /* If we were given a directory, let's see if it's a submodule */ if (ret < 0 && ret != GIT_EDIRECTORY) return ret; if (ret == GIT_EDIRECTORY) { git_submodule *sm; git_error_state err; giterr_state_capture(&err, ret); ret = git_submodule_lookup(&sm, INDEX_OWNER(index), path); if (ret == GIT_ENOTFOUND) return giterr_state_restore(&err); giterr_state_free(&err); /* * EEXISTS means that there is a repository at that path, but it's not known * as a submodule. We add its HEAD as an entry and don't register it. */ if (ret == GIT_EEXISTS) { if ((ret = add_repo_as_submodule(&entry, index, path)) < 0) return ret; if ((ret = index_insert(index, &entry, 1, false, false, true)) < 0) return ret; } else if (ret < 0) { return ret; } else { ret = git_submodule_add_to_index(sm, false); git_submodule_free(sm); return ret; } } /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove_bypath(git_index *index, const char *path) { int ret; assert(index && path); if (((ret = git_index_remove(index, path, 0)) < 0 && ret != GIT_ENOTFOUND) || ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND)) return ret; if (ret == GIT_ENOTFOUND) giterr_clear(); return 0; } int git_index__fill(git_index *index, const git_vector *source_entries) { const git_index_entry *source_entry = NULL; size_t i; int ret = 0; assert(index); if (!source_entries->length) return 0; git_vector_size_hint(&index->entries, source_entries->length); git_idxmap_resize(index->entries_map, (khint_t)(source_entries->length * 1.3)); git_vector_foreach(source_entries, i, source_entry) { git_index_entry *entry = NULL; if ((ret = index_entry_dup(&entry, index, source_entry)) < 0) break; index_entry_adjust_namemask(entry, ((struct entry_internal *)entry)->pathlen); entry->flags_extended |= GIT_IDXENTRY_UPTODATE; entry->mode = git_index__create_mode(entry->mode); if ((ret = git_vector_insert(&index->entries, entry)) < 0) break; INSERT_IN_MAP(index, entry, &ret); if (ret < 0) break; } if (!ret) git_vector_sort(&index->entries); return ret; } int git_index_add(git_index *index, const git_index_entry *source_entry) { git_index_entry *entry = NULL; int ret; assert(index && source_entry && source_entry->path); if (!valid_filemode(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid entry mode"); return -1; } if ((ret = index_entry_dup(&entry, index, source_entry)) < 0 || (ret = index_insert(index, &entry, 1, true, true, false)) < 0) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove(git_index *index, const char *path, int stage) { int error; size_t position; git_index_entry remove_key = {{ 0 }}; remove_key.path = path; GIT_IDXENTRY_STAGE_SET(&remove_key, stage); DELETE_IN_MAP(index, &remove_key); if (index_find(&position, index, path, 0, stage) < 0) { giterr_set( GITERR_INDEX, "index does not contain %s at stage %d", path, stage); error = GIT_ENOTFOUND; } else { error = index_remove_entry(index, position); } return error; } int git_index_remove_directory(git_index *index, const char *dir, int stage) { git_buf pfx = GIT_BUF_INIT; int error = 0; size_t pos; git_index_entry *entry; if (!(error = git_buf_sets(&pfx, dir)) && !(error = git_path_to_dir(&pfx))) index_find(&pos, index, pfx.ptr, pfx.size, GIT_INDEX_STAGE_ANY); while (!error) { entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, pfx.ptr) != 0) break; if (GIT_IDXENTRY_STAGE(entry) != stage) { ++pos; continue; } error = index_remove_entry(index, pos); /* removed entry at 'pos' so we don't need to increment */ } git_buf_free(&pfx); return error; } int git_index_find_prefix(size_t *at_pos, git_index *index, const char *prefix) { int error = 0; size_t pos; const git_index_entry *entry; index_find(&pos, index, prefix, strlen(prefix), GIT_INDEX_STAGE_ANY); entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, prefix) != 0) error = GIT_ENOTFOUND; if (!error && at_pos) *at_pos = pos; return error; } int git_index__find_pos( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { assert(index && path); return index_find(out, index, path, path_len, stage); } int git_index_find(size_t *at_pos, git_index *index, const char *path) { size_t pos; assert(index && path); if (git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, path) < 0) { giterr_set(GITERR_INDEX, "index does not contain %s", path); return GIT_ENOTFOUND; } /* Since our binary search only looked at path, we may be in the * middle of a list of stages. */ for (; pos > 0; --pos) { const git_index_entry *prev = git_vector_get(&index->entries, pos - 1); if (index->entries_cmp_path(prev->path, path) != 0) break; } if (at_pos) *at_pos = pos; return 0; } int git_index_conflict_add(git_index *index, const git_index_entry *ancestor_entry, const git_index_entry *our_entry, const git_index_entry *their_entry) { git_index_entry *entries[3] = { 0 }; unsigned short i; int ret = 0; assert (index); if ((ancestor_entry && (ret = index_entry_dup(&entries[0], index, ancestor_entry)) < 0) || (our_entry && (ret = index_entry_dup(&entries[1], index, our_entry)) < 0) || (their_entry && (ret = index_entry_dup(&entries[2], index, their_entry)) < 0)) goto on_error; /* Validate entries */ for (i = 0; i < 3; i++) { if (entries[i] && !valid_filemode(entries[i]->mode)) { giterr_set(GITERR_INDEX, "invalid filemode for stage %d entry", i + 1); return -1; } } /* Remove existing index entries for each path */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; if ((ret = git_index_remove(index, entries[i]->path, 0)) != 0) { if (ret != GIT_ENOTFOUND) goto on_error; giterr_clear(); ret = 0; } } /* Add the conflict entries */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; /* Make sure stage is correct */ GIT_IDXENTRY_STAGE_SET(entries[i], i + 1); if ((ret = index_insert(index, &entries[i], 1, true, true, false)) < 0) goto on_error; entries[i] = NULL; /* don't free if later entry fails */ } return 0; on_error: for (i = 0; i < 3; i++) { if (entries[i] != NULL) index_entry_free(entries[i]); } return ret; } static int index_conflict__get_byindex( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, size_t n) { const git_index_entry *conflict_entry; const char *path = NULL; size_t count; int stage, len = 0; assert(ancestor_out && our_out && their_out && index); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; for (count = git_index_entrycount(index); n < count; ++n) { conflict_entry = git_vector_get(&index->entries, n); if (path && index->entries_cmp_path(conflict_entry->path, path) != 0) break; stage = GIT_IDXENTRY_STAGE(conflict_entry); path = conflict_entry->path; switch (stage) { case 3: *their_out = conflict_entry; len++; break; case 2: *our_out = conflict_entry; len++; break; case 1: *ancestor_out = conflict_entry; len++; break; default: break; }; } return len; } int git_index_conflict_get( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, const char *path) { size_t pos; int len = 0; assert(ancestor_out && our_out && their_out && index && path); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; if (git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, index, pos)) < 0) return len; else if (len == 0) return GIT_ENOTFOUND; return 0; } static int index_conflict_remove(git_index *index, const char *path) { size_t pos = 0; git_index_entry *conflict_entry; int error = 0; if (path != NULL && git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; while ((conflict_entry = git_vector_get(&index->entries, pos)) != NULL) { if (path != NULL && index->entries_cmp_path(conflict_entry->path, path) != 0) break; if (GIT_IDXENTRY_STAGE(conflict_entry) == 0) { pos++; continue; } if ((error = index_remove_entry(index, pos)) < 0) break; } return error; } int git_index_conflict_remove(git_index *index, const char *path) { assert(index && path); return index_conflict_remove(index, path); } int git_index_conflict_cleanup(git_index *index) { assert(index); return index_conflict_remove(index, NULL); } int git_index_has_conflicts(const git_index *index) { size_t i; git_index_entry *entry; assert(index); git_vector_foreach(&index->entries, i, entry) { if (GIT_IDXENTRY_STAGE(entry) > 0) return 1; } return 0; } int git_index_conflict_iterator_new( git_index_conflict_iterator **iterator_out, git_index *index) { git_index_conflict_iterator *it = NULL; assert(iterator_out && index); it = git__calloc(1, sizeof(git_index_conflict_iterator)); GITERR_CHECK_ALLOC(it); it->index = index; *iterator_out = it; return 0; } int git_index_conflict_next( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index_conflict_iterator *iterator) { const git_index_entry *entry; int len; assert(ancestor_out && our_out && their_out && iterator); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; while (iterator->cur < iterator->index->entries.length) { entry = git_index_get_byindex(iterator->index, iterator->cur); if (git_index_entry_is_conflict(entry)) { if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, iterator->index, iterator->cur)) < 0) return len; iterator->cur += len; return 0; } iterator->cur++; } return GIT_ITEROVER; } void git_index_conflict_iterator_free(git_index_conflict_iterator *iterator) { if (iterator == NULL) return; git__free(iterator); } size_t git_index_name_entrycount(git_index *index) { assert(index); return index->names.length; } const git_index_name_entry *git_index_name_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->names); return git_vector_get(&index->names, n); } static void index_name_entry_free(git_index_name_entry *ne) { if (!ne) return; git__free(ne->ancestor); git__free(ne->ours); git__free(ne->theirs); git__free(ne); } int git_index_name_add(git_index *index, const char *ancestor, const char *ours, const char *theirs) { git_index_name_entry *conflict_name; assert((ancestor && ours) || (ancestor && theirs) || (ours && theirs)); conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); if ((ancestor && !(conflict_name->ancestor = git__strdup(ancestor))) || (ours && !(conflict_name->ours = git__strdup(ours))) || (theirs && !(conflict_name->theirs = git__strdup(theirs))) || git_vector_insert(&index->names, conflict_name) < 0) { index_name_entry_free(conflict_name); return -1; } return 0; } void git_index_name_clear(git_index *index) { size_t i; git_index_name_entry *conflict_name; assert(index); git_vector_foreach(&index->names, i, conflict_name) index_name_entry_free(conflict_name); git_vector_clear(&index->names); } size_t git_index_reuc_entrycount(git_index *index) { assert(index); return index->reuc.length; } static int index_reuc_on_dup(void **old, void *new) { index_entry_reuc_free(*old); *old = new; return GIT_EEXISTS; } static int index_reuc_insert( git_index *index, git_index_reuc_entry *reuc) { int res; assert(index && reuc && reuc->path != NULL); assert(git_vector_is_sorted(&index->reuc)); res = git_vector_insert_sorted(&index->reuc, reuc, &index_reuc_on_dup); return res == GIT_EEXISTS ? 0 : res; } int git_index_reuc_add(git_index *index, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; int error = 0; assert(index && path); if ((error = index_entry_reuc_init(&reuc, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) < 0 || (error = index_reuc_insert(index, reuc)) < 0) index_entry_reuc_free(reuc); return error; } int git_index_reuc_find(size_t *at_pos, git_index *index, const char *path) { return git_vector_bsearch2(at_pos, &index->reuc, index->reuc_search, path); } const git_index_reuc_entry *git_index_reuc_get_bypath( git_index *index, const char *path) { size_t pos; assert(index && path); if (!index->reuc.length) return NULL; assert(git_vector_is_sorted(&index->reuc)); if (git_index_reuc_find(&pos, index, path) < 0) return NULL; return git_vector_get(&index->reuc, pos); } const git_index_reuc_entry *git_index_reuc_get_byindex( git_index *index, size_t n) { assert(index); assert(git_vector_is_sorted(&index->reuc)); return git_vector_get(&index->reuc, n); } int git_index_reuc_remove(git_index *index, size_t position) { int error; git_index_reuc_entry *reuc; assert(git_vector_is_sorted(&index->reuc)); reuc = git_vector_get(&index->reuc, position); error = git_vector_remove(&index->reuc, position); if (!error) index_entry_reuc_free(reuc); return error; } void git_index_reuc_clear(git_index *index) { size_t i; assert(index); for (i = 0; i < index->reuc.length; ++i) index_entry_reuc_free(git__swap(index->reuc.contents[i], NULL)); git_vector_clear(&index->reuc); } static int index_error_invalid(const char *message) { giterr_set(GITERR_INDEX, "invalid data in index - %s", message); return -1; } static int read_reuc(git_index *index, const char *buffer, size_t size) { const char *endptr; size_t len; int i; /* If called multiple times, the vector might already be initialized */ if (index->reuc._alloc_size == 0 && git_vector_init(&index->reuc, 16, reuc_cmp) < 0) return -1; while (size) { git_index_reuc_entry *lost; len = p_strnlen(buffer, size) + 1; if (size <= len) return index_error_invalid("reading reuc entries"); lost = reuc_entry_alloc(buffer); GITERR_CHECK_ALLOC(lost); size -= len; buffer += len; /* read 3 ASCII octal numbers for stage entries */ for (i = 0; i < 3; i++) { int64_t tmp; if (git__strtol64(&tmp, buffer, &endptr, 8) < 0 || !endptr || endptr == buffer || *endptr || tmp < 0 || tmp > UINT32_MAX) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } lost->mode[i] = (uint32_t)tmp; len = (endptr + 1) - buffer; if (size <= len) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } size -= len; buffer += len; } /* read up to 3 OIDs for stage entries */ for (i = 0; i < 3; i++) { if (!lost->mode[i]) continue; if (size < 20) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry oid"); } git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer); size -= 20; buffer += 20; } /* entry was read successfully - insert into reuc vector */ if (git_vector_insert(&index->reuc, lost) < 0) return -1; } /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->reuc, true); return 0; } static int read_conflict_names(git_index *index, const char *buffer, size_t size) { size_t len; /* This gets called multiple times, the vector might already be initialized */ if (index->names._alloc_size == 0 && git_vector_init(&index->names, 16, conflict_name_cmp) < 0) return -1; #define read_conflict_name(ptr) \ len = p_strnlen(buffer, size) + 1; \ if (size < len) { \ index_error_invalid("reading conflict name entries"); \ goto out_err; \ } \ if (len == 1) \ ptr = NULL; \ else { \ ptr = git__malloc(len); \ GITERR_CHECK_ALLOC(ptr); \ memcpy(ptr, buffer, len); \ } \ \ buffer += len; \ size -= len; while (size) { git_index_name_entry *conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); read_conflict_name(conflict_name->ancestor); read_conflict_name(conflict_name->ours); read_conflict_name(conflict_name->theirs); if (git_vector_insert(&index->names, conflict_name) < 0) goto out_err; continue; out_err: git__free(conflict_name->ancestor); git__free(conflict_name->ours); git__free(conflict_name->theirs); git__free(conflict_name); return -1; } #undef read_conflict_name /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->names, true); return 0; } static size_t index_entry_size(size_t path_len, size_t varint_len, uint32_t flags) { if (varint_len) { if (flags & GIT_IDXENTRY_EXTENDED) return offsetof(struct entry_long, path) + path_len + 1 + varint_len; else return offsetof(struct entry_short, path) + path_len + 1 + varint_len; } else { #define entry_size(type,len) ((offsetof(type, path) + (len) + 8) & ~7) if (flags & GIT_IDXENTRY_EXTENDED) return entry_size(struct entry_long, path_len); else return entry_size(struct entry_short, path_len); #undef entry_size } } static size_t read_entry( git_index_entry **out, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return 0; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return 0; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return 0; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return 0; } git__free(tmp_path); return entry_size; } static int read_header(struct index_header *dest, const void *buffer) { const struct index_header *source = buffer; dest->signature = ntohl(source->signature); if (dest->signature != INDEX_HEADER_SIG) return index_error_invalid("incorrect header signature"); dest->version = ntohl(source->version); if (dest->version < INDEX_VERSION_NUMBER_LB || dest->version > INDEX_VERSION_NUMBER_UB) return index_error_invalid("incorrect header version"); dest->entry_count = ntohl(source->entry_count); return 0; } static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size) { struct index_extension dest; size_t total_size; /* buffer is not guaranteed to be aligned */ memcpy(&dest, buffer, sizeof(struct index_extension)); dest.extension_size = ntohl(dest.extension_size); total_size = dest.extension_size + sizeof(struct index_extension); if (dest.extension_size > total_size || buffer_size < total_size || buffer_size - total_size < INDEX_FOOTER_SIZE) return 0; /* optional extension */ if (dest.signature[0] >= 'A' && dest.signature[0] <= 'Z') { /* tree cache */ if (memcmp(dest.signature, INDEX_EXT_TREECACHE_SIG, 4) == 0) { if (git_tree_cache_read(&index->tree, buffer + 8, dest.extension_size, &index->tree_pool) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_UNMERGED_SIG, 4) == 0) { if (read_reuc(index, buffer + 8, dest.extension_size) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4) == 0) { if (read_conflict_names(index, buffer + 8, dest.extension_size) < 0) return 0; } /* else, unsupported extension. We cannot parse this, but we can skip * it by returning `total_size */ } else { /* we cannot handle non-ignorable extensions; * in fact they aren't even defined in the standard */ return 0; } return total_size; } static int parse_index(git_index *index, const char *buffer, size_t buffer_size) { int error = 0; unsigned int i; struct index_header header = { 0 }; git_oid checksum_calculated, checksum_expected; const char *last = NULL; const char *empty = ""; #define seek_forward(_increase) { \ if (_increase >= buffer_size) { \ error = index_error_invalid("ran out of data while parsing"); \ goto done; } \ buffer += _increase; \ buffer_size -= _increase;\ } if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE) return index_error_invalid("insufficient buffer space"); /* Precalculate the SHA1 of the files's contents -- we'll match it to * the provided SHA1 in the footer */ git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE); /* Parse header */ if ((error = read_header(&header, buffer)) < 0) return error; index->version = header.version; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = empty; seek_forward(INDEX_HEADER_SIZE); assert(!index->entries.length); if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count); else git_idxmap_resize(index->entries_map, header.entry_count); /* Parse all the entries */ for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) { git_index_entry *entry = NULL; size_t entry_size = read_entry(&entry, index, buffer, buffer_size, last); /* 0 bytes read means an object corruption */ if (entry_size == 0) { error = index_error_invalid("invalid entry"); goto done; } if ((error = git_vector_insert(&index->entries, entry)) < 0) { index_entry_free(entry); goto done; } INSERT_IN_MAP(index, entry, &error); if (error < 0) { index_entry_free(entry); goto done; } error = 0; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; seek_forward(entry_size); } if (i != header.entry_count) { error = index_error_invalid("header entries changed while parsing"); goto done; } /* There's still space for some extensions! */ while (buffer_size > INDEX_FOOTER_SIZE) { size_t extension_size; extension_size = read_extension(index, buffer, buffer_size); /* see if we have read any bytes from the extension */ if (extension_size == 0) { error = index_error_invalid("extension is truncated"); goto done; } seek_forward(extension_size); } if (buffer_size != INDEX_FOOTER_SIZE) { error = index_error_invalid( "buffer size does not match index footer size"); goto done; } /* 160-bit SHA-1 over the content of the index file before this checksum. */ git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer); if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) { error = index_error_invalid( "calculated checksum does not match expected"); goto done; } git_oid_cpy(&index->checksum, &checksum_calculated); #undef seek_forward /* Entries are stored case-sensitively on disk, so re-sort now if * in-memory index is supposed to be case-insensitive */ git_vector_set_sorted(&index->entries, !index->ignore_case); git_vector_sort(&index->entries); done: return error; } static bool is_index_extended(git_index *index) { size_t i, extended; git_index_entry *entry; extended = 0; git_vector_foreach(&index->entries, i, entry) { entry->flags &= ~GIT_IDXENTRY_EXTENDED; if (entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS) { extended++; entry->flags |= GIT_IDXENTRY_EXTENDED; } } return (extended > 0); } static int write_disk_entry(git_filebuf *file, git_index_entry *entry, const char *last) { void *mem = NULL; struct entry_short *ondisk; size_t path_len, disk_size; int varint_len = 0; char *path; const char *path_start = entry->path; size_t same_len = 0; path_len = ((struct entry_internal *)entry)->pathlen; if (last) { const char *last_c = last; while (*path_start == *last_c) { if (!*path_start || !*last_c) break; ++path_start; ++last_c; ++same_len; } path_len -= same_len; varint_len = git_encode_varint(NULL, 0, same_len); } disk_size = index_entry_size(path_len, varint_len, entry->flags); if (git_filebuf_reserve(file, &mem, disk_size) < 0) return -1; ondisk = (struct entry_short *)mem; memset(ondisk, 0x0, disk_size); /** * Yes, we have to truncate. * * The on-disk format for Index entries clearly defines * the time and size fields to be 4 bytes each -- so even if * we store these values with 8 bytes on-memory, they must * be truncated to 4 bytes before writing to disk. * * In 2038 I will be either too dead or too rich to care about this */ ondisk->ctime.seconds = htonl((uint32_t)entry->ctime.seconds); ondisk->mtime.seconds = htonl((uint32_t)entry->mtime.seconds); ondisk->ctime.nanoseconds = htonl(entry->ctime.nanoseconds); ondisk->mtime.nanoseconds = htonl(entry->mtime.nanoseconds); ondisk->dev = htonl(entry->dev); ondisk->ino = htonl(entry->ino); ondisk->mode = htonl(entry->mode); ondisk->uid = htonl(entry->uid); ondisk->gid = htonl(entry->gid); ondisk->file_size = htonl((uint32_t)entry->file_size); git_oid_cpy(&ondisk->oid, &entry->id); ondisk->flags = htons(entry->flags); if (entry->flags & GIT_IDXENTRY_EXTENDED) { struct entry_long *ondisk_ext; ondisk_ext = (struct entry_long *)ondisk; ondisk_ext->flags_extended = htons(entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); path = ondisk_ext->path; disk_size -= offsetof(struct entry_long, path); } else { path = ondisk->path; disk_size -= offsetof(struct entry_short, path); } if (last) { varint_len = git_encode_varint((unsigned char *) path, disk_size, same_len); assert(varint_len > 0); path += varint_len; disk_size -= varint_len; /* * If using path compression, we are not allowed * to have additional trailing NULs. */ assert(disk_size == path_len + 1); } else { /* * If no path compression is used, we do have * NULs as padding. As such, simply assert that * we have enough space left to write the path. */ assert(disk_size > path_len); } memcpy(path, path_start, path_len + 1); return 0; } static int write_entries(git_index *index, git_filebuf *file) { int error = 0; size_t i; git_vector case_sorted, *entries; git_index_entry *entry; const char *last = NULL; /* If index->entries is sorted case-insensitively, then we need * to re-sort it case-sensitively before writing */ if (index->ignore_case) { git_vector_dup(&case_sorted, &index->entries, git_index_entry_cmp); git_vector_sort(&case_sorted); entries = &case_sorted; } else { entries = &index->entries; } if (index->version >= INDEX_VERSION_NUMBER_COMP) last = ""; git_vector_foreach(entries, i, entry) { if ((error = write_disk_entry(file, entry, last)) < 0) break; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; } if (index->ignore_case) git_vector_free(&case_sorted); return error; } static int write_extension(git_filebuf *file, struct index_extension *header, git_buf *data) { struct index_extension ondisk; memset(&ondisk, 0x0, sizeof(struct index_extension)); memcpy(&ondisk, header, 4); ondisk.extension_size = htonl(header->extension_size); git_filebuf_write(file, &ondisk, sizeof(struct index_extension)); return git_filebuf_write(file, data->ptr, data->size); } static int create_name_extension_data(git_buf *name_buf, git_index_name_entry *conflict_name) { int error = 0; if (conflict_name->ancestor == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ancestor, strlen(conflict_name->ancestor) + 1); if (error != 0) goto on_error; if (conflict_name->ours == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ours, strlen(conflict_name->ours) + 1); if (error != 0) goto on_error; if (conflict_name->theirs == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->theirs, strlen(conflict_name->theirs) + 1); on_error: return error; } static int write_name_extension(git_index *index, git_filebuf *file) { git_buf name_buf = GIT_BUF_INIT; git_vector *out = &index->names; git_index_name_entry *conflict_name; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, conflict_name) { if ((error = create_name_extension_data(&name_buf, conflict_name)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4); extension.extension_size = (uint32_t)name_buf.size; error = write_extension(file, &extension, &name_buf); git_buf_free(&name_buf); done: return error; } static int create_reuc_extension_data(git_buf *reuc_buf, git_index_reuc_entry *reuc) { int i; int error = 0; if ((error = git_buf_put(reuc_buf, reuc->path, strlen(reuc->path) + 1)) < 0) return error; for (i = 0; i < 3; i++) { if ((error = git_buf_printf(reuc_buf, "%o", reuc->mode[i])) < 0 || (error = git_buf_put(reuc_buf, "\0", 1)) < 0) return error; } for (i = 0; i < 3; i++) { if (reuc->mode[i] && (error = git_buf_put(reuc_buf, (char *)&reuc->oid[i].id, GIT_OID_RAWSZ)) < 0) return error; } return 0; } static int write_reuc_extension(git_index *index, git_filebuf *file) { git_buf reuc_buf = GIT_BUF_INIT; git_vector *out = &index->reuc; git_index_reuc_entry *reuc; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, reuc) { if ((error = create_reuc_extension_data(&reuc_buf, reuc)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_UNMERGED_SIG, 4); extension.extension_size = (uint32_t)reuc_buf.size; error = write_extension(file, &extension, &reuc_buf); git_buf_free(&reuc_buf); done: return error; } static int write_tree_extension(git_index *index, git_filebuf *file) { struct index_extension extension; git_buf buf = GIT_BUF_INIT; int error; if (index->tree == NULL) return 0; if ((error = git_tree_cache_write(&buf, index->tree)) < 0) return error; memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_TREECACHE_SIG, 4); extension.extension_size = (uint32_t)buf.size; error = write_extension(file, &extension, &buf); git_buf_free(&buf); return error; } static void clear_uptodate(git_index *index) { git_index_entry *entry; size_t i; git_vector_foreach(&index->entries, i, entry) entry->flags_extended &= ~GIT_IDXENTRY_UPTODATE; } static int write_index(git_oid *checksum, git_index *index, git_filebuf *file) { git_oid hash_final; struct index_header header; bool is_extended; uint32_t index_version_number; assert(index && file); if (index->version <= INDEX_VERSION_NUMBER_EXT) { is_extended = is_index_extended(index); index_version_number = is_extended ? INDEX_VERSION_NUMBER_EXT : INDEX_VERSION_NUMBER_LB; } else { index_version_number = index->version; } header.signature = htonl(INDEX_HEADER_SIG); header.version = htonl(index_version_number); header.entry_count = htonl((uint32_t)index->entries.length); if (git_filebuf_write(file, &header, sizeof(struct index_header)) < 0) return -1; if (write_entries(index, file) < 0) return -1; /* write the tree cache extension */ if (index->tree != NULL && write_tree_extension(index, file) < 0) return -1; /* write the rename conflict extension */ if (index->names.length > 0 && write_name_extension(index, file) < 0) return -1; /* write the reuc extension */ if (index->reuc.length > 0 && write_reuc_extension(index, file) < 0) return -1; /* get out the hash for all the contents we've appended to the file */ git_filebuf_hash(&hash_final, file); git_oid_cpy(checksum, &hash_final); /* write it at the end of the file */ if (git_filebuf_write(file, hash_final.id, GIT_OID_RAWSZ) < 0) return -1; /* file entries are no longer up to date */ clear_uptodate(index); return 0; } int git_index_entry_stage(const git_index_entry *entry) { return GIT_IDXENTRY_STAGE(entry); } int git_index_entry_is_conflict(const git_index_entry *entry) { return (GIT_IDXENTRY_STAGE(entry) > 0); } typedef struct read_tree_data { git_index *index; git_vector *old_entries; git_vector *new_entries; git_vector_cmp entry_cmp; git_tree_cache *tree; } read_tree_data; static int read_tree_cb( const char *root, const git_tree_entry *tentry, void *payload) { read_tree_data *data = payload; git_index_entry *entry = NULL, *old_entry; git_buf path = GIT_BUF_INIT; size_t pos; if (git_tree_entry__is_tree(tentry)) return 0; if (git_buf_joinpath(&path, root, tentry->filename) < 0) return -1; if (index_entry_create(&entry, INDEX_OWNER(data->index), path.ptr, false) < 0) return -1; entry->mode = tentry->attr; git_oid_cpy(&entry->id, git_tree_entry_id(tentry)); /* look for corresponding old entry and copy data to new entry */ if (data->old_entries != NULL && !index_find_in_entries( &pos, data->old_entries, data->entry_cmp, path.ptr, 0, 0) && (old_entry = git_vector_get(data->old_entries, pos)) != NULL && entry->mode == old_entry->mode && git_oid_equal(&entry->id, &old_entry->id)) { index_entry_cpy(entry, old_entry); entry->flags_extended = 0; } index_entry_adjust_namemask(entry, path.size); git_buf_free(&path); if (git_vector_insert(data->new_entries, entry) < 0) { index_entry_free(entry); return -1; } return 0; } int git_index_read_tree(git_index *index, const git_tree *tree) { int error = 0; git_vector entries = GIT_VECTOR_INIT; git_idxmap *entries_map; read_tree_data data; size_t i; git_index_entry *e; if (git_idxmap_alloc(&entries_map) < 0) return -1; git_vector_set_cmp(&entries, index->entries._cmp); /* match sort */ data.index = index; data.old_entries = &index->entries; data.new_entries = &entries; data.entry_cmp = index->entries_search; index->tree = NULL; git_pool_clear(&index->tree_pool); git_vector_sort(&index->entries); if ((error = git_tree_walk(tree, GIT_TREEWALK_POST, read_tree_cb, &data)) < 0) goto cleanup; if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) entries_map, entries.length); else git_idxmap_resize(entries_map, entries.length); git_vector_foreach(&entries, i, e) { INSERT_IN_MAP_EX(index, entries_map, e, &error); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry into map"); return error; } } error = 0; git_vector_sort(&entries); if ((error = git_index_clear(index)) < 0) { /* well, this isn't good */; } else { git_vector_swap(&entries, &index->entries); entries_map = git__swap(index->entries_map, entries_map); } cleanup: git_vector_free(&entries); git_idxmap_free(entries_map); if (error < 0) return error; error = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool); return error; } static int git_index_read_iterator( git_index *index, git_iterator *new_iterator, size_t new_length_hint) { git_vector new_entries = GIT_VECTOR_INIT, remove_entries = GIT_VECTOR_INIT; git_idxmap *new_entries_map = NULL; git_iterator *index_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; const git_index_entry *old_entry, *new_entry; git_index_entry *entry; size_t i; int error; assert((new_iterator->flags & GIT_ITERATOR_DONT_IGNORE_CASE)); if ((error = git_vector_init(&new_entries, new_length_hint, index->entries._cmp)) < 0 || (error = git_vector_init(&remove_entries, index->entries.length, NULL)) < 0 || (error = git_idxmap_alloc(&new_entries_map)) < 0) goto done; if (index->ignore_case && new_length_hint) git_idxmap_icase_resize((khash_t(idxicase) *) new_entries_map, new_length_hint); else if (new_length_hint) git_idxmap_resize(new_entries_map, new_length_hint); opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&index_iterator, git_index_owner(index), index, &opts)) < 0 || ((error = git_iterator_current(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) || ((error = git_iterator_current(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER)) goto done; while (true) { git_index_entry *dup_entry = NULL, *add_entry = NULL, *remove_entry = NULL; int diff; error = 0; if (old_entry && new_entry) diff = git_index_entry_cmp(old_entry, new_entry); else if (!old_entry && new_entry) diff = 1; else if (old_entry && !new_entry) diff = -1; else break; if (diff < 0) { remove_entry = (git_index_entry *)old_entry; } else if (diff > 0) { dup_entry = (git_index_entry *)new_entry; } else { /* Path and stage are equal, if the OID is equal, keep it to * keep the stat cache data. */ if (git_oid_equal(&old_entry->id, &new_entry->id) && old_entry->mode == new_entry->mode) { add_entry = (git_index_entry *)old_entry; } else { dup_entry = (git_index_entry *)new_entry; remove_entry = (git_index_entry *)old_entry; } } if (dup_entry) { if ((error = index_entry_dup_nocache(&add_entry, index, dup_entry)) < 0) goto done; index_entry_adjust_namemask(add_entry, ((struct entry_internal *)add_entry)->pathlen); } /* invalidate this path in the tree cache if this is new (to * invalidate the parent trees) */ if (dup_entry && !remove_entry && index->tree) git_tree_cache_invalidate_path(index->tree, dup_entry->path); if (add_entry) { if ((error = git_vector_insert(&new_entries, add_entry)) == 0) INSERT_IN_MAP_EX(index, new_entries_map, add_entry, &error); } if (remove_entry && error >= 0) error = git_vector_insert(&remove_entries, remove_entry); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry"); goto done; } if (diff <= 0) { if ((error = git_iterator_advance(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) goto done; } if (diff >= 0) { if ((error = git_iterator_advance(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER) goto done; } } git_index_name_clear(index); git_index_reuc_clear(index); git_vector_swap(&new_entries, &index->entries); new_entries_map = git__swap(index->entries_map, new_entries_map); git_vector_foreach(&remove_entries, i, entry) { if (index->tree) git_tree_cache_invalidate_path(index->tree, entry->path); index_entry_free(entry); } clear_uptodate(index); error = 0; done: git_idxmap_free(new_entries_map); git_vector_free(&new_entries); git_vector_free(&remove_entries); git_iterator_free(index_iterator); return error; } int git_index_read_index( git_index *index, const git_index *new_index) { git_iterator *new_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; int error; opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&new_iterator, git_index_owner(new_index), (git_index *)new_index, &opts)) < 0 || (error = git_index_read_iterator(index, new_iterator, new_index->entries.length)) < 0) goto done; done: git_iterator_free(new_iterator); return error; } git_repository *git_index_owner(const git_index *index) { return INDEX_OWNER(index); } enum { INDEX_ACTION_NONE = 0, INDEX_ACTION_UPDATE = 1, INDEX_ACTION_REMOVE = 2, INDEX_ACTION_ADDALL = 3, }; int git_index_add_all( git_index *index, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_repository *repo; git_iterator *wditer = NULL; git_pathspec ps; bool no_fnmatch = (flags & GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH) != 0; assert(index); repo = INDEX_OWNER(index); if ((error = git_repository__ensure_not_bare(repo, "index add all")) < 0) return error; if ((error = git_pathspec__init(&ps, paths)) < 0) return error; /* optionally check that pathspec doesn't mention any ignored files */ if ((flags & GIT_INDEX_ADD_CHECK_PATHSPEC) != 0 && (flags & GIT_INDEX_ADD_FORCE) == 0 && (error = git_ignore__check_pathspec_for_exact_ignores( repo, &ps.pathspec, no_fnmatch)) < 0) goto cleanup; error = index_apply_to_wd_diff(index, INDEX_ACTION_ADDALL, paths, flags, cb, payload); if (error) giterr_set_after_callback(error); cleanup: git_iterator_free(wditer); git_pathspec__clear(&ps); return error; } struct foreach_diff_data { git_index *index; const git_pathspec *pathspec; unsigned int flags; git_index_matched_path_cb cb; void *payload; }; static int apply_each_file(const git_diff_delta *delta, float progress, void *payload) { struct foreach_diff_data *data = payload; const char *match, *path; int error = 0; GIT_UNUSED(progress); path = delta->old_file.path; /* We only want those which match the pathspecs */ if (!git_pathspec__match( &data->pathspec->pathspec, path, false, (bool)data->index->ignore_case, &match, NULL)) return 0; if (data->cb) error = data->cb(path, match, data->payload); if (error > 0) /* skip this entry */ return 0; if (error < 0) /* actual error */ return error; /* If the workdir item does not exist, remove it from the index. */ if ((delta->new_file.flags & GIT_DIFF_FLAG_EXISTS) == 0) error = git_index_remove_bypath(data->index, path); else error = git_index_add_bypath(data->index, delta->new_file.path); return error; } static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_diff *diff; git_pathspec ps; git_repository *repo; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; struct foreach_diff_data data = { index, NULL, flags, cb, payload, }; assert(index); assert(action == INDEX_ACTION_UPDATE || action == INDEX_ACTION_ADDALL); repo = INDEX_OWNER(index); if (!repo) { return create_index_error(-1, "cannot run update; the index is not backed up by a repository."); } /* * We do the matching ourselves intead of passing the list to * diff because we want to tell the callback which one * matched, which we do not know if we ask diff to filter for us. */ if ((error = git_pathspec__init(&ps, paths)) < 0) return error; opts.flags = GIT_DIFF_INCLUDE_TYPECHANGE; if (action == INDEX_ACTION_ADDALL) { opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_RECURSE_UNTRACKED_DIRS; if (flags == GIT_INDEX_ADD_FORCE) opts.flags |= GIT_DIFF_INCLUDE_IGNORED; } if ((error = git_diff_index_to_workdir(&diff, repo, index, &opts)) < 0) goto cleanup; data.pathspec = &ps; error = git_diff_foreach(diff, apply_each_file, NULL, NULL, NULL, &data); git_diff_free(diff); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); cleanup: git_pathspec__clear(&ps); return error; } static int index_apply_to_all( git_index *index, int action, const git_strarray *paths, git_index_matched_path_cb cb, void *payload) { int error = 0; size_t i; git_pathspec ps; const char *match; git_buf path = GIT_BUF_INIT; assert(index); if ((error = git_pathspec__init(&ps, paths)) < 0) return error; git_vector_sort(&index->entries); for (i = 0; !error && i < index->entries.length; ++i) { git_index_entry *entry = git_vector_get(&index->entries, i); /* check if path actually matches */ if (!git_pathspec__match( &ps.pathspec, entry->path, false, (bool)index->ignore_case, &match, NULL)) continue; /* issue notification callback if requested */ if (cb && (error = cb(entry->path, match, payload)) != 0) { if (error > 0) { /* return > 0 means skip this one */ error = 0; continue; } if (error < 0) /* return < 0 means abort */ break; } /* index manipulation may alter entry, so don't depend on it */ if ((error = git_buf_sets(&path, entry->path)) < 0) break; switch (action) { case INDEX_ACTION_NONE: break; case INDEX_ACTION_UPDATE: error = git_index_add_bypath(index, path.ptr); if (error == GIT_ENOTFOUND) { giterr_clear(); error = git_index_remove_bypath(index, path.ptr); if (!error) /* back up foreach if we removed this */ i--; } break; case INDEX_ACTION_REMOVE: if (!(error = git_index_remove_bypath(index, path.ptr))) i--; /* back up foreach if we removed this */ break; default: giterr_set(GITERR_INVALID, "unknown index action %d", action); error = -1; break; } } git_buf_free(&path); git_pathspec__clear(&ps); return error; } int git_index_remove_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_all( index, INDEX_ACTION_REMOVE, pathspec, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_update_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_wd_diff(index, INDEX_ACTION_UPDATE, pathspec, 0, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_snapshot_new(git_vector *snap, git_index *index) { int error; GIT_REFCOUNT_INC(index); git_atomic_inc(&index->readers); git_vector_sort(&index->entries); error = git_vector_dup(snap, &index->entries, index->entries._cmp); if (error < 0) git_index_free(index); return error; } void git_index_snapshot_release(git_vector *snap, git_index *index) { git_vector_free(snap); git_atomic_dec(&index->readers); git_index_free(index); } int git_index_snapshot_find( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { return index_find_in_entries(out, entries, entry_srch, path, path_len, stage); } int git_indexwriter_init( git_indexwriter *writer, git_index *index) { int error; GIT_REFCOUNT_INC(index); writer->index = index; if (!index->index_file_path) return create_index_error(-1, "failed to write index: The index is in-memory only"); if ((error = git_filebuf_open( &writer->file, index->index_file_path, GIT_FILEBUF_HASH_CONTENTS, GIT_INDEX_FILE_MODE)) < 0) { if (error == GIT_ELOCKED) giterr_set(GITERR_INDEX, "the index is locked; this might be due to a concurrent or crashed process"); return error; } writer->should_write = 1; return 0; } int git_indexwriter_init_for_operation( git_indexwriter *writer, git_repository *repo, unsigned int *checkout_strategy) { git_index *index; int error; if ((error = git_repository_index__weakptr(&index, repo)) < 0 || (error = git_indexwriter_init(writer, index)) < 0) return error; writer->should_write = (*checkout_strategy & GIT_CHECKOUT_DONT_WRITE_INDEX) == 0; *checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX; return 0; } int git_indexwriter_commit(git_indexwriter *writer) { int error; git_oid checksum = {{ 0 }}; if (!writer->should_write) return 0; git_vector_sort(&writer->index->entries); git_vector_sort(&writer->index->reuc); if ((error = write_index(&checksum, writer->index, &writer->file)) < 0) { git_indexwriter_cleanup(writer); return error; } if ((error = git_filebuf_commit(&writer->file)) < 0) return error; if ((error = git_futils_filestamp_check( &writer->index->stamp, writer->index->index_file_path)) < 0) { giterr_set(GITERR_OS, "could not read index timestamp"); return -1; } writer->index->on_disk = 1; git_oid_cpy(&writer->index->checksum, &checksum); git_index_free(writer->index); writer->index = NULL; return 0; } void git_indexwriter_cleanup(git_indexwriter *writer) { git_filebuf_cleanup(&writer->file); git_index_free(writer->index); writer->index = NULL; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_666_0
crossvul-cpp_data_bad_3161_0
/* * net/dccp/input.c * * An implementation of the DCCP protocol * Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/dccp.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <net/sock.h> #include "ackvec.h" #include "ccid.h" #include "dccp.h" /* rate-limit for syncs in reply to sequence-invalid packets; RFC 4340, 7.5.4 */ int sysctl_dccp_sync_ratelimit __read_mostly = HZ / 8; static void dccp_enqueue_skb(struct sock *sk, struct sk_buff *skb) { __skb_pull(skb, dccp_hdr(skb)->dccph_doff * 4); __skb_queue_tail(&sk->sk_receive_queue, skb); skb_set_owner_r(skb, sk); sk->sk_data_ready(sk); } static void dccp_fin(struct sock *sk, struct sk_buff *skb) { /* * On receiving Close/CloseReq, both RD/WR shutdown are performed. * RFC 4340, 8.3 says that we MAY send further Data/DataAcks after * receiving the closing segment, but there is no guarantee that such * data will be processed at all. */ sk->sk_shutdown = SHUTDOWN_MASK; sock_set_flag(sk, SOCK_DONE); dccp_enqueue_skb(sk, skb); } static int dccp_rcv_close(struct sock *sk, struct sk_buff *skb) { int queued = 0; switch (sk->sk_state) { /* * We ignore Close when received in one of the following states: * - CLOSED (may be a late or duplicate packet) * - PASSIVE_CLOSEREQ (the peer has sent a CloseReq earlier) * - RESPOND (already handled by dccp_check_req) */ case DCCP_CLOSING: /* * Simultaneous-close: receiving a Close after sending one. This * can happen if both client and server perform active-close and * will result in an endless ping-pong of crossing and retrans- * mitted Close packets, which only terminates when one of the * nodes times out (min. 64 seconds). Quicker convergence can be * achieved when one of the nodes acts as tie-breaker. * This is ok as both ends are done with data transfer and each * end is just waiting for the other to acknowledge termination. */ if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT) break; /* fall through */ case DCCP_REQUESTING: case DCCP_ACTIVE_CLOSEREQ: dccp_send_reset(sk, DCCP_RESET_CODE_CLOSED); dccp_done(sk); break; case DCCP_OPEN: case DCCP_PARTOPEN: /* Give waiting application a chance to read pending data */ queued = 1; dccp_fin(sk, skb); dccp_set_state(sk, DCCP_PASSIVE_CLOSE); /* fall through */ case DCCP_PASSIVE_CLOSE: /* * Retransmitted Close: we have already enqueued the first one. */ sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); } return queued; } static int dccp_rcv_closereq(struct sock *sk, struct sk_buff *skb) { int queued = 0; /* * Step 7: Check for unexpected packet types * If (S.is_server and P.type == CloseReq) * Send Sync packet acknowledging P.seqno * Drop packet and return */ if (dccp_sk(sk)->dccps_role != DCCP_ROLE_CLIENT) { dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNC); return queued; } /* Step 13: process relevant Client states < CLOSEREQ */ switch (sk->sk_state) { case DCCP_REQUESTING: dccp_send_close(sk, 0); dccp_set_state(sk, DCCP_CLOSING); break; case DCCP_OPEN: case DCCP_PARTOPEN: /* Give waiting application a chance to read pending data */ queued = 1; dccp_fin(sk, skb); dccp_set_state(sk, DCCP_PASSIVE_CLOSEREQ); /* fall through */ case DCCP_PASSIVE_CLOSEREQ: sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); } return queued; } static u16 dccp_reset_code_convert(const u8 code) { const u16 error_code[] = { [DCCP_RESET_CODE_CLOSED] = 0, /* normal termination */ [DCCP_RESET_CODE_UNSPECIFIED] = 0, /* nothing known */ [DCCP_RESET_CODE_ABORTED] = ECONNRESET, [DCCP_RESET_CODE_NO_CONNECTION] = ECONNREFUSED, [DCCP_RESET_CODE_CONNECTION_REFUSED] = ECONNREFUSED, [DCCP_RESET_CODE_TOO_BUSY] = EUSERS, [DCCP_RESET_CODE_AGGRESSION_PENALTY] = EDQUOT, [DCCP_RESET_CODE_PACKET_ERROR] = ENOMSG, [DCCP_RESET_CODE_BAD_INIT_COOKIE] = EBADR, [DCCP_RESET_CODE_BAD_SERVICE_CODE] = EBADRQC, [DCCP_RESET_CODE_OPTION_ERROR] = EILSEQ, [DCCP_RESET_CODE_MANDATORY_ERROR] = EOPNOTSUPP, }; return code >= DCCP_MAX_RESET_CODES ? 0 : error_code[code]; } static void dccp_rcv_reset(struct sock *sk, struct sk_buff *skb) { u16 err = dccp_reset_code_convert(dccp_hdr_reset(skb)->dccph_reset_code); sk->sk_err = err; /* Queue the equivalent of TCP fin so that dccp_recvmsg exits the loop */ dccp_fin(sk, skb); if (err && !sock_flag(sk, SOCK_DEAD)) sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR); dccp_time_wait(sk, DCCP_TIME_WAIT, 0); } static void dccp_handle_ackvec_processing(struct sock *sk, struct sk_buff *skb) { struct dccp_ackvec *av = dccp_sk(sk)->dccps_hc_rx_ackvec; if (av == NULL) return; if (DCCP_SKB_CB(skb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ) dccp_ackvec_clear_state(av, DCCP_SKB_CB(skb)->dccpd_ack_seq); dccp_ackvec_input(av, skb); } static void dccp_deliver_input_to_ccids(struct sock *sk, struct sk_buff *skb) { const struct dccp_sock *dp = dccp_sk(sk); /* Don't deliver to RX CCID when node has shut down read end. */ if (!(sk->sk_shutdown & RCV_SHUTDOWN)) ccid_hc_rx_packet_recv(dp->dccps_hc_rx_ccid, sk, skb); /* * Until the TX queue has been drained, we can not honour SHUT_WR, since * we need received feedback as input to adjust congestion control. */ if (sk->sk_write_queue.qlen > 0 || !(sk->sk_shutdown & SEND_SHUTDOWN)) ccid_hc_tx_packet_recv(dp->dccps_hc_tx_ccid, sk, skb); } static int dccp_check_seqno(struct sock *sk, struct sk_buff *skb) { const struct dccp_hdr *dh = dccp_hdr(skb); struct dccp_sock *dp = dccp_sk(sk); u64 lswl, lawl, seqno = DCCP_SKB_CB(skb)->dccpd_seq, ackno = DCCP_SKB_CB(skb)->dccpd_ack_seq; /* * Step 5: Prepare sequence numbers for Sync * If P.type == Sync or P.type == SyncAck, * If S.AWL <= P.ackno <= S.AWH and P.seqno >= S.SWL, * / * P is valid, so update sequence number variables * accordingly. After this update, P will pass the tests * in Step 6. A SyncAck is generated if necessary in * Step 15 * / * Update S.GSR, S.SWL, S.SWH * Otherwise, * Drop packet and return */ if (dh->dccph_type == DCCP_PKT_SYNC || dh->dccph_type == DCCP_PKT_SYNCACK) { if (between48(ackno, dp->dccps_awl, dp->dccps_awh) && dccp_delta_seqno(dp->dccps_swl, seqno) >= 0) dccp_update_gsr(sk, seqno); else return -1; } /* * Step 6: Check sequence numbers * Let LSWL = S.SWL and LAWL = S.AWL * If P.type == CloseReq or P.type == Close or P.type == Reset, * LSWL := S.GSR + 1, LAWL := S.GAR * If LSWL <= P.seqno <= S.SWH * and (P.ackno does not exist or LAWL <= P.ackno <= S.AWH), * Update S.GSR, S.SWL, S.SWH * If P.type != Sync, * Update S.GAR */ lswl = dp->dccps_swl; lawl = dp->dccps_awl; if (dh->dccph_type == DCCP_PKT_CLOSEREQ || dh->dccph_type == DCCP_PKT_CLOSE || dh->dccph_type == DCCP_PKT_RESET) { lswl = ADD48(dp->dccps_gsr, 1); lawl = dp->dccps_gar; } if (between48(seqno, lswl, dp->dccps_swh) && (ackno == DCCP_PKT_WITHOUT_ACK_SEQ || between48(ackno, lawl, dp->dccps_awh))) { dccp_update_gsr(sk, seqno); if (dh->dccph_type != DCCP_PKT_SYNC && ackno != DCCP_PKT_WITHOUT_ACK_SEQ && after48(ackno, dp->dccps_gar)) dp->dccps_gar = ackno; } else { unsigned long now = jiffies; /* * Step 6: Check sequence numbers * Otherwise, * If P.type == Reset, * Send Sync packet acknowledging S.GSR * Otherwise, * Send Sync packet acknowledging P.seqno * Drop packet and return * * These Syncs are rate-limited as per RFC 4340, 7.5.4: * at most 1 / (dccp_sync_rate_limit * HZ) Syncs per second. */ if (time_before(now, (dp->dccps_rate_last + sysctl_dccp_sync_ratelimit))) return -1; DCCP_WARN("Step 6 failed for %s packet, " "(LSWL(%llu) <= P.seqno(%llu) <= S.SWH(%llu)) and " "(P.ackno %s or LAWL(%llu) <= P.ackno(%llu) <= S.AWH(%llu), " "sending SYNC...\n", dccp_packet_name(dh->dccph_type), (unsigned long long) lswl, (unsigned long long) seqno, (unsigned long long) dp->dccps_swh, (ackno == DCCP_PKT_WITHOUT_ACK_SEQ) ? "doesn't exist" : "exists", (unsigned long long) lawl, (unsigned long long) ackno, (unsigned long long) dp->dccps_awh); dp->dccps_rate_last = now; if (dh->dccph_type == DCCP_PKT_RESET) seqno = dp->dccps_gsr; dccp_send_sync(sk, seqno, DCCP_PKT_SYNC); return -1; } return 0; } static int __dccp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); switch (dccp_hdr(skb)->dccph_type) { case DCCP_PKT_DATAACK: case DCCP_PKT_DATA: /* * FIXME: schedule DATA_DROPPED (RFC 4340, 11.7.2) if and when * - sk_shutdown == RCV_SHUTDOWN, use Code 1, "Not Listening" * - sk_receive_queue is full, use Code 2, "Receive Buffer" */ dccp_enqueue_skb(sk, skb); return 0; case DCCP_PKT_ACK: goto discard; case DCCP_PKT_RESET: /* * Step 9: Process Reset * If P.type == Reset, * Tear down connection * S.state := TIMEWAIT * Set TIMEWAIT timer * Drop packet and return */ dccp_rcv_reset(sk, skb); return 0; case DCCP_PKT_CLOSEREQ: if (dccp_rcv_closereq(sk, skb)) return 0; goto discard; case DCCP_PKT_CLOSE: if (dccp_rcv_close(sk, skb)) return 0; goto discard; case DCCP_PKT_REQUEST: /* Step 7 * or (S.is_server and P.type == Response) * or (S.is_client and P.type == Request) * or (S.state >= OPEN and P.type == Request * and P.seqno >= S.OSR) * or (S.state >= OPEN and P.type == Response * and P.seqno >= S.OSR) * or (S.state == RESPOND and P.type == Data), * Send Sync packet acknowledging P.seqno * Drop packet and return */ if (dp->dccps_role != DCCP_ROLE_LISTEN) goto send_sync; goto check_seq; case DCCP_PKT_RESPONSE: if (dp->dccps_role != DCCP_ROLE_CLIENT) goto send_sync; check_seq: if (dccp_delta_seqno(dp->dccps_osr, DCCP_SKB_CB(skb)->dccpd_seq) >= 0) { send_sync: dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNC); } break; case DCCP_PKT_SYNC: dccp_send_sync(sk, DCCP_SKB_CB(skb)->dccpd_seq, DCCP_PKT_SYNCACK); /* * From RFC 4340, sec. 5.7 * * As with DCCP-Ack packets, DCCP-Sync and DCCP-SyncAck packets * MAY have non-zero-length application data areas, whose * contents receivers MUST ignore. */ goto discard; } DCCP_INC_STATS(DCCP_MIB_INERRS); discard: __kfree_skb(skb); return 0; } int dccp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { if (dccp_check_seqno(sk, skb)) goto discard; if (dccp_parse_options(sk, NULL, skb)) return 1; dccp_handle_ackvec_processing(sk, skb); dccp_deliver_input_to_ccids(sk, skb); return __dccp_rcv_established(sk, skb, dh, len); discard: __kfree_skb(skb); return 0; } EXPORT_SYMBOL_GPL(dccp_rcv_established); static int dccp_rcv_request_sent_state_process(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { /* * Step 4: Prepare sequence numbers in REQUEST * If S.state == REQUEST, * If (P.type == Response or P.type == Reset) * and S.AWL <= P.ackno <= S.AWH, * / * Set sequence number variables corresponding to the * other endpoint, so P will pass the tests in Step 6 * / * Set S.GSR, S.ISR, S.SWL, S.SWH * / * Response processing continues in Step 10; Reset * processing continues in Step 9 * / */ if (dh->dccph_type == DCCP_PKT_RESPONSE) { const struct inet_connection_sock *icsk = inet_csk(sk); struct dccp_sock *dp = dccp_sk(sk); long tstamp = dccp_timestamp(); if (!between48(DCCP_SKB_CB(skb)->dccpd_ack_seq, dp->dccps_awl, dp->dccps_awh)) { dccp_pr_debug("invalid ackno: S.AWL=%llu, " "P.ackno=%llu, S.AWH=%llu\n", (unsigned long long)dp->dccps_awl, (unsigned long long)DCCP_SKB_CB(skb)->dccpd_ack_seq, (unsigned long long)dp->dccps_awh); goto out_invalid_packet; } /* * If option processing (Step 8) failed, return 1 here so that * dccp_v4_do_rcv() sends a Reset. The Reset code depends on * the option type and is set in dccp_parse_options(). */ if (dccp_parse_options(sk, NULL, skb)) return 1; /* Obtain usec RTT sample from SYN exchange (used by TFRC). */ if (likely(dp->dccps_options_received.dccpor_timestamp_echo)) dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * (tstamp - dp->dccps_options_received.dccpor_timestamp_echo)); /* Stop the REQUEST timer */ inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS); WARN_ON(sk->sk_send_head == NULL); kfree_skb(sk->sk_send_head); sk->sk_send_head = NULL; /* * Set ISR, GSR from packet. ISS was set in dccp_v{4,6}_connect * and GSS in dccp_transmit_skb(). Setting AWL/AWH and SWL/SWH * is done as part of activating the feature values below, since * these settings depend on the local/remote Sequence Window * features, which were undefined or not confirmed until now. */ dp->dccps_gsr = dp->dccps_isr = DCCP_SKB_CB(skb)->dccpd_seq; dccp_sync_mss(sk, icsk->icsk_pmtu_cookie); /* * Step 10: Process REQUEST state (second part) * If S.state == REQUEST, * / * If we get here, P is a valid Response from the * server (see Step 4), and we should move to * PARTOPEN state. PARTOPEN means send an Ack, * don't send Data packets, retransmit Acks * periodically, and always include any Init Cookie * from the Response * / * S.state := PARTOPEN * Set PARTOPEN timer * Continue with S.state == PARTOPEN * / * Step 12 will send the Ack completing the * three-way handshake * / */ dccp_set_state(sk, DCCP_PARTOPEN); /* * If feature negotiation was successful, activate features now; * an activation failure means that this host could not activate * one ore more features (e.g. insufficient memory), which would * leave at least one feature in an undefined state. */ if (dccp_feat_activate_values(sk, &dp->dccps_featneg)) goto unable_to_proceed; /* Make sure socket is routed, for correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); } if (sk->sk_write_pending || icsk->icsk_ack.pingpong || icsk->icsk_accept_queue.rskq_defer_accept) { /* Save one ACK. Data will be ready after * several ticks, if write_pending is set. * * It may be deleted, but with this feature tcpdumps * look so _wonderfully_ clever, that I was not able * to stand against the temptation 8) --ANK */ /* * OK, in DCCP we can as well do a similar trick, its * even in the draft, but there is no need for us to * schedule an ack here, as dccp_sendmsg does this for * us, also stated in the draft. -acme */ __kfree_skb(skb); return 0; } dccp_send_ack(sk); return -1; } out_invalid_packet: /* dccp_v4_do_rcv will send a reset */ DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_PACKET_ERROR; return 1; unable_to_proceed: DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_ABORTED; /* * We mark this socket as no longer usable, so that the loop in * dccp_sendmsg() terminates and the application gets notified. */ dccp_set_state(sk, DCCP_CLOSED); sk->sk_err = ECOMM; return 1; } static int dccp_rcv_respond_partopen_state_process(struct sock *sk, struct sk_buff *skb, const struct dccp_hdr *dh, const unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); u32 sample = dp->dccps_options_received.dccpor_timestamp_echo; int queued = 0; switch (dh->dccph_type) { case DCCP_PKT_RESET: inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); break; case DCCP_PKT_DATA: if (sk->sk_state == DCCP_RESPOND) break; case DCCP_PKT_DATAACK: case DCCP_PKT_ACK: /* * FIXME: we should be resetting the PARTOPEN (DELACK) timer * here but only if we haven't used the DELACK timer for * something else, like sending a delayed ack for a TIMESTAMP * echo, etc, for now were not clearing it, sending an extra * ACK when there is nothing else to do in DELACK is not a big * deal after all. */ /* Stop the PARTOPEN timer */ if (sk->sk_state == DCCP_PARTOPEN) inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); /* Obtain usec RTT sample from SYN exchange (used by TFRC). */ if (likely(sample)) { long delta = dccp_timestamp() - sample; dp->dccps_syn_rtt = dccp_sample_rtt(sk, 10 * delta); } dp->dccps_osr = DCCP_SKB_CB(skb)->dccpd_seq; dccp_set_state(sk, DCCP_OPEN); if (dh->dccph_type == DCCP_PKT_DATAACK || dh->dccph_type == DCCP_PKT_DATA) { __dccp_rcv_established(sk, skb, dh, len); queued = 1; /* packet was queued (by __dccp_rcv_established) */ } break; } return queued; } int dccp_rcv_state_process(struct sock *sk, struct sk_buff *skb, struct dccp_hdr *dh, unsigned int len) { struct dccp_sock *dp = dccp_sk(sk); struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); const int old_state = sk->sk_state; int queued = 0; /* * Step 3: Process LISTEN state * * If S.state == LISTEN, * If P.type == Request or P contains a valid Init Cookie option, * (* Must scan the packet's options to check for Init * Cookies. Only Init Cookies are processed here, * however; other options are processed in Step 8. This * scan need only be performed if the endpoint uses Init * Cookies *) * (* Generate a new socket and switch to that socket *) * Set S := new socket for this port pair * S.state = RESPOND * Choose S.ISS (initial seqno) or set from Init Cookies * Initialize S.GAR := S.ISS * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init * Cookies Continue with S.state == RESPOND * (* A Response packet will be generated in Step 11 *) * Otherwise, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (sk->sk_state == DCCP_LISTEN) { if (dh->dccph_type == DCCP_PKT_REQUEST) { if (inet_csk(sk)->icsk_af_ops->conn_request(sk, skb) < 0) return 1; goto discard; } if (dh->dccph_type == DCCP_PKT_RESET) goto discard; /* Caller (dccp_v4_do_rcv) will send Reset */ dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } else if (sk->sk_state == DCCP_CLOSED) { dcb->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; return 1; } /* Step 6: Check sequence numbers (omitted in LISTEN/REQUEST state) */ if (sk->sk_state != DCCP_REQUESTING && dccp_check_seqno(sk, skb)) goto discard; /* * Step 7: Check for unexpected packet types * If (S.is_server and P.type == Response) * or (S.is_client and P.type == Request) * or (S.state == RESPOND and P.type == Data), * Send Sync packet acknowledging P.seqno * Drop packet and return */ if ((dp->dccps_role != DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_RESPONSE) || (dp->dccps_role == DCCP_ROLE_CLIENT && dh->dccph_type == DCCP_PKT_REQUEST) || (sk->sk_state == DCCP_RESPOND && dh->dccph_type == DCCP_PKT_DATA)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNC); goto discard; } /* Step 8: Process options */ if (dccp_parse_options(sk, NULL, skb)) return 1; /* * Step 9: Process Reset * If P.type == Reset, * Tear down connection * S.state := TIMEWAIT * Set TIMEWAIT timer * Drop packet and return */ if (dh->dccph_type == DCCP_PKT_RESET) { dccp_rcv_reset(sk, skb); return 0; } else if (dh->dccph_type == DCCP_PKT_CLOSEREQ) { /* Step 13 */ if (dccp_rcv_closereq(sk, skb)) return 0; goto discard; } else if (dh->dccph_type == DCCP_PKT_CLOSE) { /* Step 14 */ if (dccp_rcv_close(sk, skb)) return 0; goto discard; } switch (sk->sk_state) { case DCCP_REQUESTING: queued = dccp_rcv_request_sent_state_process(sk, skb, dh, len); if (queued >= 0) return queued; __kfree_skb(skb); return 0; case DCCP_PARTOPEN: /* Step 8: if using Ack Vectors, mark packet acknowledgeable */ dccp_handle_ackvec_processing(sk, skb); dccp_deliver_input_to_ccids(sk, skb); /* fall through */ case DCCP_RESPOND: queued = dccp_rcv_respond_partopen_state_process(sk, skb, dh, len); break; } if (dh->dccph_type == DCCP_PKT_ACK || dh->dccph_type == DCCP_PKT_DATAACK) { switch (old_state) { case DCCP_PARTOPEN: sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); break; } } else if (unlikely(dh->dccph_type == DCCP_PKT_SYNC)) { dccp_send_sync(sk, dcb->dccpd_seq, DCCP_PKT_SYNCACK); goto discard; } if (!queued) { discard: __kfree_skb(skb); } return 0; } EXPORT_SYMBOL_GPL(dccp_rcv_state_process); /** * dccp_sample_rtt - Validate and finalise computation of RTT sample * @delta: number of microseconds between packet and acknowledgment * * The routine is kept generic to work in different contexts. It should be * called immediately when the ACK used for the RTT sample arrives. */ u32 dccp_sample_rtt(struct sock *sk, long delta) { /* dccpor_elapsed_time is either zeroed out or set and > 0 */ delta -= dccp_sk(sk)->dccps_options_received.dccpor_elapsed_time * 10; if (unlikely(delta <= 0)) { DCCP_WARN("unusable RTT sample %ld, using min\n", delta); return DCCP_SANE_RTT_MIN; } if (unlikely(delta > DCCP_SANE_RTT_MAX)) { DCCP_WARN("RTT sample %ld too large, using max\n", delta); return DCCP_SANE_RTT_MAX; } return delta; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_3161_0
crossvul-cpp_data_bad_2198_0
/* * Copyright (C) 2006,2008 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * A module that implements the spnego security mechanism. * It is used to negotiate the security mechanism between * peers using the GSS-API. SPNEGO is specified in RFC 4178. * */ /* * Copyright (c) 2006-2008, Novell, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The copyright holder's name is not used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* #pragma ident "@(#)spnego_mech.c 1.7 04/09/28 SMI" */ #include <k5-int.h> #include <krb5.h> #include <mglueP.h> #include "gssapiP_spnego.h" #include <gssapi_err_generic.h> #undef g_token_size #undef g_verify_token_header #undef g_make_token_header #define HARD_ERROR(v) ((v) != GSS_S_COMPLETE && (v) != GSS_S_CONTINUE_NEEDED) typedef const gss_OID_desc *gss_OID_const; /* der routines defined in libgss */ extern unsigned int gssint_der_length_size(unsigned int); extern int gssint_get_der_length(unsigned char **, unsigned int, unsigned int*); extern int gssint_put_der_length(unsigned int, unsigned char **, unsigned int); /* private routines for spnego_mechanism */ static spnego_token_t make_spnego_token(const char *); static gss_buffer_desc make_err_msg(const char *); static int g_token_size(gss_OID_const, unsigned int); static int g_make_token_header(gss_OID_const, unsigned int, unsigned char **, unsigned int); static int g_verify_token_header(gss_OID_const, unsigned int *, unsigned char **, int, unsigned int); static int g_verify_neg_token_init(unsigned char **, unsigned int); static gss_OID get_mech_oid(OM_uint32 *, unsigned char **, size_t); static gss_buffer_t get_input_token(unsigned char **, unsigned int); static gss_OID_set get_mech_set(OM_uint32 *, unsigned char **, unsigned int); static OM_uint32 get_req_flags(unsigned char **, OM_uint32, OM_uint32 *); static OM_uint32 get_available_mechs(OM_uint32 *, gss_name_t, gss_cred_usage_t, gss_const_key_value_set_t, gss_cred_id_t *, gss_OID_set *); static OM_uint32 get_negotiable_mechs(OM_uint32 *, spnego_gss_cred_id_t, gss_cred_usage_t, gss_OID_set *); static void release_spnego_ctx(spnego_gss_ctx_id_t *); static void check_spnego_options(spnego_gss_ctx_id_t); static spnego_gss_ctx_id_t create_spnego_ctx(void); static int put_mech_set(gss_OID_set mechSet, gss_buffer_t buf); static int put_input_token(unsigned char **, gss_buffer_t, unsigned int); static int put_mech_oid(unsigned char **, gss_OID_const, unsigned int); static int put_negResult(unsigned char **, OM_uint32, unsigned int); static OM_uint32 process_mic(OM_uint32 *, gss_buffer_t, spnego_gss_ctx_id_t, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 handle_mic(OM_uint32 *, gss_buffer_t, int, spnego_gss_ctx_id_t, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 init_ctx_new(OM_uint32 *, spnego_gss_cred_id_t, gss_ctx_id_t *, send_token_flag *); static OM_uint32 init_ctx_nego(OM_uint32 *, spnego_gss_ctx_id_t, OM_uint32, gss_OID, gss_buffer_t *, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 init_ctx_cont(OM_uint32 *, gss_ctx_id_t *, gss_buffer_t, gss_buffer_t *, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 init_ctx_reselect(OM_uint32 *, spnego_gss_ctx_id_t, OM_uint32, gss_OID, gss_buffer_t *, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 init_ctx_call_init(OM_uint32 *, spnego_gss_ctx_id_t, spnego_gss_cred_id_t, gss_name_t, OM_uint32, OM_uint32, gss_buffer_t, gss_OID *, gss_buffer_t, OM_uint32 *, OM_uint32 *, OM_uint32 *, send_token_flag *); static OM_uint32 acc_ctx_new(OM_uint32 *, gss_buffer_t, gss_ctx_id_t *, spnego_gss_cred_id_t, gss_buffer_t *, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 acc_ctx_cont(OM_uint32 *, gss_buffer_t, gss_ctx_id_t *, gss_buffer_t *, gss_buffer_t *, OM_uint32 *, send_token_flag *); static OM_uint32 acc_ctx_vfy_oid(OM_uint32 *, spnego_gss_ctx_id_t, gss_OID, OM_uint32 *, send_token_flag *); static OM_uint32 acc_ctx_call_acc(OM_uint32 *, spnego_gss_ctx_id_t, spnego_gss_cred_id_t, gss_buffer_t, gss_OID *, gss_buffer_t, OM_uint32 *, OM_uint32 *, gss_cred_id_t *, OM_uint32 *, send_token_flag *); static gss_OID negotiate_mech(gss_OID_set, gss_OID_set, OM_uint32 *); static int g_get_tag_and_length(unsigned char **, int, unsigned int, unsigned int *); static int make_spnego_tokenInit_msg(spnego_gss_ctx_id_t, int, gss_buffer_t, OM_uint32, gss_buffer_t, send_token_flag, gss_buffer_t); static int make_spnego_tokenTarg_msg(OM_uint32, gss_OID, gss_buffer_t, gss_buffer_t, send_token_flag, gss_buffer_t); static OM_uint32 get_negTokenInit(OM_uint32 *, gss_buffer_t, gss_buffer_t, gss_OID_set *, OM_uint32 *, gss_buffer_t *, gss_buffer_t *); static OM_uint32 get_negTokenResp(OM_uint32 *, unsigned char *, unsigned int, OM_uint32 *, gss_OID *, gss_buffer_t *, gss_buffer_t *); static int is_kerb_mech(gss_OID oid); /* SPNEGO oid structure */ static const gss_OID_desc spnego_oids[] = { {SPNEGO_OID_LENGTH, SPNEGO_OID}, }; const gss_OID_desc * const gss_mech_spnego = spnego_oids+0; static const gss_OID_set_desc spnego_oidsets[] = { {1, (gss_OID) spnego_oids+0}, }; const gss_OID_set_desc * const gss_mech_set_spnego = spnego_oidsets+0; static int make_NegHints(OM_uint32 *, spnego_gss_cred_id_t, gss_buffer_t *); static int put_neg_hints(unsigned char **, gss_buffer_t, unsigned int); static OM_uint32 acc_ctx_hints(OM_uint32 *, gss_ctx_id_t *, spnego_gss_cred_id_t, gss_buffer_t *, OM_uint32 *, send_token_flag *); /* * The Mech OID for SPNEGO: * { iso(1) org(3) dod(6) internet(1) security(5) * mechanism(5) spnego(2) } */ static struct gss_config spnego_mechanism = { {SPNEGO_OID_LENGTH, SPNEGO_OID}, NULL, spnego_gss_acquire_cred, spnego_gss_release_cred, spnego_gss_init_sec_context, #ifndef LEAN_CLIENT spnego_gss_accept_sec_context, #else NULL, #endif /* LEAN_CLIENT */ NULL, /* gss_process_context_token */ spnego_gss_delete_sec_context, /* gss_delete_sec_context */ spnego_gss_context_time, /* gss_context_time */ spnego_gss_get_mic, /* gss_get_mic */ spnego_gss_verify_mic, /* gss_verify_mic */ spnego_gss_wrap, /* gss_wrap */ spnego_gss_unwrap, /* gss_unwrap */ spnego_gss_display_status, NULL, /* gss_indicate_mechs */ spnego_gss_compare_name, spnego_gss_display_name, spnego_gss_import_name, spnego_gss_release_name, spnego_gss_inquire_cred, /* gss_inquire_cred */ NULL, /* gss_add_cred */ #ifndef LEAN_CLIENT spnego_gss_export_sec_context, /* gss_export_sec_context */ spnego_gss_import_sec_context, /* gss_import_sec_context */ #else NULL, /* gss_export_sec_context */ NULL, /* gss_import_sec_context */ #endif /* LEAN_CLIENT */ NULL, /* gss_inquire_cred_by_mech */ spnego_gss_inquire_names_for_mech, spnego_gss_inquire_context, /* gss_inquire_context */ NULL, /* gss_internal_release_oid */ spnego_gss_wrap_size_limit, /* gss_wrap_size_limit */ NULL, /* gssd_pname_to_uid */ NULL, /* gss_userok */ NULL, /* gss_export_name */ spnego_gss_duplicate_name, /* gss_duplicate_name */ NULL, /* gss_store_cred */ spnego_gss_inquire_sec_context_by_oid, /* gss_inquire_sec_context_by_oid */ spnego_gss_inquire_cred_by_oid, /* gss_inquire_cred_by_oid */ spnego_gss_set_sec_context_option, /* gss_set_sec_context_option */ spnego_gss_set_cred_option, /* gssspi_set_cred_option */ NULL, /* gssspi_mech_invoke */ spnego_gss_wrap_aead, spnego_gss_unwrap_aead, spnego_gss_wrap_iov, spnego_gss_unwrap_iov, spnego_gss_wrap_iov_length, spnego_gss_complete_auth_token, spnego_gss_acquire_cred_impersonate_name, NULL, /* gss_add_cred_impersonate_name */ spnego_gss_display_name_ext, spnego_gss_inquire_name, spnego_gss_get_name_attribute, spnego_gss_set_name_attribute, spnego_gss_delete_name_attribute, spnego_gss_export_name_composite, spnego_gss_map_name_to_any, spnego_gss_release_any_name_mapping, spnego_gss_pseudo_random, spnego_gss_set_neg_mechs, spnego_gss_inquire_saslname_for_mech, spnego_gss_inquire_mech_for_saslname, spnego_gss_inquire_attrs_for_mech, spnego_gss_acquire_cred_from, NULL, /* gss_store_cred_into */ spnego_gss_acquire_cred_with_password, spnego_gss_export_cred, spnego_gss_import_cred, NULL, /* gssspi_import_sec_context_by_mech */ NULL, /* gssspi_import_name_by_mech */ NULL, /* gssspi_import_cred_by_mech */ spnego_gss_get_mic_iov, spnego_gss_verify_mic_iov, spnego_gss_get_mic_iov_length }; #ifdef _GSS_STATIC_LINK #include "mglueP.h" static int gss_spnegomechglue_init(void) { struct gss_mech_config mech_spnego; memset(&mech_spnego, 0, sizeof(mech_spnego)); mech_spnego.mech = &spnego_mechanism; mech_spnego.mechNameStr = "spnego"; mech_spnego.mech_type = GSS_C_NO_OID; return gssint_register_mechinfo(&mech_spnego); } #else gss_mechanism KRB5_CALLCONV gss_mech_initialize(void) { return (&spnego_mechanism); } MAKE_INIT_FUNCTION(gss_krb5int_lib_init); MAKE_FINI_FUNCTION(gss_krb5int_lib_fini); int gss_krb5int_lib_init(void); #endif /* _GSS_STATIC_LINK */ int gss_spnegoint_lib_init(void) { int err; err = k5_key_register(K5_KEY_GSS_SPNEGO_STATUS, NULL); if (err) return err; #ifdef _GSS_STATIC_LINK return gss_spnegomechglue_init(); #else return 0; #endif } void gss_spnegoint_lib_fini(void) { } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_acquire_cred(OM_uint32 *minor_status, gss_name_t desired_name, OM_uint32 time_req, gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { return spnego_gss_acquire_cred_from(minor_status, desired_name, time_req, desired_mechs, cred_usage, NULL, output_cred_handle, actual_mechs, time_rec); } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_acquire_cred_from(OM_uint32 *minor_status, const gss_name_t desired_name, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_const_key_value_set_t cred_store, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 status, tmpmin; gss_OID_set amechs; gss_cred_id_t mcred = NULL; spnego_gss_cred_id_t spcred = NULL; dsyslog("Entering spnego_gss_acquire_cred\n"); if (actual_mechs) *actual_mechs = NULL; if (time_rec) *time_rec = 0; /* We will obtain a mechglue credential and wrap it in a * spnego_gss_cred_id_rec structure. Allocate the wrapper. */ spcred = malloc(sizeof(spnego_gss_cred_id_rec)); if (spcred == NULL) { *minor_status = ENOMEM; return (GSS_S_FAILURE); } spcred->neg_mechs = GSS_C_NULL_OID_SET; /* * Always use get_available_mechs to collect a list of * mechs for which creds are available. */ status = get_available_mechs(minor_status, desired_name, cred_usage, cred_store, &mcred, &amechs); if (actual_mechs && amechs != GSS_C_NULL_OID_SET) { (void) gssint_copy_oid_set(&tmpmin, amechs, actual_mechs); } (void) gss_release_oid_set(&tmpmin, &amechs); if (status == GSS_S_COMPLETE) { spcred->mcred = mcred; *output_cred_handle = (gss_cred_id_t)spcred; } else { free(spcred); *output_cred_handle = GSS_C_NO_CREDENTIAL; } dsyslog("Leaving spnego_gss_acquire_cred\n"); return (status); } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_handle) { spnego_gss_cred_id_t spcred = NULL; dsyslog("Entering spnego_gss_release_cred\n"); if (minor_status == NULL || cred_handle == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (*cred_handle == GSS_C_NO_CREDENTIAL) return (GSS_S_COMPLETE); spcred = (spnego_gss_cred_id_t)*cred_handle; *cred_handle = GSS_C_NO_CREDENTIAL; gss_release_oid_set(minor_status, &spcred->neg_mechs); gss_release_cred(minor_status, &spcred->mcred); free(spcred); dsyslog("Leaving spnego_gss_release_cred\n"); return (GSS_S_COMPLETE); } static void check_spnego_options(spnego_gss_ctx_id_t spnego_ctx) { spnego_ctx->optionStr = gssint_get_modOptions( (const gss_OID)&spnego_oids[0]); } static spnego_gss_ctx_id_t create_spnego_ctx(void) { spnego_gss_ctx_id_t spnego_ctx = NULL; spnego_ctx = (spnego_gss_ctx_id_t) malloc(sizeof (spnego_gss_ctx_id_rec)); if (spnego_ctx == NULL) { return (NULL); } spnego_ctx->magic_num = SPNEGO_MAGIC_ID; spnego_ctx->ctx_handle = GSS_C_NO_CONTEXT; spnego_ctx->mech_set = NULL; spnego_ctx->internal_mech = NULL; spnego_ctx->optionStr = NULL; spnego_ctx->DER_mechTypes.length = 0; spnego_ctx->DER_mechTypes.value = NULL; spnego_ctx->default_cred = GSS_C_NO_CREDENTIAL; spnego_ctx->mic_reqd = 0; spnego_ctx->mic_sent = 0; spnego_ctx->mic_rcvd = 0; spnego_ctx->mech_complete = 0; spnego_ctx->nego_done = 0; spnego_ctx->internal_name = GSS_C_NO_NAME; spnego_ctx->actual_mech = GSS_C_NO_OID; check_spnego_options(spnego_ctx); return (spnego_ctx); } /* iso(1) org(3) dod(6) internet(1) private(4) enterprises(1) samba(7165) * gssntlmssp(655) controls(1) spnego_req_mechlistMIC(2) */ static const gss_OID_desc spnego_req_mechlistMIC_oid = { 11, "\x2B\x06\x01\x04\x01\xB7\x7D\x85\x0F\x01\x02" }; /* * Return nonzero if the mechanism has reason to believe that a mechlistMIC * exchange will be required. Microsoft servers erroneously require SPNEGO * mechlistMIC if they see an internal MIC within an NTLMSSP Authenticate * message, even if NTLMSSP was the preferred mechanism. */ static int mech_requires_mechlistMIC(spnego_gss_ctx_id_t sc) { OM_uint32 major, minor; gss_ctx_id_t ctx = sc->ctx_handle; gss_OID oid = (gss_OID)&spnego_req_mechlistMIC_oid; gss_buffer_set_t bufs; int result; major = gss_inquire_sec_context_by_oid(&minor, ctx, oid, &bufs); if (major != GSS_S_COMPLETE) return 0; /* Report true if the mech returns a single buffer containing a single * byte with value 1. */ result = (bufs != NULL && bufs->count == 1 && bufs->elements[0].length == 1 && memcmp(bufs->elements[0].value, "\1", 1) == 0); (void) gss_release_buffer_set(&minor, &bufs); return result; } /* * Both initiator and acceptor call here to verify and/or create mechListMIC, * and to consistency-check the MIC state. handle_mic is invoked only if the * negotiated mech has completed and supports MICs. */ static OM_uint32 handle_mic(OM_uint32 *minor_status, gss_buffer_t mic_in, int send_mechtok, spnego_gss_ctx_id_t sc, gss_buffer_t *mic_out, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 ret; ret = GSS_S_FAILURE; *mic_out = GSS_C_NO_BUFFER; if (mic_in != GSS_C_NO_BUFFER) { if (sc->mic_rcvd) { /* Reject MIC if we've already received a MIC. */ *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; return GSS_S_DEFECTIVE_TOKEN; } } else if (sc->mic_reqd && !send_mechtok) { /* * If the peer sends the final mechanism token, it * must send the MIC with that token if the * negotiation requires MICs. */ *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; return GSS_S_DEFECTIVE_TOKEN; } ret = process_mic(minor_status, mic_in, sc, mic_out, negState, tokflag); if (ret != GSS_S_COMPLETE) { return ret; } if (sc->mic_reqd) { assert(sc->mic_sent || sc->mic_rcvd); } if (sc->mic_sent && sc->mic_rcvd) { ret = GSS_S_COMPLETE; *negState = ACCEPT_COMPLETE; if (*mic_out == GSS_C_NO_BUFFER) { /* * We sent a MIC on the previous pass; we * shouldn't be sending a mechanism token. */ assert(!send_mechtok); *tokflag = NO_TOKEN_SEND; } else { *tokflag = CONT_TOKEN_SEND; } } else if (sc->mic_reqd) { *negState = ACCEPT_INCOMPLETE; ret = GSS_S_CONTINUE_NEEDED; } else if (*negState == ACCEPT_COMPLETE) { ret = GSS_S_COMPLETE; } else { ret = GSS_S_CONTINUE_NEEDED; } return ret; } /* * Perform the actual verification and/or generation of mechListMIC. */ static OM_uint32 process_mic(OM_uint32 *minor_status, gss_buffer_t mic_in, spnego_gss_ctx_id_t sc, gss_buffer_t *mic_out, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 ret, tmpmin; gss_qop_t qop_state; gss_buffer_desc tmpmic = GSS_C_EMPTY_BUFFER; ret = GSS_S_FAILURE; if (mic_in != GSS_C_NO_BUFFER) { ret = gss_verify_mic(minor_status, sc->ctx_handle, &sc->DER_mechTypes, mic_in, &qop_state); if (ret != GSS_S_COMPLETE) { *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; return ret; } /* If we got a MIC, we must send a MIC. */ sc->mic_reqd = 1; sc->mic_rcvd = 1; } if (sc->mic_reqd && !sc->mic_sent) { ret = gss_get_mic(minor_status, sc->ctx_handle, GSS_C_QOP_DEFAULT, &sc->DER_mechTypes, &tmpmic); if (ret != GSS_S_COMPLETE) { gss_release_buffer(&tmpmin, &tmpmic); *tokflag = NO_TOKEN_SEND; return ret; } *mic_out = malloc(sizeof(gss_buffer_desc)); if (*mic_out == GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, &tmpmic); *tokflag = NO_TOKEN_SEND; return GSS_S_FAILURE; } **mic_out = tmpmic; sc->mic_sent = 1; } return GSS_S_COMPLETE; } /* * Initial call to spnego_gss_init_sec_context(). */ static OM_uint32 init_ctx_new(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_ctx_id_t *ctx, send_token_flag *tokflag) { OM_uint32 ret; spnego_gss_ctx_id_t sc = NULL; sc = create_spnego_ctx(); if (sc == NULL) return GSS_S_FAILURE; /* determine negotiation mech set */ ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE, &sc->mech_set); if (ret != GSS_S_COMPLETE) goto cleanup; /* Set an initial internal mech to make the first context token. */ sc->internal_mech = &sc->mech_set->elements[0]; if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } /* * The actual context is not yet determined, set the output * context handle to refer to the spnego context itself. */ sc->ctx_handle = GSS_C_NO_CONTEXT; *ctx = (gss_ctx_id_t)sc; sc = NULL; *tokflag = INIT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; cleanup: release_spnego_ctx(&sc); return ret; } /* * Called by second and later calls to spnego_gss_init_sec_context() * to decode reply and update state. */ static OM_uint32 init_ctx_cont(OM_uint32 *minor_status, gss_ctx_id_t *ctx, gss_buffer_t buf, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 ret, tmpmin, acc_negState; unsigned char *ptr; spnego_gss_ctx_id_t sc; gss_OID supportedMech = GSS_C_NO_OID; sc = (spnego_gss_ctx_id_t)*ctx; *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; ptr = buf->value; ret = get_negTokenResp(minor_status, ptr, buf->length, &acc_negState, &supportedMech, responseToken, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; if (acc_negState == REJECT) { *minor_status = ERR_SPNEGO_NEGOTIATION_FAILED; map_errcode(minor_status); *tokflag = NO_TOKEN_SEND; ret = GSS_S_FAILURE; goto cleanup; } /* * nego_done is false for the first call to init_ctx_cont() */ if (!sc->nego_done) { ret = init_ctx_nego(minor_status, sc, acc_negState, supportedMech, responseToken, mechListMIC, negState, tokflag); } else if ((!sc->mech_complete && *responseToken == GSS_C_NO_BUFFER) || (sc->mech_complete && *responseToken != GSS_C_NO_BUFFER)) { /* Missing or spurious token from acceptor. */ ret = GSS_S_DEFECTIVE_TOKEN; } else if (!sc->mech_complete || (sc->mic_reqd && (sc->ctx_flags & GSS_C_INTEG_FLAG))) { /* Not obviously done; we may decide we're done later in * init_ctx_call_init or handle_mic. */ *negState = ACCEPT_INCOMPLETE; *tokflag = CONT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; } else { /* mech finished on last pass and no MIC required, so done. */ *negState = ACCEPT_COMPLETE; *tokflag = NO_TOKEN_SEND; ret = GSS_S_COMPLETE; } cleanup: if (supportedMech != GSS_C_NO_OID) generic_gss_release_oid(&tmpmin, &supportedMech); return ret; } /* * Consistency checking and mechanism negotiation handling for second * call of spnego_gss_init_sec_context(). Call init_ctx_reselect() to * update internal state if acceptor has counter-proposed. */ static OM_uint32 init_ctx_nego(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, OM_uint32 acc_negState, gss_OID supportedMech, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 ret; *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; ret = GSS_S_DEFECTIVE_TOKEN; /* * Both supportedMech and negState must be present in first * acceptor token. */ if (supportedMech == GSS_C_NO_OID) { *minor_status = ERR_SPNEGO_NO_MECH_FROM_ACCEPTOR; map_errcode(minor_status); return GSS_S_DEFECTIVE_TOKEN; } if (acc_negState == ACCEPT_DEFECTIVE_TOKEN) { *minor_status = ERR_SPNEGO_NEGOTIATION_FAILED; map_errcode(minor_status); return GSS_S_DEFECTIVE_TOKEN; } /* * If the mechanism we sent is not the mechanism returned from * the server, we need to handle the server's counter * proposal. There is a bug in SAMBA servers that always send * the old Kerberos mech OID, even though we sent the new one. * So we will treat all the Kerberos mech OIDS as the same. */ if (!(is_kerb_mech(supportedMech) && is_kerb_mech(sc->internal_mech)) && !g_OID_equal(supportedMech, sc->internal_mech)) { ret = init_ctx_reselect(minor_status, sc, acc_negState, supportedMech, responseToken, mechListMIC, negState, tokflag); } else if (*responseToken == GSS_C_NO_BUFFER) { if (sc->mech_complete) { /* * Mech completed on first call to its * init_sec_context(). Acceptor sends no mech * token. */ *negState = ACCEPT_COMPLETE; *tokflag = NO_TOKEN_SEND; ret = GSS_S_COMPLETE; } else { /* * Reject missing mech token when optimistic * mech selected. */ *minor_status = ERR_SPNEGO_NO_TOKEN_FROM_ACCEPTOR; map_errcode(minor_status); ret = GSS_S_DEFECTIVE_TOKEN; } } else if ((*responseToken)->length == 0 && sc->mech_complete) { /* Handle old IIS servers returning empty token instead of * null tokens in the non-mutual auth case. */ *negState = ACCEPT_COMPLETE; *tokflag = NO_TOKEN_SEND; ret = GSS_S_COMPLETE; } else if (sc->mech_complete) { /* Reject spurious mech token. */ ret = GSS_S_DEFECTIVE_TOKEN; } else { *negState = ACCEPT_INCOMPLETE; *tokflag = CONT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; } sc->nego_done = 1; return ret; } /* * Handle acceptor's counter-proposal of an alternative mechanism. */ static OM_uint32 init_ctx_reselect(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, OM_uint32 acc_negState, gss_OID supportedMech, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 tmpmin; size_t i; generic_gss_release_oid(&tmpmin, &sc->internal_mech); gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); /* Find supportedMech in sc->mech_set. */ for (i = 0; i < sc->mech_set->count; i++) { if (g_OID_equal(supportedMech, &sc->mech_set->elements[i])) break; } if (i == sc->mech_set->count) return GSS_S_DEFECTIVE_TOKEN; sc->internal_mech = &sc->mech_set->elements[i]; /* * Windows 2003 and earlier don't correctly send a * negState of request-mic when counter-proposing a * mechanism. They probably don't handle mechListMICs * properly either. */ if (acc_negState != REQUEST_MIC) return GSS_S_DEFECTIVE_TOKEN; sc->mech_complete = 0; sc->mic_reqd = 1; *negState = REQUEST_MIC; *tokflag = CONT_TOKEN_SEND; return GSS_S_CONTINUE_NEEDED; } /* * Wrap call to mechanism gss_init_sec_context() and update state * accordingly. */ static OM_uint32 init_ctx_call_init(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, spnego_gss_cred_id_t spcred, gss_name_t target_name, OM_uint32 req_flags, OM_uint32 time_req, gss_buffer_t mechtok_in, gss_OID *actual_mech, gss_buffer_t mechtok_out, OM_uint32 *ret_flags, OM_uint32 *time_rec, OM_uint32 *negState, send_token_flag *send_token) { OM_uint32 ret, tmpret, tmpmin; gss_cred_id_t mcred; mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred; ret = gss_init_sec_context(minor_status, mcred, &sc->ctx_handle, target_name, sc->internal_mech, (req_flags | GSS_C_INTEG_FLAG), time_req, GSS_C_NO_CHANNEL_BINDINGS, mechtok_in, &sc->actual_mech, mechtok_out, &sc->ctx_flags, time_rec); if (ret == GSS_S_COMPLETE) { sc->mech_complete = 1; if (ret_flags != NULL) *ret_flags = sc->ctx_flags; /* * Microsoft SPNEGO implementations expect an even number of * token exchanges. So if we're sending a final token, ask for * a zero-length token back from the server. Also ask for a * token back if this is the first token or if a MIC exchange * is required. */ if (*send_token == CONT_TOKEN_SEND && mechtok_out->length == 0 && (!sc->mic_reqd || !(sc->ctx_flags & GSS_C_INTEG_FLAG))) { /* The exchange is complete. */ *negState = ACCEPT_COMPLETE; ret = GSS_S_COMPLETE; *send_token = NO_TOKEN_SEND; } else { /* Ask for one more hop. */ *negState = ACCEPT_INCOMPLETE; ret = GSS_S_CONTINUE_NEEDED; } return ret; } if (ret == GSS_S_CONTINUE_NEEDED) return ret; if (*send_token != INIT_TOKEN_SEND) { *send_token = ERROR_TOKEN_SEND; *negState = REJECT; return ret; } /* * Since this is the first token, we can fall back to later mechanisms * in the list. Since the mechanism list is expected to be short, we * can do this with recursion. If all mechanisms produce errors, the * caller should get the error from the first mech in the list. */ gssalloc_free(sc->mech_set->elements->elements); memmove(sc->mech_set->elements, sc->mech_set->elements + 1, --sc->mech_set->count * sizeof(*sc->mech_set->elements)); if (sc->mech_set->count == 0) goto fail; gss_release_buffer(&tmpmin, &sc->DER_mechTypes); if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) goto fail; tmpret = init_ctx_call_init(&tmpmin, sc, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, mechtok_out, ret_flags, time_rec, negState, send_token); if (HARD_ERROR(tmpret)) goto fail; *minor_status = tmpmin; return tmpret; fail: /* Don't output token on error from first call. */ *send_token = NO_TOKEN_SEND; *negState = REJECT; return ret; } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_init_sec_context( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { send_token_flag send_token = NO_TOKEN_SEND; OM_uint32 tmpmin, ret, negState; gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_cred_id_t spcred = NULL; spnego_gss_ctx_id_t spnego_ctx = NULL; dsyslog("Entering init_sec_context\n"); mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER; negState = REJECT; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context * function and examine the results. * 3. Process or generate MICs if necessary. * * The three steps share responsibility for determining when the * exchange is complete. If the selected mech completed in a previous * call and no MIC exchange is expected, then step 1 will decide. If * the selected mech completes in this call and no MIC exchange is * expected, then step 2 will decide. If a MIC exchange is expected, * then step 3 will decide. If an error occurs in any step, the * exchange will be aborted, possibly with an error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * send_token is used to indicate what type of token, if any, should be * generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (actual_mech != NULL) *actual_mech = GSS_C_NO_OID; /* Step 1: perform mechanism negotiation. */ spcred = (spnego_gss_cred_id_t)claimant_cred_handle; if (*context_handle == GSS_C_NO_CONTEXT) { ret = init_ctx_new(minor_status, spcred, context_handle, &send_token); if (ret != GSS_S_CONTINUE_NEEDED) { goto cleanup; } } else { ret = init_ctx_cont(minor_status, context_handle, input_token, &mechtok_in, &mechListMIC_in, &negState, &send_token); if (HARD_ERROR(ret)) { goto cleanup; } } /* Step 2: invoke the selected or optimistic mechanism's * gss_init_sec_context function, if it didn't complete previously. */ spnego_ctx = (spnego_gss_ctx_id_t)*context_handle; if (!spnego_ctx->mech_complete) { ret = init_ctx_call_init( minor_status, spnego_ctx, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, &mechtok_out, ret_flags, time_rec, &negState, &send_token); /* Give the mechanism a chance to force a mechlistMIC. */ if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx)) spnego_ctx->mic_reqd = 1; } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && spnego_ctx->mech_complete && (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mechListMIC_in, (mechtok_out.length != 0), spnego_ctx, &mechListMIC_out, &negState, &send_token); } cleanup: if (send_token == INIT_TOKEN_SEND) { if (make_spnego_tokenInit_msg(spnego_ctx, 0, mechListMIC_out, req_flags, &mechtok_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } else if (send_token != NO_TOKEN_SEND) { if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID, &mechtok_out, mechListMIC_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } gss_release_buffer(&tmpmin, &mechtok_out); if (ret == GSS_S_COMPLETE) { /* * Now, switch the output context to refer to the * negotiated mechanism's context. */ *context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle; if (actual_mech != NULL) *actual_mech = spnego_ctx->actual_mech; if (ret_flags != NULL) *ret_flags = spnego_ctx->ctx_flags; release_spnego_ctx(&spnego_ctx); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (spnego_ctx != NULL) { gss_delete_sec_context(&tmpmin, &spnego_ctx->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&spnego_ctx); } *context_handle = GSS_C_NO_CONTEXT; } if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mechListMIC_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_in); free(mechListMIC_in); } if (mechListMIC_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_out); free(mechListMIC_out); } return ret; } /* init_sec_context */ /* We don't want to import KRB5 headers here */ static const gss_OID_desc gss_mech_krb5_oid = { 9, "\052\206\110\206\367\022\001\002\002" }; static const gss_OID_desc gss_mech_krb5_wrong_oid = { 9, "\052\206\110\202\367\022\001\002\002" }; /* * verify that the input token length is not 0. If it is, just return. * If the token length is greater than 0, der encode as a sequence * and place in buf_out, advancing buf_out. */ static int put_neg_hints(unsigned char **buf_out, gss_buffer_t input_token, unsigned int buflen) { int ret; /* if token length is 0, we do not want to send */ if (input_token->length == 0) return (0); if (input_token->length > buflen) return (-1); *(*buf_out)++ = SEQUENCE; if ((ret = gssint_put_der_length(input_token->length, buf_out, input_token->length))) return (ret); TWRITE_STR(*buf_out, input_token->value, input_token->length); return (0); } /* * NegHints ::= SEQUENCE { * hintName [0] GeneralString OPTIONAL, * hintAddress [1] OCTET STRING OPTIONAL * } */ #define HOST_PREFIX "host@" #define HOST_PREFIX_LEN (sizeof(HOST_PREFIX) - 1) static int make_NegHints(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_buffer_t *outbuf) { gss_buffer_desc hintNameBuf; gss_name_t hintName = GSS_C_NO_NAME; gss_name_t hintKerberosName; gss_OID hintNameType; OM_uint32 major_status; OM_uint32 minor; unsigned int tlen = 0; unsigned int hintNameSize = 0; unsigned char *ptr; unsigned char *t; *outbuf = GSS_C_NO_BUFFER; if (spcred != NULL) { major_status = gss_inquire_cred(minor_status, spcred->mcred, &hintName, NULL, NULL, NULL); if (major_status != GSS_S_COMPLETE) return (major_status); } if (hintName == GSS_C_NO_NAME) { krb5_error_code code; krb5int_access kaccess; char hostname[HOST_PREFIX_LEN + MAXHOSTNAMELEN + 1] = HOST_PREFIX; code = krb5int_accessor(&kaccess, KRB5INT_ACCESS_VERSION); if (code != 0) { *minor_status = code; return (GSS_S_FAILURE); } /* this breaks mutual authentication but Samba relies on it */ code = (*kaccess.clean_hostname)(NULL, NULL, &hostname[HOST_PREFIX_LEN], MAXHOSTNAMELEN); if (code != 0) { *minor_status = code; return (GSS_S_FAILURE); } hintNameBuf.value = hostname; hintNameBuf.length = strlen(hostname); major_status = gss_import_name(minor_status, &hintNameBuf, GSS_C_NT_HOSTBASED_SERVICE, &hintName); if (major_status != GSS_S_COMPLETE) { return (major_status); } } hintNameBuf.value = NULL; hintNameBuf.length = 0; major_status = gss_canonicalize_name(minor_status, hintName, (gss_OID)&gss_mech_krb5_oid, &hintKerberosName); if (major_status != GSS_S_COMPLETE) { gss_release_name(&minor, &hintName); return (major_status); } gss_release_name(&minor, &hintName); major_status = gss_display_name(minor_status, hintKerberosName, &hintNameBuf, &hintNameType); if (major_status != GSS_S_COMPLETE) { gss_release_name(&minor, &hintName); return (major_status); } gss_release_name(&minor, &hintKerberosName); /* * Now encode the name hint into a NegHints ASN.1 type */ major_status = GSS_S_FAILURE; /* Length of DER encoded GeneralString */ tlen = 1 + gssint_der_length_size(hintNameBuf.length) + hintNameBuf.length; hintNameSize = tlen; /* Length of DER encoded hintName */ tlen += 1 + gssint_der_length_size(hintNameSize); t = gssalloc_malloc(tlen); if (t == NULL) { *minor_status = ENOMEM; goto errout; } ptr = t; *ptr++ = CONTEXT | 0x00; /* hintName identifier */ if (gssint_put_der_length(hintNameSize, &ptr, tlen - (int)(ptr-t))) goto errout; *ptr++ = GENERAL_STRING; if (gssint_put_der_length(hintNameBuf.length, &ptr, tlen - (int)(ptr-t))) goto errout; memcpy(ptr, hintNameBuf.value, hintNameBuf.length); ptr += hintNameBuf.length; *outbuf = (gss_buffer_t)malloc(sizeof(gss_buffer_desc)); if (*outbuf == NULL) { *minor_status = ENOMEM; goto errout; } (*outbuf)->value = (void *)t; (*outbuf)->length = ptr - t; t = NULL; /* don't free */ *minor_status = 0; major_status = GSS_S_COMPLETE; errout: if (t != NULL) { free(t); } gss_release_buffer(&minor, &hintNameBuf); return (major_status); } /* * Support the Microsoft NegHints extension to SPNEGO for compatibility with * some versions of Samba. See: * http://msdn.microsoft.com/en-us/library/cc247039(PROT.10).aspx */ static OM_uint32 acc_ctx_hints(OM_uint32 *minor_status, gss_ctx_id_t *ctx, spnego_gss_cred_id_t spcred, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 tmpmin, ret; gss_OID_set supported_mechSet; spnego_gss_ctx_id_t sc = NULL; *mechListMIC = GSS_C_NO_BUFFER; supported_mechSet = GSS_C_NO_OID_SET; *return_token = NO_TOKEN_SEND; *negState = REJECT; *minor_status = 0; /* A hint request must be the first token received. */ if (*ctx != GSS_C_NO_CONTEXT) return GSS_S_DEFECTIVE_TOKEN; ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT, &supported_mechSet); if (ret != GSS_S_COMPLETE) goto cleanup; ret = make_NegHints(minor_status, spcred, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; sc = create_spnego_ctx(); if (sc == NULL) { ret = GSS_S_FAILURE; goto cleanup; } if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } sc->internal_mech = GSS_C_NO_OID; *negState = ACCEPT_INCOMPLETE; *return_token = INIT_TOKEN_SEND; sc->firstpass = 1; *ctx = (gss_ctx_id_t)sc; sc = NULL; ret = GSS_S_COMPLETE; cleanup: release_spnego_ctx(&sc); gss_release_oid_set(&tmpmin, &supported_mechSet); return ret; } /* * Set negState to REJECT if the token is defective, else * ACCEPT_INCOMPLETE or REQUEST_MIC, depending on whether initiator's * preferred mechanism is supported. */ static OM_uint32 acc_ctx_new(OM_uint32 *minor_status, gss_buffer_t buf, gss_ctx_id_t *ctx, spnego_gss_cred_id_t spcred, gss_buffer_t *mechToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 tmpmin, ret, req_flags; gss_OID_set supported_mechSet, mechTypes; gss_buffer_desc der_mechTypes; gss_OID mech_wanted; spnego_gss_ctx_id_t sc = NULL; ret = GSS_S_DEFECTIVE_TOKEN; der_mechTypes.length = 0; der_mechTypes.value = NULL; *mechToken = *mechListMIC = GSS_C_NO_BUFFER; supported_mechSet = mechTypes = GSS_C_NO_OID_SET; *return_token = ERROR_TOKEN_SEND; *negState = REJECT; *minor_status = 0; ret = get_negTokenInit(minor_status, buf, &der_mechTypes, &mechTypes, &req_flags, mechToken, mechListMIC); if (ret != GSS_S_COMPLETE) { goto cleanup; } ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT, &supported_mechSet); if (ret != GSS_S_COMPLETE) { *return_token = NO_TOKEN_SEND; goto cleanup; } /* * Select the best match between the list of mechs * that the initiator requested and the list that * the acceptor will support. */ mech_wanted = negotiate_mech(supported_mechSet, mechTypes, negState); if (*negState == REJECT) { ret = GSS_S_BAD_MECH; goto cleanup; } sc = (spnego_gss_ctx_id_t)*ctx; if (sc != NULL) { gss_release_buffer(&tmpmin, &sc->DER_mechTypes); assert(mech_wanted != GSS_C_NO_OID); } else sc = create_spnego_ctx(); if (sc == NULL) { ret = GSS_S_FAILURE; *return_token = NO_TOKEN_SEND; goto cleanup; } sc->mech_set = mechTypes; mechTypes = GSS_C_NO_OID_SET; sc->internal_mech = mech_wanted; sc->DER_mechTypes = der_mechTypes; der_mechTypes.length = 0; der_mechTypes.value = NULL; if (*negState == REQUEST_MIC) sc->mic_reqd = 1; *return_token = INIT_TOKEN_SEND; sc->firstpass = 1; *ctx = (gss_ctx_id_t)sc; ret = GSS_S_COMPLETE; cleanup: gss_release_oid_set(&tmpmin, &mechTypes); gss_release_oid_set(&tmpmin, &supported_mechSet); if (der_mechTypes.length != 0) gss_release_buffer(&tmpmin, &der_mechTypes); return ret; } static OM_uint32 acc_ctx_cont(OM_uint32 *minstat, gss_buffer_t buf, gss_ctx_id_t *ctx, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 ret, tmpmin; gss_OID supportedMech; spnego_gss_ctx_id_t sc; unsigned int len; unsigned char *ptr, *bufstart; sc = (spnego_gss_ctx_id_t)*ctx; ret = GSS_S_DEFECTIVE_TOKEN; *negState = REJECT; *minstat = 0; supportedMech = GSS_C_NO_OID; *return_token = ERROR_TOKEN_SEND; *responseToken = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf->value; #define REMAIN (buf->length - (ptr - bufstart)) if (REMAIN > INT_MAX) return GSS_S_DEFECTIVE_TOKEN; /* * Attempt to work with old Sun SPNEGO. */ if (*ptr == HEADER_ID) { ret = g_verify_token_header(gss_mech_spnego, &len, &ptr, 0, REMAIN); if (ret) { *minstat = ret; return GSS_S_DEFECTIVE_TOKEN; } } if (*ptr != (CONTEXT | 0x01)) { return GSS_S_DEFECTIVE_TOKEN; } ret = get_negTokenResp(minstat, ptr, REMAIN, negState, &supportedMech, responseToken, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; if (*responseToken == GSS_C_NO_BUFFER && *mechListMIC == GSS_C_NO_BUFFER) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } if (supportedMech != GSS_C_NO_OID) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } sc->firstpass = 0; *negState = ACCEPT_INCOMPLETE; *return_token = CONT_TOKEN_SEND; cleanup: if (supportedMech != GSS_C_NO_OID) { generic_gss_release_oid(&tmpmin, &supportedMech); } return ret; #undef REMAIN } /* * Verify that mech OID is either exactly the same as the negotiated * mech OID, or is a mech OID supported by the negotiated mech. MS * implementations can list a most preferred mech using an incorrect * krb5 OID while emitting a krb5 initiator mech token having the * correct krb5 mech OID. */ static OM_uint32 acc_ctx_vfy_oid(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, gss_OID mechoid, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 ret, tmpmin; gss_mechanism mech = NULL; gss_OID_set mech_set = GSS_C_NO_OID_SET; int present = 0; if (g_OID_equal(sc->internal_mech, mechoid)) return GSS_S_COMPLETE; mech = gssint_get_mechanism(sc->internal_mech); if (mech == NULL || mech->gss_indicate_mechs == NULL) { *minor_status = ERR_SPNEGO_NEGOTIATION_FAILED; map_errcode(minor_status); *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; return GSS_S_BAD_MECH; } ret = mech->gss_indicate_mechs(minor_status, &mech_set); if (ret != GSS_S_COMPLETE) { *tokflag = NO_TOKEN_SEND; map_error(minor_status, mech); goto cleanup; } ret = gss_test_oid_set_member(minor_status, mechoid, mech_set, &present); if (ret != GSS_S_COMPLETE) goto cleanup; if (!present) { *minor_status = ERR_SPNEGO_NEGOTIATION_FAILED; map_errcode(minor_status); *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; ret = GSS_S_BAD_MECH; } cleanup: gss_release_oid_set(&tmpmin, &mech_set); return ret; } #ifndef LEAN_CLIENT /* * Wrap call to gss_accept_sec_context() and update state * accordingly. */ static OM_uint32 acc_ctx_call_acc(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc, spnego_gss_cred_id_t spcred, gss_buffer_t mechtok_in, gss_OID *mech_type, gss_buffer_t mechtok_out, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle, OM_uint32 *negState, send_token_flag *tokflag) { OM_uint32 ret; gss_OID_desc mechoid; gss_cred_id_t mcred; if (sc->ctx_handle == GSS_C_NO_CONTEXT) { /* * mechoid is an alias; don't free it. */ ret = gssint_get_mech_type(&mechoid, mechtok_in); if (ret != GSS_S_COMPLETE) { *tokflag = NO_TOKEN_SEND; return ret; } ret = acc_ctx_vfy_oid(minor_status, sc, &mechoid, negState, tokflag); if (ret != GSS_S_COMPLETE) return ret; } mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred; ret = gss_accept_sec_context(minor_status, &sc->ctx_handle, mcred, mechtok_in, GSS_C_NO_CHANNEL_BINDINGS, &sc->internal_name, mech_type, mechtok_out, &sc->ctx_flags, time_rec, delegated_cred_handle); if (ret == GSS_S_COMPLETE) { #ifdef MS_BUG_TEST /* * Force MIC to be not required even if we previously * requested a MIC. */ char *envstr = getenv("MS_FORCE_NO_MIC"); if (envstr != NULL && strcmp(envstr, "1") == 0 && !(sc->ctx_flags & GSS_C_MUTUAL_FLAG) && sc->mic_reqd) { sc->mic_reqd = 0; } #endif sc->mech_complete = 1; if (ret_flags != NULL) *ret_flags = sc->ctx_flags; if (!sc->mic_reqd || !(sc->ctx_flags & GSS_C_INTEG_FLAG)) { /* No MIC exchange required, so we're done. */ *negState = ACCEPT_COMPLETE; ret = GSS_S_COMPLETE; } else { /* handle_mic will decide if we're done. */ ret = GSS_S_CONTINUE_NEEDED; } } else if (ret != GSS_S_CONTINUE_NEEDED) { *negState = REJECT; *tokflag = ERROR_TOKEN_SEND; } return ret; } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { *context_handle = (gss_ctx_id_t)sc->ctx_handle; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } release_spnego_ctx(&sc); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } return ret; } #endif /* LEAN_CLIENT */ /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_display_status( OM_uint32 *minor_status, OM_uint32 status_value, int status_type, gss_OID mech_type, OM_uint32 *message_context, gss_buffer_t status_string) { OM_uint32 maj = GSS_S_COMPLETE; int ret; dsyslog("Entering display_status\n"); *message_context = 0; switch (status_value) { case ERR_SPNEGO_NO_MECHS_AVAILABLE: /* CSTYLED */ *status_string = make_err_msg(_("SPNEGO cannot find " "mechanisms to negotiate")); break; case ERR_SPNEGO_NO_CREDS_ACQUIRED: /* CSTYLED */ *status_string = make_err_msg(_("SPNEGO failed to acquire " "creds")); break; case ERR_SPNEGO_NO_MECH_FROM_ACCEPTOR: /* CSTYLED */ *status_string = make_err_msg(_("SPNEGO acceptor did not " "select a mechanism")); break; case ERR_SPNEGO_NEGOTIATION_FAILED: /* CSTYLED */ *status_string = make_err_msg(_("SPNEGO failed to negotiate a " "mechanism")); break; case ERR_SPNEGO_NO_TOKEN_FROM_ACCEPTOR: /* CSTYLED */ *status_string = make_err_msg(_("SPNEGO acceptor did not " "return a valid token")); break; default: /* Not one of our minor codes; might be from a mech. Call back * to gss_display_status, but first check for recursion. */ if (k5_getspecific(K5_KEY_GSS_SPNEGO_STATUS) != NULL) { /* Perhaps we returned a com_err code like ENOMEM. */ const char *err = error_message(status_value); *status_string = make_err_msg(err); break; } /* Set a non-null pointer value; doesn't matter which one. */ ret = k5_setspecific(K5_KEY_GSS_SPNEGO_STATUS, &ret); if (ret != 0) { *minor_status = ret; maj = GSS_S_FAILURE; break; } maj = gss_display_status(minor_status, status_value, status_type, mech_type, message_context, status_string); /* This is unlikely to fail; not much we can do if it does. */ (void)k5_setspecific(K5_KEY_GSS_SPNEGO_STATUS, NULL); break; } dsyslog("Leaving display_status\n"); return maj; } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_import_name( OM_uint32 *minor_status, gss_buffer_t input_name_buffer, gss_OID input_name_type, gss_name_t *output_name) { OM_uint32 status; dsyslog("Entering import_name\n"); status = gss_import_name(minor_status, input_name_buffer, input_name_type, output_name); dsyslog("Leaving import_name\n"); return (status); } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_release_name( OM_uint32 *minor_status, gss_name_t *input_name) { OM_uint32 status; dsyslog("Entering release_name\n"); status = gss_release_name(minor_status, input_name); dsyslog("Leaving release_name\n"); return (status); } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_duplicate_name( OM_uint32 *minor_status, const gss_name_t input_name, gss_name_t *output_name) { OM_uint32 status; dsyslog("Entering duplicate_name\n"); status = gss_duplicate_name(minor_status, input_name, output_name); dsyslog("Leaving duplicate_name\n"); return (status); } OM_uint32 KRB5_CALLCONV spnego_gss_inquire_cred( OM_uint32 *minor_status, gss_cred_id_t cred_handle, gss_name_t *name, OM_uint32 *lifetime, int *cred_usage, gss_OID_set *mechanisms) { OM_uint32 status; spnego_gss_cred_id_t spcred = NULL; gss_cred_id_t creds = GSS_C_NO_CREDENTIAL; OM_uint32 tmp_minor_status; OM_uint32 initiator_lifetime, acceptor_lifetime; dsyslog("Entering inquire_cred\n"); /* * To avoid infinite recursion, if GSS_C_NO_CREDENTIAL is * supplied we call gss_inquire_cred_by_mech() on the * first non-SPNEGO mechanism. */ spcred = (spnego_gss_cred_id_t)cred_handle; if (spcred == NULL) { status = get_available_mechs(minor_status, GSS_C_NO_NAME, GSS_C_BOTH, GSS_C_NO_CRED_STORE, &creds, mechanisms); if (status != GSS_S_COMPLETE) { dsyslog("Leaving inquire_cred\n"); return (status); } if ((*mechanisms)->count == 0) { gss_release_cred(&tmp_minor_status, &creds); gss_release_oid_set(&tmp_minor_status, mechanisms); dsyslog("Leaving inquire_cred\n"); return (GSS_S_DEFECTIVE_CREDENTIAL); } assert((*mechanisms)->elements != NULL); status = gss_inquire_cred_by_mech(minor_status, creds, &(*mechanisms)->elements[0], name, &initiator_lifetime, &acceptor_lifetime, cred_usage); if (status != GSS_S_COMPLETE) { gss_release_cred(&tmp_minor_status, &creds); dsyslog("Leaving inquire_cred\n"); return (status); } if (lifetime != NULL) *lifetime = (*cred_usage == GSS_C_ACCEPT) ? acceptor_lifetime : initiator_lifetime; gss_release_cred(&tmp_minor_status, &creds); } else { status = gss_inquire_cred(minor_status, spcred->mcred, name, lifetime, cred_usage, mechanisms); } dsyslog("Leaving inquire_cred\n"); return (status); } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_compare_name( OM_uint32 *minor_status, const gss_name_t name1, const gss_name_t name2, int *name_equal) { OM_uint32 status = GSS_S_COMPLETE; dsyslog("Entering compare_name\n"); status = gss_compare_name(minor_status, name1, name2, name_equal); dsyslog("Leaving compare_name\n"); return (status); } /*ARGSUSED*/ /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_display_name( OM_uint32 *minor_status, gss_name_t input_name, gss_buffer_t output_name_buffer, gss_OID *output_name_type) { OM_uint32 status = GSS_S_COMPLETE; dsyslog("Entering display_name\n"); status = gss_display_name(minor_status, input_name, output_name_buffer, output_name_type); dsyslog("Leaving display_name\n"); return (status); } /*ARGSUSED*/ OM_uint32 KRB5_CALLCONV spnego_gss_inquire_names_for_mech( OM_uint32 *minor_status, gss_OID mechanism, gss_OID_set *name_types) { OM_uint32 major, minor; dsyslog("Entering inquire_names_for_mech\n"); /* * We only know how to handle our own mechanism. */ if ((mechanism != GSS_C_NULL_OID) && !g_OID_equal(gss_mech_spnego, mechanism)) { *minor_status = 0; return (GSS_S_FAILURE); } major = gss_create_empty_oid_set(minor_status, name_types); if (major == GSS_S_COMPLETE) { /* Now add our members. */ if (((major = gss_add_oid_set_member(minor_status, (gss_OID) GSS_C_NT_USER_NAME, name_types)) == GSS_S_COMPLETE) && ((major = gss_add_oid_set_member(minor_status, (gss_OID) GSS_C_NT_MACHINE_UID_NAME, name_types)) == GSS_S_COMPLETE) && ((major = gss_add_oid_set_member(minor_status, (gss_OID) GSS_C_NT_STRING_UID_NAME, name_types)) == GSS_S_COMPLETE)) { major = gss_add_oid_set_member(minor_status, (gss_OID) GSS_C_NT_HOSTBASED_SERVICE, name_types); } if (major != GSS_S_COMPLETE) (void) gss_release_oid_set(&minor, name_types); } dsyslog("Leaving inquire_names_for_mech\n"); return (major); } OM_uint32 KRB5_CALLCONV spnego_gss_unwrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap(minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_wrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; ret = gss_wrap(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_process_context_token( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t token_buffer) { OM_uint32 ret; ret = gss_process_context_token(minor_status, context_handle, token_buffer); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_delete_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 ret = GSS_S_COMPLETE; spnego_gss_ctx_id_t *ctx = (spnego_gss_ctx_id_t *)context_handle; *minor_status = 0; if (context_handle == NULL) return (GSS_S_FAILURE); if (*ctx == NULL) return (GSS_S_COMPLETE); /* * If this is still an SPNEGO mech, release it locally. */ if ((*ctx)->magic_num == SPNEGO_MAGIC_ID) { (void) gss_delete_sec_context(minor_status, &(*ctx)->ctx_handle, output_token); (void) release_spnego_ctx(ctx); } else { ret = gss_delete_sec_context(minor_status, context_handle, output_token); } return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_context_time( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, OM_uint32 *time_rec) { OM_uint32 ret; ret = gss_context_time(minor_status, context_handle, time_rec); return (ret); } #ifndef LEAN_CLIENT OM_uint32 KRB5_CALLCONV spnego_gss_export_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 ret; ret = gss_export_sec_context(minor_status, context_handle, interprocess_token); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_import_sec_context( OM_uint32 *minor_status, const gss_buffer_t interprocess_token, gss_ctx_id_t *context_handle) { OM_uint32 ret; ret = gss_import_sec_context(minor_status, interprocess_token, context_handle); return (ret); } #endif /* LEAN_CLIENT */ OM_uint32 KRB5_CALLCONV spnego_gss_inquire_context( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { OM_uint32 ret = GSS_S_COMPLETE; ret = gss_inquire_context(minor_status, context_handle, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, locally_initiated, opened); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_wrap_size_limit( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { OM_uint32 ret; ret = gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_get_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_qop_t qop_req, const gss_buffer_t message_buffer, gss_buffer_t message_token) { OM_uint32 ret; ret = gss_get_mic(minor_status, context_handle, qop_req, message_buffer, message_token); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_verify_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t msg_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_verify_mic(minor_status, context_handle, msg_buffer, token_buffer, qop_state); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_inquire_sec_context_by_oid( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; ret = gss_inquire_sec_context_by_oid(minor_status, context_handle, desired_object, data_set); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_inquire_cred_by_oid( OM_uint32 *minor_status, const gss_cred_id_t cred_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { OM_uint32 ret; spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle; gss_cred_id_t mcred; mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred; ret = gss_inquire_cred_by_oid(minor_status, mcred, desired_object, data_set); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_set_cred_option( OM_uint32 *minor_status, gss_cred_id_t *cred_handle, const gss_OID desired_object, const gss_buffer_t value) { OM_uint32 ret; OM_uint32 tmp_minor_status; spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)*cred_handle; gss_cred_id_t mcred; mcred = (spcred == NULL) ? GSS_C_NO_CREDENTIAL : spcred->mcred; ret = gss_set_cred_option(minor_status, &mcred, desired_object, value); if (ret == GSS_S_COMPLETE && spcred == NULL) { /* * If the mechanism allocated a new credential handle, then * we need to wrap it up in an SPNEGO credential handle. */ spcred = malloc(sizeof(spnego_gss_cred_id_rec)); if (spcred == NULL) { gss_release_cred(&tmp_minor_status, &mcred); *minor_status = ENOMEM; return (GSS_S_FAILURE); } spcred->mcred = mcred; spcred->neg_mechs = GSS_C_NULL_OID_SET; *cred_handle = (gss_cred_id_t)spcred; } return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_set_sec_context_option( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, const gss_OID desired_object, const gss_buffer_t value) { OM_uint32 ret; ret = gss_set_sec_context_option(minor_status, context_handle, desired_object, value); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_wrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_assoc_buffer, gss_buffer_t input_payload_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; ret = gss_wrap_aead(minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap_aead(minor_status, context_handle, input_message_buffer, input_assoc_buffer, output_payload_buffer, conf_state, qop_state); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_wrap_iov(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_unwrap_iov(minor_status, context_handle, conf_state, qop_state, iov, iov_count); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_wrap_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_wrap_iov_length(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_complete_auth_token( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer) { OM_uint32 ret; ret = gss_complete_auth_token(minor_status, context_handle, input_message_buffer); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_acquire_cred_impersonate_name(OM_uint32 *minor_status, const gss_cred_id_t impersonator_cred_handle, const gss_name_t desired_name, OM_uint32 time_req, gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 status; gss_OID_set amechs = GSS_C_NULL_OID_SET; spnego_gss_cred_id_t imp_spcred = NULL, out_spcred = NULL; gss_cred_id_t imp_mcred, out_mcred; dsyslog("Entering spnego_gss_acquire_cred_impersonate_name\n"); if (actual_mechs) *actual_mechs = NULL; if (time_rec) *time_rec = 0; imp_spcred = (spnego_gss_cred_id_t)impersonator_cred_handle; imp_mcred = imp_spcred ? imp_spcred->mcred : GSS_C_NO_CREDENTIAL; if (desired_mechs == GSS_C_NO_OID_SET) { status = gss_inquire_cred(minor_status, imp_mcred, NULL, NULL, NULL, &amechs); if (status != GSS_S_COMPLETE) return status; desired_mechs = amechs; } status = gss_acquire_cred_impersonate_name(minor_status, imp_mcred, desired_name, time_req, desired_mechs, cred_usage, &out_mcred, actual_mechs, time_rec); if (amechs != GSS_C_NULL_OID_SET) (void) gss_release_oid_set(minor_status, &amechs); out_spcred = malloc(sizeof(spnego_gss_cred_id_rec)); if (out_spcred == NULL) { gss_release_cred(minor_status, &out_mcred); *minor_status = ENOMEM; return (GSS_S_FAILURE); } out_spcred->mcred = out_mcred; out_spcred->neg_mechs = GSS_C_NULL_OID_SET; *output_cred_handle = (gss_cred_id_t)out_spcred; dsyslog("Leaving spnego_gss_acquire_cred_impersonate_name\n"); return (status); } OM_uint32 KRB5_CALLCONV spnego_gss_acquire_cred_with_password(OM_uint32 *minor_status, const gss_name_t desired_name, const gss_buffer_t password, OM_uint32 time_req, const gss_OID_set desired_mechs, gss_cred_usage_t cred_usage, gss_cred_id_t *output_cred_handle, gss_OID_set *actual_mechs, OM_uint32 *time_rec) { OM_uint32 status, tmpmin; gss_OID_set amechs = GSS_C_NULL_OID_SET; gss_cred_id_t mcred = NULL; spnego_gss_cred_id_t spcred = NULL; dsyslog("Entering spnego_gss_acquire_cred_with_password\n"); if (actual_mechs) *actual_mechs = NULL; if (time_rec) *time_rec = 0; status = get_available_mechs(minor_status, desired_name, cred_usage, GSS_C_NO_CRED_STORE, NULL, &amechs); if (status != GSS_S_COMPLETE) goto cleanup; status = gss_acquire_cred_with_password(minor_status, desired_name, password, time_req, amechs, cred_usage, &mcred, actual_mechs, time_rec); if (status != GSS_S_COMPLETE) goto cleanup; spcred = malloc(sizeof(spnego_gss_cred_id_rec)); if (spcred == NULL) { *minor_status = ENOMEM; status = GSS_S_FAILURE; goto cleanup; } spcred->neg_mechs = GSS_C_NULL_OID_SET; spcred->mcred = mcred; mcred = GSS_C_NO_CREDENTIAL; *output_cred_handle = (gss_cred_id_t)spcred; cleanup: (void) gss_release_oid_set(&tmpmin, &amechs); (void) gss_release_cred(&tmpmin, &mcred); dsyslog("Leaving spnego_gss_acquire_cred_with_password\n"); return (status); } OM_uint32 KRB5_CALLCONV spnego_gss_display_name_ext(OM_uint32 *minor_status, gss_name_t name, gss_OID display_as_name_type, gss_buffer_t display_name) { OM_uint32 ret; ret = gss_display_name_ext(minor_status, name, display_as_name_type, display_name); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_inquire_name(OM_uint32 *minor_status, gss_name_t name, int *name_is_MN, gss_OID *MN_mech, gss_buffer_set_t *attrs) { OM_uint32 ret; ret = gss_inquire_name(minor_status, name, name_is_MN, MN_mech, attrs); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_get_name_attribute(OM_uint32 *minor_status, gss_name_t name, gss_buffer_t attr, int *authenticated, int *complete, gss_buffer_t value, gss_buffer_t display_value, int *more) { OM_uint32 ret; ret = gss_get_name_attribute(minor_status, name, attr, authenticated, complete, value, display_value, more); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_set_name_attribute(OM_uint32 *minor_status, gss_name_t name, int complete, gss_buffer_t attr, gss_buffer_t value) { OM_uint32 ret; ret = gss_set_name_attribute(minor_status, name, complete, attr, value); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_delete_name_attribute(OM_uint32 *minor_status, gss_name_t name, gss_buffer_t attr) { OM_uint32 ret; ret = gss_delete_name_attribute(minor_status, name, attr); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_export_name_composite(OM_uint32 *minor_status, gss_name_t name, gss_buffer_t exp_composite_name) { OM_uint32 ret; ret = gss_export_name_composite(minor_status, name, exp_composite_name); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_map_name_to_any(OM_uint32 *minor_status, gss_name_t name, int authenticated, gss_buffer_t type_id, gss_any_t *output) { OM_uint32 ret; ret = gss_map_name_to_any(minor_status, name, authenticated, type_id, output); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_release_any_name_mapping(OM_uint32 *minor_status, gss_name_t name, gss_buffer_t type_id, gss_any_t *input) { OM_uint32 ret; ret = gss_release_any_name_mapping(minor_status, name, type_id, input); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { OM_uint32 ret; ret = gss_pseudo_random(minor_status, context, prf_key, prf_in, desired_output_len, prf_out); return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_set_neg_mechs(OM_uint32 *minor_status, gss_cred_id_t cred_handle, const gss_OID_set mech_list) { OM_uint32 ret; spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle; /* Store mech_list in spcred for use in negotiation logic. */ gss_release_oid_set(minor_status, &spcred->neg_mechs); ret = generic_gss_copy_oid_set(minor_status, mech_list, &spcred->neg_mechs); return (ret); } #define SPNEGO_SASL_NAME "SPNEGO" #define SPNEGO_SASL_NAME_LEN (sizeof(SPNEGO_SASL_NAME) - 1) OM_uint32 KRB5_CALLCONV spnego_gss_inquire_mech_for_saslname(OM_uint32 *minor_status, const gss_buffer_t sasl_mech_name, gss_OID *mech_type) { if (sasl_mech_name->length == SPNEGO_SASL_NAME_LEN && memcmp(sasl_mech_name->value, SPNEGO_SASL_NAME, SPNEGO_SASL_NAME_LEN) == 0) { if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_spnego; return (GSS_S_COMPLETE); } return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV spnego_gss_inquire_saslname_for_mech(OM_uint32 *minor_status, const gss_OID desired_mech, gss_buffer_t sasl_mech_name, gss_buffer_t mech_name, gss_buffer_t mech_description) { *minor_status = 0; if (!g_OID_equal(desired_mech, gss_mech_spnego)) return (GSS_S_BAD_MECH); if (!g_make_string_buffer(SPNEGO_SASL_NAME, sasl_mech_name) || !g_make_string_buffer("spnego", mech_name) || !g_make_string_buffer("Simple and Protected GSS-API " "Negotiation Mechanism", mech_description)) goto fail; return (GSS_S_COMPLETE); fail: *minor_status = ENOMEM; return (GSS_S_FAILURE); } OM_uint32 KRB5_CALLCONV spnego_gss_inquire_attrs_for_mech(OM_uint32 *minor_status, gss_const_OID mech, gss_OID_set *mech_attrs, gss_OID_set *known_mech_attrs) { OM_uint32 major, tmpMinor; /* known_mech_attrs is handled by mechglue */ *minor_status = 0; if (mech_attrs == NULL) return (GSS_S_COMPLETE); major = gss_create_empty_oid_set(minor_status, mech_attrs); if (GSS_ERROR(major)) goto cleanup; #define MA_SUPPORTED(ma) do { \ major = gss_add_oid_set_member(minor_status, \ (gss_OID)ma, mech_attrs); \ if (GSS_ERROR(major)) \ goto cleanup; \ } while (0) MA_SUPPORTED(GSS_C_MA_MECH_NEGO); MA_SUPPORTED(GSS_C_MA_ITOK_FRAMED); cleanup: if (GSS_ERROR(major)) gss_release_oid_set(&tmpMinor, mech_attrs); return (major); } OM_uint32 KRB5_CALLCONV spnego_gss_export_cred(OM_uint32 *minor_status, gss_cred_id_t cred_handle, gss_buffer_t token) { spnego_gss_cred_id_t spcred = (spnego_gss_cred_id_t)cred_handle; return (gss_export_cred(minor_status, spcred->mcred, token)); } OM_uint32 KRB5_CALLCONV spnego_gss_import_cred(OM_uint32 *minor_status, gss_buffer_t token, gss_cred_id_t *cred_handle) { OM_uint32 ret; spnego_gss_cred_id_t spcred; gss_cred_id_t mcred; ret = gss_import_cred(minor_status, token, &mcred); if (GSS_ERROR(ret)) return (ret); spcred = malloc(sizeof(*spcred)); if (spcred == NULL) { gss_release_cred(minor_status, &mcred); *minor_status = ENOMEM; return (GSS_S_FAILURE); } spcred->mcred = mcred; spcred->neg_mechs = GSS_C_NULL_OID_SET; *cred_handle = (gss_cred_id_t)spcred; return (ret); } OM_uint32 KRB5_CALLCONV spnego_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { return gss_get_mic_iov(minor_status, context_handle, qop_req, iov, iov_count); } OM_uint32 KRB5_CALLCONV spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov, iov_count); } OM_uint32 KRB5_CALLCONV spnego_gss_get_mic_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { return gss_get_mic_iov_length(minor_status, context_handle, qop_req, iov, iov_count); } /* * We will release everything but the ctx_handle so that it * can be passed back to init/accept context. This routine should * not be called until after the ctx_handle memory is assigned to * the supplied context handle from init/accept context. */ static void release_spnego_ctx(spnego_gss_ctx_id_t *ctx) { spnego_gss_ctx_id_t context; OM_uint32 minor_stat; context = *ctx; if (context != NULL) { (void) gss_release_buffer(&minor_stat, &context->DER_mechTypes); (void) gss_release_oid_set(&minor_stat, &context->mech_set); (void) gss_release_name(&minor_stat, &context->internal_name); if (context->optionStr != NULL) { free(context->optionStr); context->optionStr = NULL; } free(context); *ctx = NULL; } } /* * Can't use gss_indicate_mechs by itself to get available mechs for * SPNEGO because it will also return the SPNEGO mech and we do not * want to consider SPNEGO as an available security mech for * negotiation. For this reason, get_available_mechs will return * all available mechs except SPNEGO. * * If a ptr to a creds list is given, this function will attempt * to acquire creds for the creds given and trim the list of * returned mechanisms to only those for which creds are valid. * */ static OM_uint32 get_available_mechs(OM_uint32 *minor_status, gss_name_t name, gss_cred_usage_t usage, gss_const_key_value_set_t cred_store, gss_cred_id_t *creds, gss_OID_set *rmechs) { unsigned int i; int found = 0; OM_uint32 major_status = GSS_S_COMPLETE, tmpmin; gss_OID_set mechs, goodmechs; major_status = gss_indicate_mechs(minor_status, &mechs); if (major_status != GSS_S_COMPLETE) { return (major_status); } major_status = gss_create_empty_oid_set(minor_status, rmechs); if (major_status != GSS_S_COMPLETE) { (void) gss_release_oid_set(minor_status, &mechs); return (major_status); } for (i = 0; i < mechs->count && major_status == GSS_S_COMPLETE; i++) { if ((mechs->elements[i].length != spnego_mechanism.mech_type.length) || memcmp(mechs->elements[i].elements, spnego_mechanism.mech_type.elements, spnego_mechanism.mech_type.length)) { major_status = gss_add_oid_set_member(minor_status, &mechs->elements[i], rmechs); if (major_status == GSS_S_COMPLETE) found++; } } /* * If the caller wanted a list of creds returned, * trim the list of mechanisms down to only those * for which the creds are valid. */ if (found > 0 && major_status == GSS_S_COMPLETE && creds != NULL) { major_status = gss_acquire_cred_from(minor_status, name, GSS_C_INDEFINITE, *rmechs, usage, cred_store, creds, &goodmechs, NULL); /* * Drop the old list in favor of the new * "trimmed" list. */ (void) gss_release_oid_set(&tmpmin, rmechs); if (major_status == GSS_S_COMPLETE) { (void) gssint_copy_oid_set(&tmpmin, goodmechs, rmechs); (void) gss_release_oid_set(&tmpmin, &goodmechs); } } (void) gss_release_oid_set(&tmpmin, &mechs); if (found == 0 || major_status != GSS_S_COMPLETE) { *minor_status = ERR_SPNEGO_NO_MECHS_AVAILABLE; map_errcode(minor_status); if (major_status == GSS_S_COMPLETE) major_status = GSS_S_FAILURE; } return (major_status); } /* * Return a list of mechanisms we are willing to negotiate for a credential, * taking into account the mech set provided with gss_set_neg_mechs if it * exists. */ static OM_uint32 get_negotiable_mechs(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_cred_usage_t usage, gss_OID_set *rmechs) { OM_uint32 ret, tmpmin; gss_cred_id_t creds = GSS_C_NO_CREDENTIAL, *credptr; gss_OID_set cred_mechs = GSS_C_NULL_OID_SET; gss_OID_set intersect_mechs = GSS_C_NULL_OID_SET; unsigned int i; int present; if (spcred == NULL) { /* * The default credentials were supplied. Return a list of all * available mechs except SPNEGO. When initiating, trim this * list to mechs we can acquire credentials for. */ credptr = (usage == GSS_C_INITIATE) ? &creds : NULL; ret = get_available_mechs(minor_status, GSS_C_NO_NAME, usage, GSS_C_NO_CRED_STORE, credptr, rmechs); gss_release_cred(&tmpmin, &creds); return (ret); } /* Get the list of mechs in the mechglue cred. */ ret = gss_inquire_cred(minor_status, spcred->mcred, NULL, NULL, NULL, &cred_mechs); if (ret != GSS_S_COMPLETE) return (ret); if (spcred->neg_mechs == GSS_C_NULL_OID_SET) { /* gss_set_neg_mechs was never called; return cred_mechs. */ *rmechs = cred_mechs; *minor_status = 0; return (GSS_S_COMPLETE); } /* Compute the intersection of cred_mechs and spcred->neg_mechs, * preserving the order in spcred->neg_mechs. */ ret = gss_create_empty_oid_set(minor_status, &intersect_mechs); if (ret != GSS_S_COMPLETE) { gss_release_oid_set(&tmpmin, &cred_mechs); return (ret); } for (i = 0; i < spcred->neg_mechs->count; i++) { gss_test_oid_set_member(&tmpmin, &spcred->neg_mechs->elements[i], cred_mechs, &present); if (!present) continue; ret = gss_add_oid_set_member(minor_status, &spcred->neg_mechs->elements[i], &intersect_mechs); if (ret != GSS_S_COMPLETE) break; } gss_release_oid_set(&tmpmin, &cred_mechs); if (intersect_mechs->count == 0 || ret != GSS_S_COMPLETE) { gss_release_oid_set(&tmpmin, &intersect_mechs); *minor_status = ERR_SPNEGO_NO_MECHS_AVAILABLE; map_errcode(minor_status); return (GSS_S_FAILURE); } *rmechs = intersect_mechs; *minor_status = 0; return (GSS_S_COMPLETE); } /* following are token creation and reading routines */ /* * If buff_in is not pointing to a MECH_OID, then return NULL and do not * advance the buffer, otherwise, decode the mech_oid from the buffer and * place in gss_OID. */ static gss_OID get_mech_oid(OM_uint32 *minor_status, unsigned char **buff_in, size_t length) { OM_uint32 status; gss_OID_desc toid; gss_OID mech_out = NULL; unsigned char *start, *end; if (length < 1 || **buff_in != MECH_OID) return (NULL); start = *buff_in; end = start + length; (*buff_in)++; toid.length = *(*buff_in)++; if ((*buff_in + toid.length) > end) return (NULL); toid.elements = *buff_in; *buff_in += toid.length; status = generic_gss_copy_oid(minor_status, &toid, &mech_out); if (status != GSS_S_COMPLETE) { map_errcode(minor_status); mech_out = NULL; } return (mech_out); } /* * der encode the given mechanism oid into buf_out, advancing the * buffer pointer. */ static int put_mech_oid(unsigned char **buf_out, gss_OID_const mech, unsigned int buflen) { if (buflen < mech->length + 2) return (-1); *(*buf_out)++ = MECH_OID; *(*buf_out)++ = (unsigned char) mech->length; memcpy(*buf_out, mech->elements, mech->length); *buf_out += mech->length; return (0); } /* * verify that buff_in points to an octet string, if it does not, * return NULL and don't advance the pointer. If it is an octet string * decode buff_in into a gss_buffer_t and return it, advancing the * buffer pointer. */ static gss_buffer_t get_input_token(unsigned char **buff_in, unsigned int buff_length) { gss_buffer_t input_token; unsigned int len; if (g_get_tag_and_length(buff_in, OCTET_STRING, buff_length, &len) < 0) return (NULL); input_token = (gss_buffer_t)malloc(sizeof (gss_buffer_desc)); if (input_token == NULL) return (NULL); input_token->length = len; if (input_token->length > 0) { input_token->value = gssalloc_malloc(input_token->length); if (input_token->value == NULL) { free(input_token); return (NULL); } memcpy(input_token->value, *buff_in, input_token->length); } else { input_token->value = NULL; } *buff_in += input_token->length; return (input_token); } /* * verify that the input token length is not 0. If it is, just return. * If the token length is greater than 0, der encode as an octet string * and place in buf_out, advancing buf_out. */ static int put_input_token(unsigned char **buf_out, gss_buffer_t input_token, unsigned int buflen) { int ret; /* if token length is 0, we do not want to send */ if (input_token->length == 0) return (0); if (input_token->length > buflen) return (-1); *(*buf_out)++ = OCTET_STRING; if ((ret = gssint_put_der_length(input_token->length, buf_out, input_token->length))) return (ret); TWRITE_STR(*buf_out, input_token->value, input_token->length); return (0); } /* * verify that buff_in points to a sequence of der encoding. The mech * set is the only sequence of encoded object in the token, so if it is * a sequence of encoding, decode the mechset into a gss_OID_set and * return it, advancing the buffer pointer. */ static gss_OID_set get_mech_set(OM_uint32 *minor_status, unsigned char **buff_in, unsigned int buff_length) { gss_OID_set returned_mechSet; OM_uint32 major_status; int length; unsigned int bytes; OM_uint32 set_length; unsigned char *start; int i; if (**buff_in != SEQUENCE_OF) return (NULL); start = *buff_in; (*buff_in)++; length = gssint_get_der_length(buff_in, buff_length, &bytes); if (length < 0 || buff_length - bytes < (unsigned int)length) return NULL; major_status = gss_create_empty_oid_set(minor_status, &returned_mechSet); if (major_status != GSS_S_COMPLETE) return (NULL); for (set_length = 0, i = 0; set_length < (unsigned int)length; i++) { gss_OID_desc *temp = get_mech_oid(minor_status, buff_in, buff_length - (*buff_in - start)); if (temp == NULL) break; major_status = gss_add_oid_set_member(minor_status, temp, &returned_mechSet); if (major_status == GSS_S_COMPLETE) { set_length += returned_mechSet->elements[i].length +2; if (generic_gss_release_oid(minor_status, &temp)) map_errcode(minor_status); } } return (returned_mechSet); } /* * Encode mechSet into buf. */ static int put_mech_set(gss_OID_set mechSet, gss_buffer_t buf) { unsigned char *ptr; unsigned int i; unsigned int tlen, ilen; tlen = ilen = 0; for (i = 0; i < mechSet->count; i++) { /* * 0x06 [DER LEN] [OID] */ ilen += 1 + gssint_der_length_size(mechSet->elements[i].length) + mechSet->elements[i].length; } /* * 0x30 [DER LEN] */ tlen = 1 + gssint_der_length_size(ilen) + ilen; ptr = gssalloc_malloc(tlen); if (ptr == NULL) return -1; buf->value = ptr; buf->length = tlen; #define REMAIN (buf->length - ((unsigned char *)buf->value - ptr)) *ptr++ = SEQUENCE_OF; if (gssint_put_der_length(ilen, &ptr, REMAIN) < 0) return -1; for (i = 0; i < mechSet->count; i++) { if (put_mech_oid(&ptr, &mechSet->elements[i], REMAIN) < 0) { return -1; } } return 0; #undef REMAIN } /* * Verify that buff_in is pointing to a BIT_STRING with the correct * length and padding for the req_flags. If it is, decode req_flags * and return them, otherwise, return NULL. */ static OM_uint32 get_req_flags(unsigned char **buff_in, OM_uint32 bodysize, OM_uint32 *req_flags) { unsigned int len; if (**buff_in != (CONTEXT | 0x01)) return (0); if (g_get_tag_and_length(buff_in, (CONTEXT | 0x01), bodysize, &len) < 0) return GSS_S_DEFECTIVE_TOKEN; if (*(*buff_in)++ != BIT_STRING) return GSS_S_DEFECTIVE_TOKEN; if (*(*buff_in)++ != BIT_STRING_LENGTH) return GSS_S_DEFECTIVE_TOKEN; if (*(*buff_in)++ != BIT_STRING_PADDING) return GSS_S_DEFECTIVE_TOKEN; *req_flags = (OM_uint32) (*(*buff_in)++ >> 1); return (0); } static OM_uint32 get_negTokenInit(OM_uint32 *minor_status, gss_buffer_t buf, gss_buffer_t der_mechSet, gss_OID_set *mechSet, OM_uint32 *req_flags, gss_buffer_t *mechtok, gss_buffer_t *mechListMIC) { OM_uint32 err; unsigned char *ptr, *bufstart; unsigned int len; gss_buffer_desc tmpbuf; *minor_status = 0; der_mechSet->length = 0; der_mechSet->value = NULL; *mechSet = GSS_C_NO_OID_SET; *req_flags = 0; *mechtok = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf->value; if ((buf->length - (ptr - bufstart)) > INT_MAX) return GSS_S_FAILURE; #define REMAIN (buf->length - (ptr - bufstart)) err = g_verify_token_header(gss_mech_spnego, &len, &ptr, 0, REMAIN); if (err) { *minor_status = err; map_errcode(minor_status); return GSS_S_FAILURE; } *minor_status = g_verify_neg_token_init(&ptr, REMAIN); if (*minor_status) { map_errcode(minor_status); return GSS_S_FAILURE; } /* alias into input_token */ tmpbuf.value = ptr; tmpbuf.length = REMAIN; *mechSet = get_mech_set(minor_status, &ptr, REMAIN); if (*mechSet == NULL) return GSS_S_FAILURE; tmpbuf.length = ptr - (unsigned char *)tmpbuf.value; der_mechSet->value = gssalloc_malloc(tmpbuf.length); if (der_mechSet->value == NULL) return GSS_S_FAILURE; memcpy(der_mechSet->value, tmpbuf.value, tmpbuf.length); der_mechSet->length = tmpbuf.length; err = get_req_flags(&ptr, REMAIN, req_flags); if (err != GSS_S_COMPLETE) { return err; } if (g_get_tag_and_length(&ptr, (CONTEXT | 0x02), REMAIN, &len) >= 0) { *mechtok = get_input_token(&ptr, len); if (*mechtok == GSS_C_NO_BUFFER) { return GSS_S_FAILURE; } } if (g_get_tag_and_length(&ptr, (CONTEXT | 0x03), REMAIN, &len) >= 0) { *mechListMIC = get_input_token(&ptr, len); if (*mechListMIC == GSS_C_NO_BUFFER) { return GSS_S_FAILURE; } } return GSS_S_COMPLETE; #undef REMAIN } static OM_uint32 get_negTokenResp(OM_uint32 *minor_status, unsigned char *buf, unsigned int buflen, OM_uint32 *negState, gss_OID *supportedMech, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC) { unsigned char *ptr, *bufstart; unsigned int len; int tmplen; unsigned int tag, bytes; *negState = ACCEPT_DEFECTIVE_TOKEN; *supportedMech = GSS_C_NO_OID; *responseToken = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf; #define REMAIN (buflen - (ptr - bufstart)) if (g_get_tag_and_length(&ptr, (CONTEXT | 0x01), REMAIN, &len) < 0) return GSS_S_DEFECTIVE_TOKEN; if (*ptr++ == SEQUENCE) { tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes); if (tmplen < 0 || REMAIN < (unsigned int)tmplen) return GSS_S_DEFECTIVE_TOKEN; } if (REMAIN < 1) tag = 0; else tag = *ptr++; if (tag == CONTEXT) { tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes); if (tmplen < 0 || REMAIN < (unsigned int)tmplen) return GSS_S_DEFECTIVE_TOKEN; if (g_get_tag_and_length(&ptr, ENUMERATED, REMAIN, &len) < 0) return GSS_S_DEFECTIVE_TOKEN; if (len != ENUMERATION_LENGTH) return GSS_S_DEFECTIVE_TOKEN; if (REMAIN < 1) return GSS_S_DEFECTIVE_TOKEN; *negState = *ptr++; if (REMAIN < 1) tag = 0; else tag = *ptr++; } if (tag == (CONTEXT | 0x01)) { tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes); if (tmplen < 0 || REMAIN < (unsigned int)tmplen) return GSS_S_DEFECTIVE_TOKEN; *supportedMech = get_mech_oid(minor_status, &ptr, REMAIN); if (*supportedMech == GSS_C_NO_OID) return GSS_S_DEFECTIVE_TOKEN; if (REMAIN < 1) tag = 0; else tag = *ptr++; } if (tag == (CONTEXT | 0x02)) { tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes); if (tmplen < 0 || REMAIN < (unsigned int)tmplen) return GSS_S_DEFECTIVE_TOKEN; *responseToken = get_input_token(&ptr, REMAIN); if (*responseToken == GSS_C_NO_BUFFER) return GSS_S_DEFECTIVE_TOKEN; if (REMAIN < 1) tag = 0; else tag = *ptr++; } if (tag == (CONTEXT | 0x03)) { tmplen = gssint_get_der_length(&ptr, REMAIN, &bytes); if (tmplen < 0 || REMAIN < (unsigned int)tmplen) return GSS_S_DEFECTIVE_TOKEN; *mechListMIC = get_input_token(&ptr, REMAIN); if (*mechListMIC == GSS_C_NO_BUFFER) return GSS_S_DEFECTIVE_TOKEN; /* Handle Windows 2000 duplicate response token */ if (*responseToken && ((*responseToken)->length == (*mechListMIC)->length) && !memcmp((*responseToken)->value, (*mechListMIC)->value, (*responseToken)->length)) { OM_uint32 tmpmin; gss_release_buffer(&tmpmin, *mechListMIC); free(*mechListMIC); *mechListMIC = NULL; } } return GSS_S_COMPLETE; #undef REMAIN } /* * der encode the passed negResults as an ENUMERATED type and * place it in buf_out, advancing the buffer. */ static int put_negResult(unsigned char **buf_out, OM_uint32 negResult, unsigned int buflen) { if (buflen < 3) return (-1); *(*buf_out)++ = ENUMERATED; *(*buf_out)++ = ENUMERATION_LENGTH; *(*buf_out)++ = (unsigned char) negResult; return (0); } /* * This routine compares the recieved mechset to the mechset that * this server can support. It looks sequentially through the mechset * and the first one that matches what the server can support is * chosen as the negotiated mechanism. If one is found, negResult * is set to ACCEPT_INCOMPLETE if it's the first mech, REQUEST_MIC if * it's not the first mech, otherwise we return NULL and negResult * is set to REJECT. The returned pointer is an alias into * received->elements and should not be freed. * * NOTE: There is currently no way to specify a preference order of * mechanisms supported by the acceptor. */ static gss_OID negotiate_mech(gss_OID_set supported, gss_OID_set received, OM_uint32 *negResult) { size_t i, j; for (i = 0; i < received->count; i++) { gss_OID mech_oid = &received->elements[i]; /* Accept wrong mechanism OID from MS clients */ if (g_OID_equal(mech_oid, &gss_mech_krb5_wrong_oid)) mech_oid = (gss_OID)&gss_mech_krb5_oid; for (j = 0; j < supported->count; j++) { if (g_OID_equal(mech_oid, &supported->elements[j])) { *negResult = (i == 0) ? ACCEPT_INCOMPLETE : REQUEST_MIC; return &received->elements[i]; } } } *negResult = REJECT; return (NULL); } /* * the next two routines make a token buffer suitable for * spnego_gss_display_status. These currently take the string * in name and place it in the token. Eventually, if * spnego_gss_display_status returns valid error messages, * these routines will be changes to return the error string. */ static spnego_token_t make_spnego_token(const char *name) { return (spnego_token_t)strdup(name); } static gss_buffer_desc make_err_msg(const char *name) { gss_buffer_desc buffer; if (name == NULL) { buffer.length = 0; buffer.value = NULL; } else { buffer.length = strlen(name)+1; buffer.value = make_spnego_token(name); } return (buffer); } /* * Create the client side spnego token passed back to gss_init_sec_context * and eventually up to the application program and over to the server. * * Use DER rules, definite length method per RFC 2478 */ static int make_spnego_tokenInit_msg(spnego_gss_ctx_id_t spnego_ctx, int negHintsCompat, gss_buffer_t mechListMIC, OM_uint32 req_flags, gss_buffer_t data, send_token_flag sendtoken, gss_buffer_t outbuf) { int ret = 0; unsigned int tlen, dataLen = 0; unsigned int negTokenInitSize = 0; unsigned int negTokenInitSeqSize = 0; unsigned int negTokenInitContSize = 0; unsigned int rspTokenSize = 0; unsigned int mechListTokenSize = 0; unsigned int micTokenSize = 0; unsigned char *t; unsigned char *ptr; if (outbuf == GSS_C_NO_BUFFER) return (-1); outbuf->length = 0; outbuf->value = NULL; /* calculate the data length */ /* * 0xa0 [DER LEN] [mechTypes] */ mechListTokenSize = 1 + gssint_der_length_size(spnego_ctx->DER_mechTypes.length) + spnego_ctx->DER_mechTypes.length; dataLen += mechListTokenSize; /* * If a token from gss_init_sec_context exists, * add the length of the token + the ASN.1 overhead */ if (data != NULL) { /* * Encoded in final output as: * 0xa2 [DER LEN] 0x04 [DER LEN] [DATA] * -----s--------|--------s2---------- */ rspTokenSize = 1 + gssint_der_length_size(data->length) + data->length; dataLen += 1 + gssint_der_length_size(rspTokenSize) + rspTokenSize; } if (mechListMIC) { /* * Encoded in final output as: * 0xa3 [DER LEN] 0x04 [DER LEN] [DATA] * --s-- -----tlen------------ */ micTokenSize = 1 + gssint_der_length_size(mechListMIC->length) + mechListMIC->length; dataLen += 1 + gssint_der_length_size(micTokenSize) + micTokenSize; } /* * Add size of DER encoding * [ SEQUENCE { MechTypeList | ReqFLags | Token | mechListMIC } ] * 0x30 [DER_LEN] [data] * */ negTokenInitContSize = dataLen; negTokenInitSeqSize = 1 + gssint_der_length_size(dataLen) + dataLen; dataLen = negTokenInitSeqSize; /* * negTokenInitSize indicates the bytes needed to * hold the ASN.1 encoding of the entire NegTokenInit * SEQUENCE. * 0xa0 [DER_LEN] + data * */ negTokenInitSize = 1 + gssint_der_length_size(negTokenInitSeqSize) + negTokenInitSeqSize; tlen = g_token_size(gss_mech_spnego, negTokenInitSize); t = (unsigned char *) gssalloc_malloc(tlen); if (t == NULL) { return (-1); } ptr = t; /* create the message */ if ((ret = g_make_token_header(gss_mech_spnego, negTokenInitSize, &ptr, tlen))) goto errout; *ptr++ = CONTEXT; /* NegotiationToken identifier */ if ((ret = gssint_put_der_length(negTokenInitSeqSize, &ptr, tlen))) goto errout; *ptr++ = SEQUENCE; if ((ret = gssint_put_der_length(negTokenInitContSize, &ptr, tlen - (int)(ptr-t)))) goto errout; *ptr++ = CONTEXT | 0x00; /* MechTypeList identifier */ if ((ret = gssint_put_der_length(spnego_ctx->DER_mechTypes.length, &ptr, tlen - (int)(ptr-t)))) goto errout; /* We already encoded the MechSetList */ (void) memcpy(ptr, spnego_ctx->DER_mechTypes.value, spnego_ctx->DER_mechTypes.length); ptr += spnego_ctx->DER_mechTypes.length; if (data != NULL) { *ptr++ = CONTEXT | 0x02; if ((ret = gssint_put_der_length(rspTokenSize, &ptr, tlen - (int)(ptr - t)))) goto errout; if ((ret = put_input_token(&ptr, data, tlen - (int)(ptr - t)))) goto errout; } if (mechListMIC != GSS_C_NO_BUFFER) { *ptr++ = CONTEXT | 0x03; if ((ret = gssint_put_der_length(micTokenSize, &ptr, tlen - (int)(ptr - t)))) goto errout; if (negHintsCompat) { ret = put_neg_hints(&ptr, mechListMIC, tlen - (int)(ptr - t)); if (ret) goto errout; } else if ((ret = put_input_token(&ptr, mechListMIC, tlen - (int)(ptr - t)))) goto errout; } errout: if (ret != 0) { if (t) free(t); t = NULL; tlen = 0; } outbuf->length = tlen; outbuf->value = (void *) t; return (ret); } /* * create the server side spnego token passed back to * gss_accept_sec_context and eventually up to the application program * and over to the client. */ static int make_spnego_tokenTarg_msg(OM_uint32 status, gss_OID mech_wanted, gss_buffer_t data, gss_buffer_t mechListMIC, send_token_flag sendtoken, gss_buffer_t outbuf) { unsigned int tlen = 0; unsigned int ret = 0; unsigned int NegTokenTargSize = 0; unsigned int NegTokenSize = 0; unsigned int rspTokenSize = 0; unsigned int micTokenSize = 0; unsigned int dataLen = 0; unsigned char *t; unsigned char *ptr; if (outbuf == GSS_C_NO_BUFFER) return (GSS_S_DEFECTIVE_TOKEN); if (sendtoken == INIT_TOKEN_SEND && mech_wanted == GSS_C_NO_OID) return (GSS_S_DEFECTIVE_TOKEN); outbuf->length = 0; outbuf->value = NULL; /* * ASN.1 encoding of the negResult * ENUMERATED type is 3 bytes * ENUMERATED TAG, Length, Value, * Plus 2 bytes for the CONTEXT id and length. */ dataLen = 5; /* * calculate data length * * If this is the initial token, include length of * mech_type and the negotiation result fields. */ if (sendtoken == INIT_TOKEN_SEND) { int mechlistTokenSize; /* * 1 byte for the CONTEXT ID(0xa0), * 1 byte for the OID ID(0x06) * 1 byte for OID Length field * Plus the rest... (OID Length, OID value) */ mechlistTokenSize = 3 + mech_wanted->length + gssint_der_length_size(mech_wanted->length); dataLen += mechlistTokenSize; } if (data != NULL && data->length > 0) { /* Length of the inner token */ rspTokenSize = 1 + gssint_der_length_size(data->length) + data->length; dataLen += rspTokenSize; /* Length of the outer token */ dataLen += 1 + gssint_der_length_size(rspTokenSize); } if (mechListMIC != NULL) { /* Length of the inner token */ micTokenSize = 1 + gssint_der_length_size(mechListMIC->length) + mechListMIC->length; dataLen += micTokenSize; /* Length of the outer token */ dataLen += 1 + gssint_der_length_size(micTokenSize); } /* * Add size of DER encoded: * NegTokenTarg [ SEQUENCE ] of * NegResult[0] ENUMERATED { * accept_completed(0), * accept_incomplete(1), * reject(2) } * supportedMech [1] MechType OPTIONAL, * responseToken [2] OCTET STRING OPTIONAL, * mechListMIC [3] OCTET STRING OPTIONAL * * size = data->length + MechListMic + SupportedMech len + * Result Length + ASN.1 overhead */ NegTokenTargSize = dataLen; dataLen += 1 + gssint_der_length_size(NegTokenTargSize); /* * NegotiationToken [ CHOICE ]{ * negTokenInit [0] NegTokenInit, * negTokenTarg [1] NegTokenTarg } */ NegTokenSize = dataLen; dataLen += 1 + gssint_der_length_size(NegTokenSize); tlen = dataLen; t = (unsigned char *) gssalloc_malloc(tlen); if (t == NULL) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } ptr = t; /* * Indicate that we are sending CHOICE 1 * (NegTokenTarg) */ *ptr++ = CONTEXT | 0x01; if (gssint_put_der_length(NegTokenSize, &ptr, dataLen) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } *ptr++ = SEQUENCE; if (gssint_put_der_length(NegTokenTargSize, &ptr, tlen - (int)(ptr-t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } /* * First field of the NegTokenTarg SEQUENCE * is the ENUMERATED NegResult. */ *ptr++ = CONTEXT; if (gssint_put_der_length(3, &ptr, tlen - (int)(ptr-t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } if (put_negResult(&ptr, status, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } if (sendtoken == INIT_TOKEN_SEND) { /* * Next, is the Supported MechType */ *ptr++ = CONTEXT | 0x01; if (gssint_put_der_length(mech_wanted->length + 2, &ptr, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } if (put_mech_oid(&ptr, mech_wanted, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } } if (data != NULL && data->length > 0) { *ptr++ = CONTEXT | 0x02; if (gssint_put_der_length(rspTokenSize, &ptr, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } if (put_input_token(&ptr, data, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } } if (mechListMIC != NULL) { *ptr++ = CONTEXT | 0x03; if (gssint_put_der_length(micTokenSize, &ptr, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } if (put_input_token(&ptr, mechListMIC, tlen - (int)(ptr - t)) < 0) { ret = GSS_S_DEFECTIVE_TOKEN; goto errout; } } ret = GSS_S_COMPLETE; errout: if (ret != GSS_S_COMPLETE) { if (t) free(t); } else { outbuf->length = ptr - t; outbuf->value = (void *) t; } return (ret); } /* determine size of token */ static int g_token_size(gss_OID_const mech, unsigned int body_size) { int hdrsize; /* * Initialize the header size to the * MECH_OID byte + the bytes needed to indicate the * length of the OID + the OID itself. * * 0x06 [MECHLENFIELD] MECHDATA */ hdrsize = 1 + gssint_der_length_size(mech->length) + mech->length; /* * Now add the bytes needed for the initial header * token bytes: * 0x60 + [DER_LEN] + HDRSIZE */ hdrsize += 1 + gssint_der_length_size(body_size + hdrsize); return (hdrsize + body_size); } /* * generate token header. * * Use DER Definite Length method per RFC2478 * Use of indefinite length encoding will not be compatible * with Microsoft or others that actually follow the spec. */ static int g_make_token_header(gss_OID_const mech, unsigned int body_size, unsigned char **buf, unsigned int totallen) { int ret = 0; unsigned int hdrsize; unsigned char *p = *buf; hdrsize = 1 + gssint_der_length_size(mech->length) + mech->length; *(*buf)++ = HEADER_ID; if ((ret = gssint_put_der_length(hdrsize + body_size, buf, totallen))) return (ret); *(*buf)++ = MECH_OID; if ((ret = gssint_put_der_length(mech->length, buf, totallen - (int)(p - *buf)))) return (ret); TWRITE_STR(*buf, mech->elements, mech->length); return (0); } /* * NOTE: This checks that the length returned by * gssint_get_der_length() is not greater than the number of octets * remaining, even though gssint_get_der_length() already checks, in * theory. */ static int g_get_tag_and_length(unsigned char **buf, int tag, unsigned int buflen, unsigned int *outlen) { unsigned char *ptr = *buf; int ret = -1; /* pessimists, assume failure ! */ unsigned int encoded_len; int tmplen = 0; *outlen = 0; if (buflen > 1 && *ptr == tag) { ptr++; tmplen = gssint_get_der_length(&ptr, buflen - 1, &encoded_len); if (tmplen < 0) { ret = -1; } else if ((unsigned int)tmplen > buflen - (ptr - *buf)) { ret = -1; } else ret = 0; } *outlen = tmplen; *buf = ptr; return (ret); } static int g_verify_neg_token_init(unsigned char **buf_in, unsigned int cur_size) { unsigned char *buf = *buf_in; unsigned char *endptr = buf + cur_size; int seqsize; int ret = 0; unsigned int bytes; /* * Verify this is a NegotiationToken type token * - check for a0(context specific identifier) * - get length and verify that enoughd ata exists */ if (g_get_tag_and_length(&buf, CONTEXT, cur_size, &bytes) < 0) return (G_BAD_TOK_HEADER); cur_size = bytes; /* should indicate bytes remaining */ /* * Verify the next piece, it should identify this as * a strucure of type NegTokenInit. */ if (*buf++ == SEQUENCE) { if ((seqsize = gssint_get_der_length(&buf, cur_size, &bytes)) < 0) return (G_BAD_TOK_HEADER); /* * Make sure we have the entire buffer as described */ if (seqsize > endptr - buf) return (G_BAD_TOK_HEADER); } else { return (G_BAD_TOK_HEADER); } cur_size = seqsize; /* should indicate bytes remaining */ /* * Verify that the first blob is a sequence of mechTypes */ if (*buf++ == CONTEXT) { if ((seqsize = gssint_get_der_length(&buf, cur_size, &bytes)) < 0) return (G_BAD_TOK_HEADER); /* * Make sure we have the entire buffer as described */ if (seqsize > endptr - buf) return (G_BAD_TOK_HEADER); } else { return (G_BAD_TOK_HEADER); } /* * At this point, *buf should be at the beginning of the * DER encoded list of mech types that are to be negotiated. */ *buf_in = buf; return (ret); } /* verify token header. */ static int g_verify_token_header(gss_OID_const mech, unsigned int *body_size, unsigned char **buf_in, int tok_type, unsigned int toksize) { unsigned char *buf = *buf_in; int seqsize; gss_OID_desc toid; int ret = 0; unsigned int bytes; if (toksize-- < 1) return (G_BAD_TOK_HEADER); if (*buf++ != HEADER_ID) return (G_BAD_TOK_HEADER); if ((seqsize = gssint_get_der_length(&buf, toksize, &bytes)) < 0) return (G_BAD_TOK_HEADER); if ((seqsize + bytes) != toksize) return (G_BAD_TOK_HEADER); if (toksize-- < 1) return (G_BAD_TOK_HEADER); if (*buf++ != MECH_OID) return (G_BAD_TOK_HEADER); if (toksize-- < 1) return (G_BAD_TOK_HEADER); toid.length = *buf++; if (toksize < toid.length) return (G_BAD_TOK_HEADER); else toksize -= toid.length; toid.elements = buf; buf += toid.length; if (!g_OID_equal(&toid, mech)) ret = G_WRONG_MECH; /* * G_WRONG_MECH is not returned immediately because it's more important * to return G_BAD_TOK_HEADER if the token header is in fact bad */ if (toksize < 2) return (G_BAD_TOK_HEADER); else toksize -= 2; if (!ret) { *buf_in = buf; *body_size = toksize; } return (ret); } /* * Return non-zero if the oid is one of the kerberos mech oids, * otherwise return zero. * * N.B. There are 3 oids that represent the kerberos mech: * RFC-specified GSS_MECH_KRB5_OID, * Old pre-RFC GSS_MECH_KRB5_OLD_OID, * Incorrect MS GSS_MECH_KRB5_WRONG_OID */ static int is_kerb_mech(gss_OID oid) { int answer = 0; OM_uint32 minor; extern const gss_OID_set_desc * const gss_mech_set_krb5_both; (void) gss_test_oid_set_member(&minor, oid, (gss_OID_set)gss_mech_set_krb5_both, &answer); return (answer); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2198_0
crossvul-cpp_data_bad_348_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid= fs->cache.array[x].objectId.id; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count+=2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_2
crossvul-cpp_data_good_2579_11
/* #pragma ident "@(#)g_unseal.c 1.13 98/01/22 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine gss_unwrap */ #include "mglueP.h" OM_uint32 KRB5_CALLCONV gss_unwrap (minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t input_message_buffer; gss_buffer_t output_message_buffer; int * conf_state; gss_qop_t * qop_state; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status != NULL) *minor_status = 0; if (output_message_buffer != GSS_C_NO_BUFFER) { output_message_buffer->length = 0; output_message_buffer->value = NULL; } if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (input_message_buffer == GSS_C_NO_BUFFER || GSS_EMPTY_BUFFER(input_message_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); if (output_message_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_unwrap) { status = mech->gss_unwrap(minor_status, ctx->internal_ctx_id, input_message_buffer, output_message_buffer, conf_state, qop_state); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else if (mech->gss_unwrap_aead || mech->gss_unwrap_iov) { status = gssint_unwrap_aead(mech, minor_status, ctx, input_message_buffer, GSS_C_NO_BUFFER, output_message_buffer, conf_state, (gss_qop_t *)qop_state); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_unseal (minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t input_message_buffer; gss_buffer_t output_message_buffer; int * conf_state; int * qop_state; { return (gss_unwrap(minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, (gss_qop_t *) qop_state)); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_11
crossvul-cpp_data_good_745_2
#include <string.h> #include <stdlib.h> #include "secretservice_linux.h" const SecretSchema *docker_get_schema(void) { static const SecretSchema docker_schema = { "io.docker.Credentials", SECRET_SCHEMA_NONE, { { "label", SECRET_SCHEMA_ATTRIBUTE_STRING }, { "server", SECRET_SCHEMA_ATTRIBUTE_STRING }, { "username", SECRET_SCHEMA_ATTRIBUTE_STRING }, { "docker_cli", SECRET_SCHEMA_ATTRIBUTE_STRING }, { "NULL", 0 }, } }; return &docker_schema; } GError *add(char *label, char *server, char *username, char *secret) { GError *err = NULL; secret_password_store_sync (DOCKER_SCHEMA, SECRET_COLLECTION_DEFAULT, server, secret, NULL, &err, "label", label, "server", server, "username", username, "docker_cli", "1", NULL); return err; } GError *delete(char *server) { GError *err = NULL; secret_password_clear_sync(DOCKER_SCHEMA, NULL, &err, "server", server, "docker_cli", "1", NULL); if (err != NULL) return err; return NULL; } char *get_attribute(const char *attribute, SecretItem *item) { GHashTable *attributes; GHashTableIter iter; gchar *value, *key; attributes = secret_item_get_attributes(item); g_hash_table_iter_init(&iter, attributes); while (g_hash_table_iter_next(&iter, (void **)&key, (void **)&value)) { if (strncmp(key, attribute, strlen(key)) == 0) return (char *)value; } g_hash_table_unref(attributes); return NULL; } GError *get(char *server, char **username, char **secret) { GError *err = NULL; GHashTable *attributes; SecretService *service; GList *items, *l; SecretSearchFlags flags = SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK; SecretValue *secretValue; gsize length; gchar *value; attributes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); g_hash_table_insert(attributes, g_strdup("server"), g_strdup(server)); g_hash_table_insert(attributes, g_strdup("docker_cli"), g_strdup("1")); service = secret_service_get_sync(SECRET_SERVICE_NONE, NULL, &err); if (err == NULL) { items = secret_service_search_sync(service, DOCKER_SCHEMA, attributes, flags, NULL, &err); if (err == NULL) { for (l = items; l != NULL; l = g_list_next(l)) { value = secret_item_get_schema_name(l->data); if (strncmp(value, "io.docker.Credentials", strlen(value)) != 0) { g_free(value); continue; } g_free(value); secretValue = secret_item_get_secret(l->data); if (secret != NULL) { *secret = strdup(secret_value_get(secretValue, &length)); secret_value_unref(secretValue); } *username = get_attribute("username", l->data); } g_list_free_full(items, g_object_unref); } g_object_unref(service); } g_hash_table_unref(attributes); if (err != NULL) { return err; } return NULL; } GError *list(char *ref_label, char *** paths, char *** accts, unsigned int *list_l) { GList *items; GError *err = NULL; SecretService *service; SecretSearchFlags flags = SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK; GHashTable *attributes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); // List credentials with the right label only g_hash_table_insert(attributes, g_strdup("label"), g_strdup(ref_label)); service = secret_service_get_sync(SECRET_SERVICE_NONE, NULL, &err); if (err != NULL) { return err; } items = secret_service_search_sync(service, NULL, attributes, flags, NULL, &err); int numKeys = g_list_length(items); if (err != NULL) { return err; } char **tmp_paths = (char **) calloc(1,(int)sizeof(char *)*numKeys); char **tmp_accts = (char **) calloc(1,(int)sizeof(char *)*numKeys); // items now contains our keys from the gnome keyring // we will now put it in our two lists to return it to go GList *current; int listNumber = 0; for(current = items; current!=NULL; current = current->next) { char *pathTmp = secret_item_get_label(current->data); // you cannot have a key without a label in the gnome keyring char *acctTmp = get_attribute("username",current->data); if (acctTmp==NULL) { acctTmp = "account not defined"; } tmp_paths[listNumber] = (char *) calloc(1, sizeof(char)*(strlen(pathTmp)+1)); tmp_accts[listNumber] = (char *) calloc(1, sizeof(char)*(strlen(acctTmp)+1)); memcpy(tmp_paths[listNumber], pathTmp, sizeof(char)*(strlen(pathTmp)+1)); memcpy(tmp_accts[listNumber], acctTmp, sizeof(char)*(strlen(acctTmp)+1)); listNumber = listNumber + 1; } *paths = (char **) realloc(tmp_paths, (int)sizeof(char *)*listNumber); *accts = (char **) realloc(tmp_accts, (int)sizeof(char *)*listNumber); *list_l = listNumber; return NULL; } void freeListData(char *** data, unsigned int length) { int i; for(i=0; i<length; i++) { free((*data)[i]); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_745_2
crossvul-cpp_data_bad_2579_16
/* #pragma ident "@(#)g_seal.c 1.19 98/04/21 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_wrap_iov */ #include "mglueP.h" static OM_uint32 val_wrap_iov_args( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (iov == GSS_C_NO_IOV_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_wrap_iov (minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; int * conf_state; gss_iov_buffer_desc * iov; int iov_count; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_wrap_iov) { status = mech->gss_wrap_iov( minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, conf_state, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_wrap_iov_length (minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; int * conf_state; gss_iov_buffer_desc * iov; int iov_count; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_wrap_iov_length) { status = mech->gss_wrap_iov_length( minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, conf_state, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } OM_uint32 KRB5_CALLCONV gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, 0, qop_req, NULL, iov, iov_count); if (status != GSS_S_COMPLETE) return status; /* Select the approprate underlying mechanism routine and call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism(ctx->mech_type); if (mech == NULL) return GSS_S_BAD_MECH; if (mech->gss_get_mic_iov == NULL) return GSS_S_UNAVAILABLE; status = mech->gss_get_mic_iov(minor_status, ctx->internal_ctx_id, qop_req, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); return status; } OM_uint32 KRB5_CALLCONV gss_get_mic_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, 0, qop_req, NULL, iov, iov_count); if (status != GSS_S_COMPLETE) return status; /* Select the approprate underlying mechanism routine and call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism(ctx->mech_type); if (mech == NULL) return GSS_S_BAD_MECH; if (mech->gss_get_mic_iov_length == NULL) return GSS_S_UNAVAILABLE; status = mech->gss_get_mic_iov_length(minor_status, ctx->internal_ctx_id, qop_req, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); return status; } OM_uint32 KRB5_CALLCONV gss_release_iov_buffer (minor_status, iov, iov_count) OM_uint32 * minor_status; gss_iov_buffer_desc * iov; int iov_count; { OM_uint32 status = GSS_S_COMPLETE; int i; if (minor_status) *minor_status = 0; if (iov == GSS_C_NO_IOV_BUFFER) return GSS_S_COMPLETE; for (i = 0; i < iov_count; i++) { if (iov[i].type & GSS_IOV_BUFFER_FLAG_ALLOCATED) { status = gss_release_buffer(minor_status, &iov[i].buffer); if (status != GSS_S_COMPLETE) break; iov[i].type &= ~(GSS_IOV_BUFFER_FLAG_ALLOCATED); } } return status; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_16
crossvul-cpp_data_good_2579_0
/* #pragma ident "@(#)g_accept_sec_context.c 1.19 04/02/23 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_accept_sec_context */ #include "mglueP.h" #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> #include <errno.h> #include <time.h> #ifndef LEAN_CLIENT static OM_uint32 val_acc_sec_ctx_args( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token_buffer, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *d_cred) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (d_cred != NULL) *d_cred = GSS_C_NO_CREDENTIAL; /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (input_token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (output_token == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_WRITE); return (GSS_S_COMPLETE); } /* Return true if mech should be accepted with no acceptor credential. */ static int allow_mech_by_default(gss_OID mech) { OM_uint32 status, minor; gss_OID_set attrs; int reject = 0, p; /* Whether we accept an interposer mech depends on whether we accept the * mech it interposes. */ mech = gssint_get_public_oid(mech); if (mech == GSS_C_NO_OID) return 0; status = gss_inquire_attrs_for_mech(&minor, mech, &attrs, NULL); if (status) return 0; /* Check for each attribute which would cause us to exclude this mech from * the default credential. */ if (generic_gss_test_oid_set_member(&minor, GSS_C_MA_DEPRECATED, attrs, &p) != GSS_S_COMPLETE || p) reject = 1; else if (generic_gss_test_oid_set_member(&minor, GSS_C_MA_NOT_DFLT_MECH, attrs, &p) != GSS_S_COMPLETE || p) reject = 1; (void) gss_release_oid_set(&minor, &attrs); return !reject; } OM_uint32 KRB5_CALLCONV gss_accept_sec_context (minor_status, context_handle, verifier_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, d_cred) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_cred_id_t verifier_cred_handle; gss_buffer_t input_token_buffer; gss_channel_bindings_t input_chan_bindings; gss_name_t * src_name; gss_OID * mech_type; gss_buffer_t output_token; OM_uint32 * ret_flags; OM_uint32 * time_rec; gss_cred_id_t * d_cred; { OM_uint32 status, temp_status, temp_minor_status; OM_uint32 temp_ret_flags = 0; gss_union_ctx_id_t union_ctx_id = NULL; gss_cred_id_t input_cred_handle = GSS_C_NO_CREDENTIAL; gss_cred_id_t tmp_d_cred = GSS_C_NO_CREDENTIAL; gss_name_t internal_name = GSS_C_NO_NAME; gss_name_t tmp_src_name = GSS_C_NO_NAME; gss_OID_desc token_mech_type_desc; gss_OID token_mech_type = &token_mech_type_desc; gss_OID actual_mech = GSS_C_NO_OID; gss_OID selected_mech = GSS_C_NO_OID; gss_OID public_mech; gss_mechanism mech = NULL; gss_union_cred_t uc; int i; status = val_acc_sec_ctx_args(minor_status, context_handle, verifier_cred_handle, input_token_buffer, input_chan_bindings, src_name, mech_type, output_token, ret_flags, time_rec, d_cred); if (status != GSS_S_COMPLETE) return (status); /* * if context_handle is GSS_C_NO_CONTEXT, allocate a union context * descriptor to hold the mech type information as well as the * underlying mechanism context handle. Otherwise, cast the * value of *context_handle to the union context variable. */ if(*context_handle == GSS_C_NO_CONTEXT) { if (input_token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); /* Get the token mech type */ status = gssint_get_mech_type(token_mech_type, input_token_buffer); if (status) return status; /* * An interposer calling back into the mechglue can't pass in a special * mech, so we have to recognize it using verifier_cred_handle. Use * the mechanism for which we have matching creds, if available. */ if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) { uc = (gss_union_cred_t)verifier_cred_handle; for (i = 0; i < uc->count; i++) { public_mech = gssint_get_public_oid(&uc->mechs_array[i]); if (public_mech && g_OID_equal(token_mech_type, public_mech)) { selected_mech = &uc->mechs_array[i]; break; } } } if (selected_mech == GSS_C_NO_OID) { status = gssint_select_mech_type(minor_status, token_mech_type, &selected_mech); if (status) return status; } } else { union_ctx_id = (gss_union_ctx_id_t)*context_handle; selected_mech = union_ctx_id->mech_type; if (union_ctx_id->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); } /* Now create a new context if we didn't get one. */ if (*context_handle == GSS_C_NO_CONTEXT) { status = GSS_S_FAILURE; union_ctx_id = (gss_union_ctx_id_t) malloc(sizeof(gss_union_ctx_id_desc)); if (!union_ctx_id) return (GSS_S_FAILURE); union_ctx_id->loopback = union_ctx_id; union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT; status = generic_gss_copy_oid(&temp_minor_status, selected_mech, &union_ctx_id->mech_type); if (status != GSS_S_COMPLETE) { free(union_ctx_id); return (status); } } /* * get the appropriate cred handle from the union cred struct. */ if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) { input_cred_handle = gssint_get_mechanism_cred((gss_union_cred_t)verifier_cred_handle, selected_mech); if (input_cred_handle == GSS_C_NO_CREDENTIAL) { /* verifier credential specified but no acceptor credential found */ status = GSS_S_NO_CRED; goto error_out; } } else if (!allow_mech_by_default(selected_mech)) { status = GSS_S_NO_CRED; goto error_out; } /* * now select the approprate underlying mechanism routine and * call it. */ mech = gssint_get_mechanism(selected_mech); if (mech && mech->gss_accept_sec_context) { status = mech->gss_accept_sec_context(minor_status, &union_ctx_id->internal_ctx_id, input_cred_handle, input_token_buffer, input_chan_bindings, src_name ? &internal_name : NULL, &actual_mech, output_token, &temp_ret_flags, time_rec, d_cred ? &tmp_d_cred : NULL); /* If there's more work to do, keep going... */ if (status == GSS_S_CONTINUE_NEEDED) { *context_handle = (gss_ctx_id_t)union_ctx_id; return GSS_S_CONTINUE_NEEDED; } /* if the call failed, return with failure */ if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); goto error_out; } /* * if src_name is non-NULL, * convert internal_name into a union name equivalent * First call the mechanism specific display_name() * then call gss_import_name() to create * the union name struct cast to src_name */ if (src_name != NULL) { if (internal_name != GSS_C_NO_NAME) { /* consumes internal_name regardless of success */ temp_status = gssint_convert_name_to_union_name( &temp_minor_status, mech, internal_name, &tmp_src_name); if (temp_status != GSS_S_COMPLETE) { status = temp_status; *minor_status = temp_minor_status; map_error(minor_status, mech); if (output_token->length) (void) gss_release_buffer(&temp_minor_status, output_token); goto error_out; } *src_name = tmp_src_name; } else *src_name = GSS_C_NO_NAME; } #define g_OID_prefix_equal(o1, o2) \ (((o1)->length >= (o2)->length) && \ (memcmp((o1)->elements, (o2)->elements, (o2)->length) == 0)) /* Ensure we're returning correct creds format */ if ((temp_ret_flags & GSS_C_DELEG_FLAG) && tmp_d_cred != GSS_C_NO_CREDENTIAL) { public_mech = gssint_get_public_oid(selected_mech); if (actual_mech != GSS_C_NO_OID && public_mech != GSS_C_NO_OID && !g_OID_prefix_equal(actual_mech, public_mech)) { *d_cred = tmp_d_cred; /* unwrapped pseudo-mech */ } else { gss_union_cred_t d_u_cred = NULL; d_u_cred = malloc(sizeof (gss_union_cred_desc)); if (d_u_cred == NULL) { status = GSS_S_FAILURE; goto error_out; } (void) memset(d_u_cred, 0, sizeof (gss_union_cred_desc)); d_u_cred->count = 1; status = generic_gss_copy_oid(&temp_minor_status, selected_mech, &d_u_cred->mechs_array); if (status != GSS_S_COMPLETE) { free(d_u_cred); goto error_out; } d_u_cred->cred_array = malloc(sizeof(gss_cred_id_t)); if (d_u_cred->cred_array != NULL) { d_u_cred->cred_array[0] = tmp_d_cred; } else { free(d_u_cred); status = GSS_S_FAILURE; goto error_out; } d_u_cred->loopback = d_u_cred; *d_cred = (gss_cred_id_t)d_u_cred; } } if (mech_type != NULL) *mech_type = gssint_get_public_oid(actual_mech); if (ret_flags != NULL) *ret_flags = temp_ret_flags; *context_handle = (gss_ctx_id_t)union_ctx_id; return GSS_S_COMPLETE; } else { status = GSS_S_BAD_MECH; } error_out: /* * RFC 2744 5.1 requires that we not create a context on a failed first * call to accept, and recommends that on a failed subsequent call we * make the caller responsible for calling gss_delete_sec_context. * Even if the mech deleted its context, keep the union context around * for the caller to delete. */ if (union_ctx_id && *context_handle == GSS_C_NO_CONTEXT) { if (union_ctx_id->mech_type) { if (union_ctx_id->mech_type->elements) free(union_ctx_id->mech_type->elements); free(union_ctx_id->mech_type); } if (union_ctx_id->internal_ctx_id && mech && mech->gss_delete_sec_context) { mech->gss_delete_sec_context(&temp_minor_status, &union_ctx_id->internal_ctx_id, GSS_C_NO_BUFFER); } free(union_ctx_id); } if (src_name) *src_name = GSS_C_NO_NAME; if (tmp_src_name != GSS_C_NO_NAME) (void) gss_release_buffer(&temp_minor_status, (gss_buffer_t)tmp_src_name); return (status); } #endif /* LEAN_CLIENT */
./CrossVul/dataset_final_sorted/CWE-415/c/good_2579_0
crossvul-cpp_data_bad_1407_0
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" /* Code drawn from ppmtogif.c, from the pbmplus package ** ** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>. A ** Lempel-Zim compression based on "compress". ** ** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl> ** ** Copyright (C) 1989 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. ** ** The Graphics Interchange Format(c) is the Copyright property of ** CompuServe Incorporated. GIF(sm) is a Service Mark property of ** CompuServe Incorporated. */ /* * a code_int must be able to hold 2**GIFBITS values of type int, and also -1 */ typedef int code_int; #ifdef SIGNED_COMPARE_SLOW typedef unsigned long int count_int; typedef unsigned short int count_short; #else /*SIGNED_COMPARE_SLOW*/ typedef long int count_int; #endif /*SIGNED_COMPARE_SLOW*/ /* 2.0.28: threadsafe */ #define maxbits GIFBITS /* should NEVER generate this code */ #define maxmaxcode ((code_int)1 << GIFBITS) #define HSIZE 5003 /* 80% occupancy */ #define hsize HSIZE /* Apparently invariant, left over from compress */ typedef struct { int Width, Height; int curx, cury; long CountDown; int Pass; int Interlace; int n_bits; /* number of bits/code */ code_int maxcode; /* maximum code, given n_bits */ count_int htab [HSIZE]; unsigned short codetab [HSIZE]; code_int free_ent; /* first unused entry */ /* * block compression parameters -- after all codes are used up, * and compression rate changes, start over. */ int clear_flg; int offset; long int in_count; /* length of input */ long int out_count; /* # of codes output (for debugging) */ int g_init_bits; gdIOCtx * g_outfile; int ClearCode; int EOFCode; unsigned long cur_accum; int cur_bits; /* * Number of characters so far in this 'packet' */ int a_count; /* * Define the storage for the packet accumulator */ char accum[ 256 ]; } GifCtx; static int gifPutWord(int w, gdIOCtx *out); static int colorstobpp(int colors); static void BumpPixel (GifCtx *ctx); static int GIFNextPixel (gdImagePtr im, GifCtx *ctx); static void GIFEncode (gdIOCtxPtr fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im); static void compress (int init_bits, gdIOCtx *outfile, gdImagePtr im, GifCtx *ctx); static void output (code_int code, GifCtx *ctx); static void cl_block (GifCtx *ctx); static void cl_hash (register count_int chsize, GifCtx *ctx); static void char_init (GifCtx *ctx); static void char_out (int c, GifCtx *ctx); static void flush_char (GifCtx *ctx); void * gdImageGifPtr (gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); gdImageGifCtx (im, out); rv = gdDPExtractData (out, size); out->gd_free (out); return rv; } void gdImageGif (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx (outFile); gdImageGifCtx (im, out); out->gd_free (out); } void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out) { gdImagePtr pim = 0, tim = im; int interlace, BitsPerPixel; interlace = im->interlace; if (im->trueColor) { /* Expensive, but the only way that produces an acceptable result: mix down to a palette based temporary image. */ pim = gdImageCreatePaletteFromTrueColor(im, 1, 256); if (!pim) { return; } tim = pim; } BitsPerPixel = colorstobpp(tim->colorsTotal); /* All set, let's do it. */ GIFEncode( out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel, tim->red, tim->green, tim->blue, tim); if (pim) { /* Destroy palette based temporary image. */ gdImageDestroy( pim); } } static int colorstobpp(int colors) { int bpp = 0; if ( colors <= 2 ) bpp = 1; else if ( colors <= 4 ) bpp = 2; else if ( colors <= 8 ) bpp = 3; else if ( colors <= 16 ) bpp = 4; else if ( colors <= 32 ) bpp = 5; else if ( colors <= 64 ) bpp = 6; else if ( colors <= 128 ) bpp = 7; else if ( colors <= 256 ) bpp = 8; return bpp; } /***************************************************************************** * * GIFENCODE.C - GIF Image compression interface * * GIFEncode( FName, GHeight, GWidth, GInterlace, Background, Transparent, * BitsPerPixel, Red, Green, Blue, gdImagePtr ) * *****************************************************************************/ #define TRUE 1 #define FALSE 0 /* * Bump the 'curx' and 'cury' to point to the next pixel */ static void BumpPixel(GifCtx *ctx) { /* * Bump the current X position */ ++(ctx->curx); /* * If we are at the end of a scan line, set curx back to the beginning * If we are interlaced, bump the cury to the appropriate spot, * otherwise, just increment it. */ if( ctx->curx == ctx->Width ) { ctx->curx = 0; if( !ctx->Interlace ) ++(ctx->cury); else { switch( ctx->Pass ) { case 0: ctx->cury += 8; if( ctx->cury >= ctx->Height ) { ++(ctx->Pass); ctx->cury = 4; } break; case 1: ctx->cury += 8; if( ctx->cury >= ctx->Height ) { ++(ctx->Pass); ctx->cury = 2; } break; case 2: ctx->cury += 4; if( ctx->cury >= ctx->Height ) { ++(ctx->Pass); ctx->cury = 1; } break; case 3: ctx->cury += 2; break; } } } } /* * Return the next pixel from the image */ static int GIFNextPixel(gdImagePtr im, GifCtx *ctx) { int r; if( ctx->CountDown == 0 ) return EOF; --(ctx->CountDown); r = gdImageGetPixel(im, ctx->curx, ctx->cury); BumpPixel(ctx); return r; } /* public */ static void GIFEncode(gdIOCtxPtr fp, int GWidth, int GHeight, int GInterlace, int Background, int Transparent, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im) { int B; int RWidth, RHeight; int LeftOfs, TopOfs; int Resolution; int ColorMapSize; int InitCodeSize; int i; GifCtx ctx; memset(&ctx, 0, sizeof(ctx)); ctx.Interlace = GInterlace; ctx.in_count = 1; ColorMapSize = 1 << BitsPerPixel; RWidth = ctx.Width = GWidth; RHeight = ctx.Height = GHeight; LeftOfs = TopOfs = 0; Resolution = BitsPerPixel; /* * Calculate number of bits we are expecting */ ctx.CountDown = (long)ctx.Width * (long)ctx.Height; /* * Indicate which pass we are on (if interlace) */ ctx.Pass = 0; /* * The initial code size */ if( BitsPerPixel <= 1 ) InitCodeSize = 2; else InitCodeSize = BitsPerPixel; /* * Set up the current x and y position */ ctx.curx = ctx.cury = 0; /* * Write the Magic header */ gdPutBuf(Transparent < 0 ? "GIF87a" : "GIF89a", 6, fp ); /* * Write out the screen width and height */ gifPutWord( RWidth, fp ); gifPutWord( RHeight, fp ); /* * Indicate that there is a global colour map */ B = 0x80; /* Yes, there is a color map */ /* * OR in the resolution */ B |= (Resolution - 1) << 5; /* * OR in the Bits per Pixel */ B |= (BitsPerPixel - 1); /* * Write it out */ gdPutC( B, fp ); /* * Write out the Background colour */ gdPutC( Background, fp ); /* * Byte of 0's (future expansion) */ gdPutC( 0, fp ); /* * Write out the Global Colour Map */ for( i=0; i<ColorMapSize; ++i ) { gdPutC( Red[i], fp ); gdPutC( Green[i], fp ); gdPutC( Blue[i], fp ); } /* * Write out extension for transparent colour index, if necessary. */ if ( Transparent >= 0 ) { gdPutC( '!', fp ); gdPutC( 0xf9, fp ); gdPutC( 4, fp ); gdPutC( 1, fp ); gdPutC( 0, fp ); gdPutC( 0, fp ); gdPutC( (unsigned char) Transparent, fp ); gdPutC( 0, fp ); } /* * Write an Image separator */ gdPutC( ',', fp ); /* * Write the Image header */ gifPutWord( LeftOfs, fp ); gifPutWord( TopOfs, fp ); gifPutWord( ctx.Width, fp ); gifPutWord( ctx.Height, fp ); /* * Write out whether or not the image is interlaced */ if( ctx.Interlace ) gdPutC( 0x40, fp ); else gdPutC( 0x00, fp ); /* * Write out the initial code size */ gdPutC( InitCodeSize, fp ); /* * Go and actually compress the data */ compress( InitCodeSize+1, fp, im, &ctx ); /* * Write out a Zero-length packet (to end the series) */ gdPutC( 0, fp ); /* * Write the GIF file terminator */ gdPutC( ';', fp ); } /*************************************************************************** * * GIFCOMPR.C - GIF Image compression routines * * Lempel-Ziv compression based on 'compress'. GIF modifications by * David Rowley (mgardi@watdcsu.waterloo.edu) * ***************************************************************************/ /* * General DEFINEs */ #define GIFBITS 12 #ifdef NO_UCHAR typedef char char_type; #else /*NO_UCHAR*/ typedef unsigned char char_type; #endif /*NO_UCHAR*/ /* * * GIF Image compression - modified 'compress' * * Based on: compress.c - File compression ala IEEE Computer, June 1984. * * By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) * Jim McKie (decvax!mcvax!jim) * Steve Davies (decvax!vax135!petsd!peora!srd) * Ken Turkowski (decvax!decwrl!turtlevax!ken) * James A. Woods (decvax!ihnp4!ames!jaw) * Joe Orost (decvax!vax135!petsd!joe) * */ #include <ctype.h> #define ARGVAL() (*++(*argv) || (--argc && *++argv)) #ifdef COMPATIBLE /* But wrong! */ # define MAXCODE(n_bits) ((code_int) 1 << (n_bits) - 1) #else /*COMPATIBLE*/ # define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1) #endif /*COMPATIBLE*/ #define HashTabOf(i) ctx->htab[i] #define CodeTabOf(i) ctx->codetab[i] /* * To save much memory, we overlay the table used by compress() with those * used by decompress(). The tab_prefix table is the same size and type * as the codetab. The tab_suffix table needs 2**GIFBITS characters. We * get this from the beginning of htab. The output stack uses the rest * of htab, and contains characters. There is plenty of room for any * possible stack (stack used to be 8000 characters). */ #define tab_prefixof(i) CodeTabOf(i) #define tab_suffixof(i) ((char_type*)(htab))[i] #define de_stack ((char_type*)&tab_suffixof((code_int)1<<GIFBITS)) /* * compress stdin to stdout * * Algorithm: use open addressing double hashing (no chaining) on the * prefix code / next character combination. We do a variant of Knuth's * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime * secondary probe. Here, the modular division first probe is gives way * to a faster exclusive-or manipulation. Also do block compression with * an adaptive reset, whereby the code table is cleared when the compression * ratio decreases, but after the table fills. The variable-length output * codes are re-sized at this point, and a special CLEAR code is generated * for the decompressor. Late addition: construct the table according to * file size for noticeable speed improvement on small files. Please direct * questions about this implementation to ames!jaw. */ static void output(code_int code, GifCtx *ctx); static void compress(int init_bits, gdIOCtxPtr outfile, gdImagePtr im, GifCtx *ctx) { register long fcode; register code_int i /* = 0 */; register int c; register code_int ent; register code_int disp; register code_int hsize_reg; register int hshift; /* * Set up the globals: g_init_bits - initial number of bits * g_outfile - pointer to output file */ ctx->g_init_bits = init_bits; ctx->g_outfile = outfile; /* * Set up the necessary values */ ctx->offset = 0; ctx->out_count = 0; ctx->clear_flg = 0; ctx->in_count = 1; ctx->maxcode = MAXCODE(ctx->n_bits = ctx->g_init_bits); ctx->ClearCode = (1 << (init_bits - 1)); ctx->EOFCode = ctx->ClearCode + 1; ctx->free_ent = ctx->ClearCode + 2; char_init(ctx); ent = GIFNextPixel( im, ctx ); hshift = 0; for ( fcode = (long) hsize; fcode < 65536L; fcode *= 2L ) ++hshift; hshift = 8 - hshift; /* set hash code range bound */ hsize_reg = hsize; cl_hash( (count_int) hsize_reg, ctx ); /* clear hash table */ output( (code_int)ctx->ClearCode, ctx ); #ifdef SIGNED_COMPARE_SLOW while ( (c = GIFNextPixel( im )) != (unsigned) EOF ) { #else /*SIGNED_COMPARE_SLOW*/ while ( (c = GIFNextPixel( im, ctx )) != EOF ) { /* } */ #endif /*SIGNED_COMPARE_SLOW*/ ++(ctx->in_count); fcode = (long) (((long) c << maxbits) + ent); i = (((code_int)c << hshift) ^ ent); /* xor hashing */ if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; } else if ( (long)HashTabOf (i) < 0 ) /* empty slot */ goto nomatch; disp = hsize_reg - i; /* secondary hash (after G. Knott) */ if ( i == 0 ) disp = 1; probe: if ( (i -= disp) < 0 ) i += hsize_reg; if ( HashTabOf (i) == fcode ) { ent = CodeTabOf (i); continue; } if ( (long)HashTabOf (i) > 0 ) goto probe; nomatch: output ( (code_int) ent, ctx ); ++(ctx->out_count); ent = c; #ifdef SIGNED_COMPARE_SLOW if ( (unsigned) ctx->free_ent < (unsigned) maxmaxcode) { #else /*SIGNED_COMPARE_SLOW*/ if ( ctx->free_ent < maxmaxcode ) { /* } */ #endif /*SIGNED_COMPARE_SLOW*/ CodeTabOf (i) = ctx->free_ent++; /* code -> hashtable */ HashTabOf (i) = fcode; } else cl_block(ctx); } /* * Put out the final code. */ output( (code_int)ent, ctx ); ++(ctx->out_count); output( (code_int) ctx->EOFCode, ctx ); } /***************************************************************** * TAG( output ) * * Output the given code. * Inputs: * code: A n_bits-bit integer. If == -1, then EOF. This assumes * that n_bits =< (long)wordsize - 1. * Outputs: * Outputs code to the file. * Assumptions: * Chars are 8 bits long. * Algorithm: * Maintain a GIFBITS character long buffer (so that 8 codes will * fit in it exactly). Use the VAX insv instruction to insert each * code in turn. When the buffer fills up empty it and start over. */ static const unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; /* Arbitrary value to mark output is done. When we see EOFCode, then we don't * expect to see any more data. If we do (e.g. corrupt image inputs), cur_bits * might be negative, so flag it to return early. */ #define CUR_BITS_FINISHED -1000 static void output(code_int code, GifCtx *ctx) { if (ctx->cur_bits == CUR_BITS_FINISHED) { return; } ctx->cur_accum &= masks[ ctx->cur_bits ]; if( ctx->cur_bits > 0 ) ctx->cur_accum |= ((long)code << ctx->cur_bits); else ctx->cur_accum = code; ctx->cur_bits += ctx->n_bits; while( ctx->cur_bits >= 8 ) { char_out( (unsigned int)(ctx->cur_accum & 0xff), ctx ); ctx->cur_accum >>= 8; ctx->cur_bits -= 8; } /* * If the next entry is going to be too big for the code size, * then increase it, if possible. */ if ( ctx->free_ent > ctx->maxcode || ctx->clear_flg ) { if( ctx->clear_flg ) { ctx->maxcode = MAXCODE (ctx->n_bits = ctx->g_init_bits); ctx->clear_flg = 0; } else { ++(ctx->n_bits); if ( ctx->n_bits == maxbits ) ctx->maxcode = maxmaxcode; else ctx->maxcode = MAXCODE(ctx->n_bits); } } if( code == ctx->EOFCode ) { /* * At EOF, write the rest of the buffer. */ while( ctx->cur_bits > 0 ) { char_out( (unsigned int)(ctx->cur_accum & 0xff), ctx); ctx->cur_accum >>= 8; ctx->cur_bits -= 8; } /* Flag that it's done to prevent re-entry. */ ctx->cur_bits = CUR_BITS_FINISHED; flush_char(ctx); } } /* * Clear out the hash table */ static void cl_block (GifCtx *ctx) /* table clear for block compress */ { cl_hash ( (count_int) hsize, ctx ); ctx->free_ent = ctx->ClearCode + 2; ctx->clear_flg = 1; output( (code_int)ctx->ClearCode, ctx); } static void cl_hash(register count_int chsize, GifCtx *ctx) /* reset code table */ { register count_int *htab_p = ctx->htab+chsize; register long i; register long m1 = -1; i = chsize - 16; do { /* might use Sys V memset(3) here */ *(htab_p-16) = m1; *(htab_p-15) = m1; *(htab_p-14) = m1; *(htab_p-13) = m1; *(htab_p-12) = m1; *(htab_p-11) = m1; *(htab_p-10) = m1; *(htab_p-9) = m1; *(htab_p-8) = m1; *(htab_p-7) = m1; *(htab_p-6) = m1; *(htab_p-5) = m1; *(htab_p-4) = m1; *(htab_p-3) = m1; *(htab_p-2) = m1; *(htab_p-1) = m1; htab_p -= 16; } while ((i -= 16) >= 0); for ( i += 16; i > 0; --i ) *--htab_p = m1; } /****************************************************************************** * * GIF Specific routines * ******************************************************************************/ /* * Set up the 'byte output' routine */ static void char_init(GifCtx *ctx) { ctx->a_count = 0; } /* * Add a character to the end of the current packet, and if it is 254 * characters, flush the packet to disk. */ static void char_out(int c, GifCtx *ctx) { ctx->accum[ ctx->a_count++ ] = c; if( ctx->a_count >= 254 ) flush_char(ctx); } /* * Flush the packet to disk, and reset the accumulator */ static void flush_char(GifCtx *ctx) { if( ctx->a_count > 0 ) { gdPutC( ctx->a_count, ctx->g_outfile ); gdPutBuf( ctx->accum, ctx->a_count, ctx->g_outfile ); ctx->a_count = 0; } } static int gifPutWord(int w, gdIOCtx *out) { /* Byte order is little-endian */ gdPutC(w & 0xFF, out); gdPutC((w >> 8) & 0xFF, out); return 0; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1407_0
crossvul-cpp_data_good_3003_0
/* * GPIO driver for AMD * * Copyright (c) 2014,2015 AMD Corporation. * Authors: Ken Xue <Ken.Xue@amd.com> * Wu, Jeff <Jeff.Wu@amd.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. */ #include <linux/err.h> #include <linux/bug.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/compiler.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/log2.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/mutex.h> #include <linux/acpi.h> #include <linux/seq_file.h> #include <linux/interrupt.h> #include <linux/list.h> #include <linux/bitops.h> #include <linux/pinctrl/pinconf.h> #include <linux/pinctrl/pinconf-generic.h> #include "pinctrl-utils.h" #include "pinctrl-amd.h" static int amd_gpio_direction_input(struct gpio_chip *gc, unsigned offset) { unsigned long flags; u32 pin_reg; struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + offset * 4); /* * Suppose BIOS or Bootloader sets specific debounce for the * GPIO. if not, set debounce to be 2.75ms and remove glitch. */ if ((pin_reg & DB_TMR_OUT_MASK) == 0) { pin_reg |= 0xf; pin_reg |= BIT(DB_TMR_OUT_UNIT_OFF); pin_reg |= DB_TYPE_REMOVE_GLITCH << DB_CNTRL_OFF; pin_reg &= ~BIT(DB_TMR_LARGE_OFF); } pin_reg &= ~BIT(OUTPUT_ENABLE_OFF); writel(pin_reg, gpio_dev->base + offset * 4); spin_unlock_irqrestore(&gpio_dev->lock, flags); return 0; } static int amd_gpio_direction_output(struct gpio_chip *gc, unsigned offset, int value) { u32 pin_reg; unsigned long flags; struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + offset * 4); pin_reg |= BIT(OUTPUT_ENABLE_OFF); if (value) pin_reg |= BIT(OUTPUT_VALUE_OFF); else pin_reg &= ~BIT(OUTPUT_VALUE_OFF); writel(pin_reg, gpio_dev->base + offset * 4); spin_unlock_irqrestore(&gpio_dev->lock, flags); return 0; } static int amd_gpio_get_value(struct gpio_chip *gc, unsigned offset) { u32 pin_reg; unsigned long flags; struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + offset * 4); spin_unlock_irqrestore(&gpio_dev->lock, flags); return !!(pin_reg & BIT(PIN_STS_OFF)); } static void amd_gpio_set_value(struct gpio_chip *gc, unsigned offset, int value) { u32 pin_reg; unsigned long flags; struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + offset * 4); if (value) pin_reg |= BIT(OUTPUT_VALUE_OFF); else pin_reg &= ~BIT(OUTPUT_VALUE_OFF); writel(pin_reg, gpio_dev->base + offset * 4); spin_unlock_irqrestore(&gpio_dev->lock, flags); } static int amd_gpio_set_debounce(struct gpio_chip *gc, unsigned offset, unsigned debounce) { u32 time; u32 pin_reg; int ret = 0; unsigned long flags; struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + offset * 4); if (debounce) { pin_reg |= DB_TYPE_REMOVE_GLITCH << DB_CNTRL_OFF; pin_reg &= ~DB_TMR_OUT_MASK; /* Debounce Debounce Timer Max TmrLarge TmrOutUnit Unit Debounce Time 0 0 61 usec (2 RtcClk) 976 usec 0 1 244 usec (8 RtcClk) 3.9 msec 1 0 15.6 msec (512 RtcClk) 250 msec 1 1 62.5 msec (2048 RtcClk) 1 sec */ if (debounce < 61) { pin_reg |= 1; pin_reg &= ~BIT(DB_TMR_OUT_UNIT_OFF); pin_reg &= ~BIT(DB_TMR_LARGE_OFF); } else if (debounce < 976) { time = debounce / 61; pin_reg |= time & DB_TMR_OUT_MASK; pin_reg &= ~BIT(DB_TMR_OUT_UNIT_OFF); pin_reg &= ~BIT(DB_TMR_LARGE_OFF); } else if (debounce < 3900) { time = debounce / 244; pin_reg |= time & DB_TMR_OUT_MASK; pin_reg |= BIT(DB_TMR_OUT_UNIT_OFF); pin_reg &= ~BIT(DB_TMR_LARGE_OFF); } else if (debounce < 250000) { time = debounce / 15600; pin_reg |= time & DB_TMR_OUT_MASK; pin_reg &= ~BIT(DB_TMR_OUT_UNIT_OFF); pin_reg |= BIT(DB_TMR_LARGE_OFF); } else if (debounce < 1000000) { time = debounce / 62500; pin_reg |= time & DB_TMR_OUT_MASK; pin_reg |= BIT(DB_TMR_OUT_UNIT_OFF); pin_reg |= BIT(DB_TMR_LARGE_OFF); } else { pin_reg &= ~DB_CNTRl_MASK; ret = -EINVAL; } } else { pin_reg &= ~BIT(DB_TMR_OUT_UNIT_OFF); pin_reg &= ~BIT(DB_TMR_LARGE_OFF); pin_reg &= ~DB_TMR_OUT_MASK; pin_reg &= ~DB_CNTRl_MASK; } writel(pin_reg, gpio_dev->base + offset * 4); spin_unlock_irqrestore(&gpio_dev->lock, flags); return ret; } #ifdef CONFIG_DEBUG_FS static void amd_gpio_dbg_show(struct seq_file *s, struct gpio_chip *gc) { u32 pin_reg; unsigned long flags; unsigned int bank, i, pin_num; struct amd_gpio *gpio_dev = gpiochip_get_data(gc); char *level_trig; char *active_level; char *interrupt_enable; char *interrupt_mask; char *wake_cntrl0; char *wake_cntrl1; char *wake_cntrl2; char *pin_sts; char *pull_up_sel; char *pull_up_enable; char *pull_down_enable; char *output_value; char *output_enable; for (bank = 0; bank < AMD_GPIO_TOTAL_BANKS; bank++) { seq_printf(s, "GPIO bank%d\t", bank); switch (bank) { case 0: i = 0; pin_num = AMD_GPIO_PINS_BANK0; break; case 1: i = 64; pin_num = AMD_GPIO_PINS_BANK1 + i; break; case 2: i = 128; pin_num = AMD_GPIO_PINS_BANK2 + i; break; } for (; i < pin_num; i++) { seq_printf(s, "pin%d\t", i); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + i * 4); spin_unlock_irqrestore(&gpio_dev->lock, flags); if (pin_reg & BIT(INTERRUPT_ENABLE_OFF)) { interrupt_enable = "interrupt is enabled|"; if (!(pin_reg & BIT(ACTIVE_LEVEL_OFF)) && !(pin_reg & BIT(ACTIVE_LEVEL_OFF+1))) active_level = "Active low|"; else if (pin_reg & BIT(ACTIVE_LEVEL_OFF) && !(pin_reg & BIT(ACTIVE_LEVEL_OFF+1))) active_level = "Active high|"; else if (!(pin_reg & BIT(ACTIVE_LEVEL_OFF)) && pin_reg & BIT(ACTIVE_LEVEL_OFF+1)) active_level = "Active on both|"; else active_level = "Unknow Active level|"; if (pin_reg & BIT(LEVEL_TRIG_OFF)) level_trig = "Level trigger|"; else level_trig = "Edge trigger|"; } else { interrupt_enable = "interrupt is disabled|"; active_level = " "; level_trig = " "; } if (pin_reg & BIT(INTERRUPT_MASK_OFF)) interrupt_mask = "interrupt is unmasked|"; else interrupt_mask = "interrupt is masked|"; if (pin_reg & BIT(WAKE_CNTRL_OFF)) wake_cntrl0 = "enable wakeup in S0i3 state|"; else wake_cntrl0 = "disable wakeup in S0i3 state|"; if (pin_reg & BIT(WAKE_CNTRL_OFF)) wake_cntrl1 = "enable wakeup in S3 state|"; else wake_cntrl1 = "disable wakeup in S3 state|"; if (pin_reg & BIT(WAKE_CNTRL_OFF)) wake_cntrl2 = "enable wakeup in S4/S5 state|"; else wake_cntrl2 = "disable wakeup in S4/S5 state|"; if (pin_reg & BIT(PULL_UP_ENABLE_OFF)) { pull_up_enable = "pull-up is enabled|"; if (pin_reg & BIT(PULL_UP_SEL_OFF)) pull_up_sel = "8k pull-up|"; else pull_up_sel = "4k pull-up|"; } else { pull_up_enable = "pull-up is disabled|"; pull_up_sel = " "; } if (pin_reg & BIT(PULL_DOWN_ENABLE_OFF)) pull_down_enable = "pull-down is enabled|"; else pull_down_enable = "Pull-down is disabled|"; if (pin_reg & BIT(OUTPUT_ENABLE_OFF)) { pin_sts = " "; output_enable = "output is enabled|"; if (pin_reg & BIT(OUTPUT_VALUE_OFF)) output_value = "output is high|"; else output_value = "output is low|"; } else { output_enable = "output is disabled|"; output_value = " "; if (pin_reg & BIT(PIN_STS_OFF)) pin_sts = "input is high|"; else pin_sts = "input is low|"; } seq_printf(s, "%s %s %s %s %s %s\n" " %s %s %s %s %s %s %s 0x%x\n", level_trig, active_level, interrupt_enable, interrupt_mask, wake_cntrl0, wake_cntrl1, wake_cntrl2, pin_sts, pull_up_sel, pull_up_enable, pull_down_enable, output_value, output_enable, pin_reg); } } } #else #define amd_gpio_dbg_show NULL #endif static void amd_gpio_irq_enable(struct irq_data *d) { u32 pin_reg; unsigned long flags; struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + (d->hwirq)*4); /* Suppose BIOS or Bootloader sets specific debounce for the GPIO. if not, set debounce to be 2.75ms. */ if ((pin_reg & DB_TMR_OUT_MASK) == 0) { pin_reg |= 0xf; pin_reg |= BIT(DB_TMR_OUT_UNIT_OFF); pin_reg &= ~BIT(DB_TMR_LARGE_OFF); } pin_reg |= BIT(INTERRUPT_ENABLE_OFF); pin_reg |= BIT(INTERRUPT_MASK_OFF); writel(pin_reg, gpio_dev->base + (d->hwirq)*4); spin_unlock_irqrestore(&gpio_dev->lock, flags); } static void amd_gpio_irq_disable(struct irq_data *d) { u32 pin_reg; unsigned long flags; struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + (d->hwirq)*4); pin_reg &= ~BIT(INTERRUPT_ENABLE_OFF); pin_reg &= ~BIT(INTERRUPT_MASK_OFF); writel(pin_reg, gpio_dev->base + (d->hwirq)*4); spin_unlock_irqrestore(&gpio_dev->lock, flags); } static void amd_gpio_irq_mask(struct irq_data *d) { u32 pin_reg; unsigned long flags; struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + (d->hwirq)*4); pin_reg &= ~BIT(INTERRUPT_MASK_OFF); writel(pin_reg, gpio_dev->base + (d->hwirq)*4); spin_unlock_irqrestore(&gpio_dev->lock, flags); } static void amd_gpio_irq_unmask(struct irq_data *d) { u32 pin_reg; unsigned long flags; struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + (d->hwirq)*4); pin_reg |= BIT(INTERRUPT_MASK_OFF); writel(pin_reg, gpio_dev->base + (d->hwirq)*4); spin_unlock_irqrestore(&gpio_dev->lock, flags); } static void amd_gpio_irq_eoi(struct irq_data *d) { u32 reg; unsigned long flags; struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_MASTER_REG); reg |= EOI_MASK; writel(reg, gpio_dev->base + WAKE_INT_MASTER_REG); spin_unlock_irqrestore(&gpio_dev->lock, flags); } static int amd_gpio_irq_set_type(struct irq_data *d, unsigned int type) { int ret = 0; u32 pin_reg; unsigned long flags; struct gpio_chip *gc = irq_data_get_irq_chip_data(d); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + (d->hwirq)*4); switch (type & IRQ_TYPE_SENSE_MASK) { case IRQ_TYPE_EDGE_RISING: pin_reg &= ~BIT(LEVEL_TRIG_OFF); pin_reg &= ~(ACTIVE_LEVEL_MASK << ACTIVE_LEVEL_OFF); pin_reg |= ACTIVE_HIGH << ACTIVE_LEVEL_OFF; pin_reg |= DB_TYPE_REMOVE_GLITCH << DB_CNTRL_OFF; irq_set_handler_locked(d, handle_edge_irq); break; case IRQ_TYPE_EDGE_FALLING: pin_reg &= ~BIT(LEVEL_TRIG_OFF); pin_reg &= ~(ACTIVE_LEVEL_MASK << ACTIVE_LEVEL_OFF); pin_reg |= ACTIVE_LOW << ACTIVE_LEVEL_OFF; pin_reg |= DB_TYPE_REMOVE_GLITCH << DB_CNTRL_OFF; irq_set_handler_locked(d, handle_edge_irq); break; case IRQ_TYPE_EDGE_BOTH: pin_reg &= ~BIT(LEVEL_TRIG_OFF); pin_reg &= ~(ACTIVE_LEVEL_MASK << ACTIVE_LEVEL_OFF); pin_reg |= BOTH_EADGE << ACTIVE_LEVEL_OFF; pin_reg |= DB_TYPE_REMOVE_GLITCH << DB_CNTRL_OFF; irq_set_handler_locked(d, handle_edge_irq); break; case IRQ_TYPE_LEVEL_HIGH: pin_reg |= LEVEL_TRIGGER << LEVEL_TRIG_OFF; pin_reg &= ~(ACTIVE_LEVEL_MASK << ACTIVE_LEVEL_OFF); pin_reg |= ACTIVE_HIGH << ACTIVE_LEVEL_OFF; pin_reg &= ~(DB_CNTRl_MASK << DB_CNTRL_OFF); pin_reg |= DB_TYPE_PRESERVE_LOW_GLITCH << DB_CNTRL_OFF; irq_set_handler_locked(d, handle_level_irq); break; case IRQ_TYPE_LEVEL_LOW: pin_reg |= LEVEL_TRIGGER << LEVEL_TRIG_OFF; pin_reg &= ~(ACTIVE_LEVEL_MASK << ACTIVE_LEVEL_OFF); pin_reg |= ACTIVE_LOW << ACTIVE_LEVEL_OFF; pin_reg &= ~(DB_CNTRl_MASK << DB_CNTRL_OFF); pin_reg |= DB_TYPE_PRESERVE_HIGH_GLITCH << DB_CNTRL_OFF; irq_set_handler_locked(d, handle_level_irq); break; case IRQ_TYPE_NONE: break; default: dev_err(&gpio_dev->pdev->dev, "Invalid type value\n"); ret = -EINVAL; } pin_reg |= CLR_INTR_STAT << INTERRUPT_STS_OFF; writel(pin_reg, gpio_dev->base + (d->hwirq)*4); spin_unlock_irqrestore(&gpio_dev->lock, flags); return ret; } static void amd_irq_ack(struct irq_data *d) { /* * based on HW design,there is no need to ack HW * before handle current irq. But this routine is * necessary for handle_edge_irq */ } static struct irq_chip amd_gpio_irqchip = { .name = "amd_gpio", .irq_ack = amd_irq_ack, .irq_enable = amd_gpio_irq_enable, .irq_disable = amd_gpio_irq_disable, .irq_mask = amd_gpio_irq_mask, .irq_unmask = amd_gpio_irq_unmask, .irq_eoi = amd_gpio_irq_eoi, .irq_set_type = amd_gpio_irq_set_type, }; static void amd_gpio_irq_handler(struct irq_desc *desc) { u32 i; u32 off; u32 reg; u32 pin_reg; u64 reg64; int handled = 0; unsigned int irq; unsigned long flags; struct irq_chip *chip = irq_desc_get_chip(desc); struct gpio_chip *gc = irq_desc_get_handler_data(desc); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); chained_irq_enter(chip, desc); /*enable GPIO interrupt again*/ spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_STATUS_REG1); reg64 = reg; reg64 = reg64 << 32; reg = readl(gpio_dev->base + WAKE_INT_STATUS_REG0); reg64 |= reg; spin_unlock_irqrestore(&gpio_dev->lock, flags); /* * first 46 bits indicates interrupt status. * one bit represents four interrupt sources. */ for (off = 0; off < 46 ; off++) { if (reg64 & BIT(off)) { for (i = 0; i < 4; i++) { pin_reg = readl(gpio_dev->base + (off * 4 + i) * 4); if ((pin_reg & BIT(INTERRUPT_STS_OFF)) || (pin_reg & BIT(WAKE_STS_OFF))) { irq = irq_find_mapping(gc->irqdomain, off * 4 + i); generic_handle_irq(irq); writel(pin_reg, gpio_dev->base + (off * 4 + i) * 4); handled++; } } } } if (handled == 0) handle_bad_irq(desc); spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_MASTER_REG); reg |= EOI_MASK; writel(reg, gpio_dev->base + WAKE_INT_MASTER_REG); spin_unlock_irqrestore(&gpio_dev->lock, flags); chained_irq_exit(chip, desc); } static int amd_get_groups_count(struct pinctrl_dev *pctldev) { struct amd_gpio *gpio_dev = pinctrl_dev_get_drvdata(pctldev); return gpio_dev->ngroups; } static const char *amd_get_group_name(struct pinctrl_dev *pctldev, unsigned group) { struct amd_gpio *gpio_dev = pinctrl_dev_get_drvdata(pctldev); return gpio_dev->groups[group].name; } static int amd_get_group_pins(struct pinctrl_dev *pctldev, unsigned group, const unsigned **pins, unsigned *num_pins) { struct amd_gpio *gpio_dev = pinctrl_dev_get_drvdata(pctldev); *pins = gpio_dev->groups[group].pins; *num_pins = gpio_dev->groups[group].npins; return 0; } static const struct pinctrl_ops amd_pinctrl_ops = { .get_groups_count = amd_get_groups_count, .get_group_name = amd_get_group_name, .get_group_pins = amd_get_group_pins, #ifdef CONFIG_OF .dt_node_to_map = pinconf_generic_dt_node_to_map_group, .dt_free_map = pinctrl_utils_free_map, #endif }; static int amd_pinconf_get(struct pinctrl_dev *pctldev, unsigned int pin, unsigned long *config) { u32 pin_reg; unsigned arg; unsigned long flags; struct amd_gpio *gpio_dev = pinctrl_dev_get_drvdata(pctldev); enum pin_config_param param = pinconf_to_config_param(*config); spin_lock_irqsave(&gpio_dev->lock, flags); pin_reg = readl(gpio_dev->base + pin*4); spin_unlock_irqrestore(&gpio_dev->lock, flags); switch (param) { case PIN_CONFIG_INPUT_DEBOUNCE: arg = pin_reg & DB_TMR_OUT_MASK; break; case PIN_CONFIG_BIAS_PULL_DOWN: arg = (pin_reg >> PULL_DOWN_ENABLE_OFF) & BIT(0); break; case PIN_CONFIG_BIAS_PULL_UP: arg = (pin_reg >> PULL_UP_SEL_OFF) & (BIT(0) | BIT(1)); break; case PIN_CONFIG_DRIVE_STRENGTH: arg = (pin_reg >> DRV_STRENGTH_SEL_OFF) & DRV_STRENGTH_SEL_MASK; break; default: dev_err(&gpio_dev->pdev->dev, "Invalid config param %04x\n", param); return -ENOTSUPP; } *config = pinconf_to_config_packed(param, arg); return 0; } static int amd_pinconf_set(struct pinctrl_dev *pctldev, unsigned int pin, unsigned long *configs, unsigned num_configs) { int i; u32 arg; int ret = 0; u32 pin_reg; unsigned long flags; enum pin_config_param param; struct amd_gpio *gpio_dev = pinctrl_dev_get_drvdata(pctldev); spin_lock_irqsave(&gpio_dev->lock, flags); for (i = 0; i < num_configs; i++) { param = pinconf_to_config_param(configs[i]); arg = pinconf_to_config_argument(configs[i]); pin_reg = readl(gpio_dev->base + pin*4); switch (param) { case PIN_CONFIG_INPUT_DEBOUNCE: pin_reg &= ~DB_TMR_OUT_MASK; pin_reg |= arg & DB_TMR_OUT_MASK; break; case PIN_CONFIG_BIAS_PULL_DOWN: pin_reg &= ~BIT(PULL_DOWN_ENABLE_OFF); pin_reg |= (arg & BIT(0)) << PULL_DOWN_ENABLE_OFF; break; case PIN_CONFIG_BIAS_PULL_UP: pin_reg &= ~BIT(PULL_UP_SEL_OFF); pin_reg |= (arg & BIT(0)) << PULL_UP_SEL_OFF; pin_reg &= ~BIT(PULL_UP_ENABLE_OFF); pin_reg |= ((arg>>1) & BIT(0)) << PULL_UP_ENABLE_OFF; break; case PIN_CONFIG_DRIVE_STRENGTH: pin_reg &= ~(DRV_STRENGTH_SEL_MASK << DRV_STRENGTH_SEL_OFF); pin_reg |= (arg & DRV_STRENGTH_SEL_MASK) << DRV_STRENGTH_SEL_OFF; break; default: dev_err(&gpio_dev->pdev->dev, "Invalid config param %04x\n", param); ret = -ENOTSUPP; } writel(pin_reg, gpio_dev->base + pin*4); } spin_unlock_irqrestore(&gpio_dev->lock, flags); return ret; } static int amd_pinconf_group_get(struct pinctrl_dev *pctldev, unsigned int group, unsigned long *config) { const unsigned *pins; unsigned npins; int ret; ret = amd_get_group_pins(pctldev, group, &pins, &npins); if (ret) return ret; if (amd_pinconf_get(pctldev, pins[0], config)) return -ENOTSUPP; return 0; } static int amd_pinconf_group_set(struct pinctrl_dev *pctldev, unsigned group, unsigned long *configs, unsigned num_configs) { const unsigned *pins; unsigned npins; int i, ret; ret = amd_get_group_pins(pctldev, group, &pins, &npins); if (ret) return ret; for (i = 0; i < npins; i++) { if (amd_pinconf_set(pctldev, pins[i], configs, num_configs)) return -ENOTSUPP; } return 0; } static const struct pinconf_ops amd_pinconf_ops = { .pin_config_get = amd_pinconf_get, .pin_config_set = amd_pinconf_set, .pin_config_group_get = amd_pinconf_group_get, .pin_config_group_set = amd_pinconf_group_set, }; static struct pinctrl_desc amd_pinctrl_desc = { .pins = kerncz_pins, .npins = ARRAY_SIZE(kerncz_pins), .pctlops = &amd_pinctrl_ops, .confops = &amd_pinconf_ops, .owner = THIS_MODULE, }; static int amd_gpio_probe(struct platform_device *pdev) { int ret = 0; int irq_base; struct resource *res; struct amd_gpio *gpio_dev; gpio_dev = devm_kzalloc(&pdev->dev, sizeof(struct amd_gpio), GFP_KERNEL); if (!gpio_dev) return -ENOMEM; spin_lock_init(&gpio_dev->lock); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Failed to get gpio io resource.\n"); return -EINVAL; } gpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start, resource_size(res)); if (!gpio_dev->base) return -ENOMEM; irq_base = platform_get_irq(pdev, 0); if (irq_base < 0) { dev_err(&pdev->dev, "Failed to get gpio IRQ.\n"); return -EINVAL; } gpio_dev->pdev = pdev; gpio_dev->gc.direction_input = amd_gpio_direction_input; gpio_dev->gc.direction_output = amd_gpio_direction_output; gpio_dev->gc.get = amd_gpio_get_value; gpio_dev->gc.set = amd_gpio_set_value; gpio_dev->gc.set_debounce = amd_gpio_set_debounce; gpio_dev->gc.dbg_show = amd_gpio_dbg_show; gpio_dev->gc.base = 0; gpio_dev->gc.label = pdev->name; gpio_dev->gc.owner = THIS_MODULE; gpio_dev->gc.parent = &pdev->dev; gpio_dev->gc.ngpio = TOTAL_NUMBER_OF_PINS; #if defined(CONFIG_OF_GPIO) gpio_dev->gc.of_node = pdev->dev.of_node; #endif gpio_dev->groups = kerncz_groups; gpio_dev->ngroups = ARRAY_SIZE(kerncz_groups); amd_pinctrl_desc.name = dev_name(&pdev->dev); gpio_dev->pctrl = devm_pinctrl_register(&pdev->dev, &amd_pinctrl_desc, gpio_dev); if (IS_ERR(gpio_dev->pctrl)) { dev_err(&pdev->dev, "Couldn't register pinctrl driver\n"); return PTR_ERR(gpio_dev->pctrl); } ret = gpiochip_add_data(&gpio_dev->gc, gpio_dev); if (ret) return ret; ret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev), 0, 0, TOTAL_NUMBER_OF_PINS); if (ret) { dev_err(&pdev->dev, "Failed to add pin range\n"); goto out2; } ret = gpiochip_irqchip_add(&gpio_dev->gc, &amd_gpio_irqchip, 0, handle_simple_irq, IRQ_TYPE_NONE); if (ret) { dev_err(&pdev->dev, "could not add irqchip\n"); ret = -ENODEV; goto out2; } gpiochip_set_chained_irqchip(&gpio_dev->gc, &amd_gpio_irqchip, irq_base, amd_gpio_irq_handler); platform_set_drvdata(pdev, gpio_dev); dev_dbg(&pdev->dev, "amd gpio driver loaded\n"); return ret; out2: gpiochip_remove(&gpio_dev->gc); return ret; } static int amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); return 0; } static const struct acpi_device_id amd_gpio_acpi_match[] = { { "AMD0030", 0 }, { "AMDI0030", 0}, { }, }; MODULE_DEVICE_TABLE(acpi, amd_gpio_acpi_match); static struct platform_driver amd_gpio_driver = { .driver = { .name = "amd_gpio", .acpi_match_table = ACPI_PTR(amd_gpio_acpi_match), }, .probe = amd_gpio_probe, .remove = amd_gpio_remove, }; module_platform_driver(amd_gpio_driver); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Ken Xue <Ken.Xue@amd.com>, Jeff Wu <Jeff.Wu@amd.com>"); MODULE_DESCRIPTION("AMD GPIO pinctrl driver");
./CrossVul/dataset_final_sorted/CWE-415/c/good_3003_0
crossvul-cpp_data_bad_348_8
/* * cryptoflex-tool.c: Tool for doing various Cryptoflex related stuff * * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "config.h" #include "libopensc/sc-ossl-compat.h" #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/err.h> #include "libopensc/pkcs15.h" #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "util.h" static const char *app_name = "cryptoflex-tool"; static char * opt_reader = NULL; static int opt_wait = 0; static int opt_key_num = 1, opt_pin_num = -1; static int verbose = 0; static int opt_exponent = 3; static int opt_mod_length = 1024; static int opt_key_count = 1; static int opt_pin_attempts = 10; static int opt_puk_attempts = 10; static const char *opt_appdf = NULL, *opt_prkeyf = NULL, *opt_pubkeyf = NULL; static u8 *pincode = NULL; static const struct option options[] = { { "list-keys", 0, NULL, 'l' }, { "create-key-files", 1, NULL, 'c' }, { "create-pin-file", 1, NULL, 'P' }, { "generate-key", 0, NULL, 'g' }, { "read-key", 0, NULL, 'R' }, { "verify-pin", 0, NULL, 'V' }, { "key-num", 1, NULL, 'k' }, { "app-df", 1, NULL, 'a' }, { "prkey-file", 1, NULL, 'p' }, { "pubkey-file", 1, NULL, 'u' }, { "exponent", 1, NULL, 'e' }, { "modulus-length", 1, NULL, 'm' }, { "reader", 1, NULL, 'r' }, { "wait", 0, NULL, 'w' }, { "verbose", 0, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static const char *option_help[] = { "Lists all keys in a public key file", "Creates new RSA key files for <arg> keys", "Creates a new CHV<arg> file", "Generates a new RSA key pair", "Reads a public key from the card", "Verifies CHV1 before issuing commands", "Selects which key number to operate on [1]", "Selects the DF to operate in", "Private key file", "Public key file", "The RSA exponent to use in key generation [3]", "Modulus length to use in key generation [1024]", "Uses reader <arg>", "Wait for card insertion", "Verbose operation. Use several times to enable debug output.", }; static sc_context_t *ctx = NULL; static sc_card_t *card = NULL; static char *getpin(const char *prompt) { char *buf, pass[20]; int i; printf("%s", prompt); fflush(stdout); if (fgets(pass, 20, stdin) == NULL) return NULL; for (i = 0; i < 20; i++) if (pass[i] == '\n') pass[i] = 0; if (strlen(pass) == 0) return NULL; buf = malloc(8); if (buf == NULL) return NULL; if (strlen(pass) > 8) { fprintf(stderr, "PIN code too long.\n"); free(buf); return NULL; } memset(buf, 0, 8); strlcpy(buf, pass, 8); return buf; } static int verify_pin(int pin) { char prompt[50]; int r, tries_left = -1; if (pincode == NULL) { sprintf(prompt, "Please enter CHV%d: ", pin); pincode = (u8 *) getpin(prompt); if (pincode == NULL || strlen((char *) pincode) == 0) return -1; } if (pin != 1 && pin != 2) return -3; r = sc_verify(card, SC_AC_CHV, pin, pincode, 8, &tries_left); if (r) { memset(pincode, 0, 8); free(pincode); pincode = NULL; fprintf(stderr, "PIN code verification failed: %s\n", sc_strerror(r)); return -1; } return 0; } static int select_app_df(void) { sc_path_t path; sc_file_t *file; char str[80]; int r; strcpy(str, "3F00"); if (opt_appdf != NULL) strlcat(str, opt_appdf, sizeof str); sc_format_path(str, &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select application DF: %s\n", sc_strerror(r)); return -1; } if (file->type != SC_FILE_TYPE_DF) { fprintf(stderr, "Selected application DF is not a DF.\n"); return -1; } sc_file_free(file); if (opt_pin_num >= 0) return verify_pin(opt_pin_num); else return 0; } static void invert_buf(u8 *dest, const u8 *src, size_t c) { size_t i; for (i = 0; i < c; i++) dest[i] = src[c-1-i]; } static BIGNUM * cf2bn(const u8 *buf, size_t bufsize, BIGNUM *num) { u8 tmp[512]; invert_buf(tmp, buf, bufsize); return BN_bin2bn(tmp, bufsize, num); } static int bn2cf(const BIGNUM *num, u8 *buf) { u8 tmp[512]; int r; r = BN_bn2bin(num, tmp); if (r <= 0) return r; invert_buf(buf, tmp, r); return r; } static int parse_public_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *n, *e; int base; base = (keysize - 7) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid public key.\n"); return -1; } p += 3; n = BN_new(); if (n == NULL) return -1; cf2bn(p, 2 * base, n); p += 2 * base; p += base; p += 2 * base; e = BN_new(); if (e == NULL) return -1; cf2bn(p, 4, e); if (RSA_set0_key(rsa, n, e, NULL) != 1) return -1; return 0; } static int gen_d(RSA *rsa) { BN_CTX *bnctx; BIGNUM *r0, *r1, *r2; const BIGNUM *rsa_p, *rsa_q, *rsa_n, *rsa_e, *rsa_d; BIGNUM *rsa_n_new, *rsa_e_new, *rsa_d_new; bnctx = BN_CTX_new(); if (bnctx == NULL) return -1; BN_CTX_start(bnctx); r0 = BN_CTX_get(bnctx); r1 = BN_CTX_get(bnctx); r2 = BN_CTX_get(bnctx); RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); BN_sub(r1, rsa_p, BN_value_one()); BN_sub(r2, rsa_q, BN_value_one()); BN_mul(r0, r1, r2, bnctx); if ((rsa_d_new = BN_mod_inverse(NULL, rsa_e, r0, bnctx)) == NULL) { fprintf(stderr, "BN_mod_inverse() failed.\n"); return -1; } /* RSA_set0_key will free previous value, and replace with new value * Thus the need to copy the contents of rsa_n and rsa_e */ rsa_n_new = BN_dup(rsa_n); rsa_e_new = BN_dup(rsa_e); if (RSA_set0_key(rsa, rsa_n_new, rsa_e_new, rsa_d_new) != 1) return -1; BN_CTX_end(bnctx); BN_CTX_free(bnctx); return 0; } static int parse_private_key(const u8 *key, size_t keysize, RSA *rsa) { const u8 *p = key; BIGNUM *bn_p, *q, *dmp1, *dmq1, *iqmp; int base; base = (keysize - 3) / 5; if (base != 32 && base != 48 && base != 64 && base != 128) { fprintf(stderr, "Invalid private key.\n"); return -1; } p += 3; bn_p = BN_new(); if (bn_p == NULL) return -1; cf2bn(p, base, bn_p); p += base; q = BN_new(); if (q == NULL) return -1; cf2bn(p, base, q); p += base; iqmp = BN_new(); if (iqmp == NULL) return -1; cf2bn(p, base, iqmp); p += base; dmp1 = BN_new(); if (dmp1 == NULL) return -1; cf2bn(p, base, dmp1); p += base; dmq1 = BN_new(); if (dmq1 == NULL) return -1; cf2bn(p, base, dmq1); p += base; if (RSA_set0_factors(rsa, bn_p, q) != 1) return -1; if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) != 1) return -1; if (gen_d(rsa)) return -1; return 0; } static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } static int read_key(void) { RSA *rsa = RSA_new(); u8 buf[1024], *p = buf; u8 b64buf[2048]; int r; if (rsa == NULL) return -1; r = read_public_key(rsa); if (r) return r; r = i2d_RSA_PUBKEY(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding public key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----\n", b64buf); r = read_private_key(rsa); if (r == 10) return 0; else if (r) return r; p = buf; r = i2d_RSAPrivateKey(rsa, &p); if (r <= 0) { fprintf(stderr, "Error encoding private key.\n"); return -1; } r = sc_base64_encode(buf, r, b64buf, sizeof(b64buf), 64); if (r < 0) { fprintf(stderr, "Error in Base64 encoding: %s\n", sc_strerror(r)); return -1; } printf("-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n", b64buf); return 0; } static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } static int generate_key(void) { sc_apdu_t apdu; u8 sbuf[4]; u8 p2; int r; switch (opt_mod_length) { case 512: p2 = 0x40; break; case 768: p2 = 0x60; break; case 1024: p2 = 0x80; break; case 2048: p2 = 0x00; break; default: fprintf(stderr, "Invalid modulus length.\n"); return 2; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, (u8) opt_key_num-1, p2); apdu.cla = 0xF0; apdu.lc = 4; apdu.datalen = 4; apdu.data = sbuf; sbuf[0] = opt_exponent & 0xFF; sbuf[1] = (opt_exponent >> 8) & 0xFF; sbuf[2] = (opt_exponent >> 16) & 0xFF; sbuf[3] = (opt_exponent >> 24) & 0xFF; r = select_app_df(); if (r) return 1; if (verbose) printf("Generating key...\n"); r = sc_transmit_apdu(card, &apdu); if (r) { fprintf(stderr, "APDU transmit failed: %s\n", sc_strerror(r)); if (r == SC_ERROR_TRANSMIT_FAILED) fprintf(stderr, "Reader has timed out. It is still possible that the key generation has\n" "succeeded.\n"); return 1; } if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { printf("Key generation successful.\n"); return 0; } if (apdu.sw1 == 0x69 && apdu.sw2 == 0x82) fprintf(stderr, "CHV1 not verified or invalid exponent value.\n"); else fprintf(stderr, "Card returned SW1=%02X, SW2=%02X.\n", apdu.sw1, apdu.sw2); return 1; } static int create_key_files(void) { sc_file_t *file; int mod_lens[] = { 512, 768, 1024, 2048 }; int sizes[] = { 163, 243, 323, 643 }; int size = -1; int r; size_t i; for (i = 0; i < sizeof(mod_lens) / sizeof(int); i++) if (mod_lens[i] == opt_mod_length) { size = sizes[i]; break; } if (size == -1) { fprintf(stderr, "Invalid modulus length.\n"); return 1; } if (verbose) printf("Creating key files for %d keys.\n", opt_key_count); file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x0012; file->size = opt_key_count * size + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create private key file: %s\n", sc_strerror(r)); return 1; } file = sc_file_new(); if (!file) { fprintf(stderr, "out of memory.\n"); return 1; } file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; file->id = 0x1012; file->size = opt_key_count * (size + 4) + 3; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_CHV, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_CHV, 1); if (select_app_df()) { sc_file_free(file); return 1; } r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "Unable to create public key file: %s\n", sc_strerror(r)); return 1; } if (verbose) printf("Key files generated successfully.\n"); return 0; } static int read_rsa_privkey(RSA **rsa_out) { RSA *rsa = NULL; BIO *in = NULL; int r; in = BIO_new(BIO_s_file()); if (opt_prkeyf == NULL) { fprintf(stderr, "Private key file must be set.\n"); return 2; } r = BIO_read_filename(in, opt_prkeyf); if (r <= 0) { perror(opt_prkeyf); return 2; } rsa = PEM_read_bio_RSAPrivateKey(in, NULL, NULL, NULL); if (rsa == NULL) { fprintf(stderr, "Unable to load private key.\n"); return 2; } BIO_free(in); *rsa_out = rsa; return 0; } static int encode_private_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_p, *rsa_q, *rsa_dmp1, *rsa_dmq1, *rsa_iqmp; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 3) >> 8; *p++ = (5 * base + 3) & 0xFF; *p++ = opt_key_num; RSA_get0_factors(rsa, &rsa_p, &rsa_q); r = bn2cf(rsa_p, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_q, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; RSA_get0_crt_params(rsa, &rsa_dmp1, &rsa_dmq1, &rsa_iqmp); r = bn2cf(rsa_iqmp, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmp1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; r = bn2cf(rsa_dmq1, bnbuf); if (r != base) { fprintf(stderr, "Invalid private key.\n"); return 2; } memcpy(p, bnbuf, base); p += base; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int encode_public_key(RSA *rsa, u8 *key, size_t *keysize) { u8 buf[1024], *p = buf; u8 bnbuf[256]; int base = 0; int r; const BIGNUM *rsa_n, *rsa_e; switch (RSA_bits(rsa)) { case 512: base = 32; break; case 768: base = 48; break; case 1024: base = 64; break; case 2048: base = 128; break; } if (base == 0) { fprintf(stderr, "Key length invalid.\n"); return 2; } *p++ = (5 * base + 7) >> 8; *p++ = (5 * base + 7) & 0xFF; *p++ = opt_key_num; RSA_get0_key(rsa, &rsa_n, &rsa_e, NULL); r = bn2cf(rsa_n, bnbuf); if (r != 2*base) { fprintf(stderr, "Invalid public key.\n"); return 2; } memcpy(p, bnbuf, 2*base); p += 2*base; memset(p, 0, base); p += base; memset(bnbuf, 0, 2*base); memcpy(p, bnbuf, 2*base); p += 2*base; r = bn2cf(rsa_e, bnbuf); memcpy(p, bnbuf, 4); p += 4; memcpy(key, buf, p - buf); *keysize = p - buf; return 0; } static int update_public_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write public key: %s\n", sc_strerror(r)); return 2; } return 0; } static int update_private_key(const u8 *key, size_t keysize) { int r, idx = 0; sc_path_t path; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } idx = keysize * (opt_key_num-1); r = sc_update_binary(card, idx, key, keysize, 0); if (r < 0) { fprintf(stderr, "Unable to write private key: %s\n", sc_strerror(r)); return 2; } return 0; } static int store_key(void) { u8 prv[1024], pub[1024]; size_t prvsize, pubsize; int r; RSA *rsa; r = read_rsa_privkey(&rsa); if (r) return r; r = encode_private_key(rsa, prv, &prvsize); if (r) return r; r = encode_public_key(rsa, pub, &pubsize); if (r) return r; if (verbose) printf("Storing private key...\n"); r = select_app_df(); if (r) return r; r = update_private_key(prv, prvsize); if (r) return r; if (verbose) printf("Storing public key...\n"); r = select_app_df(); if (r) return r; r = update_public_key(pub, pubsize); if (r) return r; return 0; } static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } static int create_pin(void) { sc_path_t path; char buf[80]; if (opt_pin_num != 1 && opt_pin_num != 2) { fprintf(stderr, "Invalid PIN number. Possible values: 1, 2.\n"); return 2; } strcpy(buf, "3F00"); if (opt_appdf != NULL) strlcat(buf, opt_appdf, sizeof buf); sc_format_path(buf, &path); return create_pin_file(&path, opt_pin_num, ""); } int main(int argc, char *argv[]) { int err = 0, r, c, long_optind = 0; int action_count = 0; int do_read_key = 0; int do_generate_key = 0; int do_create_key_files = 0; int do_list_keys = 0; int do_store_key = 0; int do_create_pin_file = 0; sc_context_param_t ctx_param; while (1) { c = getopt_long(argc, argv, "P:Vslgc:Rk:r:p:u:e:m:vwa:", options, &long_optind); if (c == -1) break; if (c == '?') util_print_usage_and_die(app_name, options, option_help, NULL); switch (c) { case 'l': do_list_keys = 1; action_count++; break; case 'P': do_create_pin_file = 1; opt_pin_num = atoi(optarg); action_count++; break; case 'R': do_read_key = 1; action_count++; break; case 'g': do_generate_key = 1; action_count++; break; case 'c': do_create_key_files = 1; opt_key_count = atoi(optarg); action_count++; break; case 's': do_store_key = 1; action_count++; break; case 'k': opt_key_num = atoi(optarg); if (opt_key_num < 1 || opt_key_num > 15) { fprintf(stderr, "Key number invalid.\n"); exit(2); } break; case 'V': opt_pin_num = 1; break; case 'e': opt_exponent = atoi(optarg); break; case 'm': opt_mod_length = atoi(optarg); break; case 'p': opt_prkeyf = optarg; break; case 'u': opt_pubkeyf = optarg; break; case 'r': opt_reader = optarg; break; case 'v': verbose++; break; case 'w': opt_wait = 1; break; case 'a': opt_appdf = optarg; break; } } if (action_count == 0) util_print_usage_and_die(app_name, options, option_help, NULL); memset(&ctx_param, 0, sizeof(ctx_param)); ctx_param.ver = 0; ctx_param.app_name = app_name; r = sc_context_create(&ctx, &ctx_param); if (r) { fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r)); return 1; } if (verbose > 1) { ctx->debug = verbose; sc_ctx_log_to_file(ctx, "stderr"); } err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose); printf("Using card driver: %s\n", card->driver->name); if (do_create_pin_file) { if ((err = create_pin()) != 0) goto end; action_count--; } if (do_create_key_files) { if ((err = create_key_files()) != 0) goto end; action_count--; } if (do_generate_key) { if ((err = generate_key()) != 0) goto end; action_count--; } if (do_store_key) { if ((err = store_key()) != 0) goto end; action_count--; } if (do_list_keys) { if ((err = list_keys()) != 0) goto end; action_count--; } if (do_read_key) { if ((err = read_key()) != 0) goto end; action_count--; } if (pincode != NULL) { memset(pincode, 0, 8); free(pincode); } end: if (card) { sc_unlock(card); sc_disconnect_card(card); } if (ctx) sc_release_context(ctx); return err; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_8
crossvul-cpp_data_good_347_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_1
crossvul-cpp_data_good_349_4
/* * PKCS15 emulation layer for EstEID card. * * Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net> * Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "internal.h" #include "opensc.h" #include "pkcs15.h" #include "esteid.h" int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *); static void set_string (char **strp, const char *value) { if (*strp) free (*strp); *strp = value ? strdup (value) : NULL; } int select_esteid_df (sc_card_t * card) { int r; sc_path_t tmppath; sc_format_path ("3F00EEEE", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed"); return r; } static int sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[MIN((size_t) r, (sizeof buff)-1)] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } static int esteid_detect_card(sc_pkcs15_card_t *p15card) { if (is_esteid_card(p15card->card)) return SC_SUCCESS; else return SC_ERROR_WRONG_CARD; } int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_esteid_init(p15card); else { int r = esteid_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_esteid_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_4
crossvul-cpp_data_good_347_6
/* * pkcs15-sc-hsm.c : Initialize PKCS#15 emulation * * Copyright (C) 2012 Andreas Schwier, CardContact, Minden, Germany * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "internal.h" #include "pkcs15.h" #include "asn1.h" #include "common/compat_strlcpy.h" #include "common/compat_strnlen.h" #include "card-sc-hsm.h" extern struct sc_aid sc_hsm_aid; void sc_hsm_set_serialnr(sc_card_t *card, char *serial); static struct ec_curve curves[] = { { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x01", 8}, // secp192r1 aka prime192r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 24}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 24}, { (unsigned char *) "\x64\x21\x05\x19\xE5\x9C\x80\xE7\x0F\xA7\xE9\xAB\x72\x24\x30\x49\xFE\xB8\xDE\xEC\xC1\x46\xB9\xB1", 24}, { (unsigned char *) "\x04\x18\x8D\xA8\x0E\xB0\x30\x90\xF6\x7C\xBF\x20\xEB\x43\xA1\x88\x00\xF4\xFF\x0A\xFD\x82\xFF\x10\x12\x07\x19\x2B\x95\xFF\xC8\xDA\x78\x63\x10\x11\xED\x6B\x24\xCD\xD5\x73\xF9\x77\xA1\x1E\x79\x48\x11", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x99\xDE\xF8\x36\x14\x6B\xC9\xB1\xB4\xD2\x28\x31", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8}, // secp256r1 aka prime256r1 { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 32}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC", 32}, { (unsigned char *) "\x5A\xC6\x35\xD8\xAA\x3A\x93\xE7\xB3\xEB\xBD\x55\x76\x98\x86\xBC\x65\x1D\x06\xB0\xCC\x53\xB0\xF6\x3B\xCE\x3C\x3E\x27\xD2\x60\x4B", 32}, { (unsigned char *) "\x04\x6B\x17\xD1\xF2\xE1\x2C\x42\x47\xF8\xBC\xE6\xE5\x63\xA4\x40\xF2\x77\x03\x7D\x81\x2D\xEB\x33\xA0\xF4\xA1\x39\x45\xD8\x98\xC2\x96\x4F\xE3\x42\xE2\xFE\x1A\x7F\x9B\x8E\xE7\xEB\x4A\x7C\x0F\x9E\x16\x2B\xCE\x33\x57\x6B\x31\x5E\xCE\xCB\xB6\x40\x68\x37\xBF\x51\xF5", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBC\xE6\xFA\xAD\xA7\x17\x9E\x84\xF3\xB9\xCA\xC2\xFC\x63\x25\x51", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x03", 9}, // brainpoolP192r1 { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x30\x93\xD1\x8D\xB7\x8F\xCE\x47\x6D\xE1\xA8\x62\x97", 24}, { (unsigned char *) "\x6A\x91\x17\x40\x76\xB1\xE0\xE1\x9C\x39\xC0\x31\xFE\x86\x85\xC1\xCA\xE0\x40\xE5\xC6\x9A\x28\xEF", 24}, { (unsigned char *) "\x46\x9A\x28\xEF\x7C\x28\xCC\xA3\xDC\x72\x1D\x04\x4F\x44\x96\xBC\xCA\x7E\xF4\x14\x6F\xBF\x25\xC9", 24}, { (unsigned char *) "\x04\xC0\xA0\x64\x7E\xAA\xB6\xA4\x87\x53\xB0\x33\xC5\x6C\xB0\xF0\x90\x0A\x2F\x5C\x48\x53\x37\x5F\xD6\x14\xB6\x90\x86\x6A\xBD\x5B\xB8\x8B\x5F\x48\x28\xC1\x49\x00\x02\xE6\x77\x3F\xA2\xFA\x29\x9B\x8F", 49}, { (unsigned char *) "\xC3\x02\xF4\x1D\x93\x2A\x36\xCD\xA7\xA3\x46\x2F\x9E\x9E\x91\x6B\x5B\xE8\xF1\x02\x9A\xC4\xAC\xC1", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x05", 9}, // brainpoolP224r1 { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF", 28}, { (unsigned char *) "\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA\xD2\x9F\x43", 28}, { (unsigned char *) "\x25\x80\xF6\x3C\xCF\xE4\x41\x38\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66\xDB\xB3\x72\x38\x6C\x40\x0B", 28}, { (unsigned char *) "\x04\x0D\x90\x29\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02\xCD", 57}, { (unsigned char *) "\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A\x18\x30\x25\x75\xD0\xFB\x98\xD1\x16\xBC\x4B\x6D\xDE\xBC\xA3\xA5\xA7\x93\x9F", 28}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x07", 9}, // brainpoolP256r1 { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x72\x6E\x3B\xF6\x23\xD5\x26\x20\x28\x20\x13\x48\x1D\x1F\x6E\x53\x77", 32}, { (unsigned char *) "\x7D\x5A\x09\x75\xFC\x2C\x30\x57\xEE\xF6\x75\x30\x41\x7A\xFF\xE7\xFB\x80\x55\xC1\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9", 32}, { (unsigned char *) "\x26\xDC\x5C\x6C\xE9\x4A\x4B\x44\xF3\x30\xB5\xD9\xBB\xD7\x7C\xBF\x95\x84\x16\x29\x5C\xF7\xE1\xCE\x6B\xCC\xDC\x18\xFF\x8C\x07\xB6", 32}, { (unsigned char *) "\x04\x8B\xD2\xAE\xB9\xCB\x7E\x57\xCB\x2C\x4B\x48\x2F\xFC\x81\xB7\xAF\xB9\xDE\x27\xE1\xE3\xBD\x23\xC2\x3A\x44\x53\xBD\x9A\xCE\x32\x62\x54\x7E\xF8\x35\xC3\xDA\xC4\xFD\x97\xF8\x46\x1A\x14\x61\x1D\xC9\xC2\x77\x45\x13\x2D\xED\x8E\x54\x5C\x1D\x54\xC7\x2F\x04\x69\x97", 65}, { (unsigned char *) "\xA9\xFB\x57\xDB\xA1\xEE\xA9\xBC\x3E\x66\x0A\x90\x9D\x83\x8D\x71\x8C\x39\x7A\xA3\xB5\x61\xA6\xF7\x90\x1E\x0E\x82\x97\x48\x56\xA7", 32}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x24\x03\x03\x02\x08\x01\x01\x09", 9}, // brainpoolP320r1 { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA6\xF6\xF4\x0D\xEF\x4F\x92\xB9\xEC\x78\x93\xEC\x28\xFC\xD4\x12\xB1\xF1\xB3\x2E\x27", 40}, { (unsigned char *) "\x3E\xE3\x0B\x56\x8F\xBA\xB0\xF8\x83\xCC\xEB\xD4\x6D\x3F\x3B\xB8\xA2\xA7\x35\x13\xF5\xEB\x79\xDA\x66\x19\x0E\xB0\x85\xFF\xA9\xF4\x92\xF3\x75\xA9\x7D\x86\x0E\xB4", 40}, { (unsigned char *) "\x52\x08\x83\x94\x9D\xFD\xBC\x42\xD3\xAD\x19\x86\x40\x68\x8A\x6F\xE1\x3F\x41\x34\x95\x54\xB4\x9A\xCC\x31\xDC\xCD\x88\x45\x39\x81\x6F\x5E\xB4\xAC\x8F\xB1\xF1\xA6", 40}, { (unsigned char *) "\x04\x43\xBD\x7E\x9A\xFB\x53\xD8\xB8\x52\x89\xBC\xC4\x8E\xE5\xBF\xE6\xF2\x01\x37\xD1\x0A\x08\x7E\xB6\xE7\x87\x1E\x2A\x10\xA5\x99\xC7\x10\xAF\x8D\x0D\x39\xE2\x06\x11\x14\xFD\xD0\x55\x45\xEC\x1C\xC8\xAB\x40\x93\x24\x7F\x77\x27\x5E\x07\x43\xFF\xED\x11\x71\x82\xEA\xA9\xC7\x78\x77\xAA\xAC\x6A\xC7\xD3\x52\x45\xD1\x69\x2E\x8E\xE1", 81}, { (unsigned char *) "\xD3\x5E\x47\x20\x36\xBC\x4F\xB7\xE1\x3C\x78\x5E\xD2\x01\xE0\x65\xF9\x8F\xCF\xA5\xB6\x8F\x12\xA3\x2D\x48\x2E\xC7\xEE\x86\x58\xE9\x86\x91\x55\x5B\x44\xC5\x93\x11", 40}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x1F", 5}, // secp192k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xEE\x37", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 24}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03", 24}, { (unsigned char *) "\x04\xDB\x4F\xF1\x0E\xC0\x57\xE9\xAE\x26\xB0\x7D\x02\x80\xB7\xF4\x34\x1D\xA5\xD1\xB1\xEA\xE0\x6C\x7D\x9B\x2F\x2F\x6D\x9C\x56\x28\xA7\x84\x41\x63\xD0\x15\xBE\x86\x34\x40\x82\xAA\x88\xD9\x5E\x2F\x9D", 49}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\x26\xF2\xFC\x17\x0F\x69\x46\x6A\x74\xDE\xFD\x8D", 24}, { (unsigned char *) "\x01", 1} }, { { (unsigned char *) "\x2B\x81\x04\x00\x0A", 5}, // secp256k1 { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFC\x2F", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 32}, { (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07", 32}, { (unsigned char *) "\x04\x79\xBE\x66\x7E\xF9\xDC\xBB\xAC\x55\xA0\x62\x95\xCE\x87\x0B\x07\x02\x9B\xFC\xDB\x2D\xCE\x28\xD9\x59\xF2\x81\x5B\x16\xF8\x17\x98\x48\x3A\xDA\x77\x26\xA3\xC4\x65\x5D\xA4\xFB\xFC\x0E\x11\x08\xA8\xFD\x17\xB4\x48\xA6\x85\x54\x19\x9C\x47\xD0\x8F\xFB\x10\xD4\xB8", 65}, { (unsigned char *) "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B\xBF\xD2\x5E\x8C\xD0\x36\x41\x41", 32}, { (unsigned char *) "\x01", 1} }, { { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0}, { NULL, 0} } }; #define C_ASN1_CVC_PUBKEY_SIZE 10 static const struct sc_asn1_entry c_asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE] = { { "publicKeyOID", SC_ASN1_OBJECT, SC_ASN1_UNI | SC_ASN1_OBJECT, 0, NULL, NULL }, { "primeOrModulus", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientAorExponent", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 2, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "coefficientB", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 3, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "basePointG", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 4, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "order", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 5, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "publicPoint", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 6, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "cofactor", SC_ASN1_OCTET_STRING, SC_ASN1_CTX | 7, SC_ASN1_OPTIONAL | SC_ASN1_ALLOC, NULL, NULL }, { "modulusSize", SC_ASN1_INTEGER, SC_ASN1_UNI | SC_ASN1_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_BODY_SIZE 5 static const struct sc_asn1_entry c_asn1_cvc_body[C_ASN1_CVC_BODY_SIZE] = { { "certificateProfileIdentifier", SC_ASN1_INTEGER, SC_ASN1_APP | 0x1F29, 0, NULL, NULL }, { "certificationAuthorityReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "publicKey", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F49, 0, NULL, NULL }, { "certificateHolderReference", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 0x1F20, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVCERT_SIZE 3 static const struct sc_asn1_entry c_asn1_cvcert[C_ASN1_CVCERT_SIZE] = { { "certificateBody", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F4E, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_CVC_SIZE 2 static const struct sc_asn1_entry c_asn1_cvc[C_ASN1_CVC_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_AUTHREQ_SIZE 4 static const struct sc_asn1_entry c_asn1_authreq[C_ASN1_AUTHREQ_SIZE] = { { "certificate", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 0x1F21, 0, NULL, NULL }, { "outerCAR", SC_ASN1_PRINTABLESTRING, SC_ASN1_APP | 2, 0, NULL, NULL }, { "signature", SC_ASN1_OCTET_STRING, SC_ASN1_APP | 0x1F37, SC_ASN1_ALLOC, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; #define C_ASN1_REQ_SIZE 2 static const struct sc_asn1_entry c_asn1_req[C_ASN1_REQ_SIZE] = { { "authenticatedrequest", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_APP | 7, 0, NULL, NULL }, { NULL, 0, 0, 0, NULL, NULL } }; static int read_file(sc_pkcs15_card_t * p15card, u8 fid[2], u8 *efbin, size_t *len, int optional) { sc_path_t path; int r; sc_path_set(&path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); /* look this up with our AID */ path.aid = sc_hsm_aid; /* we don't have a pre-known size of the file */ path.count = -1; if (!p15card->opts.use_file_cache || !efbin || SC_SUCCESS != sc_pkcs15_read_cached_file(p15card, &path, &efbin, len)) { /* avoid re-selection of SC-HSM */ path.aid.len = 0; r = sc_select_file(p15card->card, &path, NULL); if (r < 0) { sc_log(p15card->card->ctx, "Could not select EF"); } else { r = sc_read_binary(p15card->card, 0, efbin, *len, 0); } if (r < 0) { sc_log(p15card->card->ctx, "Could not read EF"); if (!optional) { return r; } /* optional files are saved as empty files to avoid card * transactions. Parsing the file's data will reveal that they were * missing. */ *len = 0; } else { *len = r; } if (p15card->opts.use_file_cache) { /* save this with our AID */ path.aid = sc_hsm_aid; sc_pkcs15_cache_file(p15card, &path, efbin, *len); } } return SC_SUCCESS; } /* * Decode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_decode_cvc(sc_pkcs15_card_t * p15card, const u8 ** buf, size_t *buflen, sc_cvc_t *cvc) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_req[C_ASN1_REQ_SIZE]; struct sc_asn1_entry asn1_authreq[C_ASN1_AUTHREQ_SIZE]; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; unsigned int cla,tag; size_t taglen; size_t lenchr = sizeof(cvc->chr); size_t lencar = sizeof(cvc->car); size_t lenoutercar = sizeof(cvc->outer_car); const u8 *tbuf; int r; memset(cvc, 0, sizeof(*cvc)); sc_copy_asn1_entry(c_asn1_req, asn1_req); sc_copy_asn1_entry(c_asn1_authreq, asn1_authreq); sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 1, &cvc->primeOrModulus, &cvc->primeOrModuluslen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 2, &cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 3, &cvc->coefficientB, &cvc->coefficientBlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 4, &cvc->basePointG, &cvc->basePointGlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 5, &cvc->order, &cvc->orderlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 6, &cvc->publicPoint, &cvc->publicPointlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 7, &cvc->cofactor, &cvc->cofactorlen, 0); sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 0); sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 0); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 0); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 0); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 0); sc_format_asn1_entry(asn1_cvcert + 1, &cvc->signature, &cvc->signatureLen, 0); sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq , &asn1_cvcert, NULL, 0); sc_format_asn1_entry(asn1_authreq + 1, &cvc->outer_car, &lenoutercar, 0); sc_format_asn1_entry(asn1_authreq + 2, &cvc->outerSignature, &cvc->outerSignatureLen, 0); sc_format_asn1_entry(asn1_req , &asn1_authreq, NULL, 0); /* sc_asn1_print_tags(*buf, *buflen); */ tbuf = *buf; r = sc_asn1_read_tag(&tbuf, *buflen, &cla, &tag, &taglen); LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); /* Determine if we deal with an authenticated request, plain request or certificate */ if ((cla == (SC_ASN1_TAG_APPLICATION|SC_ASN1_TAG_CONSTRUCTED)) && (tag == 7)) { r = sc_asn1_decode(card->ctx, asn1_req, *buf, *buflen, buf, buflen); } else { r = sc_asn1_decode(card->ctx, asn1_cvc, *buf, *buflen, buf, buflen); } LOG_TEST_RET(card->ctx, r, "Could not decode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Encode a card verifiable certificate as defined in TR-03110. */ int sc_pkcs15emu_sc_hsm_encode_cvc(sc_pkcs15_card_t * p15card, sc_cvc_t *cvc, u8 ** buf, size_t *buflen) { sc_card_t *card = p15card->card; struct sc_asn1_entry asn1_cvc[C_ASN1_CVC_SIZE]; struct sc_asn1_entry asn1_cvcert[C_ASN1_CVCERT_SIZE]; struct sc_asn1_entry asn1_cvc_body[C_ASN1_CVC_BODY_SIZE]; struct sc_asn1_entry asn1_cvc_pubkey[C_ASN1_CVC_PUBKEY_SIZE]; size_t lenchr; size_t lencar; int r; sc_copy_asn1_entry(c_asn1_cvc, asn1_cvc); sc_copy_asn1_entry(c_asn1_cvcert, asn1_cvcert); sc_copy_asn1_entry(c_asn1_cvc_body, asn1_cvc_body); sc_copy_asn1_entry(c_asn1_cvc_pubkey, asn1_cvc_pubkey); asn1_cvc_pubkey[1].flags = SC_ASN1_OPTIONAL; asn1_cvcert[1].flags = SC_ASN1_OPTIONAL; sc_format_asn1_entry(asn1_cvc_pubkey , &cvc->pukoid, NULL, 1); if (cvc->primeOrModulus && (cvc->primeOrModuluslen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 1, cvc->primeOrModulus, &cvc->primeOrModuluslen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 2, cvc->coefficientAorExponent, &cvc->coefficientAorExponentlen, 1); if (cvc->coefficientB && (cvc->coefficientBlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 3, cvc->coefficientB, &cvc->coefficientBlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 4, cvc->basePointG, &cvc->basePointGlen, 1); sc_format_asn1_entry(asn1_cvc_pubkey + 5, cvc->order, &cvc->orderlen, 1); if (cvc->publicPoint && (cvc->publicPointlen > 0)) { sc_format_asn1_entry(asn1_cvc_pubkey + 6, cvc->publicPoint, &cvc->publicPointlen, 1); } sc_format_asn1_entry(asn1_cvc_pubkey + 7, cvc->cofactor, &cvc->cofactorlen, 1); } if (cvc->modulusSize > 0) { sc_format_asn1_entry(asn1_cvc_pubkey + 8, &cvc->modulusSize, NULL, 1); } sc_format_asn1_entry(asn1_cvc_body , &cvc->cpi, NULL, 1); lencar = strnlen(cvc->car, sizeof cvc->car); sc_format_asn1_entry(asn1_cvc_body + 1, &cvc->car, &lencar, 1); sc_format_asn1_entry(asn1_cvc_body + 2, &asn1_cvc_pubkey, NULL, 1); lenchr = strnlen(cvc->chr, sizeof cvc->chr); sc_format_asn1_entry(asn1_cvc_body + 3, &cvc->chr, &lenchr, 1); sc_format_asn1_entry(asn1_cvcert , &asn1_cvc_body, NULL, 1); if (cvc->signature && (cvc->signatureLen > 0)) { sc_format_asn1_entry(asn1_cvcert + 1, cvc->signature, &cvc->signatureLen, 1); } sc_format_asn1_entry(asn1_cvc , &asn1_cvcert, NULL, 1); r = sc_asn1_encode(card->ctx, asn1_cvc, buf, buflen); LOG_TEST_RET(card->ctx, r, "Could not encode card verifiable certificate"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_get_curve(struct ec_curve **curve, u8 *oid, size_t oidlen) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].oid.len == oidlen) && !memcmp(curves[i].oid.value, oid, oidlen)) { *curve = &curves[i]; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } int sc_pkcs15emu_sc_hsm_get_curve_oid(sc_cvc_t *cvc, const struct sc_lv_data **oid) { int i; for (i = 0; curves[i].oid.value; i++) { if ((curves[i].prime.len == cvc->primeOrModuluslen) && !memcmp(curves[i].prime.value, cvc->primeOrModulus, cvc->primeOrModuluslen)) { *oid = &curves[i].oid; return SC_SUCCESS; } } return SC_ERROR_INVALID_DATA; } static int sc_pkcs15emu_sc_hsm_get_rsa_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { pubkey->algorithm = SC_ALGORITHM_RSA; pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) return SC_ERROR_OUT_OF_MEMORY; pubkey->alg_id->algorithm = SC_ALGORITHM_RSA; pubkey->u.rsa.modulus.len = cvc->primeOrModuluslen; pubkey->u.rsa.modulus.data = malloc(pubkey->u.rsa.modulus.len); pubkey->u.rsa.exponent.len = cvc->coefficientAorExponentlen; pubkey->u.rsa.exponent.data = malloc(pubkey->u.rsa.exponent.len); if (!pubkey->u.rsa.modulus.data || !pubkey->u.rsa.exponent.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.rsa.exponent.data, cvc->coefficientAorExponent, pubkey->u.rsa.exponent.len); memcpy(pubkey->u.rsa.modulus.data, cvc->primeOrModulus, pubkey->u.rsa.modulus.len); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_get_ec_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { struct sc_ec_parameters *ecp; const struct sc_lv_data *oid; int r; pubkey->algorithm = SC_ALGORITHM_EC; r = sc_pkcs15emu_sc_hsm_get_curve_oid(cvc, &oid); if (r != SC_SUCCESS) return r; ecp = calloc(1, sizeof(struct sc_ec_parameters)); if (!ecp) return SC_ERROR_OUT_OF_MEMORY; ecp->der.len = oid->len + 2; ecp->der.value = calloc(ecp->der.len, 1); if (!ecp->der.value) { free(ecp); return SC_ERROR_OUT_OF_MEMORY; } *(ecp->der.value + 0) = 0x06; *(ecp->der.value + 1) = (u8)oid->len; memcpy(ecp->der.value + 2, oid->value, oid->len); ecp->type = 1; // Named curve pubkey->alg_id = (struct sc_algorithm_id *)calloc(1, sizeof(struct sc_algorithm_id)); if (!pubkey->alg_id) { free(ecp->der.value); free(ecp); return SC_ERROR_OUT_OF_MEMORY; } pubkey->alg_id->algorithm = SC_ALGORITHM_EC; pubkey->alg_id->params = ecp; pubkey->u.ec.ecpointQ.value = malloc(cvc->publicPointlen); if (!pubkey->u.ec.ecpointQ.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.ecpointQ.value, cvc->publicPoint, cvc->publicPointlen); pubkey->u.ec.ecpointQ.len = cvc->publicPointlen; pubkey->u.ec.params.der.value = malloc(ecp->der.len); if (!pubkey->u.ec.params.der.value) return SC_ERROR_OUT_OF_MEMORY; memcpy(pubkey->u.ec.params.der.value, ecp->der.value, ecp->der.len); pubkey->u.ec.params.der.len = ecp->der.len; /* FIXME: check return value? */ sc_pkcs15_fix_ec_parameters(ctx, &pubkey->u.ec.params); return SC_SUCCESS; } int sc_pkcs15emu_sc_hsm_get_public_key(struct sc_context *ctx, sc_cvc_t *cvc, struct sc_pkcs15_pubkey *pubkey) { if (cvc->publicPoint && cvc->publicPointlen) { return sc_pkcs15emu_sc_hsm_get_ec_public_key(ctx, cvc, pubkey); } else { return sc_pkcs15emu_sc_hsm_get_rsa_public_key(ctx, cvc, pubkey); } } void sc_pkcs15emu_sc_hsm_free_cvc(sc_cvc_t *cvc) { if (cvc->signature) { free(cvc->signature); cvc->signature = NULL; } if (cvc->primeOrModulus) { free(cvc->primeOrModulus); cvc->primeOrModulus = NULL; } if (cvc->coefficientAorExponent) { free(cvc->coefficientAorExponent); cvc->coefficientAorExponent = NULL; } if (cvc->coefficientB) { free(cvc->coefficientB); cvc->coefficientB = NULL; } if (cvc->basePointG) { free(cvc->basePointG); cvc->basePointG = NULL; } if (cvc->order) { free(cvc->order); cvc->order = NULL; } if (cvc->publicPoint) { free(cvc->publicPoint); cvc->publicPoint = NULL; } if (cvc->cofactor) { free(cvc->cofactor); cvc->cofactor = NULL; } } static int sc_pkcs15emu_sc_hsm_add_pubkey(sc_pkcs15_card_t *p15card, u8 *efbin, size_t len, sc_pkcs15_prkey_info_t *key_info, char *label) { struct sc_context *ctx = p15card->card->ctx; sc_card_t *card = p15card->card; sc_pkcs15_pubkey_info_t pubkey_info; sc_pkcs15_object_t pubkey_obj; struct sc_pkcs15_pubkey pubkey; sc_cvc_t cvc; u8 *cvcpo; int r; cvcpo = efbin; memset(&cvc, 0, sizeof(cvc)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&cvcpo, &len, &cvc); LOG_TEST_RET(ctx, r, "Could decode certificate signing request"); memset(&pubkey, 0, sizeof(pubkey)); r = sc_pkcs15emu_sc_hsm_get_public_key(ctx, &cvc, &pubkey); LOG_TEST_RET(card->ctx, r, "Could not extract public key"); memset(&pubkey_info, 0, sizeof(pubkey_info)); memset(&pubkey_obj, 0, sizeof(pubkey_obj)); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_obj.content.value, &pubkey_obj.content.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey(ctx, &pubkey, &pubkey_info.direct.raw.value, &pubkey_info.direct.raw.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); r = sc_pkcs15_encode_pubkey_as_spki(ctx, &pubkey, &pubkey_info.direct.spki.value, &pubkey_info.direct.spki.len); LOG_TEST_RET(ctx, r, "Could not encode public key"); pubkey_info.id = key_info->id; strlcpy(pubkey_obj.label, label, sizeof(pubkey_obj.label)); if (pubkey.algorithm == SC_ALGORITHM_RSA) { pubkey_info.modulus_length = pubkey.u.rsa.modulus.len << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_VERIFY|SC_PKCS15_PRKEY_USAGE_WRAP; r = sc_pkcs15emu_add_rsa_pubkey(p15card, &pubkey_obj, &pubkey_info); } else { /* TODO fix if support of non multiple of 8 curves are added */ pubkey_info.field_length = cvc.primeOrModuluslen << 3; pubkey_info.usage = SC_PKCS15_PRKEY_USAGE_VERIFY; r = sc_pkcs15emu_add_ec_pubkey(p15card, &pubkey_obj, &pubkey_info); } LOG_TEST_RET(ctx, r, "Could not add public key"); sc_pkcs15emu_sc_hsm_free_cvc(&cvc); sc_pkcs15_erase_pubkey(&pubkey); return SC_SUCCESS; } /* * Add a key and the key description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t cert_info; sc_pkcs15_object_t cert_obj; struct sc_pkcs15_object prkd; sc_pkcs15_prkey_info_t *key_info; u8 fid[2]; /* enough to hold a complete certificate */ u8 efbin[4096]; u8 *ptr; size_t len; int r; fid[0] = PRKD_PREFIX; fid[1] = keyid; /* Try to select a related EF containing the PKCS#15 description of the key */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); ptr = efbin; memset(&prkd, 0, sizeof(prkd)); r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD"); /* All keys require user PIN authentication */ prkd.auth_id.len = 1; prkd.auth_id.value[0] = 1; /* * Set private key flag as all keys are private anyway */ prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE; key_info = (sc_pkcs15_prkey_info_t *)prkd.data; key_info->key_reference = keyid; key_info->path.aid.len = 0; if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) { r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info); } else { r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info); } LOG_TEST_RET(card->ctx, r, "Could not add private key to framework"); /* Check if we also have a certificate for the private key */ fid[0] = EE_CERTIFICATE_PREFIX; len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 0); LOG_TEST_RET(card->ctx, r, "Could not read EF"); if (efbin[0] == 0x67) { /* Decode CSR and create public key object */ sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label); free(key_info); return SC_SUCCESS; /* Ignore any errors */ } if (efbin[0] != 0x30) { free(key_info); return SC_SUCCESS; } memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id = key_info->id; sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0); cert_info.path.count = -1; if (p15card->opts.use_file_cache) { /* look this up with our AID, which should already be cached from the * call to `read_file`. This may have the side effect that OpenSC's * caching layer re-selects our applet *if the cached file cannot be * found/used* and we may loose the authentication status. We assume * that caching works perfectly without this side effect. */ cert_info.path.aid = sc_hsm_aid; } strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); free(key_info); LOG_TEST_RET(card->ctx, r, "Could not add certificate"); return SC_SUCCESS; } /* * Add a data object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_dcod(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_data_info_t *data_info; sc_pkcs15_object_t data_obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = DCOD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&data_obj, 0, sizeof(data_obj)); r = sc_pkcs15_decode_dodf_entry(p15card, &data_obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Could not decode optional EF.DCOD"); data_info = (sc_pkcs15_data_info_t *)data_obj.data; r = sc_pkcs15emu_add_data_object(p15card, &data_obj, data_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } /* * Add a unrelated certificate object and description in PKCS#15 format to the framework */ static int sc_pkcs15emu_sc_hsm_add_cd(sc_pkcs15_card_t * p15card, u8 id) { sc_card_t *card = p15card->card; sc_pkcs15_cert_info_t *cert_info; sc_pkcs15_object_t obj; u8 fid[2]; u8 efbin[512]; const u8 *ptr; size_t len; int r; fid[0] = CD_PREFIX; fid[1] = id; /* Try to select a related EF containing the PKCS#15 description of the data */ len = sizeof efbin; r = read_file(p15card, fid, efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.DCOD"); ptr = efbin; memset(&obj, 0, sizeof(obj)); r = sc_pkcs15_decode_cdf_entry(p15card, &obj, &ptr, &len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.CDOD"); cert_info = (sc_pkcs15_cert_info_t *)obj.data; r = sc_pkcs15emu_add_x509_cert(p15card, &obj, cert_info); LOG_TEST_RET(card->ctx, r, "Could not add data object to framework"); return SC_SUCCESS; } static int sc_pkcs15emu_sc_hsm_read_tokeninfo (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; int r; u8 efbin[512]; size_t len; LOG_FUNC_CALLED(card->ctx); /* Read token info */ len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x03", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); r = sc_pkcs15_parse_tokeninfo(card->ctx, p15card->tokeninfo, efbin, len); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.TokenInfo"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } /* * Initialize PKCS#15 emulation with user PIN, private keys, certificate and data objects * */ static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data; sc_file_t *file = NULL; sc_path_t path; u8 filelist[MAX_EXT_APDU_LENGTH]; int filelistlength; int r, i; sc_cvc_t devcert; struct sc_app_info *appinfo; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; struct sc_pin_cmd_data pindata; u8 efbin[1024]; u8 *ptr; size_t len; LOG_FUNC_CALLED(card->ctx); appinfo = calloc(1, sizeof(struct sc_app_info)); if (appinfo == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->aid = sc_hsm_aid; appinfo->ddo.aid = sc_hsm_aid; p15card->app = appinfo; sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0); r = sc_select_file(card, &path, &file); LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application"); p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */ p15card->card->version.hw_minor = 13; if (file && file->prop_attr && file->prop_attr_len >= 2) { p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2]; p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1]; } sc_file_free(file); /* Read device certificate to determine serial number */ if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) { ptr = priv->EF_C_DevAut; len = priv->EF_C_DevAut_len; } else { len = sizeof efbin; r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1); LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut"); if (len > 0) { /* save EF_C_DevAut for further use */ ptr = realloc(priv->EF_C_DevAut, len); if (ptr) { memcpy(ptr, efbin, len); priv->EF_C_DevAut = ptr; priv->EF_C_DevAut_len = len; } } ptr = efbin; } memset(&devcert, 0 ,sizeof(devcert)); r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert); LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut"); sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card); if (p15card->tokeninfo->label == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->label = strdup("GoID"); } else { p15card->tokeninfo->label = strdup("SmartCard-HSM"); } if (p15card->tokeninfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) { free(p15card->tokeninfo->manufacturer_id); p15card->tokeninfo->manufacturer_id = NULL; } if (p15card->tokeninfo->manufacturer_id == NULL) { if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID || p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) { p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH"); } else { p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de"); } if (p15card->tokeninfo->manufacturer_id == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } appinfo->label = strdup(p15card->tokeninfo->label); if (appinfo->label == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */ assert(len >= 8); len -= 5; p15card->tokeninfo->serial_number = calloc(len + 1, 1); if (p15card->tokeninfo->serial_number == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(p15card->tokeninfo->serial_number, devcert.chr, len); *(p15card->tokeninfo->serial_number + len) = 0; sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number); sc_pkcs15emu_sc_hsm_free_cvc(&devcert); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 1; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x81; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = 6; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 15; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 3; pin_info.max_tries = 3; pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 2; strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = 2; pin_info.path.aid = sc_hsm_aid; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = 0x88; pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD; pin_info.attrs.pin.min_length = 16; pin_info.attrs.pin.stored_length = 0; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = 15; pin_info.max_tries = 15; strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) LOG_FUNC_RETURN(card->ctx, r); if (card->type == SC_CARD_TYPE_SC_HSM_SOC || card->type == SC_CARD_TYPE_SC_HSM_GOID) { /* SC-HSM of this type always has a PIN-Pad */ r = SC_SUCCESS; } else { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x85; r = sc_pin_cmd(card, &pindata, NULL); } if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) { memset(&pindata, 0, sizeof(pindata)); pindata.cmd = SC_PIN_CMD_GET_INFO; pindata.pin_type = SC_AC_CHV; pindata.pin_reference = 0x86; r = sc_pin_cmd(card, &pindata, NULL); } if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS)) card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH; filelistlength = sc_list_files(card, filelist, sizeof(filelist)); LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier"); for (i = 0; i < filelistlength; i += 2) { switch(filelist[i]) { case KEY_PREFIX: r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]); break; case DCOD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]); break; case CD_PREFIX: r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]); break; } if (r != SC_SUCCESS) { sc_log(card->ctx, "Error %d adding elements to framework", r); } } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } int sc_pkcs15emu_sc_hsm_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK)) { return sc_pkcs15emu_sc_hsm_init(p15card); } else { if (p15card->card->type != SC_CARD_TYPE_SC_HSM && p15card->card->type != SC_CARD_TYPE_SC_HSM_SOC && p15card->card->type != SC_CARD_TYPE_SC_HSM_GOID) { return SC_ERROR_WRONG_CARD; } return sc_pkcs15emu_sc_hsm_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_6
crossvul-cpp_data_good_349_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-415/c/good_349_1
crossvul-cpp_data_good_5365_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * I/O Stream Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <assert.h> #if defined(HAVE_FCNTL_H) #include <fcntl.h> #endif #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #if defined(HAVE_UNISTD_H) #include <unistd.h> #endif #if defined(WIN32) || defined(HAVE_IO_H) #include <io.h> #endif #include "jasper/jas_types.h" #include "jasper/jas_stream.h" #include "jasper/jas_malloc.h" #include "jasper/jas_math.h" /******************************************************************************\ * Local function prototypes. \******************************************************************************/ static int jas_strtoopenmode(const char *s); static void jas_stream_destroy(jas_stream_t *stream); static jas_stream_t *jas_stream_create(void); static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize); static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt); static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt); static long mem_seek(jas_stream_obj_t *obj, long offset, int origin); static int mem_close(jas_stream_obj_t *obj); static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt); static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt); static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin); static int sfile_close(jas_stream_obj_t *obj); static int file_read(jas_stream_obj_t *obj, char *buf, int cnt); static int file_write(jas_stream_obj_t *obj, char *buf, int cnt); static long file_seek(jas_stream_obj_t *obj, long offset, int origin); static int file_close(jas_stream_obj_t *obj); /******************************************************************************\ * Local data. \******************************************************************************/ static jas_stream_ops_t jas_stream_fileops = { file_read, file_write, file_seek, file_close }; static jas_stream_ops_t jas_stream_sfileops = { sfile_read, sfile_write, sfile_seek, sfile_close }; static jas_stream_ops_t jas_stream_memops = { mem_read, mem_write, mem_seek, mem_close }; /******************************************************************************\ * Code for opening and closing streams. \******************************************************************************/ static jas_stream_t *jas_stream_create() { jas_stream_t *stream; if (!(stream = jas_malloc(sizeof(jas_stream_t)))) { return 0; } stream->openmode_ = 0; stream->bufmode_ = 0; stream->flags_ = 0; stream->bufbase_ = 0; stream->bufstart_ = 0; stream->bufsize_ = 0; stream->ptr_ = 0; stream->cnt_ = 0; stream->ops_ = 0; stream->obj_ = 0; stream->rwcnt_ = 0; stream->rwlimit_ = -1; return stream; } jas_stream_t *jas_stream_memopen(char *buf, int bufsize) { jas_stream_t *stream; jas_stream_memobj_t *obj; if (!(stream = jas_stream_create())) { return 0; } /* A stream associated with a memory buffer is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Since the stream data is already resident in memory, buffering is not necessary. */ /* But... It still may be faster to use buffering anyways. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a memory stream. */ stream->ops_ = &jas_stream_memops; /* Allocate memory for the underlying memory stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { jas_stream_destroy(stream); return 0; } stream->obj_ = (void *) obj; /* Initialize a few important members of the memory stream object. */ obj->myalloc_ = 0; obj->buf_ = 0; /* If the buffer size specified is nonpositive, then the buffer is allocated internally and automatically grown as needed. */ if (bufsize <= 0) { obj->bufsize_ = 1024; obj->growable_ = 1; } else { obj->bufsize_ = bufsize; obj->growable_ = 0; } if (buf) { obj->buf_ = (unsigned char *) buf; } else { obj->buf_ = jas_malloc(obj->bufsize_); obj->myalloc_ = 1; } if (!obj->buf_) { jas_stream_close(stream); return 0; } if (bufsize > 0 && buf) { /* If a buffer was supplied by the caller and its length is positive, make the associated buffer data appear in the stream initially. */ obj->len_ = bufsize; } else { /* The stream is initially empty. */ obj->len_ = 0; } obj->pos_ = 0; return stream; } jas_stream_t *jas_stream_fopen(const char *filename, const char *mode) { jas_stream_t *stream; jas_stream_fileobj_t *obj; int openflags; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); /* Determine the correct flags to use for opening the file. */ if ((stream->openmode_ & JAS_STREAM_READ) && (stream->openmode_ & JAS_STREAM_WRITE)) { openflags = O_RDWR; } else if (stream->openmode_ & JAS_STREAM_READ) { openflags = O_RDONLY; } else if (stream->openmode_ & JAS_STREAM_WRITE) { openflags = O_WRONLY; } else { openflags = 0; } if (stream->openmode_ & JAS_STREAM_APPEND) { openflags |= O_APPEND; } if (stream->openmode_ & JAS_STREAM_BINARY) { openflags |= O_BINARY; } if (stream->openmode_ & JAS_STREAM_CREATE) { openflags |= O_CREAT | O_TRUNC; } /* Allocate space for the underlying file stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = -1; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = (void *) obj; /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_fileops; /* Open the underlying file. */ if ((obj->fd = open(filename, openflags, JAS_STREAM_PERMS)) < 0) { jas_stream_destroy(stream); return 0; } /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); return stream; } jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp) { jas_stream_t *stream; int openflags; /* Eliminate compiler warning about unused variable. */ path = 0; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); /* Determine the correct flags to use for opening the file. */ if ((stream->openmode_ & JAS_STREAM_READ) && (stream->openmode_ & JAS_STREAM_WRITE)) { openflags = O_RDWR; } else if (stream->openmode_ & JAS_STREAM_READ) { openflags = O_RDONLY; } else if (stream->openmode_ & JAS_STREAM_WRITE) { openflags = O_WRONLY; } else { openflags = 0; } if (stream->openmode_ & JAS_STREAM_APPEND) { openflags |= O_APPEND; } if (stream->openmode_ & JAS_STREAM_BINARY) { openflags |= O_BINARY; } if (stream->openmode_ & JAS_STREAM_CREATE) { openflags |= O_CREAT | O_TRUNC; } stream->obj_ = JAS_CAST(void *, fp); /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_sfileops; /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); return stream; } jas_stream_t *jas_stream_tmpfile() { jas_stream_t *stream; jas_stream_fileobj_t *obj; if (!(stream = jas_stream_create())) { return 0; } /* A temporary file stream is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Allocate memory for the underlying temporary file object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = -1; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = obj; /* Choose a file name. */ tmpnam(obj->pathname); /* Open the underlying file. */ if ((obj->fd = open(obj->pathname, O_CREAT | O_EXCL | O_RDWR | O_TRUNC | O_BINARY, JAS_STREAM_PERMS)) < 0) { jas_stream_destroy(stream); return 0; } /* Unlink the file so that it will disappear if the program terminates abnormally. */ /* Under UNIX, one can unlink an open file and continue to do I/O on it. Not all operating systems support this functionality, however. For example, under Microsoft Windows the unlink operation will fail, since the file is open. */ if (unlink(obj->pathname)) { /* We will try unlinking the file again after it is closed. */ obj->flags |= JAS_STREAM_FILEOBJ_DELONCLOSE; } /* Use full buffering. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); stream->ops_ = &jas_stream_fileops; return stream; } jas_stream_t *jas_stream_fdopen(int fd, const char *mode) { jas_stream_t *stream; jas_stream_fileobj_t *obj; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); #if defined(WIN32) /* Argh!!! Someone ought to banish text mode (i.e., O_TEXT) to the greatest depths of purgatory! */ /* Ensure that the file descriptor is in binary mode, if the caller has specified the binary mode flag. Arguably, the caller ought to take care of this, but text mode is a ugly wart anyways, so we save the caller some grief by handling this within the stream library. */ /* This ugliness is mainly for the benefit of those who run the JasPer software under Windows from shells that insist on opening files in text mode. For example, in the Cygwin environment, shells often open files in text mode when I/O redirection is used. Grr... */ if (stream->openmode_ & JAS_STREAM_BINARY) { setmode(fd, O_BINARY); } #endif /* Allocate space for the underlying file stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = fd; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = (void *) obj; /* Do not close the underlying file descriptor when the stream is closed. */ obj->flags |= JAS_STREAM_FILEOBJ_NOCLOSE; /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_fileops; return stream; } static void jas_stream_destroy(jas_stream_t *stream) { /* If the memory for the buffer was allocated with malloc, free this memory. */ if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) { jas_free(stream->bufbase_); stream->bufbase_ = 0; } jas_free(stream); } int jas_stream_close(jas_stream_t *stream) { /* Flush buffer if necessary. */ jas_stream_flush(stream); /* Close the underlying stream object. */ (*stream->ops_->close_)(stream->obj_); jas_stream_destroy(stream); return 0; } /******************************************************************************\ * Code for reading and writing streams. \******************************************************************************/ int jas_stream_getc_func(jas_stream_t *stream) { assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ + JAS_STREAM_MAXPUTBACK); return jas_stream_getc_macro(stream); } int jas_stream_putc_func(jas_stream_t *stream, int c) { assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); return jas_stream_putc_macro(stream, c); } int jas_stream_ungetc(jas_stream_t *stream, int c) { if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) { return -1; } /* Reset the EOF indicator (since we now have at least one character to read). */ stream->flags_ &= ~JAS_STREAM_EOF; --stream->rwcnt_; --stream->ptr_; ++stream->cnt_; *stream->ptr_ = c; return 0; } int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; } int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } /* Note: This function uses a fixed size buffer. Therefore, it cannot handle invocations that will produce more output than can be held by the buffer. */ int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...) { va_list ap; char buf[4096]; int ret; va_start(ap, fmt); ret = vsnprintf(buf, sizeof buf, fmt, ap); jas_stream_puts(stream, buf); va_end(ap); return ret; } int jas_stream_puts(jas_stream_t *stream, const char *s) { while (*s != '\0') { if (jas_stream_putc_macro(stream, *s) == EOF) { return -1; } ++s; } return 0; } char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize) { int c; char *bufptr; assert(bufsize > 0); bufptr = buf; while (bufsize > 1) { if ((c = jas_stream_getc(stream)) == EOF) { break; } *bufptr++ = c; --bufsize; if (c == '\n') { break; } } *bufptr = '\0'; return buf; } int jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } int jas_stream_pad(jas_stream_t *stream, int n, int c) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_putc(stream, c) == EOF) return n - m; } return n; } /******************************************************************************\ * Code for getting and setting the stream position. \******************************************************************************/ int jas_stream_isseekable(jas_stream_t *stream) { if (stream->ops_ == &jas_stream_memops) { return 1; } else if (stream->ops_ == &jas_stream_fileops) { if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) { return 0; } return 1; } else { return 0; } } int jas_stream_rewind(jas_stream_t *stream) { return jas_stream_seek(stream, 0, SEEK_SET); } long jas_stream_seek(jas_stream_t *stream, long offset, int origin) { long newpos; /* The buffer cannot be in use for both reading and writing. */ assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ & JAS_STREAM_WRBUF))); /* Reset the EOF indicator (since we may not be at the EOF anymore). */ stream->flags_ &= ~JAS_STREAM_EOF; if (stream->bufmode_ & JAS_STREAM_RDBUF) { if (origin == SEEK_CUR) { offset -= stream->cnt_; } } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { if (jas_stream_flush(stream)) { return -1; } } stream->cnt_ = 0; stream->ptr_ = stream->bufstart_; stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF); if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin)) < 0) { return -1; } return newpos; } long jas_stream_tell(jas_stream_t *stream) { int adjust; int offset; if (stream->bufmode_ & JAS_STREAM_RDBUF) { adjust = -stream->cnt_; } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { adjust = stream->ptr_ - stream->bufstart_; } else { adjust = 0; } if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) { return -1; } return offset + adjust; } /******************************************************************************\ * Buffer initialization code. \******************************************************************************/ static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize) { /* If this function is being called, the buffer should not have been initialized yet. */ assert(!stream->bufbase_); if (bufmode != JAS_STREAM_UNBUF) { /* The full- or line-buffered mode is being employed. */ if (!buf) { /* The caller has not specified a buffer to employ, so allocate one. */ if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + JAS_STREAM_MAXPUTBACK))) { stream->bufmode_ |= JAS_STREAM_FREEBUF; stream->bufsize_ = JAS_STREAM_BUFSIZE; } else { /* The buffer allocation has failed. Resort to unbuffered operation. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } } else { /* The caller has specified a buffer to employ. */ /* The buffer must be large enough to accommodate maximum putback. */ assert(bufsize > JAS_STREAM_MAXPUTBACK); stream->bufbase_ = JAS_CAST(uchar *, buf); stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; } } else { /* The unbuffered mode is being employed. */ /* A buffer should not have been supplied by the caller. */ assert(!buf); /* Use a trivial one-character buffer. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; stream->ptr_ = stream->bufstart_; stream->cnt_ = 0; stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; } /******************************************************************************\ * Buffer filling and flushing code. \******************************************************************************/ int jas_stream_flush(jas_stream_t *stream) { if (stream->bufmode_ & JAS_STREAM_RDBUF) { return 0; } return jas_stream_flushbuf(stream, EOF); } int jas_stream_fillbuf(jas_stream_t *stream, int getflag) { int c; /* The stream must not be in an error or EOF state. */ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { return EOF; } /* The stream must be open for reading. */ if ((stream->openmode_ & JAS_STREAM_READ) == 0) { return EOF; } /* Make a half-hearted attempt to confirm that the buffer is not currently being used for writing. This check is not intended to be foolproof! */ assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0); assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); /* Mark the buffer as being used for reading. */ stream->bufmode_ |= JAS_STREAM_RDBUF; /* Read new data into the buffer. */ stream->ptr_ = stream->bufstart_; if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_, (char *) stream->bufstart_, stream->bufsize_)) <= 0) { if (stream->cnt_ < 0) { stream->flags_ |= JAS_STREAM_ERR; } else { stream->flags_ |= JAS_STREAM_EOF; } stream->cnt_ = 0; return EOF; } assert(stream->cnt_ > 0); /* Get or peek at the first character in the buffer. */ c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_); return c; } int jas_stream_flushbuf(jas_stream_t *stream, int c) { int len; int n; /* The stream should not be in an error or EOF state. */ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { return EOF; } /* The stream must be open for writing. */ if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) { return EOF; } /* The buffer should not currently be in use for reading. */ assert(!(stream->bufmode_ & JAS_STREAM_RDBUF)); /* Note: Do not use the quantity stream->cnt to determine the number of characters in the buffer! Depending on how this function was called, the stream->cnt value may be "off-by-one". */ len = stream->ptr_ - stream->bufstart_; if (len > 0) { n = (*stream->ops_->write_)(stream->obj_, (char *) stream->bufstart_, len); if (n != len) { stream->flags_ |= JAS_STREAM_ERR; return EOF; } } stream->cnt_ = stream->bufsize_; stream->ptr_ = stream->bufstart_; stream->bufmode_ |= JAS_STREAM_WRBUF; if (c != EOF) { assert(stream->cnt_ > 0); return jas_stream_putc2(stream, c); } return 0; } /******************************************************************************\ * Miscellaneous code. \******************************************************************************/ static int jas_strtoopenmode(const char *s) { int openmode = 0; while (*s != '\0') { switch (*s) { case 'r': openmode |= JAS_STREAM_READ; break; case 'w': openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE; break; case 'b': openmode |= JAS_STREAM_BINARY; break; case 'a': openmode |= JAS_STREAM_APPEND; break; case '+': openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE; break; default: break; } ++s; } return openmode; } int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n) { int all; int c; int m; all = (n < 0) ? 1 : 0; m = n; while (all || m > 0) { if ((c = jas_stream_getc_macro(in)) == EOF) { /* The next character of input could not be read. */ /* Return with an error if an I/O error occured (not including EOF) or if an explicit copy count was specified. */ return (!all || jas_stream_error(in)) ? (-1) : 0; } if (jas_stream_putc_macro(out, c) == EOF) { return -1; } --m; } return 0; } long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt) { int old; old = stream->rwcnt_; stream->rwcnt_ = rwcnt; return old; } int jas_stream_display(jas_stream_t *stream, FILE *fp, int n) { unsigned char buf[16]; int i; int j; int m; int c; int display; int cnt; cnt = n - (n % 16); display = 1; for (i = 0; i < n; i += 16) { if (n > 16 && i > 0) { display = (i >= cnt) ? 1 : 0; } if (display) { fprintf(fp, "%08x:", i); } m = JAS_MIN(n - i, 16); for (j = 0; j < m; ++j) { if ((c = jas_stream_getc(stream)) == EOF) { abort(); return -1; } buf[j] = c; } if (display) { for (j = 0; j < m; ++j) { fprintf(fp, " %02x", buf[j]); } fputc(' ', fp); for (; j < 16; ++j) { fprintf(fp, " "); } for (j = 0; j < m; ++j) { if (isprint(buf[j])) { fputc(buf[j], fp); } else { fputc(' ', fp); } } fprintf(fp, "\n"); } } return 0; } long jas_stream_length(jas_stream_t *stream) { long oldpos; long pos; if ((oldpos = jas_stream_tell(stream)) < 0) { return -1; } if (jas_stream_seek(stream, 0, SEEK_END) < 0) { return -1; } if ((pos = jas_stream_tell(stream)) < 0) { return -1; } if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) { return -1; } return pos; } /******************************************************************************\ * Memory stream object. \******************************************************************************/ static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt) { int n; assert(cnt >= 0); assert(buf); jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; n = m->len_ - m->pos_; cnt = JAS_MIN(n, cnt); memcpy(buf, &m->buf_[m->pos_], cnt); m->pos_ += cnt; return cnt; } static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; //assert(m->buf_); assert(bufsize >= 0); if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { return -1; } m->buf_ = buf; m->bufsize_ = bufsize; return 0; } static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt) { int n; int ret; jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newbufsize; long newpos; assert(buf); assert(cnt >= 0); newpos = m->pos_ + cnt; if (newpos > m->bufsize_ && m->growable_) { newbufsize = m->bufsize_; while (newbufsize < newpos) { newbufsize <<= 1; assert(newbufsize >= 0); } if (mem_resize(m, newbufsize)) { return -1; } } if (m->pos_ > m->len_) { /* The current position is beyond the end of the file, so pad the file to the current position with zeros. */ n = JAS_MIN(m->pos_, m->bufsize_) - m->len_; if (n > 0) { memset(&m->buf_[m->len_], 0, n); m->len_ += n; } if (m->pos_ != m->len_) { /* The buffer is not big enough. */ return 0; } } n = m->bufsize_ - m->pos_; ret = JAS_MIN(n, cnt); if (ret > 0) { memcpy(&m->buf_[m->pos_], buf, ret); m->pos_ += ret; } if (m->pos_ > m->len_) { m->len_ = m->pos_; } assert(ret == cnt); return ret; } static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newpos; switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; } static int mem_close(jas_stream_obj_t *obj) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; if (m->myalloc_ && m->buf_) { jas_free(m->buf_); m->buf_ = 0; } jas_free(obj); return 0; } /******************************************************************************\ * File stream object. \******************************************************************************/ static int file_read(jas_stream_obj_t *obj, char *buf, int cnt) { jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return read(fileobj->fd, buf, cnt); } static int file_write(jas_stream_obj_t *obj, char *buf, int cnt) { jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return write(fileobj->fd, buf, cnt); } static long file_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return lseek(fileobj->fd, offset, origin); } static int file_close(jas_stream_obj_t *obj) { jas_stream_fileobj_t *fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); int ret; ret = close(fileobj->fd); if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) { unlink(fileobj->pathname); } jas_free(fileobj); return ret; } /******************************************************************************\ * Stdio file stream object. \******************************************************************************/ static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt) { FILE *fp; fp = JAS_CAST(FILE *, obj); return fread(buf, 1, cnt, fp); } static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt) { FILE *fp; fp = JAS_CAST(FILE *, obj); return fwrite(buf, 1, cnt, fp); } static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin) { FILE *fp; fp = JAS_CAST(FILE *, obj); return fseek(fp, offset, origin); } static int sfile_close(jas_stream_obj_t *obj) { FILE *fp; fp = JAS_CAST(FILE *, obj); return fclose(fp); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_5365_0
crossvul-cpp_data_good_348_0
/* * card-cac.c: Support for CAC from NIST SP800-73 * card-default.c: Support for cards with no driver * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov> * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com> * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com> * Copyright (C) 2016 - 2018, Red Hat, Inc. * * CAC driver author: Robert Relyea <rrelyea@redhat.com> * Further work: Jakub Jelen <jjelen@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #ifdef ENABLE_OPENSSL /* openssl only needed for card administration */ #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/rsa.h> #endif /* ENABLE_OPENSSL */ #include "internal.h" #include "simpletlv.h" #include "cardctl.h" #ifdef ENABLE_ZLIB #include "compression.h" #endif #include "iso7816.h" #define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */ /* * CAC hardware and APDU constants */ #define CAC_MAX_CHUNK_SIZE 240 #define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */ #define CAC_INS_READ_FILE 0x52 /* read a TL or V file */ #define CAC_INS_GET_ACR 0x4c #define CAC_INS_GET_PROPERTIES 0x56 #define CAC_P1_STEP 0x80 #define CAC_P1_FINAL 0x00 #define CAC_FILE_TAG 1 #define CAC_FILE_VALUE 2 /* TAGS in a TL file */ #define CAC_TAG_CERTIFICATE 0x70 #define CAC_TAG_CERTINFO 0x71 #define CAC_TAG_MSCUID 0x72 #define CAC_TAG_CUID 0xF0 #define CAC_TAG_CC_VERSION_NUMBER 0xF1 #define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2 #define CAC_TAG_CARDURL 0xF3 #define CAC_TAG_PKCS15 0xF4 #define CAC_TAG_ACCESS_CONTROL 0xF6 #define CAC_TAG_DATA_MODEL 0xF5 #define CAC_TAG_CARD_APDU 0xF7 #define CAC_TAG_REDIRECTION 0xFA #define CAC_TAG_CAPABILITY_TUPLES 0xFB #define CAC_TAG_STATUS_TUPLES 0xFC #define CAC_TAG_NEXT_CCC 0xFD #define CAC_TAG_ERROR_CODES 0xFE #define CAC_TAG_APPLET_FAMILY 0x01 #define CAC_TAG_NUMBER_APPLETS 0x94 #define CAC_TAG_APPLET_ENTRY 0x93 #define CAC_TAG_APPLET_AID 0x92 #define CAC_TAG_APPLET_INFORMATION 0x01 #define CAC_TAG_NUMBER_OF_OBJECTS 0x40 #define CAC_TAG_TV_BUFFER 0x50 #define CAC_TAG_PKI_OBJECT 0x51 #define CAC_TAG_OBJECT_ID 0x41 #define CAC_TAG_BUFFER_PROPERTIES 0x42 #define CAC_TAG_PKI_PROPERTIES 0x43 #define CAC_APP_TYPE_GENERAL 0x01 #define CAC_APP_TYPE_SKI 0x02 #define CAC_APP_TYPE_PKI 0x04 #define CAC_ACR_ACR 0x00 #define CAC_ACR_APPLET_OBJECT 0x10 #define CAC_ACR_AMP 0x20 #define CAC_ACR_SERVICE 0x21 /* hardware data structures (returned in the CCC) */ /* part of the card_url */ typedef struct cac_access_profile { u8 GCACR_listID; u8 GCACR_readTagListACRID; u8 GCACR_updatevalueACRID; u8 GCACR_readvalueACRID; u8 GCACR_createACRID; u8 GCACR_deleteACRID; u8 CryptoACR_listID; u8 CryptoACR_getChallengeACRID; u8 CryptoACR_internalAuthenicateACRID; u8 CryptoACR_pkiComputeACRID; u8 CryptoACR_readTagListACRID; u8 CryptoACR_updatevalueACRID; u8 CryptoACR_readvalueACRID; u8 CryptoACR_createACRID; u8 CryptoACR_deleteACRID; } cac_access_profile_t; /* part of the card url */ typedef struct cac_access_key_info { u8 keyFileID[2]; u8 keynumber; } cac_access_key_info_t; typedef struct cac_card_url { u8 rid[5]; u8 cardApplicationType; u8 objectID[2]; u8 applicationID[2]; cac_access_profile_t accessProfile; u8 pinID; /* not used for VM cards */ cac_access_key_info_t accessKeyInfo; /* not used for VM cards */ u8 keyCryptoAlgorithm; /* not used for VM cards */ } cac_card_url_t; typedef struct cac_cuid { u8 gsc_rid[5]; u8 manufacturer_id; u8 card_type; u8 card_id; } cac_cuid_t; /* data structures to store meta data about CAC objects */ typedef struct cac_object { const char *name; int fd; sc_path_t path; } cac_object_t; #define CAC_MAX_OBJECTS 16 typedef struct { /* OID has two bytes */ unsigned char oid[2]; /* Format is NOT SimpleTLV? */ unsigned char simpletlv; /* Is certificate object and private key is initialized */ unsigned char privatekey; } cac_properties_object_t; typedef struct { unsigned int num_objects; cac_properties_object_t objects[CAC_MAX_OBJECTS]; } cac_properties_t; /* * Flags for Current Selected Object Type * CAC files are TLV files, with TL and V separated. For generic * containers we reintegrate the TL anv V portions into a single * file to read. Certs are also TLV files, but pkcs15 wants the * actual certificate. At select time we know the patch which tells * us what time of files we want to read. We remember that type * so that read_binary can do the appropriate processing. */ #define CAC_OBJECT_TYPE_CERT 1 #define CAC_OBJECT_TYPE_TLV_FILE 4 #define CAC_OBJECT_TYPE_GENERIC 5 /* * CAC private data per card state */ typedef struct cac_private_data { int object_type; /* select set this so we know how to read the file */ int cert_next; /* index number for the next certificate found in the list */ u8 *cache_buf; /* cached version of the currently selected file */ size_t cache_buf_len; /* length of the cached selected file */ int cached; /* is the cached selected file valid */ cac_cuid_t cuid; /* card unique ID from the CCC */ u8 *cac_id; /* card serial number */ size_t cac_id_len; /* card serial number len */ list_t pki_list; /* list of pki containers */ cac_object_t *pki_current; /* current pki object _ctl function */ list_t general_list; /* list of general containers */ cac_object_t *general_current; /* current object for _ctl function */ sc_path_t *aca_path; /* ACA path to be selected before pin verification */ } cac_private_data_t; #define CAC_DATA(card) ((cac_private_data_t*)card->drv_data) int cac_list_compare_path(const void *a, const void *b) { if (a == NULL || b == NULL) return 1; return memcmp( &((cac_object_t *) a)->path, &((cac_object_t *) b)->path, sizeof(sc_path_t)); } /* For SimCList autocopy, we need to know the size of the data elements */ size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } static cac_private_data_t *cac_new_private_data(void) { cac_private_data_t *priv; priv = calloc(1, sizeof(cac_private_data_t)); if (!priv) return NULL; list_init(&priv->pki_list); list_attributes_comparator(&priv->pki_list, cac_list_compare_path); list_attributes_copy(&priv->pki_list, cac_list_meter, 1); list_init(&priv->general_list); list_attributes_comparator(&priv->general_list, cac_list_compare_path); list_attributes_copy(&priv->general_list, cac_list_meter, 1); /* set other fields as appropriate */ return priv; } static void cac_free_private_data(cac_private_data_t *priv) { free(priv->cac_id); free(priv->cache_buf); free(priv->aca_path); list_destroy(&priv->pki_list); list_destroy(&priv->general_list); free(priv); return; } static int cac_add_object_to_list(list_t *list, const cac_object_t *object) { if (list_append(list, object) < 0) return SC_ERROR_UNKNOWN; return SC_SUCCESS; } /* * Set up the normal CAC paths */ #define CAC_TO_AID(x) x, sizeof(x)-1 #define CAC_2_RID "\xA0\x00\x00\x01\x16" #define CAC_1_RID "\xA0\x00\x00\x00\x79" static const sc_path_t cac_ACA_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x10\x00") } }; static const sc_path_t cac_CCC_Path = { "", 0, 0,0,SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_2_RID "\xDB\x00") } }; #define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */ /* default certificate labels for the CAC card */ static const char *cac_labels[MAX_CAC_SLOTS] = { "CAC ID Certificate", "CAC Email Signature Certificate", "CAC Email Encryption Certificate", "CAC Cert 4", "CAC Cert 5", "CAC Cert 6", "CAC Cert 7", "CAC Cert 8", "CAC Cert 9", "CAC Cert 10", "CAC Cert 11", "CAC Cert 12", "CAC Cert 13", "CAC Cert 14", "CAC Cert 15", "CAC Cert 16" }; /* template for a CAC pki object */ static const cac_object_t cac_cac_pki_obj = { "CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x01\x00") } } }; /* template for emulated cuid */ static const cac_cuid_t cac_cac_cuid = { { 0xa0, 0x00, 0x00, 0x00, 0x79 }, 2, 2, 0 }; /* * CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0. * doubles as a source for CAC-2 labels. */ static const cac_object_t cac_objects[] = { { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x00") }}}, { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x01") }}}, { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x02") }}}, { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\x03") }}}, { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}}, { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME, { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}}, }; static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]); /* * use the object id to find our object info on the object in our CAC-1 list */ static const cac_object_t *cac_find_obj_by_id(unsigned short object_id) { int i; for (i = 0; i < cac_object_count; i++) { if (cac_objects[i].fd == object_id) { return &cac_objects[i]; } } return NULL; } /* * Lookup the path in the pki list to see if it is a cert path */ static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path) { cac_object_t test_obj; test_obj.path = *in_path; test_obj.path.index = 0; test_obj.path.count = 0; return (list_contains(&priv->pki_list, &test_obj) != 0); } /* * Send a command and receive data. * * A caller may provide a buffer, and length to read. If not provided, * an internal 4096 byte buffer is used, and a copy is returned to the * caller. that need to be freed by the caller. * * modelled after a similar function in card-piv.c */ static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2, const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen) { int r; sc_apdu_t apdu; u8 rbufinitbuf[CAC_MAX_SIZE]; u8 *rbuf; size_t rbuflen; unsigned int apdu_case = SC_APDU_CASE_1; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n", ins, p1, p2, sendbuflen, card->max_send_size, card->max_recv_size); rbuf = rbufinitbuf; rbuflen = sizeof(rbufinitbuf); /* if caller provided a buffer and length */ if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) { rbuf = *recvbuf; rbuflen = *recvbuflen; } if (recvbuf) { if (sendbuf) apdu_case = SC_APDU_CASE_4_SHORT; else apdu_case = SC_APDU_CASE_2_SHORT; } else if (sendbuf) apdu_case = SC_APDU_CASE_3_SHORT; sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2); apdu.lc = sendbuflen; apdu.datalen = sendbuflen; apdu.data = sendbuf; if (recvbuf) { apdu.resp = rbuf; apdu.le = (rbuflen > 255) ? 255 : rbuflen; apdu.resplen = rbuflen; } else { apdu.resp = rbuf; apdu.le = 0; apdu.resplen = 0; } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p", apdu.flags, apdu.le, apdu.resplen, apdu.resp); /* with new adpu.c and chaining, this actually reads the whole object */ r = sc_transmit_apdu(card, &apdu); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x", r, apdu.resplen, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed"); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r < 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error "); goto err; } if (recvbuflen) { if (recvbuf && *recvbuf == NULL) { *recvbuf = malloc(apdu.resplen); if (*recvbuf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } memcpy(*recvbuf, rbuf, apdu.resplen); } *recvbuflen = apdu.resplen; r = *recvbuflen; } err: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Get ACR of currently ACA applet identified by the acr_type * 5.3.3.5 Get ACR APDU */ static int cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len) { u8 *out = NULL; /* XXX assuming it will not be longer than 255 B */ size_t len = 256; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* for simplicity we support only ACR without arguments now */ if (acr_type != 0x00 && acr_type != 0x10 && acr_type != 0x20 && acr_type != 0x21) { return SC_ERROR_INVALID_ARGUMENTS; } r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out); *out_len = len; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_buf = NULL; *out_len = 0; return r; } /* * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file */ #define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff) #define LOW_BYTE_OF_SHORT(x) ((x) & 0xff) static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len) { u8 params[2]; u8 count[2]; u8 *out = NULL; u8 *out_ptr; size_t offset = 0; size_t size = 0; size_t left = 0; size_t len; int r; params[0] = file_type; params[1] = 2; /* get the size */ len = sizeof(count); out_ptr = count; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) goto fail; left = size = lebytes2ushort(count); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)", len, out_ptr, &count, count[0], count[1], size, size); out = out_ptr = malloc(size); if (out == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto fail; } for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) { len = MIN(left, CAC_MAX_CHUNK_SIZE); params[1] = len; r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset), &params[0], sizeof(params), &out_ptr, &len); /* if there is no data, assume there is no file */ if (len == 0) { r = SC_ERROR_FILE_NOT_FOUND; } if (r < 0) { goto fail; } } *out_len = size; *out_buf = out; return SC_SUCCESS; fail: if (out) free(out); *out_len = 0; return r; } /* * Callers of this may be expecting a certificate, * select file will have saved the object type for us * as well as set that we want the cert from the object. */ static int cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr = val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; /* incomplete value */ if (val_len < len) break; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* CAC driver is read only */ static int cac_write_binary(sc_card_t *card, unsigned int idx, const u8 *buf, size_t count, unsigned long flags) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } /* initialize getting a list and return the number of elements in the list */ static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp) { *countp = list_size(list); list_iterator_start(list); *entry = list_iterator_next(list); return SC_SUCCESS; } /* finalize the list iterator */ static int cac_final_iterator(list_t *list) { list_iterator_stop(list); return SC_SUCCESS; } /* fill in the obj_info for the current object on the list and advance to the next object */ static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info) { memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t)); if (*entry == NULL) { return SC_ERROR_FILE_END_REACHED; } obj_info->path = (*entry)->path; obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */ obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff; obj_info->id.value[1] = (*entry)->fd & 0xff; obj_info->id.len = 2; strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1); *entry = list_iterator_next(list); return SC_SUCCESS; } static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, serial->len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (priv->aca_path) { *path = *priv->aca_path; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { cac_private_data_t * priv = CAC_DATA(card); LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr); if (priv == NULL) { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL); } switch(cmd) { case SC_CARDCTL_CAC_GET_ACA_PATH: return cac_get_ACA_path(card, (sc_path_t *) ptr); case SC_CARDCTL_GET_SERIALNR: return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr); case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS: return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr); case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS: return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr); case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT: return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT: return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr); case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS: return cac_final_iterator(&priv->general_list); case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS: return cac_final_iterator(&priv->pki_list); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { /* CAC requires 8 byte response */ u8 rbuf[8]; u8 *rbufp = &rbuf[0]; size_t out_len = sizeof rbuf; int r; LOG_FUNC_CALLED(card->ctx); r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len); LOG_TEST_RET(card->ctx, r, "Could not get challenge"); if (len < out_len) { out_len = len; } memcpy(rnd, rbuf, out_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len); } static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n", env->flags, env->operation, env->algorithm, env->algorithm_flags, env->algorithm_ref, env->key_ref[0], env->key_ref_len); if (env->algorithm != SC_ALGORITHM_RSA) { r = SC_ERROR_NO_CARD_SUPPORT; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } static int cac_restore_security_env(sc_card_t *card, int se_num) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_rsa_op(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; u8 *outp, *rbuf; size_t rbuflen, outplen; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n", datalen, outlen); outp = out; outplen = outlen; /* Not strictly necessary. This code requires the caller to have selected the correct PKI container * and authenticated to that container with the verifyPin command... All of this under the reader lock. * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */ r = sc_lock(card); if (r != SC_SUCCESS) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); rbuf = NULL; rbuflen = 0; for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) { r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0, data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen); if (r < 0) { break; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); outp += n; outplen -= n; } free(rbuf); rbuf = NULL; rbuflen = 0; } if (r < 0) { goto err; } rbuf = NULL; rbuflen = 0; r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen); if (r < 0) { goto err; } if (rbuflen != 0) { int n = MIN(rbuflen, outplen); memcpy(outp,rbuf, n); /*outp += n; unused */ outplen -= n; } free(rbuf); rbuf = NULL; r = outlen-outplen; err: sc_unlock(card); if (r < 0) { sc_mem_clear(out, outlen); } if (rbuf) { free(rbuf); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int cac_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen)); } static int cac_parse_properties_object(sc_card_t *card, u8 type, u8 *data, size_t data_len, cac_properties_object_t *object) { size_t len; u8 *val, *val_end, tag; int parsed = 0; if (data_len < 11) return -1; /* Initilize: non-PKI applet */ object->privatekey = 0; val = data; val_end = data + data_len; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_OBJECT_ID: if (len != 2) { sc_log(card->ctx, "TAG: Object ID: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]); memcpy(&object->oid, val, 2); parsed++; break; case CAC_TAG_BUFFER_PROPERTIES: if (len != 5) { sc_log(card->ctx, "TAG: Buffer Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* First byte is "Type of Tag Supported" */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Buffer Properties: Type of Tag Supported = 0x%02x", val[0]); object->simpletlv = val[0]; parsed++; break; case CAC_TAG_PKI_PROPERTIES: /* 4th byte is "Private Key Initialized" */ if (len != 4) { sc_log(card->ctx, "TAG: PKI Properties: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } if (type != CAC_TAG_PKI_OBJECT) { sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object"); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Properties: Private Key Initialized = 0x%02x", val[2]); object->privatekey = val[2]; parsed++; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)",tag ); break; } } if (parsed < 2) return SC_ERROR_INVALID_DATA; return SC_SUCCESS; } static int cac_get_properties(sc_card_t *card, cac_properties_t *prop) { u8 *rbuf = NULL; size_t rbuflen = 0, len; u8 *val, *val_end, tag; size_t i = 0; int r; prop->num_objects = 0; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0, &rbuf, &rbuflen); if (r < 0) return r; val = rbuf; val_end = val + rbuflen; for (; val < val_end; val += len) { /* get the tag and the length */ if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_INFORMATION: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%0x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_OF_OBJECTS: if (len != 1) { sc_log(card->ctx, "TAG: Num objects: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num objects = %hhd", *val); /* make sure we do not overrun buffer */ prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS); break; case CAC_TAG_TV_BUFFER: if (len != 17) { sc_log(card->ctx, "TAG: TV Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; case CAC_TAG_PKI_OBJECT: if (len != 17) { sc_log(card->ctx, "TAG: PKI Object: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i); if (i >= CAC_MAX_OBJECTS) { free(rbuf); return SC_SUCCESS; } if (cac_parse_properties_object(card, tag, val, len, &prop->objects[i]) == SC_SUCCESS) i++; break; default: /* ignore tags we don't understand */ sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%" SC_FORMAT_LEN_SIZE_T"u", tag, len); break; } } free(rbuf); /* sanity */ if (i != prop->num_objects) sc_log(card->ctx, "The announced number of objects (%u) " "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)", prop->num_objects, i); prop->num_objects = i; return SC_SUCCESS; } /* * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS * if it doesn't like anything about the select, so we always 'request' FCI for CAC1 * * The rest is just copied from iso7816_select_file */ static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type) { struct sc_context *ctx; struct sc_apdu apdu; unsigned char buf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen, pathtype; struct sc_file *file = NULL; cac_private_data_t * priv = CAC_DATA(card); assert(card != NULL && in_path != NULL); ctx = card->ctx; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; pathtype = in_path->type; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", in_path->aid.value[0], in_path->aid.value[1], in_path->aid.value[2], in_path->aid.value[3], in_path->aid.value[4], in_path->aid.value[5], in_path->aid.value[6], in_path->aid.len, in_path->value[0], in_path->value[1], in_path->value[2], in_path->value[3], in_path->len, in_path->type, in_path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n", file_out, in_path->index, in_path->count); /* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override. * we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file * a flag that says 'no, really this path is fine'. We only need to do this for private keys */ if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) { if (pathlen > 2) { path += 2; pathlen -= 2; } } /* CAC has multiple different type of objects that aren't PKCS #15. When we read * them we need convert them to something PKCS #15 would understand. Find the object * and object type here: */ if (priv) { /* don't record anything if we haven't been initialized yet */ priv->object_type = CAC_OBJECT_TYPE_GENERIC; if (cac_is_cert(priv, in_path)) { priv->object_type = CAC_OBJECT_TYPE_CERT; } /* forget any old cached values */ if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; } priv->cache_buf_len = 0; priv->cached = 0; } if (in_path->aid.len) { if (!pathlen) { memcpy(path, in_path->aid.value, in_path->aid.len); pathlen = in_path->aid.len; pathtype = SC_PATH_TYPE_DF_NAME; } else { /* First, select the application */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" ); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0); apdu.data = in_path->aid.value; apdu.datalen = in_path->aid.len; apdu.lc = in_path->aid.len; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0); switch (pathtype) { /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select. * Unfortunately we'd also need to update the caching code as well. For now just * use FILE_ID and change p1 here */ case SC_PATH_TYPE_FILE_ID: apdu.p1 = 2; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256; if (file_out != NULL) { apdu.p2 = 0; /* first record, return FCI */ } else { apdu.p2 = 0x0C; } r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (file_out == NULL) { /* For some cards 'SELECT' can be only with request to return FCI/FCP. */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) { apdu.p2 = 0x00; apdu.resplen = sizeof(buf); if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS) r = sc_check_sw(card, apdu.sw1, apdu.sw2); } if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_FUNC_RETURN(ctx, r); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(ctx, r); /* This needs to come after the applet selection */ if (priv && in_path->len >= 2) { /* get applet properties to know if we can treat the * buffer as SimpleLTV and if we have PKI applet. * * Do this only if we select applets for reading * (not during driver initialization) */ cac_properties_t prop; size_t i = -1; r = cac_get_properties(card, &prop); if (r == SC_SUCCESS) { for (i = 0; i < prop.num_objects; i++) { sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x", prop.objects[i].oid[0], prop.objects[i].oid[1], in_path->value[0], in_path->value[1]); if (memcmp(prop.objects[i].oid, in_path->value, 2) == 0) break; } } if (i < prop.num_objects) { if (prop.objects[i].privatekey) priv->object_type = CAC_OBJECT_TYPE_CERT; else if (prop.objects[i].simpletlv == 0) priv->object_type = CAC_OBJECT_TYPE_TLV_FILE; } } /* CAC cards never return FCI, fake one */ file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */ *file_out = file; SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { return cac_select_file_by_type(card, in_path, file_out, card->type); } static int cac_finish(sc_card_t *card) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (priv) { cac_free_private_data(priv); } return SC_SUCCESS; } /* select the Card Capabilities Container on CAC-2 */ static int cac_select_CCC(sc_card_t *card) { return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II); } /* Select ACA in non-standard location */ static int cac_select_ACA(sc_card_t *card) { return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II); } static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len) { if (len < 10) { return SC_ERROR_INVALID_DATA; } sc_mem_clear(path, sizeof(sc_path_t)); memcpy(path->aid.value, &val->rid, sizeof(val->rid)); memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID)); path->aid.len = sizeof(val->rid) + sizeof(val->applicationID); memcpy(path->value, &val->objectID, sizeof(val->objectID)); path->len = sizeof(val->objectID); path->type = SC_PATH_TYPE_FILE_ID; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)", path->aid.value[0], path->aid.value[1], path->aid.value[2], path->aid.value[3], path->aid.value[4], path->aid.value[5], path->aid.value[6], path->aid.len, path->value[0], path->value[1], path->len, path->type, path->type); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u", val->rid[0], val->rid[1], val->rid[2], val->rid[3], val->rid[4], sizeof(val->rid), val->applicationID[0], val->applicationID[1], sizeof(val->applicationID), val->objectID[0], val->objectID[1], sizeof(val->objectID)); return SC_SUCCESS; } static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len) { cac_object_t new_object; cac_properties_t prop; size_t i; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Search for PKI applets (7 B). Ignore generic objects for now */ if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0 && memcmp(aid, CAC_1_RID "\x00", 6) != 0)) return SC_SUCCESS; sc_mem_clear(&new_object.path, sizeof(sc_path_t)); memcpy(new_object.path.aid.value, aid, aid_len); new_object.path.aid.len = aid_len; /* Call without OID set will just select the AID without subseqent * OID selection, which we need to figure out just now */ cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II); r = cac_get_properties(card, &prop); if (r < 0) return SC_ERROR_INTERNAL; for (i = 0; i < prop.num_objects; i++) { /* don't fail just because we have more certs than we can support */ if (priv->cert_next >= MAX_CAC_SLOTS) return SC_SUCCESS; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA: pki_object found, cert_next=%d (%s), privkey=%d", priv->cert_next, cac_labels[priv->cert_next], prop.objects[i].privatekey); /* If the private key is not initialized, we can safely * ignore this object here, but increase the pointer to follow * the certificate labels */ if (!prop.objects[i].privatekey) { priv->cert_next++; continue; } /* OID here has always 2B */ memcpy(new_object.path.value, &prop.objects[i].oid, 2); new_object.path.len = 2; new_object.path.type = SC_PATH_TYPE_FILE_ID; new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; } return SC_SUCCESS; } static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len) { cac_object_t new_object; const cac_object_t *obj; unsigned short object_id; int r; r = cac_path_from_cardurl(card, &new_object.path, val, len); if (r != SC_SUCCESS) { return r; } switch (val->cardApplicationType) { case CAC_APP_TYPE_PKI: /* we don't want to overflow the cac_label array. This test could * go way if we create a label function that will create a unique label * from a cert index. */ if (priv->cert_next >= MAX_CAC_SLOTS) break; /* don't fail just because we have more certs than we can support */ new_object.name = cac_labels[priv->cert_next]; new_object.fd = priv->cert_next+1; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name); cac_add_object_to_list(&priv->pki_list, &new_object); priv->cert_next++; break; case CAC_APP_TYPE_GENERAL: object_id = bebytes2ushort(val->objectID); obj = cac_find_obj_by_id(object_id); if (obj == NULL) break; /* don't fail just because we don't recognize the object */ new_object.name = obj->name; new_object.fd = 0; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name); cac_add_object_to_list(&priv->general_list, &new_object); break; case CAC_APP_TYPE_SKI: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found"); break; default: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType); /* don't fail just because there is an unknown object in the CCC */ break; } return SC_SUCCESS; } static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len) { size_t card_id_len; if (len < sizeof(cac_cuid_t)) { return SC_ERROR_INVALID_DATA; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid))); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type); card_id_len = len - (&val->card_id - (u8 *)val); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)", sc_dump_hex(&val->card_id, card_id_len), card_id_len); priv->cuid = *val; priv->cac_id = malloc(card_id_len); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } memcpy(priv->cac_id, &val->card_id, card_id_len); priv->cac_id_len = card_id_len; return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv); static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl, size_t tl_len, u8 *val, size_t val_len) { size_t len = 0; u8 *tl_end = tl + tl_len; u8 *val_end = val + val_len; sc_path_t new_path; int r; for (; (tl < tl_end) && (val< val_end); val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_CUID: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID"); r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len); if (r < 0) return r; break; case CAC_TAG_CC_VERSION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: CC Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: CC Version = 0x%02x", *val); break; case CAC_TAG_GRAMMAR_VERION_NUMBER: if (len != 1) { sc_log(card->ctx, "TAG: Grammar Version: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* ignore the version numbers for now */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Grammar Version = 0x%02x", *val); break; case CAC_TAG_CARDURL: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL"); r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len); if (r < 0) return r; break; /* * The following are really for file systems cards. This code only cares about CAC VM cards */ case CAC_TAG_PKCS15: if (len != 1) { sc_log(card->ctx, "TAG: PKCS15: " "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } /* TODO should verify that this is '0'. If it's not * zero, we should drop out of here and let the PKCS 15 * code handle this card */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val); break; case CAC_TAG_DATA_MODEL: case CAC_TAG_CARD_APDU: case CAC_TAG_CAPABILITY_TUPLES: case CAC_TAG_STATUS_TUPLES: case CAC_TAG_REDIRECTION: case CAC_TAG_ERROR_CODES: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag); break; case CAC_TAG_ACCESS_CONTROL: /* TODO handle access control later */ sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len); break; case CAC_TAG_NEXT_CCC: sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC"); r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len); if (r < 0) return r; r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II); if (r < 0) return r; r = cac_process_CCC(card, priv); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag ); break; } } return SC_SUCCESS; } static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv) { u8 *tl = NULL, *val = NULL; size_t tl_len, val_len; int r; r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) goto done; r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len); done: if (tl) free(tl); if (val) free(val); return r; } /* Service Applet Table (Table 5-21) should list all the applets on the * card, which is a good start if we don't have CCC */ static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv, u8 *val, size_t val_len) { size_t len = 0; u8 *val_end = val + val_len; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); for (; val < val_end; val += len) { /* get the tag and the length */ u8 tag; if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS) break; switch (tag) { case CAC_TAG_APPLET_FAMILY: if (len != 5) { sc_log(card->ctx, "TAG: Applet Information: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Information: Family: 0x%02x", val[0]); sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, " Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x", val[1], val[2], val[3], val[4]); break; case CAC_TAG_NUMBER_APPLETS: if (len != 1) { sc_log(card->ctx, "TAG: Num applets: " "bad length %"SC_FORMAT_LEN_SIZE_T"u", len); break; } sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Num applets = %hhd", *val); break; case CAC_TAG_APPLET_ENTRY: /* Make sure we match the outer length */ if (len < 3 || val[2] != len - 3) { sc_log(card->ctx, "TAG: Applet Entry: " "bad length (%"SC_FORMAT_LEN_SIZE_T "u) or length of internal buffer", len); break; } sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Applet Entry: AID", &val[3], val[2]); /* This is SimpleTLV prefixed with applet ID (1B) */ r = cac_parse_aid(card, priv, &val[3], val[2]); if (r < 0) return r; break; default: /* ignore tags we don't understand */ sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "TAG: Unknown (0x%02x)", tag); break; } } return SC_SUCCESS; } /* select a CAC pki applet by index */ static int cac_select_pki_applet(sc_card_t *card, int index) { sc_path_t applet_path = cac_cac_pki_obj.path; applet_path.aid.value[applet_path.aid.len-1] = index; return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II); } /* * Find the first existing CAC applet. If none found, then this isn't a CAC */ static int cac_find_first_pki_applet(sc_card_t *card, int *index_out) { int r, i; for (i = 0; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { /* Try to read first two bytes of the buffer to * make sure it is not just malfunctioning card */ u8 params[2] = {CAC_FILE_TAG, 2}; u8 data[2], *out_ptr = data; size_t len = 2; r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len); if (r != 2) continue; *index_out = i; return SC_SUCCESS; } } return SC_ERROR_OBJECT_NOT_FOUND; } /* * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets */ static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv) { int r, i; cac_object_t pki_obj = cac_cac_pki_obj; u8 buf[100]; u8 *val; size_t val_len; /* populate PKI objects */ for (i = index; i < MAX_CAC_SLOTS; i++) { r = cac_select_pki_applet(card, i); if (r == SC_SUCCESS) { pki_obj.name = cac_labels[i]; sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name); pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i; pki_obj.fd = i+1; /* don't use id of zero */ cac_add_object_to_list(&priv->pki_list, &pki_obj); } } /* populate non-PKI objects */ for (i=0; i < cac_object_count; i++) { r = cac_select_file_by_type(card, &cac_objects[i].path, NULL, SC_CARD_TYPE_CAC_II); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CAC: obj_object found, cert_next=%d (%s),", i, cac_objects[i].name); cac_add_object_to_list(&priv->general_list, &cac_objects[i]); } } /* * create a cuid to simulate the cac 2 cuid. */ priv->cuid = cac_cac_cuid; /* create a serial number by hashing the first 100 bytes of the * first certificate on the card */ r = cac_select_pki_applet(card, index); if (r < 0) { return r; /* shouldn't happen unless the card has been removed or is malfunctioning */ } val = buf; val_len = cac_read_binary(card, 0, val, sizeof(buf), 0); if (val_len > 0) { priv->cac_id = malloc(20); if (priv->cac_id == NULL) { return SC_ERROR_OUT_OF_MEMORY; } #ifdef ENABLE_OPENSSL SHA1(val, val_len, priv->cac_id); priv->cac_id_len = 20; sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE, "cuid", priv->cac_id, priv->cac_id_len); #else sc_log(card->ctx, "OpenSSL Required"); return SC_ERROR_NOT_SUPPORTED; #endif /* ENABLE_OPENSSL */ } return SC_SUCCESS; } static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv) { int r; u8 *val = NULL; size_t val_len; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Assuming ACA is already selected */ r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len); if (r < 0) goto done; r = cac_parse_ACA_service(card, priv, val, val_len); if (r == SC_SUCCESS) { priv->aca_path = malloc(sizeof(sc_path_t)); if (!priv->aca_path) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t)); } done: if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } /* * Look for a CAC card. If it exists, initialize our data structures */ static int cac_find_and_initialize(sc_card_t *card, int initialize) { int r, index; cac_private_data_t *priv = NULL; /* already initialized? */ if (card->drv_data) { return SC_SUCCESS; } /* is this a CAC-2 specified in NIST Interagency Report 6887 - * "Government Smart Card Interoperability Specification v2.1 July 2003" */ r = cac_select_CCC(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2"); if (!initialize) /* match card only */ return r; priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; r = cac_process_CCC(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* Even some ALT tokens can be missing CCC so we should try with ACA */ r = cac_select_ACA(card); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } r = cac_process_ACA(card, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; card->drv_data = priv; return r; } } /* is this a CAC Alt token without any accompanying structures */ r = cac_find_first_pki_applet(card, &index); if (r == SC_SUCCESS) { sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt"); if (!initialize) /* match card only */ return r; if (!priv) { priv = cac_new_private_data(); if (!priv) return SC_ERROR_OUT_OF_MEMORY; } card->drv_data = priv; /* needed for the read_binary() */ r = cac_populate_cac_alt(card, index, priv); if (r == SC_SUCCESS) { card->type = SC_CARD_TYPE_CAC_II; return r; } card->drv_data = NULL; /* reset on failure */ } if (priv) { cac_free_private_data(priv); } return r; } /* NOTE: returns a bool, 1 card matches, 0 it does not */ static int cac_match_card(sc_card_t *card) { int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* Since we send an APDU, the card's logout function may be called... * however it may be in dirty memory */ card->ops->logout = NULL; r = cac_find_and_initialize(card, 0); return (r == SC_SUCCESS); /* never match */ } static int cac_init(sc_card_t *card) { int r; unsigned long flags; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); r = cac_find_and_initialize(card, 1); if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD); } flags = SC_ALGORITHM_RSA_RAW; _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */ _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */ _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */ card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left) { /* CAC, like PIV needs Extra validation of (new) PIN during * a PIN change request, to ensure it's not outside the * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2 * (6 character minimum) requirements. */ struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (data->cmd == SC_PIN_CMD_CHANGE) { int i = 0; if (data->pin2.len < 6) { return SC_ERROR_INVALID_PIN_LENGTH; } for(i=0; i < data->pin2.len; ++i) { if (!isdigit(data->pin2.data[i])) { return SC_ERROR_INVALID_DATA; } } } return iso_drv->ops->pin_cmd(card, data, tries_left); } static struct sc_card_operations cac_ops; static struct sc_card_driver cac_drv = { "Common Access Card (CAC)", "cac", &cac_ops, NULL, 0, NULL }; static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); cac_ops = *iso_drv->ops; cac_ops.match_card = cac_match_card; cac_ops.init = cac_init; cac_ops.finish = cac_finish; cac_ops.select_file = cac_select_file; /* need to record object type */ cac_ops.get_challenge = cac_get_challenge; cac_ops.read_binary = cac_read_binary; cac_ops.write_binary = cac_write_binary; cac_ops.set_security_env = cac_set_security_env; cac_ops.restore_security_env = cac_restore_security_env; cac_ops.compute_signature = cac_compute_signature; cac_ops.decipher = cac_decipher; cac_ops.card_ctl = cac_card_ctl; cac_ops.pin_cmd = cac_pin_cmd; return &cac_drv; } struct sc_card_driver * sc_get_cac_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_0
crossvul-cpp_data_bad_347_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_347_7
crossvul-cpp_data_good_347_2
/* * card-muscle.c: Support for MuscleCard Applet from musclecard.com * * Copyright (C) 2006, Identity Alliance, Thomas Harning <support@identityalliance.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "internal.h" #include "cardctl.h" #include "muscle.h" #include "muscle-filesystem.h" #include "types.h" #include "opensc.h" static struct sc_card_operations muscle_ops; static const struct sc_card_operations *iso_ops = NULL; static struct sc_card_driver muscle_drv = { "MuscleApplet", "muscle", &muscle_ops, NULL, 0, NULL }; static struct sc_atr_table muscle_atrs[] = { /* Tyfone JCOP 242R2 cards */ { "3b:6d:00:00:ff:54:79:66:6f:6e:65:20:32:34:32:52:32", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU, 0, NULL }, /* Aladdin eToken PRO USB 72K Java */ { "3b:d5:18:00:81:31:3a:7d:80:73:c8:21:10:30", NULL, NULL, SC_CARD_TYPE_MUSCLE_ETOKEN_72K, 0, NULL }, /* JCOP31 v2.4.1 contact interface */ { "3b:f8:13:00:00:81:31:fe:45:4a:43:4f:50:76:32:34:31:b7", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, /* JCOP31 v2.4.1 RF interface */ { "3b:88:80:01:4a:43:4f:50:76:32:34:31:5e", NULL, NULL, SC_CARD_TYPE_MUSCLE_JCOP241, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; #define MUSCLE_DATA(card) ( (muscle_private_t*)card->drv_data ) #define MUSCLE_FS(card) ( ((muscle_private_t*)card->drv_data)->fs ) typedef struct muscle_private { sc_security_env_t env; unsigned short verifiedPins; mscfs_t *fs; int rsa_key_ref; } muscle_private_t; static int muscle_finish(sc_card_t *card) { muscle_private_t *priv = MUSCLE_DATA(card); mscfs_free(priv->fs); free(priv); return 0; } static u8 muscleAppletId[] = { 0xA0, 0x00,0x00,0x00, 0x01, 0x01 }; static int muscle_match_card(sc_card_t *card) { sc_apdu_t apdu; u8 response[64]; int r; /* Since we send an APDU, the card's logout function may be called... * however it's not always properly nulled out... */ card->ops->logout = NULL; if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) == 1) { /* Muscle applet is present, check the protocol version to be sure */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2, 0x3C, 0x00, 0x00); apdu.cla = 0xB0; apdu.le = 64; apdu.resplen = 64; apdu.resp = response; r = sc_transmit_apdu(card, &apdu); if (r == SC_SUCCESS && response[0] == 0x01) { card->type = SC_CARD_TYPE_MUSCLE_V1; } else { card->type = SC_CARD_TYPE_MUSCLE_GENERIC; } return 1; } return 0; } /* Since Musclecard has a different ACL system then PKCS15 * objects need to have their READ/UPDATE/DELETE permissions mapped for files * and directory ACLS need to be set * For keys.. they have different ACLS, but are accessed in different locations, so it shouldn't be an issue here */ static unsigned short muscle_parse_singleAcl(const sc_acl_entry_t* acl) { unsigned short acl_entry = 0; while(acl) { int key = acl->key_ref; int method = acl->method; switch(method) { case SC_AC_NEVER: return 0xFFFF; /* Ignore... other items overwrite these */ case SC_AC_NONE: case SC_AC_UNKNOWN: break; case SC_AC_CHV: acl_entry |= (1 << key); /* Assuming key 0 == SO */ break; case SC_AC_AUT: case SC_AC_TERM: case SC_AC_PRO: default: /* Ignored */ break; } acl = acl->next; } return acl_entry; } static void muscle_parse_acls(const sc_file_t* file, unsigned short* read_perm, unsigned short* write_perm, unsigned short* delete_perm) { assert(read_perm && write_perm && delete_perm); *read_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_READ)); *write_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_UPDATE)); *delete_perm = muscle_parse_singleAcl(sc_file_get_acl_entry(file, SC_AC_OP_DELETE)); } static int muscle_create_directory(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); msc_id objectId; u8* oid = objectId.id; unsigned id = file->id; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; int objectSize; int r; if(id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; /* No nesting directories */ if(fs->currentPath[0] != 0x3F || fs->currentPath[1] != 0x00) return SC_ERROR_NOT_SUPPORTED; oid[0] = ((id & 0xFF00) >> 8) & 0xFF; oid[1] = id & 0xFF; oid[2] = oid[3] = 0; objectSize = file->size; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_create_file(sc_card_t *card, sc_file_t *file) { mscfs_t *fs = MUSCLE_FS(card); int objectSize = file->size; unsigned short read_perm = 0, write_perm = 0, delete_perm = 0; msc_id objectId; int r; if(file->type == SC_FILE_TYPE_DF) return muscle_create_directory(card, file); if(file->type != SC_FILE_TYPE_WORKING_EF) return SC_ERROR_NOT_SUPPORTED; if(file->id == 0) /* No null name files */ return SC_ERROR_INVALID_ARGUMENTS; muscle_parse_acls(file, &read_perm, &write_perm, &delete_perm); mscfs_lookup_local(fs, file->id, &objectId); r = msc_create_object(card, objectId, objectSize, read_perm, write_perm, delete_perm); mscfs_clear_cache(fs); if(r >= 0) return 0; return r; } static int muscle_read_binary(sc_card_t *card, unsigned int idx, u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; msc_id objectId; u8* oid = objectId.id; mscfs_file_t *file; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } r = msc_read_object(card, objectId, idx, buf, count); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } static int muscle_update_binary(sc_card_t *card, unsigned int idx, const u8* buf, size_t count, unsigned long flags) { mscfs_t *fs = MUSCLE_FS(card); int r; mscfs_file_t *file; msc_id objectId; u8* oid = objectId.id; r = mscfs_check_selection(fs, -1); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); file = &fs->cache.array[fs->currentFileIndex]; objectId = file->objectId; /* memcpy(objectId.id, file->objectId.id, 4); */ if(!file->ef) { oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; } if(file->size < idx + count) { int newFileSize = idx + count; u8* buffer = malloc(newFileSize); if(buffer == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); r = msc_read_object(card, objectId, 0, buffer, file->size); /* TODO: RETRIEVE ACLS */ if(r < 0) goto update_bin_free_buffer; r = msc_delete_object(card, objectId, 0); if(r < 0) goto update_bin_free_buffer; r = msc_create_object(card, objectId, newFileSize, 0,0,0); if(r < 0) goto update_bin_free_buffer; memcpy(buffer + idx, buf, count); r = msc_update_object(card, objectId, 0, buffer, newFileSize); if(r < 0) goto update_bin_free_buffer; file->size = newFileSize; update_bin_free_buffer: free(buffer); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } else { r = msc_update_object(card, objectId, idx, buf, count); } /* mscfs_clear_cache(fs); */ return r; } /* TODO: Evaluate correctness */ static int muscle_delete_mscfs_file(sc_card_t *card, mscfs_file_t *file_data) { mscfs_t *fs = MUSCLE_FS(card); msc_id id = file_data->objectId; u8* oid = id.id; int r; if(!file_data->ef) { int x; mscfs_file_t *childFile; /* Delete children */ mscfs_check_cache(fs); sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING Children of: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); for(x = 0; x < fs->cache.size; x++) { msc_id objectId; childFile = &fs->cache.array[x]; objectId = childFile->objectId; if(0 == memcmp(oid + 2, objectId.id, 2)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "DELETING: %02X%02X%02X%02X\n", objectId.id[0],objectId.id[1], objectId.id[2],objectId.id[3]); r = muscle_delete_mscfs_file(card, childFile); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } } oid[0] = oid[2]; oid[1] = oid[3]; oid[2] = oid[3] = 0; /* ??? objectId = objectId >> 16; */ } if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) { } r = msc_delete_object(card, id, 1); /* Check if its the root... this file generally is virtual * So don't return an error if it fails */ if((0 == memcmp(oid, "\x3F\x00\x00\x00", 4)) || (0 == memcmp(oid, "\x3F\x00\x3F\x00", 4))) return 0; if(r < 0) { printf("ID: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } return 0; } static int muscle_delete_file(sc_card_t *card, const sc_path_t *path_in) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int r = 0; r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, NULL); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); r = muscle_delete_mscfs_file(card, file_data); mscfs_clear_cache(fs); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); return 0; } static void muscle_load_single_acl(sc_file_t* file, int operation, unsigned short acl) { int key; /* Everybody by default.... */ sc_file_add_acl_entry(file, operation, SC_AC_NONE, 0); if(acl == 0xFFFF) { sc_file_add_acl_entry(file, operation, SC_AC_NEVER, 0); return; } for(key = 0; key < 16; key++) { if(acl >> key & 1) { sc_file_add_acl_entry(file, operation, SC_AC_CHV, key); } } } static void muscle_load_file_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_READ, file_data->read); muscle_load_single_acl(file, SC_AC_OP_WRITE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_UPDATE, file_data->write); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); } static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } /* Required type = -1 for don't care, 1 for EF, 0 for DF */ static int select_item(sc_card_t *card, const sc_path_t *path_in, sc_file_t ** file_out, int requiredType) { mscfs_t *fs = MUSCLE_FS(card); mscfs_file_t *file_data = NULL; int pathlen = path_in->len; int r = 0; int objectIndex; u8* oid; mscfs_check_cache(fs); r = mscfs_loadFileInfo(fs, path_in->value, path_in->len, &file_data, &objectIndex); if(r < 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); /* Check if its the right type */ if(requiredType >= 0 && requiredType != file_data->ef) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } oid = file_data->objectId.id; /* Is it a file or directory */ if(file_data->ef) { fs->currentPath[0] = oid[0]; fs->currentPath[1] = oid[1]; fs->currentFile[0] = oid[2]; fs->currentFile[1] = oid[3]; } else { fs->currentPath[0] = oid[pathlen - 2]; fs->currentPath[1] = oid[pathlen - 1]; fs->currentFile[0] = 0; fs->currentFile[1] = 0; } fs->currentFileIndex = objectIndex; if(file_out) { sc_file_t *file; file = sc_file_new(); file->path = *path_in; file->size = file_data->size; file->id = (oid[2] << 8) | oid[3]; if(!file_data->ef) { file->type = SC_FILE_TYPE_DF; } else { file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; } /* Setup ACLS */ if(file_data->ef) { muscle_load_file_acls(file, file_data); } else { muscle_load_dir_acls(file, file_data); /* Setup directory acls... */ } file->magic = SC_FILE_MAGIC; *file_out = file; } return 0; } static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in, sc_file_t **file_out) { int r; assert(card != NULL && path_in != NULL); switch (path_in->type) { case SC_PATH_TYPE_FILE_ID: r = select_item(card, path_in, file_out, 1); break; case SC_PATH_TYPE_DF_NAME: r = select_item(card, path_in, file_out, 0); break; case SC_PATH_TYPE_PATH: r = select_item(card, path_in, file_out, -1); break; default: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if(r > 0) r = 0; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r); } static int _listFile(mscfs_file_t *file, int reset, void *udata) { int next = reset ? 0x00 : 0x01; return msc_list_objects( (sc_card_t*)udata, next, file); } static int muscle_init(sc_card_t *card) { muscle_private_t *priv; card->name = "MuscleApplet"; card->drv_data = malloc(sizeof(muscle_private_t)); if(!card->drv_data) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } memset(card->drv_data, 0, sizeof(muscle_private_t)); priv = MUSCLE_DATA(card); priv->verifiedPins = 0; priv->fs = mscfs_new(); if(!priv->fs) { free(card->drv_data); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); } priv->fs->udata = card; priv->fs->listFile = _listFile; card->cla = 0xB0; card->flags |= SC_CARD_FLAG_RNG; card->caps |= SC_CARD_CAP_RNG; /* Card type detection */ _sc_match_atr(card, muscle_atrs, &card->type); if(card->type == SC_CARD_TYPE_MUSCLE_ETOKEN_72K) { card->caps |= SC_CARD_CAP_APDU_EXT; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP241) { card->caps |= SC_CARD_CAP_APDU_EXT; } if (!(card->caps & SC_CARD_CAP_APDU_EXT)) { card->max_recv_size = 255; card->max_send_size = 255; } if(card->type == SC_CARD_TYPE_MUSCLE_JCOP242R2_NO_EXT_APDU) { /* Tyfone JCOP v242R2 card that doesn't support extended APDUs */ } /* FIXME: Card type detection */ if (1) { unsigned long flags; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_HASH_NONE; flags |= SC_ALGORITHM_ONBOARD_KEY_GEN; _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return SC_SUCCESS; } static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid = fs->cache.array[x].objectId.id; if (bufLen < 2) break; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count += 2; bufLen -= 2; } } return count; } static int muscle_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *cmd, int *tries_left) { muscle_private_t* priv = MUSCLE_DATA(card); const int bufferLength = MSC_MAX_PIN_COMMAND_LENGTH; u8 buffer[MSC_MAX_PIN_COMMAND_LENGTH]; switch(cmd->cmd) { case SC_PIN_CMD_VERIFY: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; int r; msc_verify_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; cmd->pin1.offset = 5; r = iso_ops->pin_cmd(card, cmd, tries_left); if(r >= 0) priv->verifiedPins |= (1 << cmd->pin_reference); return r; } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_CHANGE: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_change_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len, cmd->pin2.data, cmd->pin2.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } case SC_PIN_CMD_UNBLOCK: switch(cmd->pin_type) { case SC_AC_CHV: { sc_apdu_t apdu; msc_unblock_pin_apdu(card, &apdu, buffer, bufferLength, cmd->pin_reference, cmd->pin1.data, cmd->pin1.len); cmd->apdu = &apdu; return iso_ops->pin_cmd(card, cmd, tries_left); } case SC_AC_TERM: case SC_AC_PRO: case SC_AC_AUT: case SC_AC_NONE: default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported authentication method\n"); return SC_ERROR_NOT_SUPPORTED; } default: sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported command\n"); return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_extract_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 1: /* RSA */ return msc_extract_rsa_public_key(card, info->keyLocation, &info->modLength, &info->modValue, &info->expLength, &info->expValue); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_import_key(sc_card_t *card, sc_cardctl_muscle_key_info_t *info) { /* CURRENTLY DONT SUPPORT EXTRACTING PRIVATE KEYS... */ switch(info->keyType) { case 0x02: /* RSA_PRIVATE */ case 0x03: /* RSA_PRIVATE_CRT */ return msc_import_key(card, info->keyLocation, info); default: return SC_ERROR_NOT_SUPPORTED; } } static int muscle_card_generate_key(sc_card_t *card, sc_cardctl_muscle_gen_key_info_t *info) { return msc_generate_keypair(card, info->privateKeyLocation, info->publicKeyLocation, info->keyType, info->keySize, 0); } static int muscle_card_verified_pins(sc_card_t *card, sc_cardctl_muscle_verified_pins_info_t *info) { muscle_private_t* priv = MUSCLE_DATA(card); info->verifiedPins = priv->verifiedPins; return 0; } static int muscle_card_ctl(sc_card_t *card, unsigned long request, void *data) { switch(request) { case SC_CARDCTL_MUSCLE_GENERATE_KEY: return muscle_card_generate_key(card, (sc_cardctl_muscle_gen_key_info_t*) data); case SC_CARDCTL_MUSCLE_EXTRACT_KEY: return muscle_card_extract_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_IMPORT_KEY: return muscle_card_import_key(card, (sc_cardctl_muscle_key_info_t*) data); case SC_CARDCTL_MUSCLE_VERIFIED_PINS: return muscle_card_verified_pins(card, (sc_cardctl_muscle_verified_pins_info_t*) data); default: return SC_ERROR_NOT_SUPPORTED; /* Unsupported.. whatever it is */ } } static int muscle_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); if (env->operation != SC_SEC_OPERATION_SIGN && env->operation != SC_SEC_OPERATION_DECIPHER) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto operation supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->algorithm != SC_ALGORITHM_RSA) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid crypto algorithm supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } /* ADJUST FOR PKCS1 padding support for decryption only */ if ((env->algorithm_flags & SC_ALGORITHM_RSA_PADS) || (env->algorithm_flags & SC_ALGORITHM_RSA_HASHES)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card supports only raw RSA.\n"); return SC_ERROR_NOT_SUPPORTED; } if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { if (env->key_ref_len != 1 || (env->key_ref[0] > 0x0F)) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid key reference supplied.\n"); return SC_ERROR_NOT_SUPPORTED; } priv->rsa_key_ref = env->key_ref[0]; } if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm reference not supported.\n"); return SC_ERROR_NOT_SUPPORTED; } /* if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) if (memcmp(env->file_ref.value, "\x00\x12", 2) != 0) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference is not 0012.\n"); return SC_ERROR_NOT_SUPPORTED; } */ priv->env = *env; return 0; } static int muscle_restore_security_env(sc_card_t *card, int se_num) { muscle_private_t* priv = MUSCLE_DATA(card); memset(&priv->env, 0, sizeof(priv->env)); return 0; } static int muscle_decipher(sc_card_t * card, const u8 * crgram, size_t crgram_len, u8 * out, size_t out_len) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; /* sanity check */ if (priv->env.operation != SC_SEC_OPERATION_DECIPHER) return SC_ERROR_INVALID_ARGUMENTS; key_id = priv->rsa_key_ref * 2; /* Private key */ if (out_len < crgram_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* decrypt */ crgram, out, crgram_len, out_len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_compute_signature(sc_card_t *card, const u8 *data, size_t data_len, u8 * out, size_t outlen) { muscle_private_t* priv = MUSCLE_DATA(card); u8 key_id; int r; key_id = priv->rsa_key_ref * 2; /* Private key */ if (outlen < data_len) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Output buffer too small"); return SC_ERROR_BUFFER_TOO_SMALL; } r = msc_compute_crypt(card, key_id, 0x00, /* RSA NO PADDING */ 0x04, /* -- decrypt raw... will do what we need since signing isn't yet supported */ data, out, data_len, outlen); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card signature failed"); return r; } static int muscle_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { if (len == 0) return SC_SUCCESS; else { SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, msc_get_challenge(card, len, 0, NULL, rnd), "GET CHALLENGE cmd failed"); return (int) len; } } static int muscle_check_sw(sc_card_t * card, unsigned int sw1, unsigned int sw2) { if(sw1 == 0x9C) { switch(sw2) { case 0x01: /* SW_NO_MEMORY_LEFT */ return SC_ERROR_NOT_ENOUGH_MEMORY; case 0x02: /* SW_AUTH_FAILED */ return SC_ERROR_PIN_CODE_INCORRECT; case 0x03: /* SW_OPERATION_NOT_ALLOWED */ return SC_ERROR_NOT_ALLOWED; case 0x05: /* SW_UNSUPPORTED_FEATURE */ return SC_ERROR_NO_CARD_SUPPORT; case 0x06: /* SW_UNAUTHORIZED */ return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; case 0x07: /* SW_OBJECT_NOT_FOUND */ return SC_ERROR_FILE_NOT_FOUND; case 0x08: /* SW_OBJECT_EXISTS */ return SC_ERROR_FILE_ALREADY_EXISTS; case 0x09: /* SW_INCORRECT_ALG */ return SC_ERROR_INCORRECT_PARAMETERS; case 0x0B: /* SW_SIGNATURE_INVALID */ return SC_ERROR_CARD_CMD_FAILED; case 0x0C: /* SW_IDENTITY_BLOCKED */ return SC_ERROR_AUTH_METHOD_BLOCKED; case 0x0F: /* SW_INVALID_PARAMETER */ case 0x10: /* SW_INCORRECT_P1 */ case 0x11: /* SW_INCORRECT_P2 */ return SC_ERROR_INCORRECT_PARAMETERS; } } return iso_ops->check_sw(card, sw1, sw2); } static int muscle_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0) { if (msc_select_applet(card, muscleAppletId, sizeof muscleAppletId) != 1) { r = SC_ERROR_INVALID_CARD; } } LOG_FUNC_RETURN(card->ctx, r); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; muscle_ops = *iso_drv->ops; muscle_ops.check_sw = muscle_check_sw; muscle_ops.pin_cmd = muscle_pin_cmd; muscle_ops.match_card = muscle_match_card; muscle_ops.init = muscle_init; muscle_ops.finish = muscle_finish; muscle_ops.get_challenge = muscle_get_challenge; muscle_ops.set_security_env = muscle_set_security_env; muscle_ops.restore_security_env = muscle_restore_security_env; muscle_ops.compute_signature = muscle_compute_signature; muscle_ops.decipher = muscle_decipher; muscle_ops.card_ctl = muscle_card_ctl; muscle_ops.read_binary = muscle_read_binary; muscle_ops.update_binary = muscle_update_binary; muscle_ops.create_file = muscle_create_file; muscle_ops.select_file = muscle_select_file; muscle_ops.delete_file = muscle_delete_file; muscle_ops.list_files = muscle_list_files; muscle_ops.card_reader_lock_obtained = muscle_card_reader_lock_obtained; return &muscle_drv; } struct sc_card_driver * sc_get_muscle_driver(void) { return sc_get_driver(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_347_2
crossvul-cpp_data_bad_348_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_1
crossvul-cpp_data_bad_348_4
/* * PKCS15 emulation layer for EstEID card. * * Copyright (C) 2004, Martin Paljak <martin@martinpaljak.net> * Copyright (C) 2004, Bud P. Bruegger <bud@comune.grosseto.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include "common/compat_strlcpy.h" #include "common/compat_strlcat.h" #include "internal.h" #include "opensc.h" #include "pkcs15.h" #include "esteid.h" int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *, struct sc_aid *, sc_pkcs15emu_opt_t *); static void set_string (char **strp, const char *value) { if (*strp) free (*strp); *strp = value ? strdup (value) : NULL; } int select_esteid_df (sc_card_t * card) { int r; sc_path_t tmppath; sc_format_path ("3F00EEEE", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "esteid select DF failed"); return r; } static int sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card) { sc_card_t *card = p15card->card; unsigned char buff[128]; int r, i; size_t field_length = 0, modulus_length = 0; sc_path_t tmppath; set_string (&p15card->tokeninfo->label, "ID-kaart"); set_string (&p15card->tokeninfo->manufacturer_id, "AS Sertifitseerimiskeskus"); /* Select application directory */ sc_format_path ("3f00eeee5044", &tmppath); r = sc_select_file (card, &tmppath, NULL); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "select esteid PD failed"); /* read the serial (document number) */ r = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "read document number failed"); buff[r] = '\0'; set_string (&p15card->tokeninfo->serial_number, (const char *) buff); p15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION | SC_PKCS15_TOKEN_EID_COMPLIANT | SC_PKCS15_TOKEN_READONLY; /* add certificates */ for (i = 0; i < 2; i++) { static const char *esteid_cert_names[2] = { "Isikutuvastus", "Allkirjastamine"}; static char const *esteid_cert_paths[2] = { "3f00eeeeaace", "3f00eeeeddce"}; static int esteid_cert_ids[2] = {1, 2}; struct sc_pkcs15_cert_info cert_info; struct sc_pkcs15_object cert_obj; memset(&cert_info, 0, sizeof(cert_info)); memset(&cert_obj, 0, sizeof(cert_obj)); cert_info.id.value[0] = esteid_cert_ids[i]; cert_info.id.len = 1; sc_format_path(esteid_cert_paths[i], &cert_info.path); strlcpy(cert_obj.label, esteid_cert_names[i], sizeof(cert_obj.label)); r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info); if (r < 0) return SC_ERROR_INTERNAL; if (i == 0) { sc_pkcs15_cert_t *cert = NULL; r = sc_pkcs15_read_certificate(p15card, &cert_info, &cert); if (r < 0) return SC_ERROR_INTERNAL; if (cert->key->algorithm == SC_ALGORITHM_EC) field_length = cert->key->u.ec.params.field_length; else modulus_length = cert->key->u.rsa.modulus.len * 8; if (r == SC_SUCCESS) { static const struct sc_object_id cn_oid = {{ 2, 5, 4, 3, -1 }}; u8 *cn_name = NULL; size_t cn_len = 0; sc_pkcs15_get_name_from_dn(card->ctx, cert->subject, cert->subject_len, &cn_oid, &cn_name, &cn_len); if (cn_len > 0) { char *token_name = malloc(cn_len+1); if (token_name) { memcpy(token_name, cn_name, cn_len); token_name[cn_len] = '\0'; set_string(&p15card->tokeninfo->label, (const char*)token_name); free(token_name); } } free(cn_name); sc_pkcs15_free_certificate(cert); } } } /* the file with key pin info (tries left) */ sc_format_path ("3f000016", &tmppath); r = sc_select_file (card, &tmppath, NULL); if (r < 0) return SC_ERROR_INTERNAL; /* add pins */ for (i = 0; i < 3; i++) { unsigned char tries_left; static const char *esteid_pin_names[3] = { "PIN1", "PIN2", "PUK" }; static const int esteid_pin_min[3] = {4, 5, 8}; static const int esteid_pin_ref[3] = {1, 2, 0}; static const int esteid_pin_authid[3] = {1, 2, 3}; static const int esteid_pin_flags[3] = {0, 0, SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN}; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; memset(&pin_info, 0, sizeof(pin_info)); memset(&pin_obj, 0, sizeof(pin_obj)); /* read the number of tries left for the PIN */ r = sc_read_record (card, i + 1, buff, sizeof(buff), SC_RECORD_BY_REC_NR); if (r < 0) return SC_ERROR_INTERNAL; tries_left = buff[5]; pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = esteid_pin_authid[i]; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = esteid_pin_ref[i]; pin_info.attrs.pin.flags = esteid_pin_flags[i]; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = esteid_pin_min[i]; pin_info.attrs.pin.stored_length = 12; pin_info.attrs.pin.max_length = 12; pin_info.attrs.pin.pad_char = '\0'; pin_info.tries_left = (int)tries_left; pin_info.max_tries = 3; strlcpy(pin_obj.label, esteid_pin_names[i], sizeof(pin_obj.label)); pin_obj.flags = esteid_pin_flags[i]; /* Link normal PINs with PUK */ if (i < 2) { pin_obj.auth_id.len = 1; pin_obj.auth_id.value[0] = 3; } r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if (r < 0) return SC_ERROR_INTERNAL; } /* add private keys */ for (i = 0; i < 2; i++) { static int prkey_pin[2] = {1, 2}; static const char *prkey_name[2] = { "Isikutuvastus", "Allkirjastamine"}; struct sc_pkcs15_prkey_info prkey_info; struct sc_pkcs15_object prkey_obj; memset(&prkey_info, 0, sizeof(prkey_info)); memset(&prkey_obj, 0, sizeof(prkey_obj)); prkey_info.id.len = 1; prkey_info.id.value[0] = prkey_pin[i]; prkey_info.native = 1; prkey_info.key_reference = i + 1; prkey_info.field_length = field_length; prkey_info.modulus_length = modulus_length; if (i == 1) prkey_info.usage = SC_PKCS15_PRKEY_USAGE_NONREPUDIATION; else if(field_length > 0) // ECC has sign and derive usage prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_DERIVE; else prkey_info.usage = SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT; strlcpy(prkey_obj.label, prkey_name[i], sizeof(prkey_obj.label)); prkey_obj.auth_id.len = 1; prkey_obj.auth_id.value[0] = prkey_pin[i]; prkey_obj.user_consent = 0; prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if(field_length > 0) r = sc_pkcs15emu_add_ec_prkey(p15card, &prkey_obj, &prkey_info); else r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info); if (r < 0) return SC_ERROR_INTERNAL; } return SC_SUCCESS; } static int esteid_detect_card(sc_pkcs15_card_t *p15card) { if (is_esteid_card(p15card->card)) return SC_SUCCESS; else return SC_ERROR_WRONG_CARD; } int sc_pkcs15emu_esteid_init_ex(sc_pkcs15_card_t *p15card, struct sc_aid *aid, sc_pkcs15emu_opt_t *opts) { if (opts && opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK) return sc_pkcs15emu_esteid_init(p15card); else { int r = esteid_detect_card(p15card); if (r) return SC_ERROR_WRONG_CARD; return sc_pkcs15emu_esteid_init(p15card); } }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_348_4
crossvul-cpp_data_good_348_1
/* * Support for ePass2003 smart cards * * Copyright (C) 2008, Weitao Sun <weitao@ftsafe.com> * Copyright (C) 2011, Xiaoshuo Wu <xiaoshuo@ftsafe.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #ifdef ENABLE_SM /* empty file without SM enabled */ #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/sha.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table epass2003_atrs[] = { /* This is a FIPS certified card using SCP01 security messaging. */ {"3B:9F:95:81:31:FE:9F:00:66:46:53:05:10:00:11:71:df:00:00:00:6a:82:5e", "FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:ff:00:ff:ff:00:00:00:00", "FTCOS/ePass2003", SC_CARD_TYPE_ENTERSAFE_FTCOS_EPASS2003, 0, NULL }, {NULL, NULL, NULL, 0, 0, NULL} }; static struct sc_card_operations *iso_ops = NULL; static struct sc_card_operations epass2003_ops; static struct sc_card_driver epass2003_drv = { "epass2003", "epass2003", &epass2003_ops, NULL, 0, NULL }; #define KEY_TYPE_AES 0x01 /* FIPS mode */ #define KEY_TYPE_DES 0x02 /* Non-FIPS mode */ #define KEY_LEN_AES 16 #define KEY_LEN_DES 8 #define KEY_LEN_DES3 24 #define HASH_LEN 24 static unsigned char PIN_ID[2] = { ENTERSAFE_USER_PIN_ID, ENTERSAFE_SO_PIN_ID }; /*0x00:plain; 0x01:scp01 sm*/ #define SM_PLAIN 0x00 #define SM_SCP01 0x01 static unsigned char g_init_key_enc[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_init_key_mac[16] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; static unsigned char g_random[8] = { 0xBF, 0xC3, 0x29, 0x11, 0xC7, 0x18, 0xC3, 0x40 }; typedef struct epass2003_exdata_st { unsigned char sm; /* SM_PLAIN or SM_SCP01 */ unsigned char smtype; /* KEY_TYPE_AES or KEY_TYPE_DES */ unsigned char sk_enc[16]; /* encrypt session key */ unsigned char sk_mac[16]; /* mac session key */ unsigned char icv_mac[16]; /* instruction counter vector(for sm) */ unsigned char currAlg; /* current Alg */ unsigned int ecAlgFlags; /* Ec Alg mechanism type*/ } epass2003_exdata; #define REVERSE_ORDER4(x) ( \ ((unsigned long)x & 0xFF000000)>> 24 | \ ((unsigned long)x & 0x00FF0000)>> 8 | \ ((unsigned long)x & 0x0000FF00)<< 8 | \ ((unsigned long)x & 0x000000FF)<< 24) static const struct sc_card_error epass2003_errors[] = { { 0x6200, SC_ERROR_CARD_CMD_FAILED, "Warning: no information given, non-volatile memory is unchanged" }, { 0x6281, SC_ERROR_CORRUPTED_DATA, "Part of returned data may be corrupted" }, { 0x6282, SC_ERROR_FILE_END_REACHED, "End of file/record reached before reading Le bytes" }, { 0x6283, SC_ERROR_CARD_CMD_FAILED, "Selected file invalidated" }, { 0x6284, SC_ERROR_CARD_CMD_FAILED, "FCI not formatted according to ISO 7816-4" }, { 0x6300, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C1, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. One tries left"}, { 0x63C2, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed. Two tries left"}, { 0x63C3, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C4, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C5, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C6, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C7, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C8, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63C9, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x63CA, SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed"}, { 0x6381, SC_ERROR_CARD_CMD_FAILED, "Warning: file filled up by last write" }, { 0x6581, SC_ERROR_MEMORY_FAILURE, "Memory failure" }, { 0x6700, SC_ERROR_WRONG_LENGTH, "Wrong length" }, { 0x6800, SC_ERROR_NO_CARD_SUPPORT, "Functions in CLA not supported" }, { 0x6881, SC_ERROR_NO_CARD_SUPPORT, "Logical channel not supported" }, { 0x6882, SC_ERROR_NO_CARD_SUPPORT, "Secure messaging not supported" }, { 0x6900, SC_ERROR_NOT_ALLOWED, "Command not allowed" }, { 0x6981, SC_ERROR_CARD_CMD_FAILED, "Command incompatible with file structure" }, { 0x6982, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Security status not satisfied" }, { 0x6983, SC_ERROR_AUTH_METHOD_BLOCKED, "Authentication method blocked" }, { 0x6984, SC_ERROR_REF_DATA_NOT_USABLE, "Referenced data not usable" }, { 0x6985, SC_ERROR_NOT_ALLOWED, "Conditions of use not satisfied" }, { 0x6986, SC_ERROR_NOT_ALLOWED, "Command not allowed (no current EF)" }, { 0x6987, SC_ERROR_INCORRECT_PARAMETERS,"Expected SM data objects missing" }, { 0x6988, SC_ERROR_INCORRECT_PARAMETERS,"SM data objects incorrect" }, { 0x6A00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6A80, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters in the data field" }, { 0x6A81, SC_ERROR_NO_CARD_SUPPORT, "Function not supported" }, { 0x6A82, SC_ERROR_FILE_NOT_FOUND, "File not found" }, { 0x6A83, SC_ERROR_RECORD_NOT_FOUND, "Record not found" }, { 0x6A84, SC_ERROR_NOT_ENOUGH_MEMORY, "Not enough memory space in the file" }, { 0x6A85, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with TLV structure" }, { 0x6A86, SC_ERROR_INCORRECT_PARAMETERS,"Incorrect parameters P1-P2" }, { 0x6A87, SC_ERROR_INCORRECT_PARAMETERS,"Lc inconsistent with P1-P2" }, { 0x6A88, SC_ERROR_DATA_OBJECT_NOT_FOUND,"Referenced data not found" }, { 0x6A89, SC_ERROR_FILE_ALREADY_EXISTS, "File already exists"}, { 0x6A8A, SC_ERROR_FILE_ALREADY_EXISTS, "DF name already exists"}, { 0x6B00, SC_ERROR_INCORRECT_PARAMETERS,"Wrong parameter(s) P1-P2" }, { 0x6D00, SC_ERROR_INS_NOT_SUPPORTED, "Instruction code not supported or invalid" }, { 0x6E00, SC_ERROR_CLASS_NOT_SUPPORTED, "Class not supported" }, { 0x6F00, SC_ERROR_CARD_CMD_FAILED, "No precise diagnosis" }, { 0x9000,SC_SUCCESS, NULL } }; static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu); static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out); int epass2003_refresh(struct sc_card *card); static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType); static int epass2003_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { const int err_count = sizeof(epass2003_errors)/sizeof(epass2003_errors[0]); int i; /* Handle special cases here */ if (sw1 == 0x6C) { sc_log(card->ctx, "Wrong length; correct length is %d", sw2); return SC_ERROR_WRONG_LENGTH; } for (i = 0; i < err_count; i++) { if (epass2003_errors[i].SWs == ((sw1 << 8) | sw2)) { sc_log(card->ctx, "%s", epass2003_errors[i].errorstr); return epass2003_errors[i].errorno; } } sc_log(card->ctx, "Unknown SWs; SW1=%02X, SW2=%02X", sw1, sw2); return SC_ERROR_CARD_CMD_FAILED; } static int sc_transmit_apdu_t(sc_card_t *card, sc_apdu_t *apdu) { int r = sc_transmit_apdu(card, apdu); if ( ((0x69 == apdu->sw1) && (0x85 == apdu->sw2)) || ((0x69 == apdu->sw1) && (0x88 == apdu->sw2))) { epass2003_refresh(card); r = sc_transmit_apdu(card, apdu); } return r; } static int openssl_enc(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_EncryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_EncryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_EncryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int openssl_dec(const EVP_CIPHER * cipher, const unsigned char *key, const unsigned char *iv, const unsigned char *input, size_t length, unsigned char *output) { int r = SC_ERROR_INTERNAL; EVP_CIPHER_CTX * ctx = NULL; int outl = 0; int outl_tmp = 0; unsigned char iv_tmp[EVP_MAX_IV_LENGTH] = { 0 }; memcpy(iv_tmp, iv, EVP_MAX_IV_LENGTH); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto out; EVP_DecryptInit_ex(ctx, cipher, NULL, key, iv_tmp); EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_DecryptUpdate(ctx, output, &outl, input, length)) goto out; if (!EVP_DecryptFinal_ex(ctx, output + outl, &outl_tmp)) goto out; r = SC_SUCCESS; out: if (ctx) EVP_CIPHER_CTX_free(ctx); return r; } static int aes128_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, size_t length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; return openssl_enc(EVP_aes_128_ecb(), key, iv, input, length, output); } static int aes128_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_aes_128_cbc(), key, iv, input, length, output); } static int aes128_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[16], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_aes_128_cbc(), key, iv, input, length, output); } static int des3_encrypt_ecb(const unsigned char *key, int keysize, const unsigned char *input, int length, unsigned char *output) { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3(), bKey, iv, input, length, output); } static int des3_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_enc(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des3_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { unsigned char bKey[24] = { 0 }; if (keysize == 16) { memcpy(&bKey[0], key, 16); memcpy(&bKey[16], key, 8); } else { memcpy(&bKey[0], key, 24); } return openssl_dec(EVP_des_ede3_cbc(), bKey, iv, input, length, output); } static int des_encrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_enc(EVP_des_cbc(), key, iv, input, length, output); } static int des_decrypt_cbc(const unsigned char *key, int keysize, unsigned char iv[EVP_MAX_IV_LENGTH], const unsigned char *input, size_t length, unsigned char *output) { return openssl_dec(EVP_des_cbc(), key, iv, input, length, output); } static int openssl_dig(const EVP_MD * digest, const unsigned char *input, size_t length, unsigned char *output) { int r = 0; EVP_MD_CTX *ctx = NULL; unsigned outl = 0; ctx = EVP_MD_CTX_create(); if (ctx == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } EVP_MD_CTX_init(ctx); EVP_DigestInit_ex(ctx, digest, NULL); if (!EVP_DigestUpdate(ctx, input, length)) { r = SC_ERROR_INTERNAL; goto err; } if (!EVP_DigestFinal_ex(ctx, output, &outl)) { r = SC_ERROR_INTERNAL; goto err; } r = SC_SUCCESS; err: if (ctx) EVP_MD_CTX_destroy(ctx); return r; } static int sha1_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha1(), input, length, output); } static int sha256_digest(const unsigned char *input, size_t length, unsigned char *output) { return openssl_dig(EVP_sha256(), input, length, output); } static int gen_init_key(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac, unsigned char *result, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned char data[256] = { 0 }; unsigned char tmp_sm; unsigned long blocksize = 0; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x50, 0x00, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = sizeof(g_random); apdu.data = g_random; /* host random */ apdu.le = apdu.resplen = 28; apdu.resp = result; /* card random is result[12~19] */ tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU gen_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "gen_init_key failed"); /* Step 1 - Generate Derivation data */ memcpy(data, &result[16], 4); memcpy(&data[4], g_random, 4); memcpy(&data[8], &result[12], 4); memcpy(&data[12], &g_random[4], 4); /* Step 2,3 - Create S-ENC/S-MAC Session Key */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); aes128_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } else { des3_encrypt_ecb(key_enc, 16, data, 16, exdata->sk_enc); des3_encrypt_ecb(key_mac, 16, data, 16, exdata->sk_mac); } memcpy(data, g_random, 8); memcpy(&data[8], &result[12], 8); data[16] = 0x80; blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); memset(&data[17], 0x00, blocksize - 1); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); /* verify card cryptogram */ if (0 != memcmp(&cryptogram[16], &result[20], 8)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int verify_init_key(struct sc_card *card, unsigned char *ran_key, unsigned char key_type) { int r; struct sc_apdu apdu; unsigned long blocksize = (key_type == KEY_TYPE_AES ? 16 : 8); unsigned char data[256] = { 0 }; unsigned char cryptogram[256] = { 0 }; /* host cryptogram */ unsigned char iv[16] = { 0 }; unsigned char mac[256] = { 0 }; unsigned long i; unsigned char tmp_sm; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); memcpy(data, ran_key, 8); memcpy(&data[8], g_random, 8); data[16] = 0x80; memset(&data[17], 0x00, blocksize - 1); memset(iv, 0, 16); /* calculate host cryptogram */ if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } else { des3_encrypt_cbc(exdata->sk_enc, 16, iv, data, 16 + blocksize, cryptogram); } memset(data, 0, sizeof(data)); memcpy(data, "\x84\x82\x03\x00\x10", 5); memcpy(&data[5], &cryptogram[16], 8); memcpy(&data[13], "\x80\x00\x00", 3); /* calculate mac icv */ memset(iv, 0x00, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 0; } else { des3_encrypt_cbc(exdata->sk_mac, 16, iv, data, 16, mac); i = 8; } /* save mac icv */ memset(exdata->icv_mac, 0x00, 16); memcpy(exdata->icv_mac, &mac[i], 8); /* verify host cryptogram */ memcpy(data, &cryptogram[16], 8); memcpy(&data[8], &mac[i], 8); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x03, 0x00); apdu.cla = 0x84; apdu.lc = apdu.datalen = 16; apdu.data = data; tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = epass2003_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; LOG_TEST_RET(card->ctx, r, "APDU verify_init_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "verify_init_key failed"); return r; } static int mutual_auth(struct sc_card *card, unsigned char *key_enc, unsigned char *key_mac) { struct sc_context *ctx = card->ctx; int r; unsigned char result[256] = { 0 }; unsigned char ran_key[8] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(ctx); r = gen_init_key(card, key_enc, key_mac, result, exdata->smtype); LOG_TEST_RET(ctx, r, "gen_init_key failed"); memcpy(ran_key, &result[12], 8); r = verify_init_key(card, ran_key, exdata->smtype); LOG_TEST_RET(ctx, r, "verify_init_key failed"); LOG_FUNC_RETURN(ctx, r); } int epass2003_refresh(struct sc_card *card) { int r = SC_SUCCESS; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (exdata->sm) { card->sm_ctx.sm_mode = 0; r = mutual_auth(card, g_init_key_enc, g_init_key_mac); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; LOG_TEST_RET(card->ctx, r, "mutual_auth failed"); } return r; } /* Data(TLV)=0x87|L|0x01+Cipher */ static int construct_data_tlv(struct sc_card *card, struct sc_apdu *apdu, unsigned char *apdu_buf, unsigned char *data_tlv, size_t * data_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char pad[4096] = { 0 }; size_t pad_len; size_t tlv_more; /* increased tlv length */ unsigned char iv[16] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* padding */ apdu_buf[block_size] = 0x87; memcpy(pad, apdu->data, apdu->lc); pad[apdu->lc] = 0x80; if ((apdu->lc + 1) % block_size) pad_len = ((apdu->lc + 1) / block_size + 1) * block_size; else pad_len = apdu->lc + 1; /* encode Lc' */ if (pad_len > 0x7E) { /* Lc' > 0x7E, use extended APDU */ apdu_buf[block_size + 1] = 0x82; apdu_buf[block_size + 2] = (unsigned char)((pad_len + 1) / 0x100); apdu_buf[block_size + 3] = (unsigned char)((pad_len + 1) % 0x100); apdu_buf[block_size + 4] = 0x01; tlv_more = 5; } else { apdu_buf[block_size + 1] = (unsigned char)pad_len + 1; apdu_buf[block_size + 2] = 0x01; tlv_more = 3; } memcpy(data_tlv, &apdu_buf[block_size], tlv_more); /* encrypt Data */ if (KEY_TYPE_AES == key_type) aes128_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); else des3_encrypt_cbc(exdata->sk_enc, 16, iv, pad, pad_len, apdu_buf + block_size + tlv_more); memcpy(data_tlv + tlv_more, apdu_buf + block_size + tlv_more, pad_len); *data_tlv_len = tlv_more + pad_len; return 0; } /* Le(TLV)=0x97|L|Le */ static int construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } /* MAC(TLV)=0x8e|0x08|MAC */ static int construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, sizeof iv); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } /* According to GlobalPlatform Card Specification's SCP01 * encode APDU from * CLA INS P1 P2 [Lc] Data [Le] * to * CLA INS P1 P2 Lc' Data' [Le] * where * Data'=Data(TLV)+Le(TLV)+MAC(TLV) */ static int encode_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm, unsigned char *apdu_buf, size_t * apdu_buf_len) { size_t block_size = 0; unsigned char dataTLV[4096] = { 0 }; size_t data_tlv_len = 0; unsigned char le_tlv[256] = { 0 }; size_t le_tlv_len = 0; size_t mac_tlv_len = 10; size_t tmp_lc = 0; size_t tmp_le = 0; unsigned char mac_tlv[256] = { 0 }; epass2003_exdata *exdata = NULL; mac_tlv[0] = 0x8E; mac_tlv[1] = 8; /* size_t plain_le = 0; */ if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata*)card->drv_data; block_size = (KEY_TYPE_DES == exdata->smtype ? 16 : 8); sm->cse = SC_APDU_CASE_4_SHORT; apdu_buf[0] = (unsigned char)plain->cla; apdu_buf[1] = (unsigned char)plain->ins; apdu_buf[2] = (unsigned char)plain->p1; apdu_buf[3] = (unsigned char)plain->p2; /* plain_le = plain->le; */ /* padding */ apdu_buf[4] = 0x80; memset(&apdu_buf[5], 0x00, block_size - 5); /* Data -> Data' */ if (plain->lc != 0) if (0 != construct_data_tlv(card, plain, apdu_buf, dataTLV, &data_tlv_len, exdata->smtype)) return -1; if (plain->le != 0 || (plain->le == 0 && plain->resplen != 0)) if (0 != construct_le_tlv(plain, apdu_buf, data_tlv_len, le_tlv, &le_tlv_len, exdata->smtype)) return -1; if (0 != construct_mac_tlv(card, apdu_buf, data_tlv_len, le_tlv_len, mac_tlv, &mac_tlv_len, exdata->smtype)) return -1; memset(apdu_buf + 4, 0, *apdu_buf_len - 4); sm->lc = sm->datalen = data_tlv_len + le_tlv_len + mac_tlv_len; if (sm->lc > 0xFF) { sm->cse = SC_APDU_CASE_4_EXT; apdu_buf[4] = (unsigned char)((sm->lc) / 0x10000); apdu_buf[5] = (unsigned char)(((sm->lc) / 0x100) % 0x100); apdu_buf[6] = (unsigned char)((sm->lc) % 0x100); tmp_lc = 3; } else { apdu_buf[4] = (unsigned char)sm->lc; tmp_lc = 1; } memcpy(apdu_buf + 4 + tmp_lc, dataTLV, data_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len, le_tlv, le_tlv_len); memcpy(apdu_buf + 4 + tmp_lc + data_tlv_len + le_tlv_len, mac_tlv, mac_tlv_len); memcpy((unsigned char *)sm->data, apdu_buf + 4 + tmp_lc, sm->datalen); *apdu_buf_len = 0; if (4 == le_tlv_len) { sm->cse = SC_APDU_CASE_4_EXT; *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)(plain->le / 0x100); *(apdu_buf + 4 + tmp_lc + sm->lc + 1) = (unsigned char)(plain->le % 0x100); tmp_le = 2; } else if (3 == le_tlv_len) { *(apdu_buf + 4 + tmp_lc + sm->lc) = (unsigned char)plain->le; tmp_le = 1; } *apdu_buf_len += 4 + tmp_lc + data_tlv_len + le_tlv_len + mac_tlv_len + tmp_le; /* sm->le = calc_le(plain_le); */ return 0; } static int epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu *sm) { unsigned char buf[4096] = { 0 }; /* APDU buffer */ size_t buf_len = sizeof(buf); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); if (exdata->sm) plain->cla |= 0x0C; sm->cse = plain->cse; sm->cla = plain->cla; sm->ins = plain->ins; sm->p1 = plain->p1; sm->p2 = plain->p2; sm->lc = plain->lc; sm->le = plain->le; sm->control = plain->control; sm->flags = plain->flags; switch (sm->cla & 0x0C) { case 0x00: case 0x04: sm->datalen = plain->datalen; memcpy((void *)sm->data, plain->data, plain->datalen); sm->resplen = plain->resplen; memcpy(sm->resp, plain->resp, plain->resplen); break; case 0x0C: memset(buf, 0, sizeof(buf)); if (0 != encode_apdu(card, plain, sm, buf, &buf_len)) return SC_ERROR_CARD_CMD_FAILED; break; default: return SC_ERROR_INCORRECT_PARAMETERS; } return SC_SUCCESS; } /* According to GlobalPlatform Card Specification's SCP01 * decrypt APDU response from * ResponseData' SW1 SW2 * to * ResponseData SW1 SW2 * where * ResponseData'=Data(TLV)+SW12(TLV)+MAC(TLV) * where * Data(TLV)=0x87|L|Cipher * SW12(TLV)=0x99|0x02|SW1+SW2 * MAC(TLV)=0x8e|0x08|MAC */ static int decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } static int epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { len = plain->resplen; if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) rv = epass2003_sm_unwrap_apdu(card, *sm_apdu, plain); if ((*sm_apdu)->data) { unsigned char * p = (unsigned char *)((*sm_apdu)->data); free(p); } if ((*sm_apdu)->resp) { free((*sm_apdu)->resp); } free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, rv); } static int epass2003_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); *sm_apdu = NULL; //construct new SM apdu from original apdu apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->data = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->data) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->resp = calloc (1, SC_MAX_EXT_APDU_BUFFER_SIZE); if (!apdu->resp) { rv = SC_ERROR_OUT_OF_MEMORY; goto err; } apdu->datalen = SC_MAX_EXT_APDU_BUFFER_SIZE; apdu->resplen = SC_MAX_EXT_APDU_BUFFER_SIZE; rv = epass2003_sm_wrap_apdu(card, plain, apdu); if (rv) { rv = epass2003_sm_free_wrapped_apdu(card, NULL, &apdu); if (rv < 0) goto err; } *sm_apdu = apdu; apdu = NULL; err: if (apdu) { free((unsigned char *) apdu->data); free(apdu->resp); free(apdu); apdu = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int epass2003_transmit_apdu(struct sc_card *card, struct sc_apdu *apdu) { int r; LOG_FUNC_CALLED(card->ctx); r = sc_transmit_apdu_t(card, apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return r; } static int get_data(struct sc_card *card, unsigned char type, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t resplen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, type); apdu.resp = resp; apdu.le = 0; apdu.resplen = resplen; if (0x86 == type) { /* No SM temporarily */ unsigned char tmp_sm = exdata->sm; exdata->sm = SM_PLAIN; r = sc_transmit_apdu(card, &apdu); exdata->sm = tmp_sm; } else { r = sc_transmit_apdu_t(card, &apdu); } LOG_TEST_RET(card->ctx, r, "APDU get_data failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get_data failed"); memcpy(data, resp, datalen); return r; } /* card driver functions */ static int epass2003_match_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); r = _sc_match_atr(card, epass2003_atrs, &card->type); if (r < 0) return 0; return 1; } static int epass2003_init(struct sc_card *card) { unsigned int flags; unsigned int ext_flags; unsigned char data[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; size_t datalen = SC_MAX_APDU_BUFFER_SIZE; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); card->name = "epass2003"; card->cla = 0x00; exdata = (epass2003_exdata *)calloc(1, sizeof(epass2003_exdata)); if (!exdata) return SC_ERROR_OUT_OF_MEMORY; card->drv_data = exdata; exdata->sm = SM_SCP01; /* decide FIPS/Non-FIPS mode */ if (SC_SUCCESS != get_data(card, 0x86, data, datalen)) return SC_ERROR_INVALID_CARD; if (0x01 == data[2]) exdata->smtype = KEY_TYPE_AES; else exdata->smtype = KEY_TYPE_DES; if (0x84 == data[14]) { if (0x00 == data[16]) { exdata->sm = SM_PLAIN; } } /* mutual authentication */ card->max_recv_size = 0xD8; card->max_send_size = 0xE8; card->sm_ctx.ops.open = epass2003_refresh; card->sm_ctx.ops.get_sm_apdu = epass2003_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = epass2003_sm_free_wrapped_apdu; /* FIXME (VT): rather then set/unset 'g_sm', better to implement filter for APDUs to be wrapped */ epass2003_refresh(card); card->sm_ctx.sm_mode = SM_MODE_TRANSMIT; flags = SC_ALGORITHM_ONBOARD_KEY_GEN | SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); //set EC Alg Flags flags = SC_ALGORITHM_ONBOARD_KEY_GEN|SC_ALGORITHM_ECDSA_HASH_SHA1|SC_ALGORITHM_ECDSA_HASH_SHA256|SC_ALGORITHM_ECDSA_HASH_NONE|SC_ALGORITHM_ECDSA_RAW; ext_flags = 0; _sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL); card->caps = SC_CARD_CAP_RNG | SC_CARD_CAP_APDU_EXT; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_finish(sc_card_t *card) { epass2003_exdata *exdata = (epass2003_exdata *)card->drv_data; if (exdata) free(exdata); return SC_SUCCESS; } /* COS implement SFI as lower 5 bits of FID, and not allow same SFI at the * same DF, so use hook functions to increase/decrease FID by 0x20 */ static int epass2003_hook_path(struct sc_path *path, int inc) { u8 fid_h = path->value[path->len - 2]; u8 fid_l = path->value[path->len - 1]; switch (fid_h) { case 0x29: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: if (inc) fid_l = fid_l * FID_STEP; else fid_l = fid_l / FID_STEP; path->value[path->len - 1] = fid_l; return 1; default: break; } return 0; } static void epass2003_hook_file(struct sc_file *file, int inc) { int fidl = file->id & 0xff; int fidh = file->id & 0xff00; if (epass2003_hook_path(&file->path, inc)) { if (inc) file->id = fidh + fidl * FID_STEP; else file->id = fidh + fidl / FID_STEP; } } static int epass2003_select_fid_(struct sc_card *card, sc_path_t * in_path, sc_file_t ** file_out) { struct sc_apdu apdu; u8 buf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; sc_file_t *file = NULL; epass2003_hook_path(in_path, 1); memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: apdu.p1 = 0; if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } apdu.p2 = 0; /* first record, return FCI */ apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 0; } else { apdu.cse = (apdu.lc == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } if (path[0] == 0x29) { /* TODO:0x29 accords with FID prefix in profile */ /* Not allowed to select private key file, so fake fci. */ /* 62 16 82 02 11 00 83 02 29 00 85 02 08 00 86 08 FF 90 90 90 FF FF FF FF */ apdu.resplen = 0x18; memcpy(apdu.resp, "\x6f\x16\x82\x02\x11\x00\x83\x02\x29\x00\x85\x02\x08\x00\x86\x08\xff\x90\x90\x90\xff\xff\xff\xff", apdu.resplen); apdu.resp[9] = path[1]; apdu.sw1 = 0x90; apdu.sw2 = 0x00; } else { r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); } if (file_out == NULL) { if (apdu.sw1 == 0x61) LOG_FUNC_RETURN(card->ctx, 0); LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) LOG_FUNC_RETURN(card->ctx, r); if (apdu.resplen < 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); switch (apdu.resp[0]) { case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->path = *in_path; if (card->ops->process_fci == NULL) { sc_file_free(file); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } if ((size_t) apdu.resp[1] + 2 <= apdu.resplen) card->ops->process_fci(card, file, apdu.resp + 2, apdu.resp[1]); epass2003_hook_file(file, 0); *file_out = file; break; case 0x00: /* proprietary coding */ LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); break; default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } return 0; } static int epass2003_select_fid(struct sc_card *card, unsigned int id_hi, unsigned int id_lo, sc_file_t ** file_out) { int r; sc_file_t *file = 0; sc_path_t path; memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_FILE_ID; path.value[0] = id_hi; path.value[1] = id_lo; path.len = 2; r = epass2003_select_fid_(card, &path, &file); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ if (file && file->type == SC_FILE_TYPE_DF) { card->cache.current_path.type = SC_PATH_TYPE_PATH; card->cache.current_path.value[0] = 0x3f; card->cache.current_path.value[1] = 0x00; if (id_hi == 0x3f && id_lo == 0x00) { card->cache.current_path.len = 2; } else { card->cache.current_path.len = 4; card->cache.current_path.value[2] = id_hi; card->cache.current_path.value[3] = id_lo; } } if (file_out) *file_out = file; LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_select_aid(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r = 0; if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_DF_NAME && card->cache.current_path.len == in_path->len && memcmp(card->cache.current_path.value, in_path->value, in_path->len) == 0) { if (file_out) { *file_out = sc_file_new(); if (!file_out) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); } } else { r = iso_ops->select_file(card, in_path, file_out); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); /* update cache */ card->cache.current_path.type = SC_PATH_TYPE_DF_NAME; card->cache.current_path.len = in_path->len; memcpy(card->cache.current_path.value, in_path->value, in_path->len); } if (file_out) { sc_file_t *file = *file_out; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->path.len = 0; file->size = 0; /* AID */ memcpy(file->name, in_path->value, in_path->len); file->namelen = in_path->len; file->id = 0x0000; } LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_select_path(struct sc_card *card, const u8 pathbuf[16], const size_t len, sc_file_t ** file_out) { u8 n_pathbuf[SC_MAX_PATH_SIZE]; const u8 *path = pathbuf; size_t pathlen = len; int bMatch = -1; unsigned int i; int r; if (pathlen % 2 != 0 || pathlen > 6 || pathlen <= 0) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* if pathlen == 6 then the first FID must be MF (== 3F00) */ if (pathlen == 6 && (path[0] != 0x3f || path[1] != 0x00)) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); /* unify path (the first FID should be MF) */ if (path[0] != 0x3f || path[1] != 0x00) { n_pathbuf[0] = 0x3f; n_pathbuf[1] = 0x00; for (i = 0; i < pathlen; i++) n_pathbuf[i + 2] = pathbuf[i]; path = n_pathbuf; pathlen += 2; } /* check current working directory */ if (card->cache.valid && card->cache.current_path.type == SC_PATH_TYPE_PATH && card->cache.current_path.len >= 2 && card->cache.current_path.len <= pathlen) { bMatch = 0; for (i = 0; i < card->cache.current_path.len; i += 2) if (card->cache.current_path.value[i] == path[i] && card->cache.current_path.value[i + 1] == path[i + 1]) bMatch += 2; } if (card->cache.valid && bMatch > 2) { if (pathlen - bMatch == 2) { /* we are in the right directory */ return epass2003_select_fid(card, path[bMatch], path[bMatch + 1], file_out); } else if (pathlen - bMatch > 2) { /* two more steps to go */ sc_path_t new_path; /* first step: change directory */ r = epass2003_select_fid(card, path[bMatch], path[bMatch + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); new_path.type = SC_PATH_TYPE_PATH; new_path.len = pathlen - bMatch - 2; memcpy(new_path.value, &(path[bMatch + 2]), new_path.len); /* final step: select file */ return epass2003_select_file(card, &new_path, file_out); } else { /* if (bMatch - pathlen == 0) */ /* done: we are already in the * requested directory */ sc_log(card->ctx, "cache hit\n"); /* copy file info (if necessary) */ if (file_out) { sc_file_t *file = sc_file_new(); if (!file) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); file->id = (path[pathlen - 2] << 8) + path[pathlen - 1]; file->path = card->cache.current_path; file->type = SC_FILE_TYPE_DF; file->ef_structure = SC_FILE_EF_UNKNOWN; file->size = 0; file->namelen = 0; file->magic = SC_FILE_MAGIC; *file_out = file; } /* nothing left to do */ return SC_SUCCESS; } } else { /* no usable cache */ for (i = 0; i < pathlen - 2; i += 2) { r = epass2003_select_fid(card, path[i], path[i + 1], NULL); LOG_TEST_RET(card->ctx, r, "SELECT FILE (DF-ID) failed"); } return epass2003_select_fid(card, path[pathlen - 2], path[pathlen - 1], file_out); } } static int epass2003_select_file(struct sc_card *card, const sc_path_t * in_path, sc_file_t ** file_out) { int r; char pbuf[SC_MAX_PATH_STRING_SIZE]; LOG_FUNC_CALLED(card->ctx); r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path); if (r != SC_SUCCESS) pbuf[0] = '\0'; sc_log(card->ctx, "current path (%s, %s): %s (len: %"SC_FORMAT_LEN_SIZE_T"u)\n", card->cache.current_path.type == SC_PATH_TYPE_DF_NAME ? "aid" : "path", card->cache.valid ? "valid" : "invalid", pbuf, card->cache.current_path.len); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (in_path->len != 2) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); return epass2003_select_fid(card, in_path->value[0], in_path->value[1], file_out); case SC_PATH_TYPE_DF_NAME: return epass2003_select_aid(card, in_path, file_out); case SC_PATH_TYPE_PATH: return epass2003_select_path(card, in_path->value, in_path->len, file_out); default: LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } } static int epass2003_set_security_env(struct sc_card *card, const sc_security_env_t * env, int se_num) { struct sc_apdu apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 *p; unsigned short fid = 0; int r, locked = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, 0); p = sbuf; *p++ = 0x80; /* algorithm reference */ *p++ = 0x01; *p++ = 0x84; *p++ = 0x81; *p++ = 0x02; fid = 0x2900; fid += (unsigned short)(0x20 * (env->key_ref[0] & 0xff)); *p++ = fid >> 8; *p++ = fid & 0xff; r = p - sbuf; apdu.lc = r; apdu.datalen = r; apdu.data = sbuf; if (env->algorithm == SC_ALGORITHM_EC) { apdu.p2 = 0xB6; exdata->currAlg = SC_ALGORITHM_EC; if(env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA1) { sbuf[2] = 0x91; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA1; } else if (env->algorithm_flags & SC_ALGORITHM_ECDSA_HASH_SHA256) { sbuf[2] = 0x92; exdata->ecAlgFlags = SC_ALGORITHM_ECDSA_HASH_SHA256; } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm_flags); goto err; } } else if(env->algorithm == SC_ALGORITHM_RSA) { exdata->currAlg = SC_ALGORITHM_RSA; apdu.p2 = 0xB8; sc_log(card->ctx, "setenv RSA Algorithm alg_flags = %0x\n",env->algorithm_flags); } else { sc_log(card->ctx, "%0x Alg Not Support! ", env->algorithm); } if (se_num > 0) { r = sc_lock(card); LOG_TEST_RET(card->ctx, r, "sc_lock() failed"); locked = 1; } if (apdu.datalen != 0) { r = sc_transmit_apdu_t(card, &apdu); if (r) { sc_log(card->ctx, "%s: APDU transmit failed", sc_strerror(r)); goto err; } r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r) { sc_log(card->ctx, "%s: Card returned error", sc_strerror(r)); goto err; } } if (se_num <= 0) return 0; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0xF2, se_num); r = sc_transmit_apdu_t(card, &apdu); sc_unlock(card); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); err: if (locked) sc_unlock(card); return r; } static int epass2003_restore_security_env(struct sc_card *card, int se_num) { LOG_FUNC_CALLED(card->ctx); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_decipher(struct sc_card *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { int r; struct sc_apdu apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; epass2003_exdata *exdata = NULL; LOG_FUNC_CALLED(card->ctx); if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if(exdata->currAlg == SC_ALGORITHM_EC) { if(exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA1) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x14; apdu.datalen = 0x14; } else if (exdata->ecAlgFlags & SC_ALGORITHM_ECDSA_HASH_SHA256) { r = hash_data(data, datalen, sbuf, SC_ALGORITHM_ECDSA_HASH_SHA256); LOG_TEST_RET(card->ctx, r, "hash_data failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3,0x2A, 0x9E, 0x9A); apdu.data = sbuf; apdu.lc = 0x20; apdu.datalen = 0x20; } else { return SC_ERROR_NOT_SUPPORTED; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } else if(exdata->currAlg == SC_ALGORITHM_RSA) { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_4_EXT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; memcpy(sbuf, data, datalen); apdu.data = sbuf; apdu.lc = datalen; apdu.datalen = datalen; } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) { size_t len = apdu.resplen > outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); LOG_FUNC_RETURN(card->ctx, len); } LOG_FUNC_RETURN(card->ctx, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int acl_to_ac_byte(struct sc_card *card, const struct sc_acl_entry *e) { if (e == NULL) return SC_ERROR_OBJECT_NOT_FOUND; switch (e->method) { case SC_AC_NONE: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE); case SC_AC_NEVER: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_NOONE); default: LOG_FUNC_RETURN(card->ctx, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_USER); } LOG_FUNC_RETURN(card->ctx, SC_ERROR_INCORRECT_PARAMETERS); } static int epass2003_process_fci(struct sc_card *card, sc_file_t * file, const u8 * buf, size_t buflen) { sc_context_t *ctx = card->ctx; size_t taglen, len = buflen; const u8 *tag = NULL, *p = buf; sc_log(ctx, "processing FCI bytes"); tag = sc_asn1_find_tag(ctx, p, len, 0x83, &taglen); if (tag != NULL && taglen == 2) { file->id = (tag[0] << 8) | tag[1]; sc_log(ctx, " file identifier: 0x%02X%02X", tag[0], tag[1]); } tag = sc_asn1_find_tag(ctx, p, len, 0x80, &taglen); if (tag != NULL && taglen > 0 && taglen < 3) { file->size = tag[0]; if (taglen == 2) file->size = (file->size << 8) + tag[1]; sc_log(ctx, " bytes in file: %"SC_FORMAT_LEN_SIZE_T"u", file->size); } if (tag == NULL) { tag = sc_asn1_find_tag(ctx, p, len, 0x81, &taglen); if (tag != NULL && taglen >= 2) { int bytes = (tag[0] << 8) + tag[1]; sc_log(ctx, " bytes in file: %d", bytes); file->size = bytes; } } tag = sc_asn1_find_tag(ctx, p, len, 0x82, &taglen); if (tag != NULL) { if (taglen > 0) { unsigned char byte = tag[0]; const char *type; if (byte == 0x38) { type = "DF"; file->type = SC_FILE_TYPE_DF; } else if (0x01 <= byte && byte <= 0x07) { type = "working EF"; file->type = SC_FILE_TYPE_WORKING_EF; switch (byte) { case 0x01: file->ef_structure = SC_FILE_EF_TRANSPARENT; break; case 0x02: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x04: file->ef_structure = SC_FILE_EF_LINEAR_FIXED; break; case 0x03: case 0x05: case 0x06: case 0x07: break; default: break; } } else if (0x10 == byte) { type = "BSO"; file->type = SC_FILE_TYPE_BSO; } else if (0x11 <= byte) { type = "internal EF"; file->type = SC_FILE_TYPE_INTERNAL_EF; switch (byte) { case 0x11: break; case 0x12: break; default: break; } } else { type = "unknown"; file->type = SC_FILE_TYPE_INTERNAL_EF; } sc_log(ctx, "type %s, EF structure %d", type, byte); } } tag = sc_asn1_find_tag(ctx, p, len, 0x84, &taglen); if (tag != NULL && taglen > 0 && taglen <= 16) { memcpy(file->name, tag, taglen); file->namelen = taglen; sc_log_hex(ctx, "File name", file->name, file->namelen); if (!file->type) file->type = SC_FILE_TYPE_DF; } tag = sc_asn1_find_tag(ctx, p, len, 0x85, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); else file->prop_attr_len = 0; tag = sc_asn1_find_tag(ctx, p, len, 0xA5, &taglen); if (tag != NULL && taglen) sc_file_set_prop_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x86, &taglen); if (tag != NULL && taglen) sc_file_set_sec_attr(file, tag, taglen); tag = sc_asn1_find_tag(ctx, p, len, 0x8A, &taglen); if (tag != NULL && taglen == 1) { if (tag[0] == 0x01) file->status = SC_FILE_STATUS_CREATION; else if (tag[0] == 0x07 || tag[0] == 0x05) file->status = SC_FILE_STATUS_ACTIVATED; else if (tag[0] == 0x06 || tag[0] == 0x04) file->status = SC_FILE_STATUS_INVALIDATED; } file->magic = SC_FILE_MAGIC; return 0; } static int epass2003_construct_fci(struct sc_card *card, const sc_file_t * file, u8 * out, size_t * outlen) { u8 *p = out; u8 buf[64]; unsigned char ops[8] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; int rv; unsigned ii; if (*outlen < 2) return SC_ERROR_BUFFER_TOO_SMALL; *p++ = 0x62; p++; if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p); } } if (file->type == SC_FILE_TYPE_DF) { buf[0] = 0x38; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_WORKING_EF) { buf[0] = file->ef_structure & 7; if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x40; /* record length */ buf[4] = 0x00; /* record count */ sc_asn1_put_tag(0x82, buf, 5, p, *outlen - (p - out), &p); } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { buf[0] = 0x11; buf[1] = 0x00; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = 0x12; buf[1] = 0x00; } else { return SC_ERROR_NOT_SUPPORTED; } sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = 0x10; buf[1] = 0x00; sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p); } buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p); if (file->type == SC_FILE_TYPE_DF) { if (file->namelen != 0) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, *outlen - (p - out), &p); } else { return SC_ERROR_INVALID_ARGUMENTS; } } if (file->type == SC_FILE_TYPE_DF) { unsigned char data[2] = {0x00, 0x7F}; /* 127 files at most */ sc_asn1_put_tag(0x85, data, sizeof(data), p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_BSO) { buf[0] = file->size & 0xff; sc_asn1_put_tag(0x85, buf, 1, p, *outlen - (p - out), &p); } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x85, buf, 2, p, *outlen - (p - out), &p); } } if (file->sec_attr_len) { memcpy(buf, file->sec_attr, file->sec_attr_len); sc_asn1_put_tag(0x86, buf, file->sec_attr_len, p, *outlen - (p - out), &p); } else { sc_log(card->ctx, "SC_FILE_ACL"); if (file->type == SC_FILE_TYPE_DF) { ops[0] = SC_AC_OP_LIST_FILES; ops[1] = SC_AC_OP_CREATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_WORKING_EF) { if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_FILE_EF_LINEAR_FIXED || file->ef_structure == SC_FILE_EF_LINEAR_VARIABLE) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_WRITE; ops[3] = SC_AC_OP_DELETE; } else { return SC_ERROR_NOT_SUPPORTED; } } else if (file->type == SC_FILE_TYPE_BSO) { ops[0] = SC_AC_OP_UPDATE; ops[3] = SC_AC_OP_DELETE; } else if (file->type == SC_FILE_TYPE_INTERNAL_EF) { if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_CRT || file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_CRT) { ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } else if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { ops[0] = SC_AC_OP_READ; ops[1] = SC_AC_OP_UPDATE; ops[2] = SC_AC_OP_CRYPTO; ops[3] = SC_AC_OP_DELETE; } } else { return SC_ERROR_NOT_SUPPORTED; } for (ii = 0; ii < sizeof(ops); ii++) { const struct sc_acl_entry *entry; buf[ii] = 0xFF; if (ops[ii] == 0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); rv = acl_to_ac_byte(card, entry); LOG_TEST_RET(card->ctx, rv, "Invalid ACL"); buf[ii] = rv; } sc_asn1_put_tag(0x86, buf, sizeof(ops), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x13; } } /* VT ??? */ if (file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC|| file->ef_structure == SC_CARDCTL_OBERTHUR_KEY_EC_PUBLIC) { unsigned char data[2] = {0x00, 0x66}; sc_asn1_put_tag(0x87, data, sizeof(data), p, *outlen - (p - out), &p); if(file->size == 256) { out[4]= 0x14; } } out[1] = p - out - 2; *outlen = p - out; return 0; } static int epass2003_create_file(struct sc_card *card, sc_file_t * file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; struct sc_apdu apdu; len = SC_MAX_APDU_BUFFER_SIZE; epass2003_hook_file(file, 1); if (card->ops->construct_fci == NULL) LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); r = epass2003_construct_fci(card, file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "APDU sw1/2 wrong"); epass2003_hook_file(file, 0); return r; } static int epass2003_delete_file(struct sc_card *card, const sc_path_t * path) { int r; u8 sbuf[2]; struct sc_apdu apdu; LOG_FUNC_CALLED(card->ctx); r = sc_select_file(card, path, NULL); epass2003_hook_path((struct sc_path *)path, 1); if (r == SC_SUCCESS) { sbuf[0] = path->value[path->len - 2]; sbuf[1] = path->value[path->len - 1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Delete file failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_list_files(struct sc_card *card, unsigned char *buf, size_t buflen) { struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE] = { 0 }; int r; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x34, 0x00, 0x00); apdu.cla = 0x80; apdu.le = 0; apdu.resplen = sizeof(rbuf); apdu.resp = rbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Card returned error"); if (apdu.resplen == 0x100 && rbuf[0] == 0 && rbuf[1] == 0) LOG_FUNC_RETURN(card->ctx, 0); buflen = buflen < apdu.resplen ? buflen : apdu.resplen; memcpy(buf, rbuf, buflen); LOG_FUNC_RETURN(card->ctx, buflen); } static int internal_write_rsa_key_factor(struct sc_card *card, unsigned short fid, u8 factor, sc_pkcs15_bignum_t data) { int r; struct sc_apdu apdu; u8 sbuff[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); sbuff[0] = ((fid & 0xff00) >> 8); sbuff[1] = (fid & 0x00ff); memcpy(&sbuff[2], data.data, data.len); // sc_mem_reverse(&sbuff[2], data.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0xe7, factor, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 2 + data.len; apdu.data = sbuff; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "Write rsa key factor failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int internal_write_rsa_key(struct sc_card *card, unsigned short fid, struct sc_pkcs15_prkey_rsa *rsa) { int r; LOG_FUNC_CALLED(card->ctx); r = internal_write_rsa_key_factor(card, fid, 0x02, rsa->modulus); LOG_TEST_RET(card->ctx, r, "write n failed"); r = internal_write_rsa_key_factor(card, fid, 0x03, rsa->d); LOG_TEST_RET(card->ctx, r, "write d failed"); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int hash_data(const unsigned char *data, size_t datalen, unsigned char *hash, unsigned int mechanismType) { if ((NULL == data) || (NULL == hash)) return SC_ERROR_INVALID_ARGUMENTS; if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA1) { unsigned char data_hash[24] = { 0 }; size_t len = 0; sha1_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[20], &len, 4); memcpy(hash, data_hash, 24); } else if(mechanismType & SC_ALGORITHM_ECDSA_HASH_SHA256) { unsigned char data_hash[36] = { 0 }; size_t len = 0; sha256_digest(data, datalen, data_hash); len = REVERSE_ORDER4(datalen); memcpy(&data_hash[32], &len, 4); memcpy(hash, data_hash, 36); } else { return SC_ERROR_NOT_SUPPORTED; } return SC_SUCCESS; } static int install_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, unsigned char useac, unsigned char modifyac, unsigned char EC, unsigned char *data, unsigned long dataLen) { int r; struct sc_apdu apdu; unsigned char isapp = 0x00; /* appendable */ unsigned char tmp_data[256] = { 0 }; tmp_data[0] = ktype; tmp_data[1] = kid; tmp_data[2] = useac; tmp_data[3] = modifyac; tmp_data[8] = 0xFF; if (0x04 == ktype || 0x06 == ktype) { tmp_data[4] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[5] = EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_SO; tmp_data[7] = (kid == PIN_ID[0] ? EPASS2003_AC_USER : EPASS2003_AC_SO); tmp_data[9] = (EC << 4) | EC; } memcpy(&tmp_data[10], data, dataLen); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe3, isapp, 0x00); apdu.cla = 0x80; apdu.lc = apdu.datalen = 10 + dataLen; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU install_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "install_secret_key failed"); return r; } static int internal_install_pre(struct sc_card *card) { int r; /* init key for enc */ r = install_secret_key(card, 0x01, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_enc, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); /* init key for mac */ r = install_secret_key(card, 0x02, 0x00, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, EPASS2003_AC_MAC_NOLESS | EPASS2003_AC_EVERYONE, 0, g_init_key_mac, 16); LOG_TEST_RET(card->ctx, r, "Install init key failed"); return r; } /* use external auth secret as pin */ static int internal_install_pin(struct sc_card *card, sc_epass2003_wkey_data * pin) { int r; unsigned char hash[HASH_LEN] = { 0 }; r = hash_data(pin->key_data.es_secret.key_val, pin->key_data.es_secret.key_len, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = install_secret_key(card, 0x04, pin->key_data.es_secret.kid, pin->key_data.es_secret.ac[0], pin->key_data.es_secret.ac[1], pin->key_data.es_secret.EC, hash, HASH_LEN); LOG_TEST_RET(card->ctx, r, "Install failed"); return r; } static int epass2003_write_key(struct sc_card *card, sc_epass2003_wkey_data * data) { LOG_FUNC_CALLED(card->ctx); if (data->type & SC_EPASS2003_KEY) { if (data->type == SC_EPASS2003_KEY_RSA) return internal_write_rsa_key(card, data->key_data.es_key.fid, data->key_data.es_key.rsa); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else if (data->type & SC_EPASS2003_SECRET) { if (data->type == SC_EPASS2003_SECRET_PRE) return internal_install_pre(card); else if (data->type == SC_EPASS2003_SECRET_PIN) return internal_install_pin(card, data); else LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } else { LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); } LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_gen_key(struct sc_card *card, sc_epass2003_gen_key_data * data) { int r; size_t len = data->key_length; struct sc_apdu apdu; u8 rbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; u8 sbuf[SC_MAX_EXT_APDU_BUFFER_SIZE] = { 0 }; LOG_FUNC_CALLED(card->ctx); if(len == 256) { sbuf[0] = 0x02; } else { sbuf[0] = 0x01; } sbuf[1] = (u8) ((len >> 8) & 0xff); sbuf[2] = (u8) (len & 0xff); sbuf[3] = (u8) ((data->prkey_id >> 8) & 0xFF); sbuf[4] = (u8) ((data->prkey_id) & 0xFF); sbuf[5] = (u8) ((data->pukey_id >> 8) & 0xFF); sbuf[6] = (u8) ((data->pukey_id) & 0xFF); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.lc = apdu.datalen = 7; apdu.data = sbuf; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "generate keypair failed"); /* read public key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xb4, 0x02, 0x00); if(len == 256) { apdu.p1 = 0x00; } apdu.cla = 0x80; apdu.lc = apdu.datalen = 2; apdu.data = &sbuf[5]; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x00; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "get pukey failed"); if (len < apdu.resplen) LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); data->modulus = (u8 *) malloc(len); if (!data->modulus) LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(data->modulus, rbuf, len); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_erase_card(struct sc_card *card) { int r; LOG_FUNC_CALLED(card->ctx); sc_invalidate_cache(card); r = sc_delete_file(card, sc_get_mf_path()); LOG_TEST_RET(card->ctx, r, "delete MF failed"); LOG_FUNC_RETURN(card->ctx, r); } static int epass2003_get_serialnr(struct sc_card *card, sc_serial_number_t * serial) { u8 rbuf[8]; size_t rbuf_len = sizeof(rbuf); LOG_FUNC_CALLED(card->ctx); if (SC_SUCCESS != get_data(card, 0x80, rbuf, rbuf_len)) return SC_ERROR_CARD_CMD_FAILED; card->serialnr.len = serial->len = 8; memcpy(card->serialnr.value, rbuf, 8); memcpy(serial->value, rbuf, 8); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } static int epass2003_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "cmd is %0lx", cmd); switch (cmd) { case SC_CARDCTL_ENTERSAFE_WRITE_KEY: return epass2003_write_key(card, (sc_epass2003_wkey_data *) ptr); case SC_CARDCTL_ENTERSAFE_GENERATE_KEY: return epass2003_gen_key(card, (sc_epass2003_gen_key_data *) ptr); case SC_CARDCTL_ERASE_CARD: return epass2003_erase_card(card); case SC_CARDCTL_GET_SERIALNR: return epass2003_get_serialnr(card, (sc_serial_number_t *) ptr); default: return SC_ERROR_NOT_SUPPORTED; } } static void internal_sanitize_pin_info(struct sc_pin_cmd_pin *pin, unsigned int num) { pin->encoding = SC_PIN_ENCODING_ASCII; pin->min_length = 4; pin->max_length = 16; pin->pad_length = 16; pin->offset = 5 + num * 16; pin->pad_char = 0x00; } static int get_external_key_maxtries(struct sc_card *card, unsigned char *maxtries) { unsigned char maxcounter[2] = { 0 }; static const sc_path_t file_path = { {0x3f, 0x00, 0x50, 0x15, 0x9f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 6, 0, 0, SC_PATH_TYPE_PATH, {{0}, 0} }; int ret; ret = sc_select_file(card, &file_path, NULL); LOG_TEST_RET(card->ctx, ret, "select max counter file failed"); ret = sc_read_binary(card, 0, maxcounter, 2, 0); LOG_TEST_RET(card->ctx, ret, "read max counter file failed"); *maxtries = maxcounter[0]; return SC_SUCCESS; } static int get_external_key_retries(struct sc_card *card, unsigned char kid, unsigned char *retries) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge get_external_key_retries failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x82, 0x01, 0x80 | kid); apdu.resp = NULL; apdu.resplen = 0; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU get_external_key_retries failed"); if (retries && ((0x63 == (apdu.sw1 & 0xff)) && (0xC0 == (apdu.sw2 & 0xf0)))) { *retries = (apdu.sw2 & 0x0f); r = SC_SUCCESS; } else { LOG_TEST_RET(card->ctx, r, "get_external_key_retries failed"); r = SC_ERROR_CARD_CMD_FAILED; } return r; } static int epass2003_get_challenge(sc_card_t *card, u8 *rnd, size_t len) { u8 rbuf[16]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, (int) out_len); } static int external_key_auth(struct sc_card *card, unsigned char kid, unsigned char *data, size_t datalen) { int r; struct sc_apdu apdu; unsigned char random[16] = { 0 }; unsigned char tmp_data[16] = { 0 }; unsigned char hash[HASH_LEN] = { 0 }; unsigned char iv[16] = { 0 }; r = sc_get_challenge(card, random, 8); LOG_TEST_RET(card->ctx, r, "get challenge external_key_auth failed"); r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); des3_encrypt_cbc(hash, HASH_LEN, iv, random, 8, tmp_data); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x01, 0x80 | kid); apdu.lc = apdu.datalen = 8; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU external_key_auth failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "external_key_auth failed"); return r; } static int update_secret_key(struct sc_card *card, unsigned char ktype, unsigned char kid, const unsigned char *data, unsigned long datalen) { int r; struct sc_apdu apdu; unsigned char hash[HASH_LEN] = { 0 }; unsigned char tmp_data[256] = { 0 }; unsigned char maxtries = 0; r = hash_data(data, datalen, hash, SC_ALGORITHM_ECDSA_HASH_SHA1); LOG_TEST_RET(card->ctx, r, "hash data failed"); r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); tmp_data[0] = (maxtries << 4) | maxtries; memcpy(&tmp_data[1], hash, HASH_LEN); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe5, ktype, kid); apdu.cla = 0x80; apdu.lc = apdu.datalen = 1 + HASH_LEN; apdu.data = tmp_data; r = sc_transmit_apdu_t(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU update_secret_key failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, r, "update_secret_key failed"); return r; } /* use external auth secret as pin */ static int epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } //remove below code, because the old implement only return PIN retries, now modify the code and return PIN status // return r; } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } static struct sc_card_driver *sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; epass2003_ops = *iso_ops; epass2003_ops.match_card = epass2003_match_card; epass2003_ops.init = epass2003_init; epass2003_ops.finish = epass2003_finish; epass2003_ops.write_binary = NULL; epass2003_ops.write_record = NULL; epass2003_ops.select_file = epass2003_select_file; epass2003_ops.get_response = NULL; epass2003_ops.restore_security_env = epass2003_restore_security_env; epass2003_ops.set_security_env = epass2003_set_security_env; epass2003_ops.decipher = epass2003_decipher; epass2003_ops.compute_signature = epass2003_decipher; epass2003_ops.create_file = epass2003_create_file; epass2003_ops.delete_file = epass2003_delete_file; epass2003_ops.list_files = epass2003_list_files; epass2003_ops.card_ctl = epass2003_card_ctl; epass2003_ops.process_fci = epass2003_process_fci; epass2003_ops.construct_fci = epass2003_construct_fci; epass2003_ops.pin_cmd = epass2003_pin_cmd; epass2003_ops.check_sw = epass2003_check_sw; epass2003_ops.get_challenge = epass2003_get_challenge; return &epass2003_drv; } struct sc_card_driver *sc_get_epass2003_driver(void) { return sc_get_driver(); } #endif /* #ifdef ENABLE_OPENSSL */ #endif /* #ifdef ENABLE_SM */
./CrossVul/dataset_final_sorted/CWE-415/c/good_348_1
crossvul-cpp_data_good_2633_1
/* zip_dirent.c -- read directory entry (local or central), clean dirent Copyright (C) 1999-2016 Dieter Baron and Thomas Klausner This file is part of libzip, a library to manipulate ZIP archives. The authors can be contacted at <libzip@nih.at> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include "zipint.h" static time_t _zip_d2u_time(zip_uint16_t, zip_uint16_t); static zip_string_t *_zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str); static zip_extra_field_t *_zip_ef_utf8(zip_uint16_t, zip_string_t *, zip_error_t *); static bool _zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error); void _zip_cdir_free(zip_cdir_t *cd) { zip_uint64_t i; if (!cd) return; for (i=0; i<cd->nentry; i++) _zip_entry_finalize(cd->entry+i); free(cd->entry); _zip_string_free(cd->comment); free(cd); } zip_cdir_t * _zip_cdir_new(zip_uint64_t nentry, zip_error_t *error) { zip_cdir_t *cd; if ((cd=(zip_cdir_t *)malloc(sizeof(*cd))) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); return NULL; } cd->entry = NULL; cd->nentry = cd->nentry_alloc = 0; cd->size = cd->offset = 0; cd->comment = NULL; cd->is_zip64 = false; if (!_zip_cdir_grow(cd, nentry, error)) { _zip_cdir_free(cd); return NULL; } return cd; } bool _zip_cdir_grow(zip_cdir_t *cd, zip_uint64_t additional_entries, zip_error_t *error) { zip_uint64_t i, new_alloc; zip_entry_t *new_entry; if (additional_entries == 0) { return true; } new_alloc = cd->nentry_alloc + additional_entries; if (new_alloc < additional_entries || new_alloc > SIZE_MAX/sizeof(*(cd->entry))) { zip_error_set(error, ZIP_ER_MEMORY, 0); return false; } if ((new_entry = (zip_entry_t *)realloc(cd->entry, sizeof(*(cd->entry))*(size_t)new_alloc)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); return false; } cd->entry = new_entry; for (i = cd->nentry; i < new_alloc; i++) { _zip_entry_init(cd->entry+i); } cd->nentry = cd->nentry_alloc = new_alloc; return true; } zip_int64_t _zip_cdir_write(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors) { zip_uint64_t offset, size; zip_string_t *comment; zip_uint8_t buf[EOCDLEN + EOCD64LEN + EOCD64LOCLEN]; zip_buffer_t *buffer; zip_int64_t off; zip_uint64_t i; bool is_zip64; int ret; if ((off = zip_source_tell_write(za->src)) < 0) { _zip_error_set_from_source(&za->error, za->src); return -1; } offset = (zip_uint64_t)off; is_zip64 = false; for (i=0; i<survivors; i++) { zip_entry_t *entry = za->entry+filelist[i].idx; if ((ret=_zip_dirent_write(za, entry->changes ? entry->changes : entry->orig, ZIP_FL_CENTRAL)) < 0) return -1; if (ret) is_zip64 = true; } if ((off = zip_source_tell_write(za->src)) < 0) { _zip_error_set_from_source(&za->error, za->src); return -1; } size = (zip_uint64_t)off - offset; if (offset > ZIP_UINT32_MAX || survivors > ZIP_UINT16_MAX) is_zip64 = true; if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); return -1; } if (is_zip64) { _zip_buffer_put(buffer, EOCD64_MAGIC, 4); _zip_buffer_put_64(buffer, EOCD64LEN-12); _zip_buffer_put_16(buffer, 45); _zip_buffer_put_16(buffer, 45); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_64(buffer, survivors); _zip_buffer_put_64(buffer, survivors); _zip_buffer_put_64(buffer, size); _zip_buffer_put_64(buffer, offset); _zip_buffer_put(buffer, EOCD64LOC_MAGIC, 4); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_64(buffer, offset+size); _zip_buffer_put_32(buffer, 1); } _zip_buffer_put(buffer, EOCD_MAGIC, 4); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); _zip_buffer_put_32(buffer, size >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)size); _zip_buffer_put_32(buffer, offset >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)offset); comment = za->comment_changed ? za->comment_changes : za->comment_orig; _zip_buffer_put_16(buffer, (zip_uint16_t)(comment ? comment->length : 0)); if (!_zip_buffer_ok(buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); return -1; } if (_zip_write(za, _zip_buffer_data(buffer), _zip_buffer_offset(buffer)) < 0) { _zip_buffer_free(buffer); return -1; } _zip_buffer_free(buffer); if (comment) { if (_zip_write(za, comment->raw, comment->length) < 0) { return -1; } } return (zip_int64_t)size; } zip_dirent_t * _zip_dirent_clone(const zip_dirent_t *sde) { zip_dirent_t *tde; if ((tde=(zip_dirent_t *)malloc(sizeof(*tde))) == NULL) return NULL; if (sde) memcpy(tde, sde, sizeof(*sde)); else _zip_dirent_init(tde); tde->changed = 0; tde->cloned = 1; return tde; } void _zip_dirent_finalize(zip_dirent_t *zde) { if (!zde->cloned || zde->changed & ZIP_DIRENT_FILENAME) { _zip_string_free(zde->filename); zde->filename = NULL; } if (!zde->cloned || zde->changed & ZIP_DIRENT_EXTRA_FIELD) { _zip_ef_free(zde->extra_fields); zde->extra_fields = NULL; } if (!zde->cloned || zde->changed & ZIP_DIRENT_COMMENT) { _zip_string_free(zde->comment); zde->comment = NULL; } if (!zde->cloned || zde->changed & ZIP_DIRENT_PASSWORD) { if (zde->password) { _zip_crypto_clear(zde->password, strlen(zde->password)); } free(zde->password); zde->password = NULL; } } void _zip_dirent_free(zip_dirent_t *zde) { if (zde == NULL) return; _zip_dirent_finalize(zde); free(zde); } void _zip_dirent_init(zip_dirent_t *de) { de->changed = 0; de->local_extra_fields_read = 0; de->cloned = 0; de->crc_valid = true; de->version_madeby = 63 | (ZIP_OPSYS_DEFAULT << 8); de->version_needed = 10; /* 1.0 */ de->bitflags = 0; de->comp_method = ZIP_CM_DEFAULT; de->last_mod = 0; de->crc = 0; de->comp_size = 0; de->uncomp_size = 0; de->filename = NULL; de->extra_fields = NULL; de->comment = NULL; de->disk_number = 0; de->int_attrib = 0; de->ext_attrib = ZIP_EXT_ATTRIB_DEFAULT; de->offset = 0; de->compression_level = 0; de->encryption_method = ZIP_EM_NONE; de->password = NULL; } bool _zip_dirent_needs_zip64(const zip_dirent_t *de, zip_flags_t flags) { if (de->uncomp_size >= ZIP_UINT32_MAX || de->comp_size >= ZIP_UINT32_MAX || ((flags & ZIP_FL_CENTRAL) && de->offset >= ZIP_UINT32_MAX)) return true; return false; } zip_dirent_t * _zip_dirent_new(void) { zip_dirent_t *de; if ((de=(zip_dirent_t *)malloc(sizeof(*de))) == NULL) return NULL; _zip_dirent_init(de); return de; } /* _zip_dirent_read(zde, fp, bufp, left, localp, error): Fills the zip directory entry zde. If buffer is non-NULL, data is taken from there; otherwise data is read from fp as needed. If local is true, it reads a local header instead of a central directory entry. Returns size of dirent read if successful. On error, error is filled in and -1 is returned. */ zip_int64_t _zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error) { zip_uint8_t buf[CDENTRYSIZE]; zip_uint16_t dostime, dosdate; zip_uint32_t size, variable_size; zip_uint16_t filename_len, comment_len, ef_len; bool from_buffer = (buffer != NULL); size = local ? LENTRYSIZE : CDENTRYSIZE; if (buffer) { if (_zip_buffer_left(buffer) < size) { zip_error_set(error, ZIP_ER_NOZIP, 0); return -1; } } else { if ((buffer = _zip_buffer_new_from_source(src, size, buf, error)) == NULL) { return -1; } } if (memcmp(_zip_buffer_get(buffer, 4), (local ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) { zip_error_set(error, ZIP_ER_NOZIP, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } /* convert buffercontents to zip_dirent */ _zip_dirent_init(zde); if (!local) zde->version_madeby = _zip_buffer_get_16(buffer); else zde->version_madeby = 0; zde->version_needed = _zip_buffer_get_16(buffer); zde->bitflags = _zip_buffer_get_16(buffer); zde->comp_method = _zip_buffer_get_16(buffer); /* convert to time_t */ dostime = _zip_buffer_get_16(buffer); dosdate = _zip_buffer_get_16(buffer); zde->last_mod = _zip_d2u_time(dostime, dosdate); zde->crc = _zip_buffer_get_32(buffer); zde->comp_size = _zip_buffer_get_32(buffer); zde->uncomp_size = _zip_buffer_get_32(buffer); filename_len = _zip_buffer_get_16(buffer); ef_len = _zip_buffer_get_16(buffer); if (local) { comment_len = 0; zde->disk_number = 0; zde->int_attrib = 0; zde->ext_attrib = 0; zde->offset = 0; } else { comment_len = _zip_buffer_get_16(buffer); zde->disk_number = _zip_buffer_get_16(buffer); zde->int_attrib = _zip_buffer_get_16(buffer); zde->ext_attrib = _zip_buffer_get_32(buffer); zde->offset = _zip_buffer_get_32(buffer); } if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCRYPTED) { if (zde->bitflags & ZIP_GPBF_STRONG_ENCRYPTION) { /* TODO */ zde->encryption_method = ZIP_EM_UNKNOWN; } else { zde->encryption_method = ZIP_EM_TRAD_PKWARE; } } else { zde->encryption_method = ZIP_EM_NONE; } zde->filename = NULL; zde->extra_fields = NULL; zde->comment = NULL; variable_size = (zip_uint32_t)filename_len+(zip_uint32_t)ef_len+(zip_uint32_t)comment_len; if (from_buffer) { if (_zip_buffer_left(buffer) < variable_size) { zip_error_set(error, ZIP_ER_INCONS, 0); return -1; } } else { _zip_buffer_free(buffer); if ((buffer = _zip_buffer_new_from_source(src, variable_size, NULL, error)) == NULL) { return -1; } } if (filename_len) { zde->filename = _zip_read_string(buffer, src, filename_len, 1, error); if (!zde->filename) { if (zip_error_code_zip(error) == ZIP_ER_EOF) { zip_error_set(error, ZIP_ER_INCONS, 0); } if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { if (_zip_guess_encoding(zde->filename, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { zip_error_set(error, ZIP_ER_INCONS, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } } } if (ef_len) { zip_uint8_t *ef = _zip_read_data(buffer, src, ef_len, 0, error); if (ef == NULL) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (!_zip_ef_parse(ef, ef_len, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, &zde->extra_fields, error)) { free(ef); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } free(ef); if (local) zde->local_extra_fields_read = 1; } if (comment_len) { zde->comment = _zip_read_string(buffer, src, comment_len, 0, error); if (!zde->comment) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { if (_zip_guess_encoding(zde->comment, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { zip_error_set(error, ZIP_ER_INCONS, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } } } zde->filename = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_NAME, zde->filename); zde->comment = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_COMMENT, zde->comment); /* Zip64 */ if (zde->uncomp_size == ZIP_UINT32_MAX || zde->comp_size == ZIP_UINT32_MAX || zde->offset == ZIP_UINT32_MAX) { zip_uint16_t got_len; zip_buffer_t *ef_buffer; const zip_uint8_t *ef = _zip_ef_get_by_id(zde->extra_fields, &got_len, ZIP_EF_ZIP64, 0, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, error); /* TODO: if got_len == 0 && !ZIP64_EOCD: no error, 0xffffffff is valid value */ if (ef == NULL) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if ((ef_buffer = _zip_buffer_new((zip_uint8_t *)ef, got_len)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->uncomp_size == ZIP_UINT32_MAX) zde->uncomp_size = _zip_buffer_get_64(ef_buffer); else if (local) { /* From appnote.txt: This entry in the Local header MUST include BOTH original and compressed file size fields. */ (void)_zip_buffer_skip(ef_buffer, 8); /* error is caught by _zip_buffer_eof() call */ } if (zde->comp_size == ZIP_UINT32_MAX) zde->comp_size = _zip_buffer_get_64(ef_buffer); if (!local) { if (zde->offset == ZIP_UINT32_MAX) zde->offset = _zip_buffer_get_64(ef_buffer); if (zde->disk_number == ZIP_UINT16_MAX) zde->disk_number = _zip_buffer_get_32(buffer); } if (!_zip_buffer_eof(ef_buffer)) { zip_error_set(error, ZIP_ER_INCONS, 0); _zip_buffer_free(ef_buffer); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } _zip_buffer_free(ef_buffer); } if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (!from_buffer) { _zip_buffer_free(buffer); } /* zip_source_seek / zip_source_tell don't support values > ZIP_INT64_MAX */ if (zde->offset > ZIP_INT64_MAX) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return -1; } if (!_zip_dirent_process_winzip_aes(zde, error)) { return -1; } zde->extra_fields = _zip_ef_remove_internal(zde->extra_fields); return (zip_int64_t)(size + variable_size); } static zip_string_t * _zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str) { zip_uint16_t ef_len; zip_uint32_t ef_crc; zip_buffer_t *buffer; const zip_uint8_t *ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, id, 0, ZIP_EF_BOTH, NULL); if (ef == NULL || ef_len < 5 || ef[0] != 1) { return str; } if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { return str; } _zip_buffer_get_8(buffer); ef_crc = _zip_buffer_get_32(buffer); if (_zip_string_crc32(str) == ef_crc) { zip_uint16_t len = (zip_uint16_t)_zip_buffer_left(buffer); zip_string_t *ef_str = _zip_string_new(_zip_buffer_get(buffer, len), len, ZIP_FL_ENC_UTF_8, NULL); if (ef_str != NULL) { _zip_string_free(str); str = ef_str; } } _zip_buffer_free(buffer); return str; } static bool _zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error) { zip_uint16_t ef_len; zip_buffer_t *buffer; const zip_uint8_t *ef; bool crc_valid; zip_uint16_t enc_method; if (de->comp_method != ZIP_CM_WINZIP_AES) { return true; } ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, ZIP_EF_WINZIP_AES, 0, ZIP_EF_BOTH, NULL); if (ef == NULL || ef_len < 7) { zip_error_set(error, ZIP_ER_INCONS, 0); return false; } if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { zip_error_set(error, ZIP_ER_INTERNAL, 0); return false; } /* version */ crc_valid = true; switch (_zip_buffer_get_16(buffer)) { case 1: break; case 2: if (de->uncomp_size < 20 /* TODO: constant */) { crc_valid = false; } break; default: zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); _zip_buffer_free(buffer); return false; } /* vendor */ if (memcmp(_zip_buffer_get(buffer, 2), "AE", 2) != 0) { zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); _zip_buffer_free(buffer); return false; } /* mode */ switch (_zip_buffer_get_8(buffer)) { case 1: enc_method = ZIP_EM_AES_128; break; case 2: enc_method = ZIP_EM_AES_192; break; case 3: enc_method = ZIP_EM_AES_256; break; default: zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); _zip_buffer_free(buffer); return false; } if (ef_len != 7) { zip_error_set(error, ZIP_ER_INCONS, 0); _zip_buffer_free(buffer); return false; } de->crc_valid = crc_valid; de->encryption_method = enc_method; de->comp_method = _zip_buffer_get_16(buffer); _zip_buffer_free(buffer); return true; } zip_int32_t _zip_dirent_size(zip_source_t *src, zip_uint16_t flags, zip_error_t *error) { zip_int32_t size; bool local = (flags & ZIP_EF_LOCAL) != 0; int i; zip_uint8_t b[6]; zip_buffer_t *buffer; size = local ? LENTRYSIZE : CDENTRYSIZE; if (zip_source_seek(src, local ? 26 : 28, SEEK_CUR) < 0) { _zip_error_set_from_source(error, src); return -1; } if ((buffer = _zip_buffer_new_from_source(src, local ? 4 : 6, b, error)) == NULL) { return -1; } for (i=0; i<(local ? 2 : 3); i++) { size += _zip_buffer_get_16(buffer); } if (!_zip_buffer_eof(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); return -1; } _zip_buffer_free(buffer); return size; } /* _zip_dirent_write Writes zip directory entry. If flags & ZIP_EF_LOCAL, it writes a local header instead of a central directory entry. If flags & ZIP_EF_FORCE_ZIP64, a ZIP64 extra field is written, even if not needed. Returns 0 if successful, 1 if successful and wrote ZIP64 extra field. On error, error is filled in and -1 is returned. */ int _zip_dirent_write(zip_t *za, zip_dirent_t *de, zip_flags_t flags) { zip_uint16_t dostime, dosdate; zip_encoding_type_t com_enc, name_enc; zip_extra_field_t *ef; zip_extra_field_t *ef64; zip_uint32_t ef_total_size; bool is_zip64; bool is_really_zip64; bool is_winzip_aes; zip_uint8_t buf[CDENTRYSIZE]; zip_buffer_t *buffer; ef = NULL; name_enc = _zip_guess_encoding(de->filename, ZIP_ENCODING_UNKNOWN); com_enc = _zip_guess_encoding(de->comment, ZIP_ENCODING_UNKNOWN); if ((name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_ASCII) || (name_enc == ZIP_ENCODING_ASCII && com_enc == ZIP_ENCODING_UTF8_KNOWN) || (name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_UTF8_KNOWN)) de->bitflags |= ZIP_GPBF_ENCODING_UTF_8; else { de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCODING_UTF_8; if (name_enc == ZIP_ENCODING_UTF8_KNOWN) { ef = _zip_ef_utf8(ZIP_EF_UTF_8_NAME, de->filename, &za->error); if (ef == NULL) return -1; } if ((flags & ZIP_FL_LOCAL) == 0 && com_enc == ZIP_ENCODING_UTF8_KNOWN){ zip_extra_field_t *ef2 = _zip_ef_utf8(ZIP_EF_UTF_8_COMMENT, de->comment, &za->error); if (ef2 == NULL) { _zip_ef_free(ef); return -1; } ef2->next = ef; ef = ef2; } } if (de->encryption_method == ZIP_EM_NONE) { de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCRYPTED; } else { de->bitflags |= (zip_uint16_t)ZIP_GPBF_ENCRYPTED; } is_really_zip64 = _zip_dirent_needs_zip64(de, flags); is_zip64 = (flags & (ZIP_FL_LOCAL|ZIP_FL_FORCE_ZIP64)) == (ZIP_FL_LOCAL|ZIP_FL_FORCE_ZIP64) || is_really_zip64; is_winzip_aes = de->encryption_method == ZIP_EM_AES_128 || de->encryption_method == ZIP_EM_AES_192 || de->encryption_method == ZIP_EM_AES_256; if (is_zip64) { zip_uint8_t ef_zip64[EFZIP64SIZE]; zip_buffer_t *ef_buffer = _zip_buffer_new(ef_zip64, sizeof(ef_zip64)); if (ef_buffer == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_ef_free(ef); return -1; } if (flags & ZIP_FL_LOCAL) { if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->uncomp_size); _zip_buffer_put_64(ef_buffer, de->comp_size); } } else { if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX || de->offset > ZIP_UINT32_MAX) { if (de->uncomp_size >= ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->uncomp_size); } if (de->comp_size >= ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->comp_size); } if (de->offset >= ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->offset); } } } if (!_zip_buffer_ok(ef_buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(ef_buffer); _zip_ef_free(ef); return -1; } ef64 = _zip_ef_new(ZIP_EF_ZIP64, (zip_uint16_t)(_zip_buffer_offset(ef_buffer)), ef_zip64, ZIP_EF_BOTH); _zip_buffer_free(ef_buffer); ef64->next = ef; ef = ef64; } if (is_winzip_aes) { zip_uint8_t data[EF_WINZIP_AES_SIZE]; zip_buffer_t *ef_buffer = _zip_buffer_new(data, sizeof(data)); zip_extra_field_t *ef_winzip; if (ef_buffer == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_ef_free(ef); return -1; } _zip_buffer_put_16(ef_buffer, 2); _zip_buffer_put(ef_buffer, "AE", 2); _zip_buffer_put_8(ef_buffer, (zip_uint8_t)(de->encryption_method & 0xff)); _zip_buffer_put_16(ef_buffer, (zip_uint16_t)de->comp_method); if (!_zip_buffer_ok(ef_buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(ef_buffer); _zip_ef_free(ef); return -1; } ef_winzip = _zip_ef_new(ZIP_EF_WINZIP_AES, EF_WINZIP_AES_SIZE, data, ZIP_EF_BOTH); _zip_buffer_free(ef_buffer); ef_winzip->next = ef; ef = ef_winzip; } if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_ef_free(ef); return -1; } _zip_buffer_put(buffer, (flags & ZIP_FL_LOCAL) ? LOCAL_MAGIC : CENTRAL_MAGIC, 4); if ((flags & ZIP_FL_LOCAL) == 0) { _zip_buffer_put_16(buffer, (zip_uint16_t)(is_really_zip64 ? 45 : de->version_madeby)); } _zip_buffer_put_16(buffer, (zip_uint16_t)(is_really_zip64 ? 45 : de->version_needed)); _zip_buffer_put_16(buffer, de->bitflags); if (is_winzip_aes) { _zip_buffer_put_16(buffer, ZIP_CM_WINZIP_AES); } else { _zip_buffer_put_16(buffer, (zip_uint16_t)de->comp_method); } _zip_u2d_time(de->last_mod, &dostime, &dosdate); _zip_buffer_put_16(buffer, dostime); _zip_buffer_put_16(buffer, dosdate); if (is_winzip_aes && de->uncomp_size < 20) { _zip_buffer_put_32(buffer, 0); } else { _zip_buffer_put_32(buffer, de->crc); } if (((flags & ZIP_FL_LOCAL) == ZIP_FL_LOCAL) && ((de->comp_size >= ZIP_UINT32_MAX) || (de->uncomp_size >= ZIP_UINT32_MAX))) { /* In local headers, if a ZIP64 EF is written, it MUST contain * both compressed and uncompressed sizes (even if one of the * two is smaller than 0xFFFFFFFF); on the other hand, those * may only appear when the corresponding standard entry is * 0xFFFFFFFF. (appnote.txt 4.5.3) */ _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } else { if (de->comp_size < ZIP_UINT32_MAX) { _zip_buffer_put_32(buffer, (zip_uint32_t)de->comp_size); } else { _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } if (de->uncomp_size < ZIP_UINT32_MAX) { _zip_buffer_put_32(buffer, (zip_uint32_t)de->uncomp_size); } else { _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } } _zip_buffer_put_16(buffer, _zip_string_length(de->filename)); /* TODO: check for overflow */ ef_total_size = (zip_uint32_t)_zip_ef_size(de->extra_fields, flags) + (zip_uint32_t)_zip_ef_size(ef, ZIP_EF_BOTH); _zip_buffer_put_16(buffer, (zip_uint16_t)ef_total_size); if ((flags & ZIP_FL_LOCAL) == 0) { _zip_buffer_put_16(buffer, _zip_string_length(de->comment)); _zip_buffer_put_16(buffer, (zip_uint16_t)de->disk_number); _zip_buffer_put_16(buffer, de->int_attrib); _zip_buffer_put_32(buffer, de->ext_attrib); if (de->offset < ZIP_UINT32_MAX) _zip_buffer_put_32(buffer, (zip_uint32_t)de->offset); else _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } if (!_zip_buffer_ok(buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); _zip_ef_free(ef); return -1; } if (_zip_write(za, buf, _zip_buffer_offset(buffer)) < 0) { _zip_buffer_free(buffer); _zip_ef_free(ef); return -1; } _zip_buffer_free(buffer); if (de->filename) { if (_zip_string_write(za, de->filename) < 0) { _zip_ef_free(ef); return -1; } } if (ef) { if (_zip_ef_write(za, ef, ZIP_EF_BOTH) < 0) { _zip_ef_free(ef); return -1; } } _zip_ef_free(ef); if (de->extra_fields) { if (_zip_ef_write(za, de->extra_fields, flags) < 0) { return -1; } } if ((flags & ZIP_FL_LOCAL) == 0) { if (de->comment) { if (_zip_string_write(za, de->comment) < 0) { return -1; } } } return is_zip64; } static time_t _zip_d2u_time(zip_uint16_t dtime, zip_uint16_t ddate) { struct tm tm; memset(&tm, 0, sizeof(tm)); /* let mktime decide if DST is in effect */ tm.tm_isdst = -1; tm.tm_year = ((ddate>>9)&127) + 1980 - 1900; tm.tm_mon = ((ddate>>5)&15) - 1; tm.tm_mday = ddate&31; tm.tm_hour = (dtime>>11)&31; tm.tm_min = (dtime>>5)&63; tm.tm_sec = (dtime<<1)&62; return mktime(&tm); } static zip_extra_field_t * _zip_ef_utf8(zip_uint16_t id, zip_string_t *str, zip_error_t *error) { const zip_uint8_t *raw; zip_uint32_t len; zip_buffer_t *buffer; zip_extra_field_t *ef; if ((raw=_zip_string_get(str, &len, ZIP_FL_ENC_RAW, NULL)) == NULL) { /* error already set */ return NULL; } if (len+5 > ZIP_UINT16_MAX) { zip_error_set(error, ZIP_ER_INVAL, 0); /* TODO: better error code? */ return NULL; } if ((buffer = _zip_buffer_new(NULL, len+5)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); return NULL; } _zip_buffer_put_8(buffer, 1); _zip_buffer_put_32(buffer, _zip_string_crc32(str)); _zip_buffer_put(buffer, raw, len); if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); return NULL; } ef = _zip_ef_new(id, (zip_uint16_t)(_zip_buffer_offset(buffer)), _zip_buffer_data(buffer), ZIP_EF_BOTH); _zip_buffer_free(buffer); return ef; } zip_dirent_t * _zip_get_dirent(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_error_t *error) { if (error == NULL) error = &za->error; if (idx >= za->nentry) { zip_error_set(error, ZIP_ER_INVAL, 0); return NULL; } if ((flags & ZIP_FL_UNCHANGED) || za->entry[idx].changes == NULL) { if (za->entry[idx].orig == NULL) { zip_error_set(error, ZIP_ER_INVAL, 0); return NULL; } if (za->entry[idx].deleted && (flags & ZIP_FL_UNCHANGED) == 0) { zip_error_set(error, ZIP_ER_DELETED, 0); return NULL; } return za->entry[idx].orig; } else return za->entry[idx].changes; } void _zip_u2d_time(time_t intime, zip_uint16_t *dtime, zip_uint16_t *ddate) { struct tm *tm; tm = localtime(&intime); if (tm->tm_year < 80) { tm->tm_year = 80; } *ddate = (zip_uint16_t)(((tm->tm_year+1900-1980)<<9) + ((tm->tm_mon+1)<<5) + tm->tm_mday); *dtime = (zip_uint16_t)(((tm->tm_hour)<<11) + ((tm->tm_min)<<5) + ((tm->tm_sec)>>1)); return; } void _zip_dirent_set_version_needed(zip_dirent_t *de, bool force_zip64) { zip_uint16_t length; if (de->comp_method == ZIP_CM_LZMA) { de->version_needed = 63; return; } if (de->comp_method == ZIP_CM_BZIP2) { de->version_needed = 46; return; } if (force_zip64 || _zip_dirent_needs_zip64(de, 0)) { de->version_needed = 45; return; } if (de->comp_method == ZIP_CM_DEFLATE || de->encryption_method == ZIP_EM_TRAD_PKWARE) { de->version_needed = 20; return; } /* directory */ if ((length = _zip_string_length(de->filename)) > 0) { if (de->filename->raw[length-1] == '/') { de->version_needed = 20; return; } } de->version_needed = 10; }
./CrossVul/dataset_final_sorted/CWE-415/c/good_2633_1
crossvul-cpp_data_bad_5172_1
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_INFO(0, var_name) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_INFO(0, var_name) ZEND_ARG_INFO(0, ...) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; TSRMLS_FETCH(); MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; PHP_CLASS_ATTRIBUTES; PHP_SET_CLASS_ATTRIBUTES(obj); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); PHP_CLEANUP_CLASS_ATTRIBUTES(); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i], strlen(atts[i])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { stack->varname = estrdup(atts[i]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) { zval *tmp; char *key; char *p1, *p2, *endp; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-415/c/bad_5172_1
crossvul-cpp_data_bad_347_9
/* * Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com> * * This file is part of OpenSC. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "egk-tool-cmdline.h" #include "libopensc/log.h" #include "libopensc/opensc.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif #ifdef ENABLE_ZLIB #include <zlib.h> int uncompress_gzip(void* uncompressed, size_t *uncompressed_len, const void* compressed, size_t compressed_len) { z_stream stream; memset(&stream, 0, sizeof stream); stream.total_in = compressed_len; stream.avail_in = compressed_len; stream.total_out = *uncompressed_len; stream.avail_out = *uncompressed_len; stream.next_in = (Bytef *) compressed; stream.next_out = (Bytef *) uncompressed; /* 15 window bits, and the +32 tells zlib to to detect if using gzip or zlib */ if (Z_OK == inflateInit2(&stream, (15 + 32)) && Z_STREAM_END == inflate(&stream, Z_FINISH)) { *uncompressed_len = stream.total_out; } else { return SC_ERROR_INVALID_DATA; } inflateEnd(&stream); return SC_SUCCESS; } #else int uncompress_gzip(void* uncompressed, size_t *uncompressed_len, const void* compressed, size_t compressed_len) { return SC_ERROR_NOT_SUPPORTED; } #endif #define PRINT(c) (isprint(c) ? c : '?') void dump_binary(void *buf, size_t buf_len) { #ifdef _WIN32 _setmode(fileno(stdout), _O_BINARY); #endif fwrite(buf, 1, buf_len, stdout); #ifdef _WIN32 _setmode(fileno(stdout), _O_TEXT); #endif } const unsigned char aid_hca[] = {0xD2, 0x76, 0x00, 0x00, 0x01, 0x02}; static int initialize(int reader_id, int verbose, sc_context_t **ctx, sc_reader_t **reader) { unsigned int i, reader_count; int r; if (!ctx || !reader) return SC_ERROR_INVALID_ARGUMENTS; r = sc_establish_context(ctx, ""); if (r < 0 || !*ctx) { fprintf(stderr, "Failed to create initial context: %s", sc_strerror(r)); return r; } (*ctx)->debug = verbose; (*ctx)->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER; reader_count = sc_ctx_get_reader_count(*ctx); if (reader_count == 0) { sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No reader not found.\n"); return SC_ERROR_NO_READERS_FOUND; } if (reader_id < 0) { /* Automatically try to skip to a reader with a card if reader not specified */ for (i = 0; i < reader_count; i++) { *reader = sc_ctx_get_reader(*ctx, i); if (sc_detect_card_presence(*reader) & SC_READER_CARD_PRESENT) { reader_id = i; sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Using the first reader" " with a card: %s", (*reader)->name); break; } } if ((unsigned int) reader_id >= reader_count) { sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "No card found, using the first reader."); reader_id = 0; } } if ((unsigned int) reader_id >= reader_count) { sc_debug(*ctx, SC_LOG_DEBUG_NORMAL, "Invalid reader number " "(%d), only %d available.\n", reader_id, reader_count); return SC_ERROR_NO_READERS_FOUND; } *reader = sc_ctx_get_reader(*ctx, reader_id); return SC_SUCCESS; } int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len) { struct sc_path path; struct sc_file *file; unsigned char *p; int ok = 0; int r; size_t len; sc_format_path(str_path, &path); if (SC_SUCCESS != sc_select_file(card, &path, &file)) { goto err; } len = file ? file->size : 4096; p = realloc(*data, len); if (!p) { goto err; } *data = p; *data_len = len; r = sc_read_binary(card, 0, p, len, 0); if (r < 0) goto err; *data_len = r; ok = 1; err: sc_file_free(file); return ok; } void decode_version(unsigned char *bcd, unsigned int *major, unsigned int *minor, unsigned int *fix) { *major = 0; *minor = 0; *fix = 0; /* decode BCD to decimal */ if ((bcd[0]>>4) < 10 && ((bcd[0]&0xF) < 10) && ((bcd[1]>>4) < 10)) { *major = (bcd[0]>>4)*100 + (bcd[0]&0xF)*10 + (bcd[1]>>4); } if (((bcd[1]&0xF) < 10) && ((bcd[2]>>4) < 10) && ((bcd[2]&0xF) < 10)) { *minor = (bcd[1]&0xF)*100 + (bcd[2]>>4)*10 + (bcd[2]&0xF); } if ((bcd[3]>>4) < 10 && ((bcd[3]&0xF) < 10) && (bcd[4]>>4) < 10 && ((bcd[4]&0xF) < 10)) { *fix = (bcd[3]>>4)*1000 + (bcd[3]&0xF)*100 + (bcd[4]>>4)*10 + (bcd[4]&0xF); } } int main (int argc, char **argv) { struct gengetopt_args_info cmdline; struct sc_path path; struct sc_context *ctx; struct sc_reader *reader = NULL; struct sc_card *card; unsigned char *data = NULL; size_t data_len = 0; int r; if (cmdline_parser(argc, argv, &cmdline) != 0) exit(1); r = initialize(cmdline.reader_arg, cmdline.verbose_given, &ctx, &reader); if (r < 0) { fprintf(stderr, "Can't initialize reader\n"); exit(1); } if (sc_connect_card(reader, &card) < 0) { fprintf(stderr, "Could not connect to card\n"); sc_release_context(ctx); exit(1); } sc_path_set(&path, SC_PATH_TYPE_DF_NAME, aid_hca, sizeof aid_hca, 0, 0); if (SC_SUCCESS != sc_select_file(card, &path, NULL)) goto err; if (cmdline.pd_flag && read_file(card, "D001", &data, &data_len) && data_len >= 2) { size_t len_pd = (data[0] << 8) | data[1]; if (len_pd + 2 <= data_len) { unsigned char uncompressed[1024]; size_t uncompressed_len = sizeof uncompressed; if (uncompress_gzip(uncompressed, &uncompressed_len, data + 2, len_pd) == SC_SUCCESS) { dump_binary(uncompressed, uncompressed_len); } else { dump_binary(data + 2, len_pd); } } } if ((cmdline.vd_flag || cmdline.gvd_flag) && read_file(card, "D001", &data, &data_len) && data_len >= 8) { size_t off_vd = (data[0] << 8) | data[1]; size_t end_vd = (data[2] << 8) | data[3]; size_t off_gvd = (data[4] << 8) | data[5]; size_t end_gvd = (data[6] << 8) | data[7]; size_t len_vd = end_vd - off_vd + 1; size_t len_gvd = end_gvd - off_gvd + 1; if (off_vd <= end_vd && end_vd < data_len && off_gvd <= end_gvd && end_gvd < data_len) { unsigned char uncompressed[1024]; size_t uncompressed_len = sizeof uncompressed; if (cmdline.vd_flag) { if (uncompress_gzip(uncompressed, &uncompressed_len, data + off_vd, len_vd) == SC_SUCCESS) { dump_binary(uncompressed, uncompressed_len); } else { dump_binary(data + off_vd, len_vd); } } if (cmdline.gvd_flag) { if (uncompress_gzip(uncompressed, &uncompressed_len, data + off_gvd, len_gvd) == SC_SUCCESS) { dump_binary(uncompressed, uncompressed_len); } else { dump_binary(data + off_gvd, len_gvd); } } } } if (cmdline.vsd_status_flag && read_file(card, "D00C", &data, &data_len) && data_len >= 25) { char *status; unsigned int major, minor, fix; switch (data[0]) { case '0': status = "Transactions pending"; break; case '1': status = "No transactions pending"; break; default: status = "Unknown"; break; } decode_version(data+15, &major, &minor, &fix); printf( "Status %s\n" "Timestamp %c%c.%c%c.%c%c%c%c at %c%c:%c%c:%c%c\n" "Version %u.%u.%u\n", status, PRINT(data[7]), PRINT(data[8]), PRINT(data[5]), PRINT(data[6]), PRINT(data[1]), PRINT(data[2]), PRINT(data[3]), PRINT(data[4]), PRINT(data[9]), PRINT(data[10]), PRINT(data[11]), PRINT(data[12]), PRINT(data[13]), PRINT(data[14]), major, minor, fix); } err: sc_disconnect_card(card); sc_release_context(ctx); cmdline_parser_free (&cmdline); return 0; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_347_9
crossvul-cpp_data_bad_2633_1
/* zip_dirent.c -- read directory entry (local or central), clean dirent Copyright (C) 1999-2016 Dieter Baron and Thomas Klausner This file is part of libzip, a library to manipulate ZIP archives. The authors can be contacted at <libzip@nih.at> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include "zipint.h" static time_t _zip_d2u_time(zip_uint16_t, zip_uint16_t); static zip_string_t *_zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str); static zip_extra_field_t *_zip_ef_utf8(zip_uint16_t, zip_string_t *, zip_error_t *); static bool _zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error); void _zip_cdir_free(zip_cdir_t *cd) { zip_uint64_t i; if (!cd) return; for (i=0; i<cd->nentry; i++) _zip_entry_finalize(cd->entry+i); free(cd->entry); _zip_string_free(cd->comment); free(cd); } zip_cdir_t * _zip_cdir_new(zip_uint64_t nentry, zip_error_t *error) { zip_cdir_t *cd; if ((cd=(zip_cdir_t *)malloc(sizeof(*cd))) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); return NULL; } cd->entry = NULL; cd->nentry = cd->nentry_alloc = 0; cd->size = cd->offset = 0; cd->comment = NULL; cd->is_zip64 = false; if (!_zip_cdir_grow(cd, nentry, error)) { _zip_cdir_free(cd); return NULL; } return cd; } bool _zip_cdir_grow(zip_cdir_t *cd, zip_uint64_t additional_entries, zip_error_t *error) { zip_uint64_t i, new_alloc; zip_entry_t *new_entry; if (additional_entries == 0) { return true; } new_alloc = cd->nentry_alloc + additional_entries; if (new_alloc < additional_entries || new_alloc > SIZE_MAX/sizeof(*(cd->entry))) { zip_error_set(error, ZIP_ER_MEMORY, 0); return false; } if ((new_entry = (zip_entry_t *)realloc(cd->entry, sizeof(*(cd->entry))*(size_t)new_alloc)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); return false; } cd->entry = new_entry; for (i = cd->nentry; i < new_alloc; i++) { _zip_entry_init(cd->entry+i); } cd->nentry = cd->nentry_alloc = new_alloc; return true; } zip_int64_t _zip_cdir_write(zip_t *za, const zip_filelist_t *filelist, zip_uint64_t survivors) { zip_uint64_t offset, size; zip_string_t *comment; zip_uint8_t buf[EOCDLEN + EOCD64LEN + EOCD64LOCLEN]; zip_buffer_t *buffer; zip_int64_t off; zip_uint64_t i; bool is_zip64; int ret; if ((off = zip_source_tell_write(za->src)) < 0) { _zip_error_set_from_source(&za->error, za->src); return -1; } offset = (zip_uint64_t)off; is_zip64 = false; for (i=0; i<survivors; i++) { zip_entry_t *entry = za->entry+filelist[i].idx; if ((ret=_zip_dirent_write(za, entry->changes ? entry->changes : entry->orig, ZIP_FL_CENTRAL)) < 0) return -1; if (ret) is_zip64 = true; } if ((off = zip_source_tell_write(za->src)) < 0) { _zip_error_set_from_source(&za->error, za->src); return -1; } size = (zip_uint64_t)off - offset; if (offset > ZIP_UINT32_MAX || survivors > ZIP_UINT16_MAX) is_zip64 = true; if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); return -1; } if (is_zip64) { _zip_buffer_put(buffer, EOCD64_MAGIC, 4); _zip_buffer_put_64(buffer, EOCD64LEN-12); _zip_buffer_put_16(buffer, 45); _zip_buffer_put_16(buffer, 45); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_64(buffer, survivors); _zip_buffer_put_64(buffer, survivors); _zip_buffer_put_64(buffer, size); _zip_buffer_put_64(buffer, offset); _zip_buffer_put(buffer, EOCD64LOC_MAGIC, 4); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_64(buffer, offset+size); _zip_buffer_put_32(buffer, 1); } _zip_buffer_put(buffer, EOCD_MAGIC, 4); _zip_buffer_put_32(buffer, 0); _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); _zip_buffer_put_16(buffer, (zip_uint16_t)(survivors >= ZIP_UINT16_MAX ? ZIP_UINT16_MAX : survivors)); _zip_buffer_put_32(buffer, size >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)size); _zip_buffer_put_32(buffer, offset >= ZIP_UINT32_MAX ? ZIP_UINT32_MAX : (zip_uint32_t)offset); comment = za->comment_changed ? za->comment_changes : za->comment_orig; _zip_buffer_put_16(buffer, (zip_uint16_t)(comment ? comment->length : 0)); if (!_zip_buffer_ok(buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); return -1; } if (_zip_write(za, _zip_buffer_data(buffer), _zip_buffer_offset(buffer)) < 0) { _zip_buffer_free(buffer); return -1; } _zip_buffer_free(buffer); if (comment) { if (_zip_write(za, comment->raw, comment->length) < 0) { return -1; } } return (zip_int64_t)size; } zip_dirent_t * _zip_dirent_clone(const zip_dirent_t *sde) { zip_dirent_t *tde; if ((tde=(zip_dirent_t *)malloc(sizeof(*tde))) == NULL) return NULL; if (sde) memcpy(tde, sde, sizeof(*sde)); else _zip_dirent_init(tde); tde->changed = 0; tde->cloned = 1; return tde; } void _zip_dirent_finalize(zip_dirent_t *zde) { if (!zde->cloned || zde->changed & ZIP_DIRENT_FILENAME) { _zip_string_free(zde->filename); zde->filename = NULL; } if (!zde->cloned || zde->changed & ZIP_DIRENT_EXTRA_FIELD) { _zip_ef_free(zde->extra_fields); zde->extra_fields = NULL; } if (!zde->cloned || zde->changed & ZIP_DIRENT_COMMENT) { _zip_string_free(zde->comment); zde->comment = NULL; } if (!zde->cloned || zde->changed & ZIP_DIRENT_PASSWORD) { if (zde->password) { _zip_crypto_clear(zde->password, strlen(zde->password)); } free(zde->password); zde->password = NULL; } } void _zip_dirent_free(zip_dirent_t *zde) { if (zde == NULL) return; _zip_dirent_finalize(zde); free(zde); } void _zip_dirent_init(zip_dirent_t *de) { de->changed = 0; de->local_extra_fields_read = 0; de->cloned = 0; de->crc_valid = true; de->version_madeby = 63 | (ZIP_OPSYS_DEFAULT << 8); de->version_needed = 10; /* 1.0 */ de->bitflags = 0; de->comp_method = ZIP_CM_DEFAULT; de->last_mod = 0; de->crc = 0; de->comp_size = 0; de->uncomp_size = 0; de->filename = NULL; de->extra_fields = NULL; de->comment = NULL; de->disk_number = 0; de->int_attrib = 0; de->ext_attrib = ZIP_EXT_ATTRIB_DEFAULT; de->offset = 0; de->compression_level = 0; de->encryption_method = ZIP_EM_NONE; de->password = NULL; } bool _zip_dirent_needs_zip64(const zip_dirent_t *de, zip_flags_t flags) { if (de->uncomp_size >= ZIP_UINT32_MAX || de->comp_size >= ZIP_UINT32_MAX || ((flags & ZIP_FL_CENTRAL) && de->offset >= ZIP_UINT32_MAX)) return true; return false; } zip_dirent_t * _zip_dirent_new(void) { zip_dirent_t *de; if ((de=(zip_dirent_t *)malloc(sizeof(*de))) == NULL) return NULL; _zip_dirent_init(de); return de; } /* _zip_dirent_read(zde, fp, bufp, left, localp, error): Fills the zip directory entry zde. If buffer is non-NULL, data is taken from there; otherwise data is read from fp as needed. If local is true, it reads a local header instead of a central directory entry. Returns size of dirent read if successful. On error, error is filled in and -1 is returned. */ zip_int64_t _zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error) { zip_uint8_t buf[CDENTRYSIZE]; zip_uint16_t dostime, dosdate; zip_uint32_t size, variable_size; zip_uint16_t filename_len, comment_len, ef_len; bool from_buffer = (buffer != NULL); size = local ? LENTRYSIZE : CDENTRYSIZE; if (buffer) { if (_zip_buffer_left(buffer) < size) { zip_error_set(error, ZIP_ER_NOZIP, 0); return -1; } } else { if ((buffer = _zip_buffer_new_from_source(src, size, buf, error)) == NULL) { return -1; } } if (memcmp(_zip_buffer_get(buffer, 4), (local ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) { zip_error_set(error, ZIP_ER_NOZIP, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } /* convert buffercontents to zip_dirent */ _zip_dirent_init(zde); if (!local) zde->version_madeby = _zip_buffer_get_16(buffer); else zde->version_madeby = 0; zde->version_needed = _zip_buffer_get_16(buffer); zde->bitflags = _zip_buffer_get_16(buffer); zde->comp_method = _zip_buffer_get_16(buffer); /* convert to time_t */ dostime = _zip_buffer_get_16(buffer); dosdate = _zip_buffer_get_16(buffer); zde->last_mod = _zip_d2u_time(dostime, dosdate); zde->crc = _zip_buffer_get_32(buffer); zde->comp_size = _zip_buffer_get_32(buffer); zde->uncomp_size = _zip_buffer_get_32(buffer); filename_len = _zip_buffer_get_16(buffer); ef_len = _zip_buffer_get_16(buffer); if (local) { comment_len = 0; zde->disk_number = 0; zde->int_attrib = 0; zde->ext_attrib = 0; zde->offset = 0; } else { comment_len = _zip_buffer_get_16(buffer); zde->disk_number = _zip_buffer_get_16(buffer); zde->int_attrib = _zip_buffer_get_16(buffer); zde->ext_attrib = _zip_buffer_get_32(buffer); zde->offset = _zip_buffer_get_32(buffer); } if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCRYPTED) { if (zde->bitflags & ZIP_GPBF_STRONG_ENCRYPTION) { /* TODO */ zde->encryption_method = ZIP_EM_UNKNOWN; } else { zde->encryption_method = ZIP_EM_TRAD_PKWARE; } } else { zde->encryption_method = ZIP_EM_NONE; } zde->filename = NULL; zde->extra_fields = NULL; zde->comment = NULL; variable_size = (zip_uint32_t)filename_len+(zip_uint32_t)ef_len+(zip_uint32_t)comment_len; if (from_buffer) { if (_zip_buffer_left(buffer) < variable_size) { zip_error_set(error, ZIP_ER_INCONS, 0); return -1; } } else { _zip_buffer_free(buffer); if ((buffer = _zip_buffer_new_from_source(src, variable_size, NULL, error)) == NULL) { return -1; } } if (filename_len) { zde->filename = _zip_read_string(buffer, src, filename_len, 1, error); if (!zde->filename) { if (zip_error_code_zip(error) == ZIP_ER_EOF) { zip_error_set(error, ZIP_ER_INCONS, 0); } if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { if (_zip_guess_encoding(zde->filename, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { zip_error_set(error, ZIP_ER_INCONS, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } } } if (ef_len) { zip_uint8_t *ef = _zip_read_data(buffer, src, ef_len, 0, error); if (ef == NULL) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (!_zip_ef_parse(ef, ef_len, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, &zde->extra_fields, error)) { free(ef); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } free(ef); if (local) zde->local_extra_fields_read = 1; } if (comment_len) { zde->comment = _zip_read_string(buffer, src, comment_len, 0, error); if (!zde->comment) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) { if (_zip_guess_encoding(zde->comment, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) { zip_error_set(error, ZIP_ER_INCONS, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } } } zde->filename = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_NAME, zde->filename); zde->comment = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_COMMENT, zde->comment); /* Zip64 */ if (zde->uncomp_size == ZIP_UINT32_MAX || zde->comp_size == ZIP_UINT32_MAX || zde->offset == ZIP_UINT32_MAX) { zip_uint16_t got_len; zip_buffer_t *ef_buffer; const zip_uint8_t *ef = _zip_ef_get_by_id(zde->extra_fields, &got_len, ZIP_EF_ZIP64, 0, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, error); /* TODO: if got_len == 0 && !ZIP64_EOCD: no error, 0xffffffff is valid value */ if (ef == NULL) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if ((ef_buffer = _zip_buffer_new((zip_uint8_t *)ef, got_len)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (zde->uncomp_size == ZIP_UINT32_MAX) zde->uncomp_size = _zip_buffer_get_64(ef_buffer); else if (local) { /* From appnote.txt: This entry in the Local header MUST include BOTH original and compressed file size fields. */ (void)_zip_buffer_skip(ef_buffer, 8); /* error is caught by _zip_buffer_eof() call */ } if (zde->comp_size == ZIP_UINT32_MAX) zde->comp_size = _zip_buffer_get_64(ef_buffer); if (!local) { if (zde->offset == ZIP_UINT32_MAX) zde->offset = _zip_buffer_get_64(ef_buffer); if (zde->disk_number == ZIP_UINT16_MAX) zde->disk_number = _zip_buffer_get_32(buffer); } if (!_zip_buffer_eof(ef_buffer)) { zip_error_set(error, ZIP_ER_INCONS, 0); _zip_buffer_free(ef_buffer); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } _zip_buffer_free(ef_buffer); } if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } if (!from_buffer) { _zip_buffer_free(buffer); } /* zip_source_seek / zip_source_tell don't support values > ZIP_INT64_MAX */ if (zde->offset > ZIP_INT64_MAX) { zip_error_set(error, ZIP_ER_SEEK, EFBIG); return -1; } if (!_zip_dirent_process_winzip_aes(zde, error)) { if (!from_buffer) { _zip_buffer_free(buffer); } return -1; } zde->extra_fields = _zip_ef_remove_internal(zde->extra_fields); return (zip_int64_t)(size + variable_size); } static zip_string_t * _zip_dirent_process_ef_utf_8(const zip_dirent_t *de, zip_uint16_t id, zip_string_t *str) { zip_uint16_t ef_len; zip_uint32_t ef_crc; zip_buffer_t *buffer; const zip_uint8_t *ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, id, 0, ZIP_EF_BOTH, NULL); if (ef == NULL || ef_len < 5 || ef[0] != 1) { return str; } if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { return str; } _zip_buffer_get_8(buffer); ef_crc = _zip_buffer_get_32(buffer); if (_zip_string_crc32(str) == ef_crc) { zip_uint16_t len = (zip_uint16_t)_zip_buffer_left(buffer); zip_string_t *ef_str = _zip_string_new(_zip_buffer_get(buffer, len), len, ZIP_FL_ENC_UTF_8, NULL); if (ef_str != NULL) { _zip_string_free(str); str = ef_str; } } _zip_buffer_free(buffer); return str; } static bool _zip_dirent_process_winzip_aes(zip_dirent_t *de, zip_error_t *error) { zip_uint16_t ef_len; zip_buffer_t *buffer; const zip_uint8_t *ef; bool crc_valid; zip_uint16_t enc_method; if (de->comp_method != ZIP_CM_WINZIP_AES) { return true; } ef = _zip_ef_get_by_id(de->extra_fields, &ef_len, ZIP_EF_WINZIP_AES, 0, ZIP_EF_BOTH, NULL); if (ef == NULL || ef_len < 7) { zip_error_set(error, ZIP_ER_INCONS, 0); return false; } if ((buffer = _zip_buffer_new((zip_uint8_t *)ef, ef_len)) == NULL) { zip_error_set(error, ZIP_ER_INTERNAL, 0); return false; } /* version */ crc_valid = true; switch (_zip_buffer_get_16(buffer)) { case 1: break; case 2: if (de->uncomp_size < 20 /* TODO: constant */) { crc_valid = false; } break; default: zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); _zip_buffer_free(buffer); return false; } /* vendor */ if (memcmp(_zip_buffer_get(buffer, 2), "AE", 2) != 0) { zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); _zip_buffer_free(buffer); return false; } /* mode */ switch (_zip_buffer_get_8(buffer)) { case 1: enc_method = ZIP_EM_AES_128; break; case 2: enc_method = ZIP_EM_AES_192; break; case 3: enc_method = ZIP_EM_AES_256; break; default: zip_error_set(error, ZIP_ER_ENCRNOTSUPP, 0); _zip_buffer_free(buffer); return false; } if (ef_len != 7) { zip_error_set(error, ZIP_ER_INCONS, 0); _zip_buffer_free(buffer); return false; } de->crc_valid = crc_valid; de->encryption_method = enc_method; de->comp_method = _zip_buffer_get_16(buffer); _zip_buffer_free(buffer); return true; } zip_int32_t _zip_dirent_size(zip_source_t *src, zip_uint16_t flags, zip_error_t *error) { zip_int32_t size; bool local = (flags & ZIP_EF_LOCAL) != 0; int i; zip_uint8_t b[6]; zip_buffer_t *buffer; size = local ? LENTRYSIZE : CDENTRYSIZE; if (zip_source_seek(src, local ? 26 : 28, SEEK_CUR) < 0) { _zip_error_set_from_source(error, src); return -1; } if ((buffer = _zip_buffer_new_from_source(src, local ? 4 : 6, b, error)) == NULL) { return -1; } for (i=0; i<(local ? 2 : 3); i++) { size += _zip_buffer_get_16(buffer); } if (!_zip_buffer_eof(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); return -1; } _zip_buffer_free(buffer); return size; } /* _zip_dirent_write Writes zip directory entry. If flags & ZIP_EF_LOCAL, it writes a local header instead of a central directory entry. If flags & ZIP_EF_FORCE_ZIP64, a ZIP64 extra field is written, even if not needed. Returns 0 if successful, 1 if successful and wrote ZIP64 extra field. On error, error is filled in and -1 is returned. */ int _zip_dirent_write(zip_t *za, zip_dirent_t *de, zip_flags_t flags) { zip_uint16_t dostime, dosdate; zip_encoding_type_t com_enc, name_enc; zip_extra_field_t *ef; zip_extra_field_t *ef64; zip_uint32_t ef_total_size; bool is_zip64; bool is_really_zip64; bool is_winzip_aes; zip_uint8_t buf[CDENTRYSIZE]; zip_buffer_t *buffer; ef = NULL; name_enc = _zip_guess_encoding(de->filename, ZIP_ENCODING_UNKNOWN); com_enc = _zip_guess_encoding(de->comment, ZIP_ENCODING_UNKNOWN); if ((name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_ASCII) || (name_enc == ZIP_ENCODING_ASCII && com_enc == ZIP_ENCODING_UTF8_KNOWN) || (name_enc == ZIP_ENCODING_UTF8_KNOWN && com_enc == ZIP_ENCODING_UTF8_KNOWN)) de->bitflags |= ZIP_GPBF_ENCODING_UTF_8; else { de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCODING_UTF_8; if (name_enc == ZIP_ENCODING_UTF8_KNOWN) { ef = _zip_ef_utf8(ZIP_EF_UTF_8_NAME, de->filename, &za->error); if (ef == NULL) return -1; } if ((flags & ZIP_FL_LOCAL) == 0 && com_enc == ZIP_ENCODING_UTF8_KNOWN){ zip_extra_field_t *ef2 = _zip_ef_utf8(ZIP_EF_UTF_8_COMMENT, de->comment, &za->error); if (ef2 == NULL) { _zip_ef_free(ef); return -1; } ef2->next = ef; ef = ef2; } } if (de->encryption_method == ZIP_EM_NONE) { de->bitflags &= (zip_uint16_t)~ZIP_GPBF_ENCRYPTED; } else { de->bitflags |= (zip_uint16_t)ZIP_GPBF_ENCRYPTED; } is_really_zip64 = _zip_dirent_needs_zip64(de, flags); is_zip64 = (flags & (ZIP_FL_LOCAL|ZIP_FL_FORCE_ZIP64)) == (ZIP_FL_LOCAL|ZIP_FL_FORCE_ZIP64) || is_really_zip64; is_winzip_aes = de->encryption_method == ZIP_EM_AES_128 || de->encryption_method == ZIP_EM_AES_192 || de->encryption_method == ZIP_EM_AES_256; if (is_zip64) { zip_uint8_t ef_zip64[EFZIP64SIZE]; zip_buffer_t *ef_buffer = _zip_buffer_new(ef_zip64, sizeof(ef_zip64)); if (ef_buffer == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_ef_free(ef); return -1; } if (flags & ZIP_FL_LOCAL) { if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->uncomp_size); _zip_buffer_put_64(ef_buffer, de->comp_size); } } else { if ((flags & ZIP_FL_FORCE_ZIP64) || de->comp_size > ZIP_UINT32_MAX || de->uncomp_size > ZIP_UINT32_MAX || de->offset > ZIP_UINT32_MAX) { if (de->uncomp_size >= ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->uncomp_size); } if (de->comp_size >= ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->comp_size); } if (de->offset >= ZIP_UINT32_MAX) { _zip_buffer_put_64(ef_buffer, de->offset); } } } if (!_zip_buffer_ok(ef_buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(ef_buffer); _zip_ef_free(ef); return -1; } ef64 = _zip_ef_new(ZIP_EF_ZIP64, (zip_uint16_t)(_zip_buffer_offset(ef_buffer)), ef_zip64, ZIP_EF_BOTH); _zip_buffer_free(ef_buffer); ef64->next = ef; ef = ef64; } if (is_winzip_aes) { zip_uint8_t data[EF_WINZIP_AES_SIZE]; zip_buffer_t *ef_buffer = _zip_buffer_new(data, sizeof(data)); zip_extra_field_t *ef_winzip; if (ef_buffer == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_ef_free(ef); return -1; } _zip_buffer_put_16(ef_buffer, 2); _zip_buffer_put(ef_buffer, "AE", 2); _zip_buffer_put_8(ef_buffer, (zip_uint8_t)(de->encryption_method & 0xff)); _zip_buffer_put_16(ef_buffer, (zip_uint16_t)de->comp_method); if (!_zip_buffer_ok(ef_buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(ef_buffer); _zip_ef_free(ef); return -1; } ef_winzip = _zip_ef_new(ZIP_EF_WINZIP_AES, EF_WINZIP_AES_SIZE, data, ZIP_EF_BOTH); _zip_buffer_free(ef_buffer); ef_winzip->next = ef; ef = ef_winzip; } if ((buffer = _zip_buffer_new(buf, sizeof(buf))) == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_ef_free(ef); return -1; } _zip_buffer_put(buffer, (flags & ZIP_FL_LOCAL) ? LOCAL_MAGIC : CENTRAL_MAGIC, 4); if ((flags & ZIP_FL_LOCAL) == 0) { _zip_buffer_put_16(buffer, (zip_uint16_t)(is_really_zip64 ? 45 : de->version_madeby)); } _zip_buffer_put_16(buffer, (zip_uint16_t)(is_really_zip64 ? 45 : de->version_needed)); _zip_buffer_put_16(buffer, de->bitflags); if (is_winzip_aes) { _zip_buffer_put_16(buffer, ZIP_CM_WINZIP_AES); } else { _zip_buffer_put_16(buffer, (zip_uint16_t)de->comp_method); } _zip_u2d_time(de->last_mod, &dostime, &dosdate); _zip_buffer_put_16(buffer, dostime); _zip_buffer_put_16(buffer, dosdate); if (is_winzip_aes && de->uncomp_size < 20) { _zip_buffer_put_32(buffer, 0); } else { _zip_buffer_put_32(buffer, de->crc); } if (((flags & ZIP_FL_LOCAL) == ZIP_FL_LOCAL) && ((de->comp_size >= ZIP_UINT32_MAX) || (de->uncomp_size >= ZIP_UINT32_MAX))) { /* In local headers, if a ZIP64 EF is written, it MUST contain * both compressed and uncompressed sizes (even if one of the * two is smaller than 0xFFFFFFFF); on the other hand, those * may only appear when the corresponding standard entry is * 0xFFFFFFFF. (appnote.txt 4.5.3) */ _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } else { if (de->comp_size < ZIP_UINT32_MAX) { _zip_buffer_put_32(buffer, (zip_uint32_t)de->comp_size); } else { _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } if (de->uncomp_size < ZIP_UINT32_MAX) { _zip_buffer_put_32(buffer, (zip_uint32_t)de->uncomp_size); } else { _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } } _zip_buffer_put_16(buffer, _zip_string_length(de->filename)); /* TODO: check for overflow */ ef_total_size = (zip_uint32_t)_zip_ef_size(de->extra_fields, flags) + (zip_uint32_t)_zip_ef_size(ef, ZIP_EF_BOTH); _zip_buffer_put_16(buffer, (zip_uint16_t)ef_total_size); if ((flags & ZIP_FL_LOCAL) == 0) { _zip_buffer_put_16(buffer, _zip_string_length(de->comment)); _zip_buffer_put_16(buffer, (zip_uint16_t)de->disk_number); _zip_buffer_put_16(buffer, de->int_attrib); _zip_buffer_put_32(buffer, de->ext_attrib); if (de->offset < ZIP_UINT32_MAX) _zip_buffer_put_32(buffer, (zip_uint32_t)de->offset); else _zip_buffer_put_32(buffer, ZIP_UINT32_MAX); } if (!_zip_buffer_ok(buffer)) { zip_error_set(&za->error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); _zip_ef_free(ef); return -1; } if (_zip_write(za, buf, _zip_buffer_offset(buffer)) < 0) { _zip_buffer_free(buffer); _zip_ef_free(ef); return -1; } _zip_buffer_free(buffer); if (de->filename) { if (_zip_string_write(za, de->filename) < 0) { _zip_ef_free(ef); return -1; } } if (ef) { if (_zip_ef_write(za, ef, ZIP_EF_BOTH) < 0) { _zip_ef_free(ef); return -1; } } _zip_ef_free(ef); if (de->extra_fields) { if (_zip_ef_write(za, de->extra_fields, flags) < 0) { return -1; } } if ((flags & ZIP_FL_LOCAL) == 0) { if (de->comment) { if (_zip_string_write(za, de->comment) < 0) { return -1; } } } return is_zip64; } static time_t _zip_d2u_time(zip_uint16_t dtime, zip_uint16_t ddate) { struct tm tm; memset(&tm, 0, sizeof(tm)); /* let mktime decide if DST is in effect */ tm.tm_isdst = -1; tm.tm_year = ((ddate>>9)&127) + 1980 - 1900; tm.tm_mon = ((ddate>>5)&15) - 1; tm.tm_mday = ddate&31; tm.tm_hour = (dtime>>11)&31; tm.tm_min = (dtime>>5)&63; tm.tm_sec = (dtime<<1)&62; return mktime(&tm); } static zip_extra_field_t * _zip_ef_utf8(zip_uint16_t id, zip_string_t *str, zip_error_t *error) { const zip_uint8_t *raw; zip_uint32_t len; zip_buffer_t *buffer; zip_extra_field_t *ef; if ((raw=_zip_string_get(str, &len, ZIP_FL_ENC_RAW, NULL)) == NULL) { /* error already set */ return NULL; } if (len+5 > ZIP_UINT16_MAX) { zip_error_set(error, ZIP_ER_INVAL, 0); /* TODO: better error code? */ return NULL; } if ((buffer = _zip_buffer_new(NULL, len+5)) == NULL) { zip_error_set(error, ZIP_ER_MEMORY, 0); return NULL; } _zip_buffer_put_8(buffer, 1); _zip_buffer_put_32(buffer, _zip_string_crc32(str)); _zip_buffer_put(buffer, raw, len); if (!_zip_buffer_ok(buffer)) { zip_error_set(error, ZIP_ER_INTERNAL, 0); _zip_buffer_free(buffer); return NULL; } ef = _zip_ef_new(id, (zip_uint16_t)(_zip_buffer_offset(buffer)), _zip_buffer_data(buffer), ZIP_EF_BOTH); _zip_buffer_free(buffer); return ef; } zip_dirent_t * _zip_get_dirent(zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_error_t *error) { if (error == NULL) error = &za->error; if (idx >= za->nentry) { zip_error_set(error, ZIP_ER_INVAL, 0); return NULL; } if ((flags & ZIP_FL_UNCHANGED) || za->entry[idx].changes == NULL) { if (za->entry[idx].orig == NULL) { zip_error_set(error, ZIP_ER_INVAL, 0); return NULL; } if (za->entry[idx].deleted && (flags & ZIP_FL_UNCHANGED) == 0) { zip_error_set(error, ZIP_ER_DELETED, 0); return NULL; } return za->entry[idx].orig; } else return za->entry[idx].changes; } void _zip_u2d_time(time_t intime, zip_uint16_t *dtime, zip_uint16_t *ddate) { struct tm *tm; tm = localtime(&intime); if (tm->tm_year < 80) { tm->tm_year = 80; } *ddate = (zip_uint16_t)(((tm->tm_year+1900-1980)<<9) + ((tm->tm_mon+1)<<5) + tm->tm_mday); *dtime = (zip_uint16_t)(((tm->tm_hour)<<11) + ((tm->tm_min)<<5) + ((tm->tm_sec)>>1)); return; } void _zip_dirent_set_version_needed(zip_dirent_t *de, bool force_zip64) { zip_uint16_t length; if (de->comp_method == ZIP_CM_LZMA) { de->version_needed = 63; return; } if (de->comp_method == ZIP_CM_BZIP2) { de->version_needed = 46; return; } if (force_zip64 || _zip_dirent_needs_zip64(de, 0)) { de->version_needed = 45; return; } if (de->comp_method == ZIP_CM_DEFLATE || de->encryption_method == ZIP_EM_TRAD_PKWARE) { de->version_needed = 20; return; } /* directory */ if ((length = _zip_string_length(de->filename)) > 0) { if (de->filename->raw[length-1] == '/') { de->version_needed = 20; return; } } de->version_needed = 10; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2633_1
crossvul-cpp_data_bad_1858_0
/* * History: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com), * to allow user process control of SCSI devices. * Development Sponsored by Killy Corp. NY NY * * Original driver (sg.c): * Copyright (C) 1992 Lawrence Foard * Version 2 and 3 extensions to driver: * Copyright (C) 1998 - 2014 Douglas Gilbert * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * */ static int sg_version_num = 30536; /* 2 digits for each component */ #define SG_VERSION_STR "3.5.36" /* * D. P. Gilbert (dgilbert@interlog.com), notes: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First * the kernel/module needs to be built with CONFIG_SCSI_LOGGING * (otherwise the macros compile to empty statements). * */ #include <linux/module.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/errno.h> #include <linux/mtio.h> #include <linux/ioctl.h> #include <linux/slab.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/moduleparam.h> #include <linux/cdev.h> #include <linux/idr.h> #include <linux/seq_file.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/blktrace_api.h> #include <linux/mutex.h> #include <linux/atomic.h> #include <linux/ratelimit.h> #include <linux/uio.h> #include "scsi.h" #include <scsi/scsi_dbg.h> #include <scsi/scsi_host.h> #include <scsi/scsi_driver.h> #include <scsi/scsi_ioctl.h> #include <scsi/sg.h> #include "scsi_logging.h" #ifdef CONFIG_SCSI_PROC_FS #include <linux/proc_fs.h> static char *sg_version_date = "20140603"; static int sg_proc_init(void); static void sg_proc_cleanup(void); #endif #define SG_ALLOW_DIO_DEF 0 #define SG_MAX_DEVS 32768 /* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater * than 16 bytes are "variable length" whose length is a multiple of 4 */ #define SG_MAX_CDB_SIZE 252 /* * Suppose you want to calculate the formula muldiv(x,m,d)=int(x * m / d) * Then when using 32 bit integers x * m may overflow during the calculation. * Replacing muldiv(x) by muldiv(x)=((x % d) * m) / d + int(x / d) * m * calculates the same, but prevents the overflow when both m and d * are "small" numbers (like HZ and USER_HZ). * Of course an overflow is inavoidable if the result of muldiv doesn't fit * in 32 bits. */ #define MULDIV(X,MUL,DIV) ((((X % DIV) * MUL) / DIV) + ((X / DIV) * MUL)) #define SG_DEFAULT_TIMEOUT MULDIV(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ) int sg_big_buff = SG_DEF_RESERVED_SIZE; /* N.B. This variable is readable and writeable via /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer of this size (or less if there is not enough memory) will be reserved for use by this file descriptor. [Deprecated usage: this variable is also readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into the kernel (i.e. it is not a module).] */ static int def_reserved_size = -1; /* picks up init parameter */ static int sg_allow_dio = SG_ALLOW_DIO_DEF; static int scatter_elem_sz = SG_SCATTER_SZ; static int scatter_elem_sz_prev = SG_SCATTER_SZ; #define SG_SECTOR_SZ 512 static int sg_add_device(struct device *, struct class_interface *); static void sg_remove_device(struct device *, struct class_interface *); static DEFINE_IDR(sg_index_idr); static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock file descriptor list for device */ static struct class_interface sg_interface = { .add_dev = sg_add_device, .remove_dev = sg_remove_device, }; typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */ unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */ unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */ unsigned bufflen; /* Size of (aggregate) data buffer */ struct page **pages; int page_order; char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */ unsigned char cmd_opcode; /* first byte of command */ } Sg_scatter_hold; struct sg_device; /* forward declarations */ struct sg_fd; typedef struct sg_request { /* SG_MAX_QUEUE requests outstanding per file */ struct sg_request *nextrp; /* NULL -> tail request (slist) */ struct sg_fd *parentfp; /* NULL -> not in use */ Sg_scatter_hold data; /* hold buffer, perhaps scatter list */ sg_io_hdr_t header; /* scsi command+info, see <scsi/sg.h> */ unsigned char sense_b[SCSI_SENSE_BUFFERSIZE]; char res_used; /* 1 -> using reserve buffer, 0 -> not ... */ char orphan; /* 1 -> drop on sight, 0 -> normal */ char sg_io_owned; /* 1 -> packet belongs to SG_IO */ /* done protected by rq_list_lock */ char done; /* 0->before bh, 1->before read, 2->read */ struct request *rq; struct bio *bio; struct execute_work ew; } Sg_request; typedef struct sg_fd { /* holds the state of a file descriptor */ struct list_head sfd_siblings; /* protected by device's sfd_lock */ struct sg_device *parentdp; /* owning device */ wait_queue_head_t read_wait; /* queue read until command done */ rwlock_t rq_list_lock; /* protect access to list in req_arr */ int timeout; /* defaults to SG_DEFAULT_TIMEOUT */ int timeout_user; /* defaults to SG_DEFAULT_TIMEOUT_USER */ Sg_scatter_hold reserve; /* buffer held for this file descriptor */ unsigned save_scat_len; /* original length of trunc. scat. element */ Sg_request *headrp; /* head of request slist, NULL->empty */ struct fasync_struct *async_qp; /* used by asynchronous notification */ Sg_request req_arr[SG_MAX_QUEUE]; /* used as singly-linked list */ char low_dma; /* as in parent but possibly overridden to 1 */ char force_packid; /* 1 -> pack_id input to read(), 0 -> ignored */ char cmd_q; /* 1 -> allow command queuing, 0 -> don't */ unsigned char next_cmd_len; /* 0: automatic, >0: use on next write() */ char keep_orphan; /* 0 -> drop orphan (def), 1 -> keep for read() */ char mmap_called; /* 0 -> mmap() never called on this fd */ struct kref f_ref; struct execute_work ew; } Sg_fd; typedef struct sg_device { /* holds the state of each scsi generic device */ struct scsi_device *device; wait_queue_head_t open_wait; /* queue open() when O_EXCL present */ struct mutex open_rel_lock; /* held when in open() or release() */ int sg_tablesize; /* adapter's max scatter-gather table size */ u32 index; /* device index number */ struct list_head sfds; rwlock_t sfd_lock; /* protect access to sfd list */ atomic_t detaching; /* 0->device usable, 1->device detaching */ bool exclude; /* 1->open(O_EXCL) succeeded and is active */ int open_cnt; /* count of opens (perhaps < num(sfds) ) */ char sgdebug; /* 0->off, 1->sense, 9->dump dev, 10-> all devs */ struct gendisk *disk; struct cdev * cdev; /* char_dev [sysfs: /sys/cdev/major/sg<n>] */ struct kref d_ref; } Sg_device; /* tasklet or soft irq callback */ static void sg_rq_end_io(struct request *rq, int uptodate); static int sg_start_req(Sg_request *srp, unsigned char *cmd); static int sg_finish_rem_req(Sg_request * srp); static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size); static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp); static ssize_t sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf, size_t count, int blocking, int read_only, int sg_io_owned, Sg_request **o_srp); static int sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking); static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer); static void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp); static void sg_build_reserve(Sg_fd * sfp, int req_size); static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size); static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp); static Sg_fd *sg_add_sfp(Sg_device * sdp); static void sg_remove_sfp(struct kref *); static Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id); static Sg_request *sg_add_request(Sg_fd * sfp); static int sg_remove_request(Sg_fd * sfp, Sg_request * srp); static int sg_res_in_use(Sg_fd * sfp); static Sg_device *sg_get_dev(int dev); static void sg_device_destroy(struct kref *kref); #define SZ_SG_HEADER sizeof(struct sg_header) #define SZ_SG_IO_HDR sizeof(sg_io_hdr_t) #define SZ_SG_IOVEC sizeof(sg_iovec_t) #define SZ_SG_REQ_INFO sizeof(sg_req_info_t) #define sg_printk(prefix, sdp, fmt, a...) \ sdev_prefix_printk(prefix, (sdp)->device, \ (sdp)->disk->disk_name, fmt, ##a) static int sg_allow_access(struct file *filp, unsigned char *cmd) { struct sg_fd *sfp = filp->private_data; if (sfp->parentdp->device->type == TYPE_SCANNER) return 0; return blk_verify_command(cmd, filp->f_mode & FMODE_WRITE); } static int open_wait(Sg_device *sdp, int flags) { int retval = 0; if (flags & O_EXCL) { while (sdp->open_cnt > 0) { mutex_unlock(&sdp->open_rel_lock); retval = wait_event_interruptible(sdp->open_wait, (atomic_read(&sdp->detaching) || !sdp->open_cnt)); mutex_lock(&sdp->open_rel_lock); if (retval) /* -ERESTARTSYS */ return retval; if (atomic_read(&sdp->detaching)) return -ENODEV; } } else { while (sdp->exclude) { mutex_unlock(&sdp->open_rel_lock); retval = wait_event_interruptible(sdp->open_wait, (atomic_read(&sdp->detaching) || !sdp->exclude)); mutex_lock(&sdp->open_rel_lock); if (retval) /* -ERESTARTSYS */ return retval; if (atomic_read(&sdp->detaching)) return -ENODEV; } } return retval; } /* Returns 0 on success, else a negated errno value */ static int sg_open(struct inode *inode, struct file *filp) { int dev = iminor(inode); int flags = filp->f_flags; struct request_queue *q; Sg_device *sdp; Sg_fd *sfp; int retval; nonseekable_open(inode, filp); if ((flags & O_EXCL) && (O_RDONLY == (flags & O_ACCMODE))) return -EPERM; /* Can't lock it with read only access */ sdp = sg_get_dev(dev); if (IS_ERR(sdp)) return PTR_ERR(sdp); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_open: flags=0x%x\n", flags)); /* This driver's module count bumped by fops_get in <linux/fs.h> */ /* Prevent the device driver from vanishing while we sleep */ retval = scsi_device_get(sdp->device); if (retval) goto sg_put; retval = scsi_autopm_get_device(sdp->device); if (retval) goto sdp_put; /* scsi_block_when_processing_errors() may block so bypass * check if O_NONBLOCK. Permits SCSI commands to be issued * during error recovery. Tread carefully. */ if (!((flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) { retval = -ENXIO; /* we are in error recovery for this device */ goto error_out; } mutex_lock(&sdp->open_rel_lock); if (flags & O_NONBLOCK) { if (flags & O_EXCL) { if (sdp->open_cnt > 0) { retval = -EBUSY; goto error_mutex_locked; } } else { if (sdp->exclude) { retval = -EBUSY; goto error_mutex_locked; } } } else { retval = open_wait(sdp, flags); if (retval) /* -ERESTARTSYS or -ENODEV */ goto error_mutex_locked; } /* N.B. at this point we are holding the open_rel_lock */ if (flags & O_EXCL) sdp->exclude = true; if (sdp->open_cnt < 1) { /* no existing opens */ sdp->sgdebug = 0; q = sdp->device->request_queue; sdp->sg_tablesize = queue_max_segments(q); } sfp = sg_add_sfp(sdp); if (IS_ERR(sfp)) { retval = PTR_ERR(sfp); goto out_undo; } filp->private_data = sfp; sdp->open_cnt++; mutex_unlock(&sdp->open_rel_lock); retval = 0; sg_put: kref_put(&sdp->d_ref, sg_device_destroy); return retval; out_undo: if (flags & O_EXCL) { sdp->exclude = false; /* undo if error */ wake_up_interruptible(&sdp->open_wait); } error_mutex_locked: mutex_unlock(&sdp->open_rel_lock); error_out: scsi_autopm_put_device(sdp->device); sdp_put: scsi_device_put(sdp->device); goto sg_put; } /* Release resources associated with a successful sg_open() * Returns 0 on success, else a negated errno value */ static int sg_release(struct inode *inode, struct file *filp) { Sg_device *sdp; Sg_fd *sfp; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_release\n")); mutex_lock(&sdp->open_rel_lock); scsi_autopm_put_device(sdp->device); kref_put(&sfp->f_ref, sg_remove_sfp); sdp->open_cnt--; /* possibly many open()s waiting on exlude clearing, start many; * only open(O_EXCL)s wait on 0==open_cnt so only start one */ if (sdp->exclude) { sdp->exclude = false; wake_up_interruptible_all(&sdp->open_wait); } else if (0 == sdp->open_cnt) { wake_up_interruptible(&sdp->open_wait); } mutex_unlock(&sdp->open_rel_lock); return 0; } static ssize_t sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos) { Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; int req_pack_id = -1; sg_io_hdr_t *hp; struct sg_header *old_hdr = NULL; int retval = 0; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_read: count=%d\n", (int) count)); if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; if (sfp->force_packid && (count >= SZ_SG_HEADER)) { old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL); if (!old_hdr) return -ENOMEM; if (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } if (old_hdr->reply_len < 0) { if (count >= SZ_SG_IO_HDR) { sg_io_hdr_t *new_hdr; new_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL); if (!new_hdr) { retval = -ENOMEM; goto free_old_hdr; } retval =__copy_from_user (new_hdr, buf, SZ_SG_IO_HDR); req_pack_id = new_hdr->pack_id; kfree(new_hdr); if (retval) { retval = -EFAULT; goto free_old_hdr; } } } else req_pack_id = old_hdr->pack_id; } srp = sg_get_rq_mark(sfp, req_pack_id); if (!srp) { /* now wait on packet to arrive */ if (atomic_read(&sdp->detaching)) { retval = -ENODEV; goto free_old_hdr; } if (filp->f_flags & O_NONBLOCK) { retval = -EAGAIN; goto free_old_hdr; } retval = wait_event_interruptible(sfp->read_wait, (atomic_read(&sdp->detaching) || (srp = sg_get_rq_mark(sfp, req_pack_id)))); if (atomic_read(&sdp->detaching)) { retval = -ENODEV; goto free_old_hdr; } if (retval) { /* -ERESTARTSYS as signal hit process */ goto free_old_hdr; } } if (srp->header.interface_id != '\0') { retval = sg_new_read(sfp, buf, count, srp); goto free_old_hdr; } hp = &srp->header; if (old_hdr == NULL) { old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL); if (! old_hdr) { retval = -ENOMEM; goto free_old_hdr; } } memset(old_hdr, 0, SZ_SG_HEADER); old_hdr->reply_len = (int) hp->timeout; old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */ old_hdr->pack_id = hp->pack_id; old_hdr->twelve_byte = ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0; old_hdr->target_status = hp->masked_status; old_hdr->host_status = hp->host_status; old_hdr->driver_status = hp->driver_status; if ((CHECK_CONDITION & hp->masked_status) || (DRIVER_SENSE & hp->driver_status)) memcpy(old_hdr->sense_buffer, srp->sense_b, sizeof (old_hdr->sense_buffer)); switch (hp->host_status) { /* This setup of 'result' is for backward compatibility and is best ignored by the user who should use target, host + driver status */ case DID_OK: case DID_PASSTHROUGH: case DID_SOFT_ERROR: old_hdr->result = 0; break; case DID_NO_CONNECT: case DID_BUS_BUSY: case DID_TIME_OUT: old_hdr->result = EBUSY; break; case DID_BAD_TARGET: case DID_ABORT: case DID_PARITY: case DID_RESET: case DID_BAD_INTR: old_hdr->result = EIO; break; case DID_ERROR: old_hdr->result = (srp->sense_b[0] == 0 && hp->masked_status == GOOD) ? 0 : EIO; break; default: old_hdr->result = EIO; break; } /* Now copy the result back to the user buffer. */ if (count >= SZ_SG_HEADER) { if (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } buf += SZ_SG_HEADER; if (count > old_hdr->reply_len) count = old_hdr->reply_len; if (count > SZ_SG_HEADER) { if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } } } else count = (old_hdr->result == 0) ? 0 : -EIO; sg_finish_rem_req(srp); retval = count; free_old_hdr: kfree(old_hdr); return retval; } static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp) { sg_io_hdr_t *hp = &srp->header; int err = 0, err2; int len; if (count < SZ_SG_IO_HDR) { err = -EINVAL; goto err_out; } hp->sb_len_wr = 0; if ((hp->mx_sb_len > 0) && hp->sbp) { if ((CHECK_CONDITION & hp->masked_status) || (DRIVER_SENSE & hp->driver_status)) { int sb_len = SCSI_SENSE_BUFFERSIZE; sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len; len = 8 + (int) srp->sense_b[7]; /* Additional sense length field */ len = (len > sb_len) ? sb_len : len; if (copy_to_user(hp->sbp, srp->sense_b, len)) { err = -EFAULT; goto err_out; } hp->sb_len_wr = len; } } if (hp->masked_status || hp->host_status || hp->driver_status) hp->info |= SG_INFO_CHECK; if (copy_to_user(buf, hp, SZ_SG_IO_HDR)) { err = -EFAULT; goto err_out; } err_out: err2 = sg_finish_rem_req(srp); return err ? : err2 ? : count; } static ssize_t sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos) { int mxsize, cmd_size, k; int input_size, blocking; unsigned char opcode; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; struct sg_header old_hdr; sg_io_hdr_t *hp; unsigned char cmnd[SG_MAX_CDB_SIZE]; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_write: count=%d\n", (int) count)); if (atomic_read(&sdp->detaching)) return -ENODEV; if (!((filp->f_flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) return -ENXIO; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ if (count < SZ_SG_HEADER) return -EIO; if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER)) return -EFAULT; blocking = !(filp->f_flags & O_NONBLOCK); if (old_hdr.reply_len < 0) return sg_new_write(sfp, filp, buf, count, blocking, 0, 0, NULL); if (count < (SZ_SG_HEADER + 6)) return -EIO; /* The minimum scsi command length is 6 bytes. */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp, "sg_write: queue full\n")); return -EDOM; } buf += SZ_SG_HEADER; __get_user(opcode, buf); if (sfp->next_cmd_len > 0) { cmd_size = sfp->next_cmd_len; sfp->next_cmd_len = 0; /* reset so only this write() effected */ } else { cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */ if ((opcode >= 0xc0) && old_hdr.twelve_byte) cmd_size = 12; } SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp, "sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size)); /* Determine buffer size. */ input_size = count - cmd_size; mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len; mxsize -= SZ_SG_HEADER; input_size -= SZ_SG_HEADER; if (input_size < 0) { sg_remove_request(sfp, srp); return -EIO; /* User did not pass enough bytes for this command. */ } hp = &srp->header; hp->interface_id = '\0'; /* indicator of old interface tunnelled */ hp->cmd_len = (unsigned char) cmd_size; hp->iovec_count = 0; hp->mx_sb_len = 0; if (input_size > 0) hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ? SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV; else hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE; hp->dxfer_len = mxsize; if (hp->dxfer_direction == SG_DXFER_TO_DEV) hp->dxferp = (char __user *)buf + cmd_size; else hp->dxferp = NULL; hp->sbp = NULL; hp->timeout = old_hdr.reply_len; /* structure abuse ... */ hp->flags = input_size; /* structure abuse ... */ hp->pack_id = old_hdr.pack_id; hp->usr_ptr = NULL; if (__copy_from_user(cmnd, buf, cmd_size)) return -EFAULT; /* * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV, * but is is possible that the app intended SG_DXFER_TO_DEV, because there * is a non-zero input_size, so emit a warning. */ if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) { static char cmd[TASK_COMM_LEN]; if (strcmp(current->comm, cmd)) { printk_ratelimited(KERN_WARNING "sg_write: data in/out %d/%d bytes " "for SCSI command 0x%x-- guessing " "data in;\n program %s not setting " "count and/or reply_len properly\n", old_hdr.reply_len - (int)SZ_SG_HEADER, input_size, (unsigned int) cmnd[0], current->comm); strcpy(cmd, current->comm); } } k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking); return (k < 0) ? k : count; } static ssize_t sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf, size_t count, int blocking, int read_only, int sg_io_owned, Sg_request **o_srp) { int k; Sg_request *srp; sg_io_hdr_t *hp; unsigned char cmnd[SG_MAX_CDB_SIZE]; int timeout; unsigned long ul_timeout; if (count < SZ_SG_IO_HDR) return -EINVAL; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ sfp->cmd_q = 1; /* when sg_io_hdr seen, set command queuing on */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_new_write: queue full\n")); return -EDOM; } srp->sg_io_owned = sg_io_owned; hp = &srp->header; if (__copy_from_user(hp, buf, SZ_SG_IO_HDR)) { sg_remove_request(sfp, srp); return -EFAULT; } if (hp->interface_id != 'S') { sg_remove_request(sfp, srp); return -ENOSYS; } if (hp->flags & SG_FLAG_MMAP_IO) { if (hp->dxfer_len > sfp->reserve.bufflen) { sg_remove_request(sfp, srp); return -ENOMEM; /* MMAP_IO size must fit in reserve buffer */ } if (hp->flags & SG_FLAG_DIRECT_IO) { sg_remove_request(sfp, srp); return -EINVAL; /* either MMAP_IO or DIRECT_IO (not both) */ } if (sg_res_in_use(sfp)) { sg_remove_request(sfp, srp); return -EBUSY; /* reserve buffer already being used */ } } ul_timeout = msecs_to_jiffies(srp->header.timeout); timeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX; if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) { sg_remove_request(sfp, srp); return -EMSGSIZE; } if (!access_ok(VERIFY_READ, hp->cmdp, hp->cmd_len)) { sg_remove_request(sfp, srp); return -EFAULT; /* protects following copy_from_user()s + get_user()s */ } if (__copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) { sg_remove_request(sfp, srp); return -EFAULT; } if (read_only && sg_allow_access(file, cmnd)) { sg_remove_request(sfp, srp); return -EPERM; } k = sg_common_write(sfp, srp, cmnd, timeout, blocking); if (k < 0) return k; if (o_srp) *o_srp = srp; return count; } static int sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_common_write: start_req err=%d\n", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) blk_end_request_all(srp->rq, -EIO); sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; } static int srp_done(Sg_fd *sfp, Sg_request *srp) { unsigned long flags; int ret; read_lock_irqsave(&sfp->rq_list_lock, flags); ret = srp->done; read_unlock_irqrestore(&sfp->rq_list_lock, flags); return ret; } static int max_sectors_bytes(struct request_queue *q) { unsigned int max_sectors = queue_max_sectors(q); max_sectors = min_t(unsigned int, max_sectors, INT_MAX >> 9); return max_sectors << 9; } static long sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { void __user *p = (void __user *)arg; int __user *ip = p; int result, val, read_only; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; unsigned long iflags; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_ioctl: cmd=0x%x\n", (int) cmd_in)); read_only = (O_RDWR != (filp->f_flags & O_ACCMODE)); switch (cmd_in) { case SG_IO: if (atomic_read(&sdp->detaching)) return -ENODEV; if (!scsi_block_when_processing_errors(sdp->device)) return -ENXIO; if (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR)) return -EFAULT; result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR, 1, read_only, 1, &srp); if (result < 0) return result; result = wait_event_interruptible(sfp->read_wait, (srp_done(sfp, srp) || atomic_read(&sdp->detaching))); if (atomic_read(&sdp->detaching)) return -ENODEV; write_lock_irq(&sfp->rq_list_lock); if (srp->done) { srp->done = 2; write_unlock_irq(&sfp->rq_list_lock); result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp); return (result < 0) ? result : 0; } srp->orphan = 1; write_unlock_irq(&sfp->rq_list_lock); return result; /* -ERESTARTSYS because signal hit process */ case SG_SET_TIMEOUT: result = get_user(val, ip); if (result) return result; if (val < 0) return -EIO; if (val >= MULDIV (INT_MAX, USER_HZ, HZ)) val = MULDIV (INT_MAX, USER_HZ, HZ); sfp->timeout_user = val; sfp->timeout = MULDIV (val, HZ, USER_HZ); return 0; case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */ /* strange ..., for backward compatibility */ return sfp->timeout_user; case SG_SET_FORCE_LOW_DMA: result = get_user(val, ip); if (result) return result; if (val) { sfp->low_dma = 1; if ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) { val = (int) sfp->reserve.bufflen; sg_remove_scat(sfp, &sfp->reserve); sg_build_reserve(sfp, val); } } else { if (atomic_read(&sdp->detaching)) return -ENODEV; sfp->low_dma = sdp->device->host->unchecked_isa_dma; } return 0; case SG_GET_LOW_DMA: return put_user((int) sfp->low_dma, ip); case SG_GET_SCSI_ID: if (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t))) return -EFAULT; else { sg_scsi_id_t __user *sg_idp = p; if (atomic_read(&sdp->detaching)) return -ENODEV; __put_user((int) sdp->device->host->host_no, &sg_idp->host_no); __put_user((int) sdp->device->channel, &sg_idp->channel); __put_user((int) sdp->device->id, &sg_idp->scsi_id); __put_user((int) sdp->device->lun, &sg_idp->lun); __put_user((int) sdp->device->type, &sg_idp->scsi_type); __put_user((short) sdp->device->host->cmd_per_lun, &sg_idp->h_cmd_per_lun); __put_user((short) sdp->device->queue_depth, &sg_idp->d_queue_depth); __put_user(0, &sg_idp->unused[0]); __put_user(0, &sg_idp->unused[1]); return 0; } case SG_SET_FORCE_PACK_ID: result = get_user(val, ip); if (result) return result; sfp->force_packid = val ? 1 : 0; return 0; case SG_GET_PACK_ID: if (!access_ok(VERIFY_WRITE, ip, sizeof (int))) return -EFAULT; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) { if ((1 == srp->done) && (!srp->sg_io_owned)) { read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(srp->header.pack_id, ip); return 0; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(-1, ip); return 0; case SG_GET_NUM_WAITING: read_lock_irqsave(&sfp->rq_list_lock, iflags); for (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) { if ((1 == srp->done) && (!srp->sg_io_owned)) ++val; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return put_user(val, ip); case SG_GET_SG_TABLESIZE: return put_user(sdp->sg_tablesize, ip); case SG_SET_RESERVED_SIZE: result = get_user(val, ip); if (result) return result; if (val < 0) return -EINVAL; val = min_t(int, val, max_sectors_bytes(sdp->device->request_queue)); if (val != sfp->reserve.bufflen) { if (sg_res_in_use(sfp) || sfp->mmap_called) return -EBUSY; sg_remove_scat(sfp, &sfp->reserve); sg_build_reserve(sfp, val); } return 0; case SG_GET_RESERVED_SIZE: val = min_t(int, sfp->reserve.bufflen, max_sectors_bytes(sdp->device->request_queue)); return put_user(val, ip); case SG_SET_COMMAND_Q: result = get_user(val, ip); if (result) return result; sfp->cmd_q = val ? 1 : 0; return 0; case SG_GET_COMMAND_Q: return put_user((int) sfp->cmd_q, ip); case SG_SET_KEEP_ORPHAN: result = get_user(val, ip); if (result) return result; sfp->keep_orphan = val; return 0; case SG_GET_KEEP_ORPHAN: return put_user((int) sfp->keep_orphan, ip); case SG_NEXT_CMD_LEN: result = get_user(val, ip); if (result) return result; sfp->next_cmd_len = (val > 0) ? val : 0; return 0; case SG_GET_VERSION_NUM: return put_user(sg_version_num, ip); case SG_GET_ACCESS_COUNT: /* faked - we don't have a real access count anymore */ val = (sdp->device ? 1 : 0); return put_user(val, ip); case SG_GET_REQUEST_TABLE: if (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE)) return -EFAULT; else { sg_req_info_t *rinfo; unsigned int ms; rinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE, GFP_KERNEL); if (!rinfo) return -ENOMEM; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE; ++val, srp = srp ? srp->nextrp : srp) { memset(&rinfo[val], 0, SZ_SG_REQ_INFO); if (srp) { rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); result = __copy_to_user(p, rinfo, SZ_SG_REQ_INFO * SG_MAX_QUEUE); result = result ? -EFAULT : 0; kfree(rinfo); return result; } case SG_EMULATED_HOST: if (atomic_read(&sdp->detaching)) return -ENODEV; return put_user(sdp->device->host->hostt->emulated, ip); case SCSI_IOCTL_SEND_COMMAND: if (atomic_read(&sdp->detaching)) return -ENODEV; if (read_only) { unsigned char opcode = WRITE_6; Scsi_Ioctl_Command __user *siocp = p; if (copy_from_user(&opcode, siocp->data, 1)) return -EFAULT; if (sg_allow_access(filp, &opcode)) return -EPERM; } return sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p); case SG_SET_DEBUG: result = get_user(val, ip); if (result) return result; sdp->sgdebug = (char) val; return 0; case BLKSECTGET: return put_user(max_sectors_bytes(sdp->device->request_queue), ip); case BLKTRACESETUP: return blk_trace_setup(sdp->device->request_queue, sdp->disk->disk_name, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), NULL, (char *)arg); case BLKTRACESTART: return blk_trace_startstop(sdp->device->request_queue, 1); case BLKTRACESTOP: return blk_trace_startstop(sdp->device->request_queue, 0); case BLKTRACETEARDOWN: return blk_trace_remove(sdp->device->request_queue); case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: case SCSI_IOCTL_PROBE_HOST: case SG_GET_TRANSFORM: case SG_SCSI_RESET: if (atomic_read(&sdp->detaching)) return -ENODEV; break; default: if (read_only) return -EPERM; /* don't know so take safe approach */ break; } result = scsi_ioctl_block_when_processing_errors(sdp->device, cmd_in, filp->f_flags & O_NDELAY); if (result) return result; return scsi_ioctl(sdp->device, cmd_in, p); } #ifdef CONFIG_COMPAT static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { Sg_device *sdp; Sg_fd *sfp; struct scsi_device *sdev; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; sdev = sdp->device; if (sdev->host->hostt->compat_ioctl) { int ret; ret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg); return ret; } return -ENOIOCTLCMD; } #endif static unsigned int sg_poll(struct file *filp, poll_table * wait) { unsigned int res = 0; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; int count = 0; unsigned long iflags; sfp = filp->private_data; if (!sfp) return POLLERR; sdp = sfp->parentdp; if (!sdp) return POLLERR; poll_wait(filp, &sfp->read_wait, wait); read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) { /* if any read waiting, flag it */ if ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned)) res = POLLIN | POLLRDNORM; ++count; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); if (atomic_read(&sdp->detaching)) res |= POLLHUP; else if (!sfp->cmd_q) { if (0 == count) res |= POLLOUT | POLLWRNORM; } else if (count < SG_MAX_QUEUE) res |= POLLOUT | POLLWRNORM; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_poll: res=0x%x\n", (int) res)); return res; } static int sg_fasync(int fd, struct file *filp, int mode) { Sg_device *sdp; Sg_fd *sfp; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_fasync: mode=%d\n", mode)); return fasync_helper(fd, filp, mode, &sfp->async_qp); } static int sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { Sg_fd *sfp; unsigned long offset, len, sa; Sg_scatter_hold *rsv_schp; int k, length; if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data))) return VM_FAULT_SIGBUS; rsv_schp = &sfp->reserve; offset = vmf->pgoff << PAGE_SHIFT; if (offset >= rsv_schp->bufflen) return VM_FAULT_SIGBUS; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp, "sg_vma_fault: offset=%lu, scatg=%d\n", offset, rsv_schp->k_use_sg)); sa = vma->vm_start; length = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { len = vma->vm_end - sa; len = (len < length) ? len : length; if (offset < len) { struct page *page = nth_page(rsv_schp->pages[k], offset >> PAGE_SHIFT); get_page(page); /* increment page count */ vmf->page = page; return 0; /* success */ } sa += len; offset -= len; } return VM_FAULT_SIGBUS; } static const struct vm_operations_struct sg_mmap_vm_ops = { .fault = sg_vma_fault, }; static int sg_mmap(struct file *filp, struct vm_area_struct *vma) { Sg_fd *sfp; unsigned long req_sz, len, sa; Sg_scatter_hold *rsv_schp; int k, length; if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data))) return -ENXIO; req_sz = vma->vm_end - vma->vm_start; SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp, "sg_mmap starting, vm_start=%p, len=%d\n", (void *) vma->vm_start, (int) req_sz)); if (vma->vm_pgoff) return -EINVAL; /* want no offset */ rsv_schp = &sfp->reserve; if (req_sz > rsv_schp->bufflen) return -ENOMEM; /* cannot map more than reserved buffer */ sa = vma->vm_start; length = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { len = vma->vm_end - sa; len = (len < length) ? len : length; sa += len; } sfp->mmap_called = 1; vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP; vma->vm_private_data = sfp; vma->vm_ops = &sg_mmap_vm_ops; return 0; } static void sg_rq_end_io_usercontext(struct work_struct *work) { struct sg_request *srp = container_of(work, struct sg_request, ew.work); struct sg_fd *sfp = srp->parentfp; sg_finish_rem_req(srp); kref_put(&sfp->f_ref, sg_remove_sfp); } /* * This function is a "bottom half" handler that is called by the mid * level when a command is completed (or has failed). */ static void sg_rq_end_io(struct request *rq, int uptodate) { struct sg_request *srp = rq->end_io_data; Sg_device *sdp; Sg_fd *sfp; unsigned long iflags; unsigned int ms; char *sense; int result, resid, done = 1; if (WARN_ON(srp->done != 0)) return; sfp = srp->parentfp; if (WARN_ON(sfp == NULL)) return; sdp = sfp->parentdp; if (unlikely(atomic_read(&sdp->detaching))) pr_info("%s: device detaching\n", __func__); sense = rq->sense; result = rq->errors; resid = rq->resid_len; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp, "sg_cmd_done: pack_id=%d, res=0x%x\n", srp->header.pack_id, result)); srp->header.resid = resid; ms = jiffies_to_msecs(jiffies); srp->header.duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; if (0 != result) { struct scsi_sense_hdr sshdr; srp->header.status = 0xff & result; srp->header.masked_status = status_byte(result); srp->header.msg_status = msg_byte(result); srp->header.host_status = host_byte(result); srp->header.driver_status = driver_byte(result); if ((sdp->sgdebug > 0) && ((CHECK_CONDITION == srp->header.masked_status) || (COMMAND_TERMINATED == srp->header.masked_status))) __scsi_print_sense(sdp->device, __func__, sense, SCSI_SENSE_BUFFERSIZE); /* Following if statement is a patch supplied by Eric Youngdale */ if (driver_byte(result) != 0 && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr) && !scsi_sense_is_deferred(&sshdr) && sshdr.sense_key == UNIT_ATTENTION && sdp->device->removable) { /* Detected possible disc change. Set the bit - this */ /* may be used if there are filesystems using this device */ sdp->device->changed = 1; } } /* Rely on write phase to clean out srp status values, so no "else" */ /* * Free the request as soon as it is complete so that its resources * can be reused without waiting for userspace to read() the * result. But keep the associated bio (if any) around until * blk_rq_unmap_user() can be called from user context. */ srp->rq = NULL; if (rq->cmd != rq->__cmd) kfree(rq->cmd); __blk_put_request(rq->q, rq); write_lock_irqsave(&sfp->rq_list_lock, iflags); if (unlikely(srp->orphan)) { if (sfp->keep_orphan) srp->sg_io_owned = 0; else done = 0; } srp->done = done; write_unlock_irqrestore(&sfp->rq_list_lock, iflags); if (likely(done)) { /* Now wake up any sg_read() that is waiting for this * packet. */ wake_up_interruptible(&sfp->read_wait); kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN); kref_put(&sfp->f_ref, sg_remove_sfp); } else { INIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext); schedule_work(&srp->ew.work); } } static const struct file_operations sg_fops = { .owner = THIS_MODULE, .read = sg_read, .write = sg_write, .poll = sg_poll, .unlocked_ioctl = sg_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = sg_compat_ioctl, #endif .open = sg_open, .mmap = sg_mmap, .release = sg_release, .fasync = sg_fasync, .llseek = no_llseek, }; static struct class *sg_sysfs_class; static int sg_sysfs_valid = 0; static Sg_device * sg_alloc(struct gendisk *disk, struct scsi_device *scsidp) { struct request_queue *q = scsidp->request_queue; Sg_device *sdp; unsigned long iflags; int error; u32 k; sdp = kzalloc(sizeof(Sg_device), GFP_KERNEL); if (!sdp) { sdev_printk(KERN_WARNING, scsidp, "%s: kmalloc Sg_device " "failure\n", __func__); return ERR_PTR(-ENOMEM); } idr_preload(GFP_KERNEL); write_lock_irqsave(&sg_index_lock, iflags); error = idr_alloc(&sg_index_idr, sdp, 0, SG_MAX_DEVS, GFP_NOWAIT); if (error < 0) { if (error == -ENOSPC) { sdev_printk(KERN_WARNING, scsidp, "Unable to attach sg device type=%d, minor number exceeds %d\n", scsidp->type, SG_MAX_DEVS - 1); error = -ENODEV; } else { sdev_printk(KERN_WARNING, scsidp, "%s: idr " "allocation Sg_device failure: %d\n", __func__, error); } goto out_unlock; } k = error; SCSI_LOG_TIMEOUT(3, sdev_printk(KERN_INFO, scsidp, "sg_alloc: dev=%d \n", k)); sprintf(disk->disk_name, "sg%d", k); disk->first_minor = k; sdp->disk = disk; sdp->device = scsidp; mutex_init(&sdp->open_rel_lock); INIT_LIST_HEAD(&sdp->sfds); init_waitqueue_head(&sdp->open_wait); atomic_set(&sdp->detaching, 0); rwlock_init(&sdp->sfd_lock); sdp->sg_tablesize = queue_max_segments(q); sdp->index = k; kref_init(&sdp->d_ref); error = 0; out_unlock: write_unlock_irqrestore(&sg_index_lock, iflags); idr_preload_end(); if (error) { kfree(sdp); return ERR_PTR(error); } return sdp; } static int sg_add_device(struct device *cl_dev, struct class_interface *cl_intf) { struct scsi_device *scsidp = to_scsi_device(cl_dev->parent); struct gendisk *disk; Sg_device *sdp = NULL; struct cdev * cdev = NULL; int error; unsigned long iflags; disk = alloc_disk(1); if (!disk) { pr_warn("%s: alloc_disk failed\n", __func__); return -ENOMEM; } disk->major = SCSI_GENERIC_MAJOR; error = -ENOMEM; cdev = cdev_alloc(); if (!cdev) { pr_warn("%s: cdev_alloc failed\n", __func__); goto out; } cdev->owner = THIS_MODULE; cdev->ops = &sg_fops; sdp = sg_alloc(disk, scsidp); if (IS_ERR(sdp)) { pr_warn("%s: sg_alloc failed\n", __func__); error = PTR_ERR(sdp); goto out; } error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1); if (error) goto cdev_add_err; sdp->cdev = cdev; if (sg_sysfs_valid) { struct device *sg_class_member; sg_class_member = device_create(sg_sysfs_class, cl_dev->parent, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), sdp, "%s", disk->disk_name); if (IS_ERR(sg_class_member)) { pr_err("%s: device_create failed\n", __func__); error = PTR_ERR(sg_class_member); goto cdev_add_err; } error = sysfs_create_link(&scsidp->sdev_gendev.kobj, &sg_class_member->kobj, "generic"); if (error) pr_err("%s: unable to make symlink 'generic' back " "to sg%d\n", __func__, sdp->index); } else pr_warn("%s: sg_sys Invalid\n", __func__); sdev_printk(KERN_NOTICE, scsidp, "Attached scsi generic sg%d " "type %d\n", sdp->index, scsidp->type); dev_set_drvdata(cl_dev, sdp); return 0; cdev_add_err: write_lock_irqsave(&sg_index_lock, iflags); idr_remove(&sg_index_idr, sdp->index); write_unlock_irqrestore(&sg_index_lock, iflags); kfree(sdp); out: put_disk(disk); if (cdev) cdev_del(cdev); return error; } static void sg_device_destroy(struct kref *kref) { struct sg_device *sdp = container_of(kref, struct sg_device, d_ref); unsigned long flags; /* CAUTION! Note that the device can still be found via idr_find() * even though the refcount is 0. Therefore, do idr_remove() BEFORE * any other cleanup. */ write_lock_irqsave(&sg_index_lock, flags); idr_remove(&sg_index_idr, sdp->index); write_unlock_irqrestore(&sg_index_lock, flags); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_device_destroy\n")); put_disk(sdp->disk); kfree(sdp); } static void sg_remove_device(struct device *cl_dev, struct class_interface *cl_intf) { struct scsi_device *scsidp = to_scsi_device(cl_dev->parent); Sg_device *sdp = dev_get_drvdata(cl_dev); unsigned long iflags; Sg_fd *sfp; int val; if (!sdp) return; /* want sdp->detaching non-zero as soon as possible */ val = atomic_inc_return(&sdp->detaching); if (val > 1) return; /* only want to do following once per device */ SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "%s\n", __func__)); read_lock_irqsave(&sdp->sfd_lock, iflags); list_for_each_entry(sfp, &sdp->sfds, sfd_siblings) { wake_up_interruptible_all(&sfp->read_wait); kill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP); } wake_up_interruptible_all(&sdp->open_wait); read_unlock_irqrestore(&sdp->sfd_lock, iflags); sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic"); device_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index)); cdev_del(sdp->cdev); sdp->cdev = NULL; kref_put(&sdp->d_ref, sg_device_destroy); } module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR); module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO | S_IWUSR); module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR); MODULE_AUTHOR("Douglas Gilbert"); MODULE_DESCRIPTION("SCSI generic (sg) driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(SG_VERSION_STR); MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR); MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element " "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))"); MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd"); MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))"); static int __init init_sg(void) { int rc; if (scatter_elem_sz < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = scatter_elem_sz; } if (def_reserved_size >= 0) sg_big_buff = def_reserved_size; else def_reserved_size = sg_big_buff; rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS, "sg"); if (rc) return rc; sg_sysfs_class = class_create(THIS_MODULE, "scsi_generic"); if ( IS_ERR(sg_sysfs_class) ) { rc = PTR_ERR(sg_sysfs_class); goto err_out; } sg_sysfs_valid = 1; rc = scsi_register_interface(&sg_interface); if (0 == rc) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_init(); #endif /* CONFIG_SCSI_PROC_FS */ return 0; } class_destroy(sg_sysfs_class); err_out: unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); return rc; } static void __exit exit_sg(void) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_cleanup(); #endif /* CONFIG_SCSI_PROC_FS */ scsi_unregister_interface(&sg_interface); class_destroy(sg_sysfs_class); sg_sysfs_valid = 0; unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); idr_destroy(&sg_index_idr); } static int sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { struct iovec *iov = NULL; struct iov_iter i; res = import_iovec(rw, hp->dxferp, iov_count, 0, &iov, &i); if (res < 0) return res; iov_iter_truncate(&i, hp->dxfer_len); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } static int sg_finish_rem_req(Sg_request *srp) { int ret = 0; Sg_fd *sfp = srp->parentfp; Sg_scatter_hold *req_schp = &srp->data; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_finish_rem_req: res_used=%d\n", (int) srp->res_used)); if (srp->bio) ret = blk_rq_unmap_user(srp->bio); if (srp->rq) { if (srp->rq->cmd != srp->rq->__cmd) kfree(srp->rq->cmd); blk_put_request(srp->rq); } if (srp->res_used) sg_unlink_reserve(sfp, srp); else sg_remove_scat(sfp, req_schp); sg_remove_request(sfp, srp); return ret; } static int sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize) { int sg_bufflen = tablesize * sizeof(struct page *); gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN; schp->pages = kzalloc(sg_bufflen, gfp_flags); if (!schp->pages) return -ENOMEM; schp->sglist_len = sg_bufflen; return tablesize; /* number of scat_gath elements allocated */ } static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size) { int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems; int sg_tablesize = sfp->parentdp->sg_tablesize; int blk_size = buff_size, order; gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN; if (blk_size < 0) return -EFAULT; if (0 == blk_size) ++blk_size; /* don't know why */ /* round request up to next highest SG_SECTOR_SZ byte boundary */ blk_size = ALIGN(blk_size, SG_SECTOR_SZ); SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: buff_size=%d, blk_size=%d\n", buff_size, blk_size)); /* N.B. ret_sz carried into this block ... */ mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize); if (mx_sc_elems < 0) return mx_sc_elems; /* most likely -ENOMEM */ num = scatter_elem_sz; if (unlikely(num != scatter_elem_sz_prev)) { if (num < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = PAGE_SIZE; } else scatter_elem_sz_prev = num; } if (sfp->low_dma) gfp_mask |= GFP_DMA; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) gfp_mask |= __GFP_ZERO; order = get_order(num); retry: ret_sz = 1 << (PAGE_SHIFT + order); for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems; k++, rem_sz -= ret_sz) { num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz; schp->pages[k] = alloc_pages(gfp_mask, order); if (!schp->pages[k]) goto out; if (num == scatter_elem_sz_prev) { if (unlikely(ret_sz > scatter_elem_sz_prev)) { scatter_elem_sz = ret_sz; scatter_elem_sz_prev = ret_sz; } } SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n", k, num, ret_sz)); } /* end of for loop */ schp->page_order = order; schp->k_use_sg = k; SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n", k, rem_sz)); schp->bufflen = blk_size; if (rem_sz > 0) /* must have failed */ return -ENOMEM; return 0; out: for (i = 0; i < k; i++) __free_pages(schp->pages[i], order); if (--order >= 0) goto retry; return -ENOMEM; } static void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp) { SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg)); if (schp->pages && schp->sglist_len > 0) { if (!schp->dio_in_use) { int k; for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_remove_scat: k=%d, pg=0x%p\n", k, schp->pages[k])); __free_pages(schp->pages[k], schp->page_order); } kfree(schp->pages); } } memset(schp, 0, sizeof (*schp)); } static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer) { Sg_scatter_hold *schp = &srp->data; int k, num; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp, "sg_read_oxfer: num_read_xfer=%d\n", num_read_xfer)); if ((!outp) || (num_read_xfer <= 0)) return 0; num = 1 << (PAGE_SHIFT + schp->page_order); for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { if (num > num_read_xfer) { if (__copy_to_user(outp, page_address(schp->pages[k]), num_read_xfer)) return -EFAULT; break; } else { if (__copy_to_user(outp, page_address(schp->pages[k]), num)) return -EFAULT; num_read_xfer -= num; if (num_read_xfer <= 0) break; outp += num; } } return 0; } static void sg_build_reserve(Sg_fd * sfp, int req_size) { Sg_scatter_hold *schp = &sfp->reserve; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_reserve: req_size=%d\n", req_size)); do { if (req_size < PAGE_SIZE) req_size = PAGE_SIZE; if (0 == sg_build_indirect(schp, sfp, req_size)) return; else sg_remove_scat(sfp, schp); req_size >>= 1; /* divide by 2 */ } while (req_size > (PAGE_SIZE / 2)); } static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size) { Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; int k, num, rem; srp->res_used = 1; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_link_reserve: size=%d\n", size)); rem = size; num = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg; k++) { if (rem <= num) { req_schp->k_use_sg = k + 1; req_schp->sglist_len = rsv_schp->sglist_len; req_schp->pages = rsv_schp->pages; req_schp->bufflen = size; req_schp->page_order = rsv_schp->page_order; break; } else rem -= num; } if (k >= rsv_schp->k_use_sg) SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, "sg_link_reserve: BAD size\n")); } static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp) { Sg_scatter_hold *req_schp = &srp->data; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp, "sg_unlink_reserve: req->k_use_sg=%d\n", (int) req_schp->k_use_sg)); req_schp->k_use_sg = 0; req_schp->bufflen = 0; req_schp->pages = NULL; req_schp->page_order = 0; req_schp->sglist_len = 0; sfp->save_scat_len = 0; srp->res_used = 0; } static Sg_request * sg_get_rq_mark(Sg_fd * sfp, int pack_id) { Sg_request *resp; unsigned long iflags; write_lock_irqsave(&sfp->rq_list_lock, iflags); for (resp = sfp->headrp; resp; resp = resp->nextrp) { /* look for requests that are ready + not SG_IO owned */ if ((1 == resp->done) && (!resp->sg_io_owned) && ((-1 == pack_id) || (resp->header.pack_id == pack_id))) { resp->done = 2; /* guard against other readers */ break; } } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return resp; } /* always adds to end of list */ static Sg_request * sg_add_request(Sg_fd * sfp) { int k; unsigned long iflags; Sg_request *resp; Sg_request *rp = sfp->req_arr; write_lock_irqsave(&sfp->rq_list_lock, iflags); resp = sfp->headrp; if (!resp) { memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; resp = rp; sfp->headrp = resp; } else { if (0 == sfp->cmd_q) resp = NULL; /* command queuing disallowed */ else { for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) { if (!rp->parentfp) break; } if (k < SG_MAX_QUEUE) { memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; while (resp->nextrp) resp = resp->nextrp; resp->nextrp = rp; resp = rp; } else resp = NULL; } } if (resp) { resp->nextrp = NULL; resp->header.duration = jiffies_to_msecs(jiffies); } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return resp; } /* Return of 1 for found; 0 for not found */ static int sg_remove_request(Sg_fd * sfp, Sg_request * srp) { Sg_request *prev_rp; Sg_request *rp; unsigned long iflags; int res = 0; if ((!sfp) || (!srp) || (!sfp->headrp)) return res; write_lock_irqsave(&sfp->rq_list_lock, iflags); prev_rp = sfp->headrp; if (srp == prev_rp) { sfp->headrp = prev_rp->nextrp; prev_rp->parentfp = NULL; res = 1; } else { while ((rp = prev_rp->nextrp)) { if (srp == rp) { prev_rp->nextrp = rp->nextrp; rp->parentfp = NULL; res = 1; break; } prev_rp = rp; } } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return res; } static Sg_fd * sg_add_sfp(Sg_device * sdp) { Sg_fd *sfp; unsigned long iflags; int bufflen; sfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN); if (!sfp) return ERR_PTR(-ENOMEM); init_waitqueue_head(&sfp->read_wait); rwlock_init(&sfp->rq_list_lock); kref_init(&sfp->f_ref); sfp->timeout = SG_DEFAULT_TIMEOUT; sfp->timeout_user = SG_DEFAULT_TIMEOUT_USER; sfp->force_packid = SG_DEF_FORCE_PACK_ID; sfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ? sdp->device->host->unchecked_isa_dma : 1; sfp->cmd_q = SG_DEF_COMMAND_Q; sfp->keep_orphan = SG_DEF_KEEP_ORPHAN; sfp->parentdp = sdp; write_lock_irqsave(&sdp->sfd_lock, iflags); if (atomic_read(&sdp->detaching)) { write_unlock_irqrestore(&sdp->sfd_lock, iflags); return ERR_PTR(-ENODEV); } list_add_tail(&sfp->sfd_siblings, &sdp->sfds); write_unlock_irqrestore(&sdp->sfd_lock, iflags); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_add_sfp: sfp=0x%p\n", sfp)); if (unlikely(sg_big_buff != def_reserved_size)) sg_big_buff = def_reserved_size; bufflen = min_t(int, sg_big_buff, max_sectors_bytes(sdp->device->request_queue)); sg_build_reserve(sfp, bufflen); SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_add_sfp: bufflen=%d, k_use_sg=%d\n", sfp->reserve.bufflen, sfp->reserve.k_use_sg)); kref_get(&sdp->d_ref); __module_get(THIS_MODULE); return sfp; } static void sg_remove_sfp_usercontext(struct work_struct *work) { struct sg_fd *sfp = container_of(work, struct sg_fd, ew.work); struct sg_device *sdp = sfp->parentdp; /* Cleanup any responses which were never read(). */ while (sfp->headrp) sg_finish_rem_req(sfp->headrp); if (sfp->reserve.bufflen > 0) { SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp, "sg_remove_sfp: bufflen=%d, k_use_sg=%d\n", (int) sfp->reserve.bufflen, (int) sfp->reserve.k_use_sg)); sg_remove_scat(sfp, &sfp->reserve); } SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp, "sg_remove_sfp: sfp=0x%p\n", sfp)); kfree(sfp); scsi_device_put(sdp->device); kref_put(&sdp->d_ref, sg_device_destroy); module_put(THIS_MODULE); } static void sg_remove_sfp(struct kref *kref) { struct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref); struct sg_device *sdp = sfp->parentdp; unsigned long iflags; write_lock_irqsave(&sdp->sfd_lock, iflags); list_del(&sfp->sfd_siblings); write_unlock_irqrestore(&sdp->sfd_lock, iflags); INIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext); schedule_work(&sfp->ew.work); } static int sg_res_in_use(Sg_fd * sfp) { const Sg_request *srp; unsigned long iflags; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) if (srp->res_used) break; read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return srp ? 1 : 0; } #ifdef CONFIG_SCSI_PROC_FS static int sg_idr_max_id(int id, void *p, void *data) { int *k = data; if (*k < id) *k = id; return 0; } static int sg_last_dev(void) { int k = -1; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); idr_for_each(&sg_index_idr, sg_idr_max_id, &k); read_unlock_irqrestore(&sg_index_lock, iflags); return k + 1; /* origin 1 */ } #endif /* must be called with sg_index_lock held */ static Sg_device *sg_lookup_dev(int dev) { return idr_find(&sg_index_idr, dev); } static Sg_device * sg_get_dev(int dev) { struct sg_device *sdp; unsigned long flags; read_lock_irqsave(&sg_index_lock, flags); sdp = sg_lookup_dev(dev); if (!sdp) sdp = ERR_PTR(-ENXIO); else if (atomic_read(&sdp->detaching)) { /* If sdp->detaching, then the refcount may already be 0, in * which case it would be a bug to do kref_get(). */ sdp = ERR_PTR(-ENODEV); } else kref_get(&sdp->d_ref); read_unlock_irqrestore(&sg_index_lock, flags); return sdp; } #ifdef CONFIG_SCSI_PROC_FS static struct proc_dir_entry *sg_proc_sgp = NULL; static char sg_proc_sg_dirname[] = "scsi/sg"; static int sg_proc_seq_show_int(struct seq_file *s, void *v); static int sg_proc_single_open_adio(struct inode *inode, struct file *file); static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer, size_t count, loff_t *off); static const struct file_operations adio_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_adio, .read = seq_read, .llseek = seq_lseek, .write = sg_proc_write_adio, .release = single_release, }; static int sg_proc_single_open_dressz(struct inode *inode, struct file *file); static ssize_t sg_proc_write_dressz(struct file *filp, const char __user *buffer, size_t count, loff_t *off); static const struct file_operations dressz_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_dressz, .read = seq_read, .llseek = seq_lseek, .write = sg_proc_write_dressz, .release = single_release, }; static int sg_proc_seq_show_version(struct seq_file *s, void *v); static int sg_proc_single_open_version(struct inode *inode, struct file *file); static const struct file_operations version_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_version, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v); static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file); static const struct file_operations devhdr_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_devhdr, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int sg_proc_seq_show_dev(struct seq_file *s, void *v); static int sg_proc_open_dev(struct inode *inode, struct file *file); static void * dev_seq_start(struct seq_file *s, loff_t *pos); static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos); static void dev_seq_stop(struct seq_file *s, void *v); static const struct file_operations dev_fops = { .owner = THIS_MODULE, .open = sg_proc_open_dev, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations dev_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_dev, }; static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v); static int sg_proc_open_devstrs(struct inode *inode, struct file *file); static const struct file_operations devstrs_fops = { .owner = THIS_MODULE, .open = sg_proc_open_devstrs, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations devstrs_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_devstrs, }; static int sg_proc_seq_show_debug(struct seq_file *s, void *v); static int sg_proc_open_debug(struct inode *inode, struct file *file); static const struct file_operations debug_fops = { .owner = THIS_MODULE, .open = sg_proc_open_debug, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations debug_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_debug, }; struct sg_proc_leaf { const char * name; const struct file_operations * fops; }; static const struct sg_proc_leaf sg_proc_leaf_arr[] = { {"allow_dio", &adio_fops}, {"debug", &debug_fops}, {"def_reserved_size", &dressz_fops}, {"device_hdr", &devhdr_fops}, {"devices", &dev_fops}, {"device_strs", &devstrs_fops}, {"version", &version_fops} }; static int sg_proc_init(void) { int num_leaves = ARRAY_SIZE(sg_proc_leaf_arr); int k; sg_proc_sgp = proc_mkdir(sg_proc_sg_dirname, NULL); if (!sg_proc_sgp) return 1; for (k = 0; k < num_leaves; ++k) { const struct sg_proc_leaf *leaf = &sg_proc_leaf_arr[k]; umode_t mask = leaf->fops->write ? S_IRUGO | S_IWUSR : S_IRUGO; proc_create(leaf->name, mask, sg_proc_sgp, leaf->fops); } return 0; } static void sg_proc_cleanup(void) { int k; int num_leaves = ARRAY_SIZE(sg_proc_leaf_arr); if (!sg_proc_sgp) return; for (k = 0; k < num_leaves; ++k) remove_proc_entry(sg_proc_leaf_arr[k].name, sg_proc_sgp); remove_proc_entry(sg_proc_sg_dirname, NULL); } static int sg_proc_seq_show_int(struct seq_file *s, void *v) { seq_printf(s, "%d\n", *((int *)s->private)); return 0; } static int sg_proc_single_open_adio(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_int, &sg_allow_dio); } static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer, size_t count, loff_t *off) { int err; unsigned long num; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; err = kstrtoul_from_user(buffer, count, 0, &num); if (err) return err; sg_allow_dio = num ? 1 : 0; return count; } static int sg_proc_single_open_dressz(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_int, &sg_big_buff); } static ssize_t sg_proc_write_dressz(struct file *filp, const char __user *buffer, size_t count, loff_t *off) { int err; unsigned long k = ULONG_MAX; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; err = kstrtoul_from_user(buffer, count, 0, &k); if (err) return err; if (k <= 1048576) { /* limit "big buff" to 1 MB */ sg_big_buff = k; return count; } return -ERANGE; } static int sg_proc_seq_show_version(struct seq_file *s, void *v) { seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR, sg_version_date); return 0; } static int sg_proc_single_open_version(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_version, NULL); } static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v) { seq_puts(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n"); return 0; } static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_devhdr, NULL); } struct sg_proc_deviter { loff_t index; size_t max; }; static void * dev_seq_start(struct seq_file *s, loff_t *pos) { struct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL); s->private = it; if (! it) return NULL; it->index = *pos; it->max = sg_last_dev(); if (it->index >= it->max) return NULL; return it; } static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos) { struct sg_proc_deviter * it = s->private; *pos = ++it->index; return (it->index < it->max) ? it : NULL; } static void dev_seq_stop(struct seq_file *s, void *v) { kfree(s->private); } static int sg_proc_open_dev(struct inode *inode, struct file *file) { return seq_open(file, &dev_seq_ops); } static int sg_proc_seq_show_dev(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; struct scsi_device *scsidp; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if ((NULL == sdp) || (NULL == sdp->device) || (atomic_read(&sdp->detaching))) seq_puts(s, "-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n"); else { scsidp = sdp->device; seq_printf(s, "%d\t%d\t%d\t%llu\t%d\t%d\t%d\t%d\t%d\n", scsidp->host->host_no, scsidp->channel, scsidp->id, scsidp->lun, (int) scsidp->type, 1, (int) scsidp->queue_depth, (int) atomic_read(&scsidp->device_busy), (int) scsi_device_online(scsidp)); } read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } static int sg_proc_open_devstrs(struct inode *inode, struct file *file) { return seq_open(file, &devstrs_seq_ops); } static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; struct scsi_device *scsidp; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; scsidp = sdp ? sdp->device : NULL; if (sdp && scsidp && (!atomic_read(&sdp->detaching))) seq_printf(s, "%8.8s\t%16.16s\t%4.4s\n", scsidp->vendor, scsidp->model, scsidp->rev); else seq_puts(s, "<no active device>\n"); read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } /* must be called while holding sg_index_lock */ static void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp) { int k, m, new_interface, blen, usg; Sg_request *srp; Sg_fd *fp; const sg_io_hdr_t *hp; const char * cp; unsigned int ms; k = 0; list_for_each_entry(fp, &sdp->sfds, sfd_siblings) { k++; read_lock(&fp->rq_list_lock); /* irqs already disabled */ seq_printf(s, " FD(%d): timeout=%dms bufflen=%d " "(res)sgat=%d low_dma=%d\n", k, jiffies_to_msecs(fp->timeout), fp->reserve.bufflen, (int) fp->reserve.k_use_sg, (int) fp->low_dma); seq_printf(s, " cmd_q=%d f_packid=%d k_orphan=%d closed=0\n", (int) fp->cmd_q, (int) fp->force_packid, (int) fp->keep_orphan); for (m = 0, srp = fp->headrp; srp != NULL; ++m, srp = srp->nextrp) { hp = &srp->header; new_interface = (hp->interface_id == '\0') ? 0 : 1; if (srp->res_used) { if (new_interface && (SG_FLAG_MMAP_IO & hp->flags)) cp = " mmap>> "; else cp = " rb>> "; } else { if (SG_INFO_DIRECT_IO_MASK & hp->info) cp = " dio>> "; else cp = " "; } seq_puts(s, cp); blen = srp->data.bufflen; usg = srp->data.k_use_sg; seq_puts(s, srp->done ? ((1 == srp->done) ? "rcv:" : "fin:") : "act:"); seq_printf(s, " id=%d blen=%d", srp->header.pack_id, blen); if (srp->done) seq_printf(s, " dur=%d", hp->duration); else { ms = jiffies_to_msecs(jiffies); seq_printf(s, " t_o/elap=%d/%d", (new_interface ? hp->timeout : jiffies_to_msecs(fp->timeout)), (ms > hp->duration ? ms - hp->duration : 0)); } seq_printf(s, "ms sgat=%d op=0x%02x\n", usg, (int) srp->data.cmd_opcode); } if (0 == m) seq_puts(s, " No requests active\n"); read_unlock(&fp->rq_list_lock); } } static int sg_proc_open_debug(struct inode *inode, struct file *file) { return seq_open(file, &debug_seq_ops); } static int sg_proc_seq_show_debug(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; unsigned long iflags; if (it && (0 == it->index)) seq_printf(s, "max_active_device=%d def_reserved_size=%d\n", (int)it->max, sg_big_buff); read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if (NULL == sdp) goto skip; read_lock(&sdp->sfd_lock); if (!list_empty(&sdp->sfds)) { seq_printf(s, " >>> device=%s ", sdp->disk->disk_name); if (atomic_read(&sdp->detaching)) seq_puts(s, "detaching pending close "); else if (sdp->device) { struct scsi_device *scsidp = sdp->device; seq_printf(s, "%d:%d:%d:%llu em=%d", scsidp->host->host_no, scsidp->channel, scsidp->id, scsidp->lun, scsidp->host->hostt->emulated); } seq_printf(s, " sg_tablesize=%d excl=%d open_cnt=%d\n", sdp->sg_tablesize, sdp->exclude, sdp->open_cnt); sg_proc_debug_helper(s, sdp); } read_unlock(&sdp->sfd_lock); skip: read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } #endif /* CONFIG_SCSI_PROC_FS */ module_init(init_sg); module_exit(exit_sg);
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1858_0
crossvul-cpp_data_bad_1360_2
/* A Bison parser, made by GNU Bison 3.2.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.2.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 2 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* First part of user prologue. */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "libyang.h" #include "common.h" #include "context.h" #include "resolve.h" #include "parser_yang.h" #include "parser_yang_lex.h" #include "parser.h" #define YANG_ADDELEM(current_ptr, size, array_name) \ if ((size) == LY_ARRAY_MAX(size)) { \ LOGERR(trg->ctx, LY_EINT, "Reached limit (%"PRIu64") for storing %s.", LY_ARRAY_MAX(size), array_name); \ free(s); \ YYABORT; \ } else if (!((size) % LY_YANG_ARRAY_SIZE)) { \ void *tmp; \ \ tmp = realloc((current_ptr), (sizeof *(current_ptr)) * ((size) + LY_YANG_ARRAY_SIZE)); \ if (!tmp) { \ LOGMEM(trg->ctx); \ free(s); \ YYABORT; \ } \ memset(tmp + (sizeof *(current_ptr)) * (size), 0, (sizeof *(current_ptr)) * LY_YANG_ARRAY_SIZE); \ (current_ptr) = tmp; \ } \ actual = &(current_ptr)[(size)++]; \ void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...); /* pointer on the current parsed element 'actual' */ # ifndef YY_NULLPTR # if defined __cplusplus # if 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # else # define YY_NULLPTR ((void*)0) # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "parser_yang_bis.h". */ #ifndef YY_YY_PARSER_YANG_BIS_H_INCLUDED # define YY_YY_PARSER_YANG_BIS_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { UNION_KEYWORD = 258, ANYXML_KEYWORD = 259, WHITESPACE = 260, ERROR = 261, EOL = 262, STRING = 263, STRINGS = 264, IDENTIFIER = 265, IDENTIFIERPREFIX = 266, REVISION_DATE = 267, TAB = 268, DOUBLEDOT = 269, URI = 270, INTEGER = 271, NON_NEGATIVE_INTEGER = 272, ZERO = 273, DECIMAL = 274, ARGUMENT_KEYWORD = 275, AUGMENT_KEYWORD = 276, BASE_KEYWORD = 277, BELONGS_TO_KEYWORD = 278, BIT_KEYWORD = 279, CASE_KEYWORD = 280, CHOICE_KEYWORD = 281, CONFIG_KEYWORD = 282, CONTACT_KEYWORD = 283, CONTAINER_KEYWORD = 284, DEFAULT_KEYWORD = 285, DESCRIPTION_KEYWORD = 286, ENUM_KEYWORD = 287, ERROR_APP_TAG_KEYWORD = 288, ERROR_MESSAGE_KEYWORD = 289, EXTENSION_KEYWORD = 290, DEVIATION_KEYWORD = 291, DEVIATE_KEYWORD = 292, FEATURE_KEYWORD = 293, FRACTION_DIGITS_KEYWORD = 294, GROUPING_KEYWORD = 295, IDENTITY_KEYWORD = 296, IF_FEATURE_KEYWORD = 297, IMPORT_KEYWORD = 298, INCLUDE_KEYWORD = 299, INPUT_KEYWORD = 300, KEY_KEYWORD = 301, LEAF_KEYWORD = 302, LEAF_LIST_KEYWORD = 303, LENGTH_KEYWORD = 304, LIST_KEYWORD = 305, MANDATORY_KEYWORD = 306, MAX_ELEMENTS_KEYWORD = 307, MIN_ELEMENTS_KEYWORD = 308, MODULE_KEYWORD = 309, MUST_KEYWORD = 310, NAMESPACE_KEYWORD = 311, NOTIFICATION_KEYWORD = 312, ORDERED_BY_KEYWORD = 313, ORGANIZATION_KEYWORD = 314, OUTPUT_KEYWORD = 315, PATH_KEYWORD = 316, PATTERN_KEYWORD = 317, POSITION_KEYWORD = 318, PREFIX_KEYWORD = 319, PRESENCE_KEYWORD = 320, RANGE_KEYWORD = 321, REFERENCE_KEYWORD = 322, REFINE_KEYWORD = 323, REQUIRE_INSTANCE_KEYWORD = 324, REVISION_KEYWORD = 325, REVISION_DATE_KEYWORD = 326, RPC_KEYWORD = 327, STATUS_KEYWORD = 328, SUBMODULE_KEYWORD = 329, TYPE_KEYWORD = 330, TYPEDEF_KEYWORD = 331, UNIQUE_KEYWORD = 332, UNITS_KEYWORD = 333, USES_KEYWORD = 334, VALUE_KEYWORD = 335, WHEN_KEYWORD = 336, YANG_VERSION_KEYWORD = 337, YIN_ELEMENT_KEYWORD = 338, ADD_KEYWORD = 339, CURRENT_KEYWORD = 340, DELETE_KEYWORD = 341, DEPRECATED_KEYWORD = 342, FALSE_KEYWORD = 343, NOT_SUPPORTED_KEYWORD = 344, OBSOLETE_KEYWORD = 345, REPLACE_KEYWORD = 346, SYSTEM_KEYWORD = 347, TRUE_KEYWORD = 348, UNBOUNDED_KEYWORD = 349, USER_KEYWORD = 350, ACTION_KEYWORD = 351, MODIFIER_KEYWORD = 352, ANYDATA_KEYWORD = 353, NODE = 354, NODE_PRINT = 355, EXTENSION_INSTANCE = 356, SUBMODULE_EXT_KEYWORD = 357 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { int32_t i; uint32_t uint; char *str; char **p_str; void *v; char ch; struct yang_type *type; struct lys_deviation *dev; struct lys_deviate *deviate; union { uint32_t index; struct lys_node_container *container; struct lys_node_anydata *anydata; struct type_node node; struct lys_node_case *cs; struct lys_node_grp *grouping; struct lys_refine *refine; struct lys_node_notif *notif; struct lys_node_uses *uses; struct lys_node_inout *inout; struct lys_node_augment *augment; } nodes; enum yytokentype token; struct { void *actual; enum yytokentype token; } backup_token; struct { struct lys_revision **revision; int index; } revisions; }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif int yyparse (void *scanner, struct yang_parameter *param); #endif /* !YY_YY_PARSER_YANG_BIS_H_INCLUDED */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 6 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 3466 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 113 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 329 /* YYNRULES -- Number of rules. */ #define YYNRULES 827 /* YYNSTATES -- Number of states. */ #define YYNSTATES 1318 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 357 #define YYTRANSLATE(YYX) \ ((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 111, 112, 2, 103, 2, 2, 2, 107, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 106, 2, 110, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 108, 2, 109, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 104, 2, 105, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 338, 338, 339, 340, 342, 365, 368, 370, 369, 393, 404, 414, 424, 425, 431, 436, 442, 453, 463, 476, 477, 483, 485, 489, 491, 495, 497, 498, 499, 501, 509, 517, 518, 523, 534, 545, 556, 564, 569, 570, 574, 575, 586, 597, 608, 612, 614, 637, 654, 658, 660, 661, 666, 671, 676, 682, 686, 688, 692, 694, 698, 700, 704, 706, 719, 730, 731, 743, 747, 748, 752, 753, 758, 765, 765, 776, 782, 830, 849, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 864, 879, 886, 887, 891, 892, 893, 899, 904, 910, 928, 930, 931, 935, 940, 941, 963, 964, 965, 978, 983, 985, 986, 987, 988, 1003, 1017, 1022, 1023, 1038, 1039, 1040, 1046, 1051, 1057, 1114, 1119, 1120, 1122, 1138, 1143, 1144, 1169, 1170, 1184, 1185, 1191, 1196, 1202, 1206, 1208, 1261, 1272, 1275, 1278, 1283, 1288, 1294, 1299, 1305, 1310, 1319, 1320, 1324, 1371, 1372, 1374, 1375, 1379, 1385, 1398, 1399, 1400, 1404, 1405, 1407, 1411, 1429, 1434, 1436, 1437, 1453, 1458, 1467, 1468, 1472, 1488, 1493, 1498, 1503, 1509, 1513, 1529, 1544, 1545, 1549, 1550, 1560, 1565, 1570, 1575, 1581, 1585, 1596, 1608, 1609, 1612, 1620, 1631, 1632, 1647, 1648, 1649, 1661, 1667, 1672, 1678, 1683, 1685, 1686, 1701, 1706, 1707, 1712, 1716, 1718, 1723, 1725, 1726, 1727, 1740, 1752, 1753, 1755, 1763, 1775, 1776, 1791, 1792, 1793, 1805, 1811, 1816, 1822, 1827, 1829, 1830, 1846, 1850, 1852, 1856, 1858, 1862, 1864, 1868, 1870, 1880, 1887, 1888, 1892, 1893, 1899, 1904, 1909, 1910, 1911, 1912, 1913, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1929, 1939, 1946, 1947, 1970, 1971, 1972, 1973, 1974, 1979, 1985, 1991, 1996, 2001, 2002, 2003, 2008, 2009, 2011, 2051, 2061, 2064, 2065, 2066, 2069, 2074, 2075, 2080, 2086, 2092, 2098, 2103, 2109, 2119, 2174, 2177, 2178, 2179, 2182, 2193, 2198, 2199, 2205, 2218, 2231, 2241, 2247, 2252, 2258, 2268, 2315, 2318, 2319, 2320, 2321, 2330, 2336, 2342, 2355, 2368, 2378, 2384, 2389, 2394, 2395, 2396, 2397, 2402, 2404, 2414, 2421, 2422, 2442, 2445, 2446, 2447, 2457, 2464, 2471, 2478, 2484, 2490, 2492, 2493, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2507, 2517, 2524, 2525, 2539, 2540, 2541, 2542, 2548, 2553, 2558, 2561, 2571, 2578, 2588, 2595, 2596, 2619, 2622, 2623, 2624, 2625, 2632, 2639, 2646, 2651, 2657, 2667, 2674, 2675, 2707, 2708, 2709, 2710, 2716, 2721, 2726, 2727, 2729, 2730, 2732, 2745, 2750, 2751, 2783, 2786, 2800, 2816, 2838, 2889, 2908, 2927, 2948, 2969, 2974, 2980, 2981, 2984, 2999, 3008, 3009, 3011, 3022, 3031, 3032, 3033, 3034, 3040, 3045, 3050, 3051, 3052, 3057, 3059, 3074, 3081, 3091, 3098, 3099, 3123, 3126, 3127, 3133, 3138, 3143, 3144, 3145, 3152, 3160, 3175, 3205, 3206, 3207, 3208, 3209, 3211, 3226, 3256, 3265, 3272, 3273, 3305, 3306, 3307, 3308, 3314, 3319, 3324, 3325, 3326, 3328, 3340, 3360, 3361, 3367, 3373, 3375, 3376, 3378, 3379, 3382, 3390, 3395, 3396, 3398, 3399, 3400, 3402, 3410, 3415, 3416, 3448, 3449, 3455, 3456, 3462, 3468, 3475, 3482, 3490, 3499, 3507, 3512, 3513, 3545, 3546, 3552, 3553, 3559, 3566, 3574, 3579, 3580, 3594, 3595, 3596, 3602, 3608, 3615, 3622, 3630, 3639, 3648, 3653, 3654, 3658, 3659, 3664, 3670, 3675, 3677, 3678, 3679, 3692, 3697, 3699, 3700, 3701, 3714, 3718, 3720, 3725, 3727, 3728, 3748, 3753, 3755, 3756, 3757, 3777, 3782, 3784, 3785, 3786, 3798, 3867, 3872, 3873, 3877, 3881, 3883, 3884, 3886, 3890, 3892, 3892, 3899, 3902, 3911, 3930, 3932, 3933, 3936, 3936, 3953, 3953, 3960, 3960, 3967, 3970, 3972, 3974, 3975, 3977, 3979, 3981, 3982, 3984, 3986, 3987, 3989, 3990, 3992, 3994, 3997, 4000, 4002, 4003, 4005, 4006, 4008, 4010, 4021, 4022, 4025, 4026, 4038, 4039, 4041, 4042, 4044, 4045, 4051, 4052, 4055, 4056, 4057, 4081, 4082, 4085, 4091, 4095, 4100, 4101, 4102, 4105, 4110, 4120, 4122, 4123, 4125, 4126, 4128, 4129, 4130, 4132, 4133, 4135, 4136, 4138, 4139, 4143, 4144, 4171, 4209, 4210, 4212, 4214, 4216, 4217, 4219, 4220, 4222, 4223, 4226, 4227, 4230, 4232, 4233, 4236, 4236, 4243, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4253, 4254, 4255, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301, 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, 4320, 4321, 4322, 4323, 4324, 4325, 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340, 4347, 4354, 4374, 4392, 4408, 4435, 4442, 4460, 4500, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4531, 4532, 4533, 4534, 4536, 4544, 4545, 4550, 4555, 4560, 4565, 4570, 4575, 4580, 4585, 4590, 4595, 4600, 4605, 4610, 4615, 4620, 4634, 4654, 4659, 4664, 4669, 4682, 4687, 4691, 4701, 4716, 4731, 4746, 4761, 4781, 4796, 4797, 4803, 4810, 4825, 4828 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "UNION_KEYWORD", "ANYXML_KEYWORD", "WHITESPACE", "ERROR", "EOL", "STRING", "STRINGS", "IDENTIFIER", "IDENTIFIERPREFIX", "REVISION_DATE", "TAB", "DOUBLEDOT", "URI", "INTEGER", "NON_NEGATIVE_INTEGER", "ZERO", "DECIMAL", "ARGUMENT_KEYWORD", "AUGMENT_KEYWORD", "BASE_KEYWORD", "BELONGS_TO_KEYWORD", "BIT_KEYWORD", "CASE_KEYWORD", "CHOICE_KEYWORD", "CONFIG_KEYWORD", "CONTACT_KEYWORD", "CONTAINER_KEYWORD", "DEFAULT_KEYWORD", "DESCRIPTION_KEYWORD", "ENUM_KEYWORD", "ERROR_APP_TAG_KEYWORD", "ERROR_MESSAGE_KEYWORD", "EXTENSION_KEYWORD", "DEVIATION_KEYWORD", "DEVIATE_KEYWORD", "FEATURE_KEYWORD", "FRACTION_DIGITS_KEYWORD", "GROUPING_KEYWORD", "IDENTITY_KEYWORD", "IF_FEATURE_KEYWORD", "IMPORT_KEYWORD", "INCLUDE_KEYWORD", "INPUT_KEYWORD", "KEY_KEYWORD", "LEAF_KEYWORD", "LEAF_LIST_KEYWORD", "LENGTH_KEYWORD", "LIST_KEYWORD", "MANDATORY_KEYWORD", "MAX_ELEMENTS_KEYWORD", "MIN_ELEMENTS_KEYWORD", "MODULE_KEYWORD", "MUST_KEYWORD", "NAMESPACE_KEYWORD", "NOTIFICATION_KEYWORD", "ORDERED_BY_KEYWORD", "ORGANIZATION_KEYWORD", "OUTPUT_KEYWORD", "PATH_KEYWORD", "PATTERN_KEYWORD", "POSITION_KEYWORD", "PREFIX_KEYWORD", "PRESENCE_KEYWORD", "RANGE_KEYWORD", "REFERENCE_KEYWORD", "REFINE_KEYWORD", "REQUIRE_INSTANCE_KEYWORD", "REVISION_KEYWORD", "REVISION_DATE_KEYWORD", "RPC_KEYWORD", "STATUS_KEYWORD", "SUBMODULE_KEYWORD", "TYPE_KEYWORD", "TYPEDEF_KEYWORD", "UNIQUE_KEYWORD", "UNITS_KEYWORD", "USES_KEYWORD", "VALUE_KEYWORD", "WHEN_KEYWORD", "YANG_VERSION_KEYWORD", "YIN_ELEMENT_KEYWORD", "ADD_KEYWORD", "CURRENT_KEYWORD", "DELETE_KEYWORD", "DEPRECATED_KEYWORD", "FALSE_KEYWORD", "NOT_SUPPORTED_KEYWORD", "OBSOLETE_KEYWORD", "REPLACE_KEYWORD", "SYSTEM_KEYWORD", "TRUE_KEYWORD", "UNBOUNDED_KEYWORD", "USER_KEYWORD", "ACTION_KEYWORD", "MODIFIER_KEYWORD", "ANYDATA_KEYWORD", "NODE", "NODE_PRINT", "EXTENSION_INSTANCE", "SUBMODULE_EXT_KEYWORD", "'+'", "'{'", "'}'", "';'", "'/'", "'['", "']'", "'='", "'('", "')'", "$accept", "start", "tmp_string", "string_1", "string_2", "$@1", "module_arg_str", "module_stmt", "module_header_stmts", "module_header_stmt", "submodule_arg_str", "submodule_stmt", "submodule_header_stmts", "submodule_header_stmt", "yang_version_arg", "yang_version_stmt", "namespace_arg_str", "namespace_stmt", "linkage_stmts", "import_stmt", "import_arg_str", "import_opt_stmt", "include_arg_str", "include_stmt", "include_end", "include_opt_stmt", "revision_date_arg", "revision_date_stmt", "belongs_to_arg_str", "belongs_to_stmt", "prefix_arg", "prefix_stmt", "meta_stmts", "organization_arg", "organization_stmt", "contact_arg", "contact_stmt", "description_arg", "description_stmt", "reference_arg", "reference_stmt", "revision_stmts", "revision_arg_stmt", "revision_stmts_opt", "revision_stmt", "revision_end", "revision_opt_stmt", "date_arg_str", "$@2", "body_stmts_end", "body_stmts", "body_stmt", "extension_arg_str", "extension_stmt", "extension_end", "extension_opt_stmt", "argument_str", "argument_stmt", "argument_end", "yin_element_arg", "yin_element_stmt", "yin_element_arg_str", "status_arg", "status_stmt", "status_arg_str", "feature_arg_str", "feature_stmt", "feature_end", "feature_opt_stmt", "if_feature_arg", "if_feature_stmt", "if_feature_end", "identity_arg_str", "identity_stmt", "identity_end", "identity_opt_stmt", "base_arg", "base_stmt", "typedef_arg_str", "typedef_stmt", "type_opt_stmt", "type_stmt", "type_arg_str", "type_end", "type_body_stmts", "some_restrictions", "union_stmt", "union_spec", "fraction_digits_arg", "fraction_digits_stmt", "fraction_digits_arg_str", "length_stmt", "length_arg_str", "length_end", "message_opt_stmt", "pattern_sep", "pattern_stmt", "pattern_arg_str", "pattern_end", "pattern_opt_stmt", "modifier_arg", "modifier_stmt", "enum_specification", "enum_stmts", "enum_stmt", "enum_arg_str", "enum_end", "enum_opt_stmt", "value_arg", "value_stmt", "integer_value_arg_str", "range_stmt", "range_end", "path_arg", "path_stmt", "require_instance_arg", "require_instance_stmt", "require_instance_arg_str", "bits_specification", "bit_stmts", "bit_stmt", "bit_arg_str", "bit_end", "bit_opt_stmt", "position_value_arg", "position_stmt", "position_value_arg_str", "error_message_arg", "error_message_stmt", "error_app_tag_arg", "error_app_tag_stmt", "units_arg", "units_stmt", "default_arg", "default_stmt", "grouping_arg_str", "grouping_stmt", "grouping_end", "grouping_opt_stmt", "data_def_stmt", "container_arg_str", "container_stmt", "container_end", "container_opt_stmt", "leaf_stmt", "leaf_arg_str", "leaf_opt_stmt", "leaf_list_arg_str", "leaf_list_stmt", "leaf_list_opt_stmt", "list_arg_str", "list_stmt", "list_opt_stmt", "choice_arg_str", "choice_stmt", "choice_end", "choice_opt_stmt", "short_case_case_stmt", "short_case_stmt", "case_arg_str", "case_stmt", "case_end", "case_opt_stmt", "anyxml_arg_str", "anyxml_stmt", "anydata_arg_str", "anydata_stmt", "anyxml_end", "anyxml_opt_stmt", "uses_arg_str", "uses_stmt", "uses_end", "uses_opt_stmt", "refine_args_str", "refine_arg_str", "refine_stmt", "refine_end", "refine_body_opt_stmts", "uses_augment_arg_str", "uses_augment_arg", "uses_augment_stmt", "augment_arg_str", "augment_arg", "augment_stmt", "augment_opt_stmt", "action_arg_str", "action_stmt", "rpc_arg_str", "rpc_stmt", "rpc_end", "rpc_opt_stmt", "input_arg", "input_stmt", "input_output_opt_stmt", "output_arg", "output_stmt", "notification_arg_str", "notification_stmt", "notification_end", "notification_opt_stmt", "deviation_arg", "deviation_stmt", "deviation_opt_stmt", "deviation_arg_str", "deviate_body_stmt", "deviate_not_supported", "deviate_not_supported_stmt", "deviate_not_supported_end", "deviate_stmts", "deviate_add", "deviate_add_stmt", "deviate_add_end", "deviate_add_opt_stmt", "deviate_delete", "deviate_delete_stmt", "deviate_delete_end", "deviate_delete_opt_stmt", "deviate_replace", "deviate_replace_stmt", "deviate_replace_end", "deviate_replace_opt_stmt", "when_arg_str", "when_stmt", "when_end", "when_opt_stmt", "config_arg", "config_stmt", "config_arg_str", "mandatory_arg", "mandatory_stmt", "mandatory_arg_str", "presence_arg", "presence_stmt", "min_value_arg", "min_elements_stmt", "min_value_arg_str", "max_value_arg", "max_elements_stmt", "max_value_arg_str", "ordered_by_arg", "ordered_by_stmt", "ordered_by_arg_str", "must_agr_str", "must_stmt", "must_end", "unique_arg", "unique_stmt", "unique_arg_str", "key_arg", "key_stmt", "key_arg_str", "$@3", "range_arg_str", "absolute_schema_nodeid", "absolute_schema_nodeids", "absolute_schema_nodeid_opt", "descendant_schema_nodeid", "$@4", "path_arg_str", "$@5", "$@6", "absolute_path", "absolute_paths", "absolute_path_opt", "relative_path", "relative_path_part1", "relative_path_part1_opt", "descendant_path", "descendant_path_opt", "path_predicate", "path_equality_expr", "path_key_expr", "rel_path_keyexpr", "rel_path_keyexpr_part1", "rel_path_keyexpr_part1_opt", "rel_path_keyexpr_part2", "current_function_invocation", "positive_integer_value", "non_negative_integer_value", "integer_value", "integer_value_convert", "prefix_arg_str", "identifier_arg_str", "node_identifier", "identifier_ref_arg_str", "stmtend", "semicolom", "curly_bracket_close", "curly_bracket_open", "stmtsep", "unknown_statement", "string_opt", "string_opt_part1", "string_opt_part2", "unknown_string", "unknown_string_part1", "unknown_string_part2", "unknown_statement_end", "unknown_statement2_opt", "unknown_statement2", "unknown_statement2_end", "unknown_statement2_yang_stmt", "unknown_statement2_module_stmt", "unknown_statement3_opt", "unknown_statement3_opt_end", "sep_stmt", "optsep", "sep", "whitespace_opt", "string", "$@7", "strings", "identifier", "identifier1", "yang_stmt", "identifiers", "identifiers_ref", "type_ext_alloc", "typedef_ext_alloc", "iffeature_ext_alloc", "restriction_ext_alloc", "when_ext_alloc", "revision_ext_alloc", "datadef_ext_check", "not_supported_ext_check", "not_supported_ext", "datadef_ext_stmt", "restriction_ext_stmt", "ext_substatements", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 43, 123, 125, 59, 47, 91, 93, 61, 40, 41 }; # endif #define YYPACT_NINF -1012 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-1012))) #define YYTABLE_NINF -757 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 440, 100, -1012, -1012, 566, 1894, -1012, -1012, -1012, 266, 266, -1012, 266, -1012, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -8, 31, 79, 868, 70, 125, 481, 266, -1012, -1012, 3273, 3273, 3273, 2893, 3273, 71, 2703, 2703, 2703, 2703, 2703, 98, 2988, 94, 52, 287, 2703, 77, 2703, 104, 287, 3273, 2703, 2703, 182, 58, 246, 2988, 2703, 321, 2703, 279, 279, 266, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, 266, 266, 266, 266, 266, -1012, 266, 266, 266, 266, -1012, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 29, -1012, 134, -1012, -1012, -1012, -22, 2798, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 151, -1012, -1012, -1012, -1012, -1012, 156, -1012, 67, -1012, -1012, -1012, 224, -1012, -1012, -1012, 161, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, 224, -1012, 224, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, 224, -1012, -1012, 224, -1012, 262, 202, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, 224, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, -1012, 224, -1012, -1012, -1012, 224, -1012, -1012, -1012, -1012, 2893, 279, 3273, 279, 2703, 279, 2703, 2703, 2703, -1012, 2703, 279, 2703, 279, 58, 279, 3273, 3273, 3273, 3273, 3273, 266, 3273, 3273, 3273, 3273, 266, 2893, 3273, 3273, -1012, -1012, 279, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, 266, 266, -1012, 266, -1012, 266, -1012, 266, -1012, 266, 266, -1012, -1012, -1012, 3368, -1012, -1012, 291, -1012, -1012, -1012, 266, -1012, 266, -1012, -1012, 266, 266, -1012, -1012, -1012, 266, 266, 266, -1012, -1012, 266, -1012, -1012, -1012, 266, -1012, 228, 2703, 266, 274, -1012, 189, -1012, 288, -1012, 298, -1012, 303, -1012, 370, -1012, 380, -1012, 389, -1012, 393, -1012, 407, -1012, 411, -1012, 419, -1012, 426, -1012, 463, -1012, 238, -1012, 314, -1012, 317, -1012, 505, -1012, 506, -1012, 521, -1012, 407, -1012, 279, 279, 266, 266, 266, 266, 326, 279, 279, 109, 279, 112, 608, 266, 266, -1012, 262, -1012, 3083, 266, 332, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 1964, 1994, 2191, 347, -1012, -1012, 19, -1012, 54, 266, 355, -1012, -1012, 368, 373, -1012, -1012, -1012, 48, 3368, -1012, 266, 831, 279, 186, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, 127, 515, 266, -1012, -1012, -1012, 515, -1012, -1012, 188, -1012, 279, -1012, 473, -1012, 306, -1012, 2552, 266, 266, 397, 1000, -1012, -1012, -1012, -1012, 783, -1012, 230, 503, 404, 887, 359, 438, 929, 1958, 1645, 817, 947, 344, 2074, 1547, 1768, 235, 852, 279, 279, 279, 279, 266, -22, 280, -1012, 266, 266, -1012, -1012, 375, 2703, 375, 279, -1012, -1012, -1012, 224, -1012, -1012, 3368, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, 3273, 2703, -1012, -1012, -1012, -8, -1012, -1012, -1012, -1012, -1012, -1012, 279, 474, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 3273, 3273, 279, 279, -1012, -1012, -1012, -1012, -1012, 125, 224, -1012, -1012, 266, 266, -1012, 399, 473, 266, 528, 528, 545, -1012, 567, -1012, 279, -1012, 279, 279, 279, 480, -1012, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 2988, 2988, 279, 279, 279, 279, 279, 279, 279, 279, 279, 266, 266, 423, -1012, 570, -1012, 428, 2046, -1012, -1012, 434, -1012, 465, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 479, -1012, -1012, -1012, 571, -1012, -1012, -1012, -1012, -1012, -1012, 266, 266, 266, 266, 266, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, -1012, 473, 266, 279, 279, 279, 279, -1012, 266, -1012, -1012, -1012, 266, 279, 279, 266, 51, 3273, 51, 3273, 3273, 3273, 279, 266, 459, 2367, 385, 509, 279, 279, 341, 365, -1012, -1012, 483, -1012, -1012, 574, -1012, -1012, 486, -1012, -1012, 591, -1012, 592, -1012, 521, -1012, 473, -1012, 473, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 885, 1126, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 332, 266, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 467, 492, 279, 279, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279, 279, 279, 473, 473, 279, 279, 279, 279, 279, 279, 279, 279, 1460, 205, 524, 216, 201, 493, 579, -1012, -1012, -1012, -1012, -1012, -1012, 266, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 293, 279, 279, 497, 3178, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 473, -1012, -1012, 279, 73, 120, 133, 163, -1012, 50, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 510, 222, 279, 279, 279, 473, -1012, 824, 346, 985, 3368, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 279, 279, 279 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 790, 0, 2, 3, 0, 757, 1, 649, 650, 0, 0, 652, 0, 763, 0, 0, 761, 0, 0, 0, 0, 762, 0, 0, 766, 764, 765, 767, 0, 768, 769, 770, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 759, 760, 0, 771, 802, 806, 619, 792, 803, 797, 793, 794, 619, 809, 796, 815, 814, 819, 804, 813, 818, 799, 800, 795, 798, 810, 811, 805, 816, 817, 812, 820, 801, 0, 0, 0, 0, 0, 0, 0, 627, 758, 651, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 791, 822, 0, 619, 0, 619, 0, 619, 0, 0, 0, 0, 789, 787, 788, 786, 619, 0, 619, 0, 619, 0, 0, 0, 0, 0, 651, 0, 0, 0, 0, 651, 0, 0, 0, 778, 777, 780, 781, 782, 776, 775, 774, 773, 785, 772, 0, 779, 0, 784, 783, 619, 0, 629, 653, 679, 5, 669, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 666, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 670, 744, 671, 672, 673, 674, 745, 675, 676, 677, 678, 746, 747, 748, 651, 608, 0, 10, 749, 667, 668, 651, 0, 17, 0, 99, 750, 613, 0, 138, 651, 651, 0, 47, 651, 651, 529, 0, 525, 659, 662, 660, 664, 665, 663, 658, 0, 58, 656, 661, 0, 243, 0, 60, 0, 239, 0, 237, 598, 170, 0, 167, 651, 610, 563, 0, 559, 561, 609, 651, 651, 534, 0, 530, 651, 545, 0, 541, 651, 599, 540, 0, 537, 600, 651, 0, 25, 651, 651, 550, 0, 546, 0, 56, 575, 0, 213, 0, 0, 236, 0, 233, 651, 605, 0, 49, 651, 0, 535, 0, 62, 651, 651, 219, 0, 215, 74, 76, 0, 45, 651, 651, 651, 114, 0, 109, 558, 0, 555, 651, 569, 0, 241, 603, 604, 601, 209, 0, 206, 651, 602, 0, 191, 621, 620, 651, 0, 807, 0, 808, 0, 821, 0, 0, 0, 180, 0, 823, 0, 824, 0, 825, 0, 0, 0, 0, 0, 445, 0, 0, 0, 0, 452, 0, 0, 0, 619, 619, 826, 651, 651, 827, 651, 628, 651, 7, 619, 607, 619, 619, 101, 100, 618, 616, 139, 619, 619, 611, 612, 619, 528, 527, 526, 59, 651, 244, 61, 240, 238, 168, 169, 560, 651, 533, 532, 531, 543, 542, 544, 538, 539, 26, 549, 548, 547, 57, 214, 0, 578, 572, 0, 574, 582, 234, 235, 50, 606, 536, 63, 218, 217, 216, 651, 46, 111, 113, 112, 110, 556, 557, 567, 242, 207, 208, 192, 0, 625, 624, 0, 150, 0, 140, 0, 124, 0, 172, 0, 551, 0, 182, 0, 564, 0, 518, 0, 65, 0, 368, 0, 357, 0, 334, 0, 266, 0, 245, 0, 285, 0, 298, 0, 314, 0, 454, 0, 383, 0, 430, 0, 370, 447, 447, 645, 647, 632, 630, 6, 13, 20, 104, 614, 0, 0, 657, 562, 587, 577, 581, 0, 75, 570, 651, 634, 622, 623, 626, 619, 151, 149, 619, 619, 126, 125, 619, 173, 171, 619, 553, 552, 619, 183, 181, 619, 211, 210, 619, 520, 519, 619, 69, 68, 619, 372, 369, 619, 359, 358, 619, 336, 335, 619, 268, 267, 619, 247, 246, 619, 619, 619, 619, 456, 455, 619, 385, 384, 619, 434, 431, 371, 0, 0, 0, 631, 651, 27, 12, 27, 19, 0, 0, 617, 619, 0, 576, 579, 583, 580, 585, 0, 568, 636, 156, 142, 0, 175, 175, 185, 175, 522, 71, 374, 361, 338, 270, 249, 286, 300, 316, 458, 387, 436, 446, 619, 619, 619, 258, 259, 260, 261, 262, 263, 264, 265, 619, 453, 651, 627, 651, 0, 51, 0, 14, 15, 16, 51, 21, 619, 0, 102, 615, 48, 654, 584, 0, 565, 0, 0, 0, 0, 153, 154, 619, 155, 221, 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 449, 450, 451, 448, 648, 0, 0, 8, 0, 0, 619, 619, 66, 0, 66, 22, 651, 651, 108, 0, 103, 655, 0, 586, 644, 635, 638, 651, 627, 627, 643, 0, 0, 152, 159, 619, 0, 162, 619, 619, 619, 158, 157, 194, 220, 141, 147, 148, 146, 619, 144, 145, 174, 178, 179, 176, 177, 554, 184, 189, 190, 186, 187, 188, 212, 521, 523, 524, 70, 72, 73, 373, 381, 382, 380, 619, 619, 378, 379, 619, 360, 365, 366, 364, 619, 619, 619, 337, 345, 346, 344, 619, 341, 350, 351, 352, 353, 356, 619, 348, 349, 354, 355, 619, 342, 343, 269, 277, 278, 276, 619, 619, 619, 619, 619, 619, 619, 275, 274, 619, 248, 251, 252, 250, 619, 619, 619, 619, 619, 284, 296, 297, 295, 619, 619, 290, 292, 619, 293, 294, 619, 299, 312, 313, 311, 619, 619, 305, 304, 619, 307, 308, 309, 310, 619, 315, 327, 328, 326, 619, 619, 619, 619, 619, 619, 619, 322, 323, 324, 325, 619, 321, 320, 457, 462, 463, 461, 619, 619, 619, 619, 619, 0, 0, 386, 391, 392, 390, 619, 619, 619, 619, 435, 439, 440, 438, 619, 619, 619, 619, 619, 646, 651, 651, 0, 0, 28, 29, 52, 53, 54, 55, 78, 64, 0, 23, 78, 107, 106, 105, 0, 654, 637, 0, 0, 0, 224, 0, 197, 164, 165, 160, 161, 163, 193, 222, 143, 376, 375, 377, 363, 367, 362, 340, 347, 339, 272, 282, 279, 283, 280, 281, 271, 273, 254, 253, 255, 256, 257, 288, 289, 287, 291, 302, 303, 301, 306, 318, 329, 330, 333, 331, 332, 317, 319, 460, 464, 465, 466, 459, 0, 0, 389, 393, 394, 388, 437, 441, 442, 443, 444, 633, 9, 0, 31, 0, 37, 0, 77, 619, 24, 0, 588, 0, 651, 641, 639, 640, 619, 225, 619, 619, 198, 196, 619, 413, 414, 0, 651, 396, 397, 0, 651, 619, 619, 39, 38, 651, 0, 0, 0, 0, 0, 0, 619, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 67, 651, 654, 645, 227, 223, 200, 195, 619, 412, 619, 399, 398, 395, 32, 41, 11, 0, 0, 0, 0, 0, 0, 79, 18, 0, 0, 0, 0, 420, 401, 0, 0, 417, 418, 0, 567, 651, 0, 90, 474, 0, 467, 651, 0, 115, 0, 128, 0, 432, 654, 589, 654, 642, 226, 231, 232, 230, 619, 229, 199, 204, 205, 203, 619, 202, 0, 0, 30, 36, 33, 34, 35, 40, 44, 42, 43, 619, 566, 416, 619, 92, 91, 619, 473, 619, 117, 116, 619, 130, 129, 433, 0, 0, 228, 201, 415, 424, 425, 423, 619, 619, 619, 619, 619, 619, 400, 410, 411, 619, 405, 406, 407, 404, 408, 409, 619, 420, 94, 469, 119, 132, 654, 654, 422, 426, 429, 427, 428, 421, 403, 402, 0, 0, 0, 0, 0, 0, 0, 419, 93, 97, 98, 619, 96, 0, 468, 470, 471, 118, 122, 123, 121, 619, 131, 136, 137, 135, 619, 133, 597, 654, 590, 593, 95, 0, 120, 134, 0, 0, 484, 497, 477, 506, 619, 651, 475, 476, 651, 481, 651, 483, 651, 482, 654, 594, 595, 472, 0, 0, 0, 0, 592, 591, 619, 479, 478, 619, 486, 485, 619, 499, 498, 619, 508, 507, 0, 0, 488, 501, 510, 654, 480, 0, 0, 0, 0, 487, 489, 492, 493, 494, 495, 496, 619, 491, 500, 502, 505, 619, 504, 509, 619, 512, 513, 514, 515, 516, 517, 596, 490, 503, 511 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -1012, -1012, -1012, 245, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -16, -1012, -2, -9, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1011, -1012, 22, -1012, -534, -24, -1012, 658, -1012, 681, -1012, 63, -1012, 105, -41, -1012, -1012, -237, -1012, -1012, 305, -1012, -225, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -486, -1012, -1012, -1012, -1012, -1012, 41, -1012, -1012, -1012, -1012, -1012, -1012, -11, -1012, -1012, -1012, -1012, -1012, -1012, -657, -1012, -3, -1012, -653, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 23, -1012, 30, -1012, -1012, 53, -1012, 35, -1012, -1012, -1012, -1012, 10, -1012, -1012, -236, -1012, -1012, -1012, -1012, -366, -1012, 38, -1012, -1012, 40, -1012, 43, -1012, -1012, -1012, -21, -1012, -1012, -1012, -1012, -355, -1012, -1012, 12, -1012, 18, -1012, -704, -1012, -480, -1012, 16, -1012, -1012, -560, -1012, -80, -1012, -1012, -67, -1012, -1012, -1012, -63, -1012, -1012, -39, -1012, -1012, -36, -1012, -1012, -1012, -1012, -1012, -33, -1012, -1012, -1012, -28, -1012, -27, 206, -1012, -1012, 667, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -435, -1012, -62, -1012, -1012, -365, -1012, -1012, 42, 211, -1012, 44, -1012, -87, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, 74, -1012, -1012, -1012, -473, -1012, -1012, -667, -1012, -1012, -675, -1012, -722, -1012, -1012, -662, -1012, -1012, -271, -1012, -1012, -35, -1012, -1012, -725, -1012, -1012, 46, -1012, -1012, -1012, -390, -319, -335, -461, -1012, -1012, -1012, -1012, 214, 97, -1012, -1012, 239, -1012, -1012, -1012, 135, -1012, -1012, -1012, -441, -1012, -1012, -1012, 155, 693, -1012, -1012, -1012, 185, -93, -328, 1164, -1012, -1012, -1012, 526, 110, -1012, -1012, -1012, -433, -1012, -1012, -1012, -1012, -1012, -143, -1012, -1012, -260, 84, -4, 1453, 166, -694, 119, -1012, 660, -12, -1012, 137, -20, -23, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012, -1012 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 1, 261, 262, 553, 933, 263, 2, 631, 632, 269, 3, 633, 634, 944, 688, 332, 54, 686, 740, 1023, 1106, 1025, 741, 1056, 1107, 365, 55, 279, 56, 351, 57, 742, 339, 938, 293, 939, 299, 783, 356, 784, 942, 521, 943, 144, 597, 718, 366, 489, 1027, 1028, 1064, 1113, 1065, 1157, 1208, 271, 62, 438, 749, 636, 750, 371, 1174, 372, 1119, 1066, 1162, 1210, 509, 1175, 579, 1121, 1067, 1165, 1211, 275, 64, 507, 669, 711, 127, 505, 575, 705, 706, 765, 766, 307, 65, 308, 136, 511, 582, 713, 401, 137, 515, 588, 715, 388, 66, 707, 964, 708, 957, 1043, 1103, 384, 67, 385, 138, 591, 342, 68, 361, 69, 362, 709, 774, 710, 955, 1040, 1102, 347, 70, 348, 303, 785, 301, 786, 378, 73, 297, 74, 531, 670, 612, 723, 671, 529, 672, 609, 722, 673, 533, 724, 535, 674, 725, 537, 675, 726, 527, 676, 606, 721, 828, 829, 525, 1177, 603, 720, 523, 677, 545, 678, 600, 719, 541, 679, 621, 728, 1050, 1051, 919, 1087, 1142, 1046, 1047, 920, 1109, 1110, 1071, 1141, 543, 1178, 1123, 1072, 624, 729, 170, 171, 626, 172, 173, 539, 1179, 618, 727, 1116, 1074, 1209, 1117, 1249, 1250, 1251, 1271, 1252, 1253, 1254, 1274, 1288, 1255, 1256, 1277, 1289, 1257, 1258, 1280, 1290, 519, 1180, 594, 717, 284, 75, 285, 319, 76, 320, 354, 77, 328, 78, 329, 323, 79, 324, 337, 80, 338, 513, 680, 585, 374, 81, 375, 312, 82, 313, 459, 517, 646, 1112, 567, 376, 497, 343, 344, 345, 475, 476, 563, 478, 479, 565, 643, 699, 640, 950, 1126, 1237, 1238, 1244, 1268, 1127, 330, 331, 386, 387, 352, 264, 377, 276, 441, 442, 638, 443, 124, 390, 502, 503, 571, 176, 430, 629, 570, 702, 757, 1036, 758, 759, 628, 428, 391, 4, 177, 752, 294, 451, 295, 265, 266, 267, 268, 392, 83, 84, 85, 86, 87, 88, 89, 90, 91, 175, 140, 5 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 11, 901, 174, 881, 897, 92, 92, 780, 92, 160, 92, 92, 314, 92, 92, 92, 92, 71, 92, 92, 865, 877, 161, 72, 92, 639, 162, 169, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 63, 848, 92, 764, 163, 139, 808, 164, 835, 751, 165, 869, 779, 180, 180, 166, 167, 882, 898, 506, 180, 126, 60, 305, 363, 864, 876, 278, 131, 36, 277, 15, 7, 180, 8, 129, 426, 41, 427, 180, 92, 296, 296, 296, 296, 296, 542, 315, 353, 1144, 1149, 296, 690, 296, 6, 687, 180, 296, 296, 159, 180, 128, 315, 296, 61, 296, 180, 960, 7, 305, 8, 7, -573, 8, 273, 130, 92, 273, 92, 7, 92, 8, 92, 92, 92, 92, 7, 423, 8, 737, 687, 92, 7, 92, 8, 92, 92, 92, 92, 92, 321, 92, 92, 92, 92, 141, 92, 92, 92, -587, -587, -654, 645, 281, 815, 142, 843, 856, 282, 296, 892, 910, 7, 334, 8, 436, 335, 437, 11, 93, 94, 1269, 95, 1270, 96, 97, 316, 98, 99, 100, 101, 317, 102, 103, 180, 7, 635, 8, 104, 143, 180, 273, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 477, 637, 123, 298, 300, 302, 304, 14, 1272, 12, 1273, 7, 333, 8, 340, 781, 20, 273, 355, 357, 20, 1275, 424, 1276, 379, 822, 389, 130, 866, 878, 807, 20, 834, 847, 735, 868, 880, 896, 180, 433, 912, 1033, 130, 309, 435, 20, 325, 22, 23, 446, 20, 1278, 43, 1279, 358, 7, 43, 8, 46, 359, 746, 130, 46, 270, 272, 747, 280, 43, 7, 7, 8, 8, 932, 46, 273, 712, 393, 576, 395, 180, 397, 43, 399, 400, 402, 403, 43, 913, 305, 326, 1229, 405, 46, 407, 1215, 409, 410, 411, 412, 413, 141, 415, 416, 417, 418, 1224, 420, 421, 422, 953, 954, 1287, 439, 180, 440, 367, 568, 368, 569, 782, 369, 380, 381, 382, 914, 274, 613, 283, 292, 292, 292, 292, 292, 306, 311, 318, 322, 327, 292, 336, 292, 341, 346, 350, 292, 292, 360, 364, 370, 373, 292, 383, 292, 474, 278, 17, 20, 277, 19, 20, 19, 1245, 573, 1246, 574, 562, 1247, 1100, 1248, 296, 130, 296, 296, 296, 20, 296, 577, 296, 578, 33, 20, 278, 564, 133, 277, 133, 580, 18, 581, 41, 20, 583, 43, 584, 11, 43, 45, 474, 698, 11, 20, 46, 614, 126, 1189, 615, 48, 47, 48, 141, 43, 130, 11, 630, 11, 1167, 43, 1168, 38, 20, 45, 22, 23, 645, 11, 11, 43, 11, 11, -651, 1143, -651, 40, 859, 684, 1301, 43, 11, 883, 899, 11, 11, 46, 11, 695, 11, 315, 11, 795, 11, 11, 1188, 1070, 20, 1148, 43, 644, 697, 586, 1187, 587, 11, 751, 11, 1190, 698, 11, 11, 589, 145, 590, 11, 11, 11, 1129, 296, 11, 592, -651, 593, 11, 595, 703, 596, 11, 52, 763, 1212, 1213, 43, 146, 147, 1032, 788, 148, 598, 704, 599, -651, 601, 510, 602, 512, 514, 516, 149, 518, 604, 520, 605, 150, 1053, 151, 152, 607, 153, 608, 1057, 20, 683, 22, 23, 154, 1076, 20, 155, 1243, 798, 1125, 11, 11, 11, 11, 1048, 1052, 130, 701, 315, 1234, 20, 11, 11, 738, 739, 156, 1220, 11, 1300, 1305, 1267, 1297, 610, 1312, 611, 43, 7, 1145, 8, 1281, 1077, 43, 157, 1197, 158, 508, 1176, 46, 1083, 1293, 1302, 1308, 1152, 125, 49, 1158, 43, 1291, 1236, 524, 526, 528, 530, 532, 1198, 534, 536, 538, 540, 1259, 1235, 544, 546, 787, 616, 619, 617, 620, 7, 1135, 8, 315, 1286, 692, 273, 9, 1296, 572, 1311, 691, 622, 1298, 623, 1313, 1221, 689, 92, 1034, 315, 1035, 845, 858, 1307, 274, 894, 10, 823, 292, 11, 292, 292, 292, 1176, 292, 1038, 292, 1039, 364, 394, 824, 396, 693, 398, 825, 951, 844, 857, 1185, 58, 893, 274, 404, 744, 406, 1186, 408, 1041, 41, 1042, 1054, 1085, 1055, 1086, 1155, 92, 1156, 11, 826, 92, 809, 827, 59, 849, 830, 870, 884, 900, 911, 831, 832, 1160, 1163, 1161, 1164, 92, 92, 425, 1111, 946, 1111, 714, 1029, 716, 805, 814, 821, 840, 522, 863, 875, 889, 907, 918, 926, 841, 854, 1031, 1218, 890, 908, 791, 927, 792, 1044, 767, 11, 296, 11, 793, 92, 92, 768, 1140, 842, 855, 315, 769, 891, 909, 770, 928, 771, 1134, 292, 772, 296, 625, 778, 965, 92, 92, 168, 1207, 1166, 627, 804, 813, 820, 839, 853, 862, 874, 888, 906, 917, 925, 929, 902, 930, 776, 1118, 1153, 641, 789, 700, 796, 799, 802, 811, 818, 837, 851, 860, 872, 886, 904, 915, 923, 806, 816, 833, 846, 753, 867, 879, 895, 694, 921, 1260, 642, 940, 349, 940, 1294, 1303, 1309, 1037, 756, 19, 20, 1295, 777, 1310, 1101, 931, 790, 145, 797, 800, 803, 812, 819, 838, 852, 861, 873, 887, 905, 916, 924, 0, 7, 431, 8, 760, 0, 0, 273, 147, 17, 0, 148, 941, 20, 941, 43, 17, 0, 743, 19, 703, 46, 149, 126, 130, 0, 48, 945, 704, 151, 152, 0, 153, 0, 761, 762, 0, 133, 0, 154, 33, 34, 35, 0, 133, 0, 958, 42, 20, 43, 0, 0, 0, 775, 145, 46, 0, 149, 128, 130, 0, 156, 150, 141, 0, 0, 47, 48, 0, 934, 935, 0, 0, 92, 92, 146, 147, 155, 157, 148, 158, 20, 132, 20, 43, 22, 23, 836, 133, 0, 46, 0, 130, 128, 1292, 134, 0, 151, 152, 135, 153, 0, 0, 0, 748, 0, 1073, 154, 11, 11, 0, 956, 0, 11, 547, 548, 145, 43, 0, 43, 0, 17, 922, 46, 554, 20, 555, 556, 0, 156, 0, 141, 0, 557, 558, 0, 130, 559, 147, 0, 0, 148, 0, 20, 0, 33, 157, 0, 158, 133, 0, 0, 149, 292, 0, 1171, 0, 794, 0, 151, 152, 43, 153, 315, 315, 0, 0, 46, 0, 154, 0, 0, 292, 683, 0, 141, 0, 17, 0, 43, 19, 0, 11, 11, 0, 46, 0, 14, 128, 0, 1068, 156, 0, 0, 0, 0, 0, 0, 0, 801, 0, 33, 34, 35, 28, 0, 0, 0, 157, 1069, 158, 0, 0, 0, 132, 0, 0, 850, 0, 92, 92, 92, 92, 92, 92, 126, 39, 134, 48, 0, 0, 135, 0, 0, 44, 0, 0, 0, 0, 11, -166, 0, 0, 1010, 1011, 11, 0, 0, 0, 11, 0, 0, 11, 0, 315, 1306, 1133, 1139, 0, 0, 11, 0, 0, 0, 648, 0, 0, 649, 650, 0, 0, 651, 1191, 0, 652, 0, 0, 653, 0, 0, 654, 0, 0, 655, 1024, 1026, 656, 0, 0, 657, 0, 0, 658, 0, 0, 659, 1184, 0, 660, 0, 0, 661, 0, 0, 662, 663, 664, 665, 1132, 1138, 666, 0, 0, 667, 0, 11, 1261, 0, 17, 0, 11, 19, 20, 0, 0, 0, 0, 0, 0, 696, 1130, 1136, 0, 130, 1146, 1150, 0, 0, 0, 0, 0, 0, 33, 34, 35, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 43, 0, 730, 731, 732, 1314, 1228, 1233, 0, 0, 0, 1172, 1182, 733, 1131, 1137, 0, 0, 1147, 1151, 0, 0, 0, 92, 0, 0, 745, 0, 0, 0, 0, 1092, 1093, 1094, 1095, 1096, 1097, 0, 1181, 315, 0, 773, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1173, 1183, 0, 1219, 0, 1227, 1232, 1299, 1304, 1045, 1049, 0, 0, 11, 11, 11, 11, 0, 0, 0, 936, 937, 0, 0, 1172, 1216, 1222, 1225, 1230, 0, 0, 0, 1114, 315, 1120, 1122, 1124, 0, 0, 0, 0, 0, 0, 0, 0, 959, 0, 0, 961, 962, 963, 0, 0, 0, 0, 0, 0, 0, 0, 966, 0, 0, 0, 0, 0, 0, 1173, 1217, 1223, 1226, 1231, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 967, 968, 0, 0, 969, 0, 1108, 0, 1115, 970, 971, 972, 0, 0, 0, 0, 973, 0, 0, 0, 0, 0, 0, 974, 0, 0, 0, 0, 975, 0, 0, 0, 0, 0, 0, 976, 977, 978, 979, 980, 981, 982, 0, 0, 983, 0, 0, 0, 0, 984, 985, 986, 987, 988, 0, 1240, 0, 0, 989, 990, 0, 0, 991, 0, 0, 992, 0, 0, 0, 0, 993, 994, 0, 0, 995, 0, 0, 0, 0, 996, 0, 0, 0, 0, 997, 998, 999, 1000, 1001, 1002, 1003, 0, 0, 0, 0, 1004, 0, 0, 0, 0, 0, 0, 1005, 1006, 1007, 1008, 1009, 0, 0, 0, 0, 0, 0, 1012, 1013, 1014, 1015, 449, 0, 0, 0, 1016, 1017, 1018, 1019, 1020, 450, 0, 0, 0, 452, 0, 453, 145, 454, 0, 455, 0, 0, 0, 456, 0, 0, 0, 0, 458, 0, 0, 0, 0, 0, 0, 462, 0, 146, 147, 464, 0, 148, 0, 20, 466, 0, 0, 0, 468, 0, 0, 0, 0, 471, 130, 472, 0, 0, 473, 151, 152, 0, 153, 480, 0, 0, 0, 482, 0, 154, 484, 0, 485, 0, 0, 0, 0, 488, 0, 43, 0, 490, 0, 0, 0, 46, 0, 494, 0, 0, 495, 156, 0, 141, 498, 0, 0, 178, 0, 0, 499, 0, 0, 145, 501, 0, 0, 1075, 157, 0, 158, 0, 0, 0, 0, 0, 1079, 1214, 1080, 1081, 0, 0, 1082, 0, 0, 147, 17, 0, 148, 0, 20, 1089, 1090, 0, 0, 0, 0, 0, 0, 149, 0, 130, 1098, 0, 0, 32, 151, 152, 0, 153, 0, 34, 35, 0, 133, 414, 154, 37, 0, 0, 419, 1104, 0, 1105, 0, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 128, 47, 0, 156, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 157, 0, 158, 0, 0, 0, 145, 0, 0, 885, 0, 0, 0, 0, 0, 0, 1169, 0, 0, 0, 0, 0, 1170, 0, 0, 0, 0, 146, 147, 17, 0, 148, 19, 20, 0, 1192, 0, 0, 1193, 0, 0, 1194, 0, 1195, 130, 0, 1196, 0, 0, 151, 152, 0, 153, 33, 0, 0, 0, 0, 1199, 1200, 1201, 1202, 1203, 1204, 0, 0, 0, 1205, 0, 43, 0, 432, 0, 0, 1206, 46, 0, 0, 434, 0, 0, 0, 0, 141, 0, 0, 0, 444, 445, 0, 0, 447, 448, 0, 0, 0, 0, 0, 0, 0, 158, 1239, 0, 0, 0, 0, 0, 817, 0, 0, 0, 1241, 0, 0, 0, 0, 1242, 0, 0, 457, 0, 0, 0, 0, 0, 0, 460, 461, 0, 145, 0, 463, 1262, 0, 0, 465, 0, 0, 0, 0, 0, 467, 0, 0, 469, 470, 0, 0, 0, 0, 0, 147, 1282, 0, 148, 1283, 20, 0, 1284, 481, 0, 1285, 0, 483, 0, 149, 0, 130, 486, 487, 0, 0, 151, 152, 0, 153, 0, 491, 492, 493, 133, 0, 1315, 0, 0, 0, 496, 1316, 0, 0, 1317, 0, 43, 0, 0, 0, 500, 0, 46, 0, 0, 128, 504, 0, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 0, 903, 0, 0, 0, 0, 0, 549, 550, 0, 551, 0, 552, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 560, 0, 0, 0, 0, 0, 0, 0, 561, 949, 12, 13, 14, 15, 16, 0, 0, 17, 18, 0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 0, 29, -753, 30, 31, 0, 32, 0, 566, -754, 0, 33, 34, 35, 0, -754, 36, 0, 37, 38, 0, 39, -754, 40, 41, 42, -754, 43, 145, 44, -756, 45, 0, 46, 145, -751, -752, 47, 48, 0, 49, -755, 50, 51, 0, 0, 0, 0, 0, 0, 147, 0, 0, 148, 0, 20, 147, 52, 0, 148, 0, 0, 53, 0, 145, 0, 130, 0, 0, 0, 149, 151, 152, 0, 153, 0, 0, 151, 152, 0, 153, 0, 0, 0, 0, 133, 147, 647, 0, 148, 0, 43, 0, 0, 0, 0, 0, 46, 0, 0, 149, 0, 0, 156, 0, 141, 128, 151, 152, 156, 153, 0, 0, 0, 0, 133, 145, 0, 0, 0, 0, 0, 158, 0, 0, 0, 0, 0, 158, 810, 0, 0, 0, 1058, 0, 668, 128, 0, 147, 156, 0, 148, 0, 0, 0, 0, 0, 1059, 1060, 685, 1061, 0, 149, 1062, 0, 0, 0, 0, 158, 151, 152, 0, 153, 0, 0, 681, 0, 17, 0, 154, 19, 20, 0, 0, 1030, 0, 0, 0, 0, 0, 0, 0, 130, 0, 1063, 0, 0, 0, 128, 0, 0, 156, 34, 35, 0, 133, 0, 0, 37, 0, 0, 734, 0, 736, 0, 0, 0, 43, 0, 0, 158, 0, 0, 46, 0, 126, 0, 0, 48, 0, 0, 141, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 871, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 947, 948, 181, 310, 0, 0, 0, 0, 0, 0, 0, 952, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 682, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 1021, 1022, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 0, 0, 0, 0, 0, 0, 1128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1078, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1084, 0, 0, 0, 1088, 0, 0, 0, 0, 1091, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1099, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 179, 0, 0, 0, 0, 0, 0, 273, 0, 1154, 0, 0, 0, 0, 0, 1159, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 754, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 0, 248, 0, 0, 0, 0, 253, 0, 0, 0, 0, 258, 259, 260, 0, 0, 0, 0, 0, 0, 755, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1263, 0, 0, 1264, 179, 1265, 0, 1266, 180, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 429, 286, 181, 287, 288, 0, 0, 0, 289, 290, 291, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 273, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 477, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 1236, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 180, 0, 181, 0, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 179, 0, 0, 0, 0, 0, 181, 310, 0, 0, 0, 0, 0, 0, 0, 0, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260 }; static const yytype_int16 yycheck[] = { 4, 726, 89, 725, 726, 9, 10, 711, 12, 89, 14, 15, 105, 17, 18, 19, 20, 5, 22, 23, 724, 725, 89, 5, 28, 559, 89, 89, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 5, 722, 52, 706, 89, 86, 719, 89, 721, 5, 89, 724, 711, 8, 8, 89, 89, 725, 726, 393, 8, 75, 5, 17, 12, 724, 725, 96, 85, 56, 96, 23, 5, 8, 7, 84, 104, 64, 106, 8, 90, 99, 100, 101, 102, 103, 420, 105, 114, 1106, 1107, 109, 632, 111, 0, 82, 8, 115, 116, 89, 8, 76, 120, 121, 5, 123, 8, 766, 5, 17, 7, 5, 14, 7, 11, 42, 126, 11, 128, 5, 130, 7, 132, 133, 134, 135, 5, 104, 7, 8, 82, 141, 5, 143, 7, 145, 146, 147, 148, 149, 94, 151, 152, 153, 154, 81, 156, 157, 158, 107, 108, 107, 107, 88, 720, 87, 722, 723, 93, 177, 726, 727, 5, 92, 7, 104, 95, 106, 178, 9, 10, 104, 12, 106, 14, 15, 88, 17, 18, 19, 20, 93, 22, 23, 8, 5, 83, 7, 28, 70, 8, 11, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 14, 105, 52, 100, 101, 102, 103, 22, 104, 20, 106, 5, 109, 7, 111, 711, 31, 11, 115, 116, 31, 104, 104, 106, 121, 721, 123, 42, 724, 725, 719, 31, 721, 722, 683, 724, 725, 726, 8, 104, 21, 951, 42, 104, 104, 31, 107, 33, 34, 104, 31, 104, 67, 106, 88, 5, 67, 7, 73, 93, 88, 42, 73, 94, 95, 93, 97, 67, 5, 5, 7, 7, 8, 73, 11, 105, 126, 104, 128, 8, 130, 67, 132, 133, 134, 135, 67, 68, 17, 18, 105, 141, 73, 143, 105, 145, 146, 147, 148, 149, 81, 151, 152, 153, 154, 105, 156, 157, 158, 758, 759, 105, 104, 8, 106, 85, 104, 87, 106, 105, 90, 16, 17, 18, 105, 96, 104, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 107, 393, 27, 31, 393, 30, 31, 30, 84, 104, 86, 106, 474, 89, 1077, 91, 397, 42, 399, 400, 401, 31, 403, 104, 405, 106, 51, 31, 420, 107, 55, 420, 55, 104, 28, 106, 64, 31, 104, 67, 106, 414, 67, 71, 107, 108, 419, 31, 73, 104, 75, 1142, 104, 78, 77, 78, 81, 67, 42, 432, 103, 434, 1125, 67, 1127, 59, 31, 71, 33, 34, 107, 444, 445, 67, 447, 448, 5, 105, 7, 63, 105, 103, 105, 67, 457, 725, 726, 460, 461, 73, 463, 105, 465, 474, 467, 105, 469, 470, 1142, 1028, 31, 105, 67, 565, 105, 104, 1142, 106, 481, 5, 483, 1142, 108, 486, 487, 104, 4, 106, 491, 492, 493, 105, 503, 496, 104, 54, 106, 500, 104, 24, 106, 504, 97, 105, 1197, 1198, 67, 25, 26, 109, 105, 29, 104, 32, 106, 74, 104, 397, 106, 399, 400, 401, 40, 403, 104, 405, 106, 45, 104, 47, 48, 104, 50, 106, 105, 31, 628, 33, 34, 57, 105, 31, 60, 1236, 105, 85, 549, 550, 551, 552, 1010, 1011, 42, 645, 565, 1211, 31, 560, 561, 43, 44, 79, 37, 566, 1288, 1289, 1259, 1288, 104, 1290, 106, 67, 5, 1106, 7, 1268, 110, 67, 96, 111, 98, 395, 1141, 73, 104, 1288, 1289, 1290, 104, 62, 80, 104, 67, 1286, 14, 409, 410, 411, 412, 413, 107, 415, 416, 417, 418, 107, 112, 421, 422, 105, 104, 104, 106, 106, 5, 105, 7, 628, 107, 634, 11, 54, 1288, 503, 1290, 633, 104, 1288, 106, 1290, 105, 632, 635, 104, 645, 106, 722, 723, 1290, 393, 726, 74, 721, 397, 647, 399, 400, 401, 1207, 403, 104, 405, 106, 407, 127, 721, 129, 634, 131, 721, 752, 722, 723, 1142, 5, 726, 420, 140, 691, 142, 1142, 144, 104, 64, 106, 104, 104, 106, 106, 104, 683, 106, 685, 721, 687, 719, 721, 5, 722, 721, 724, 725, 726, 727, 721, 721, 104, 104, 106, 106, 703, 704, 175, 1092, 744, 1094, 652, 943, 654, 719, 720, 721, 722, 407, 724, 725, 726, 727, 728, 729, 722, 723, 946, 1208, 726, 727, 715, 729, 715, 964, 706, 734, 743, 736, 715, 738, 739, 706, 1103, 722, 723, 752, 706, 726, 727, 706, 729, 706, 1102, 503, 706, 762, 545, 711, 774, 758, 759, 89, 1192, 1123, 548, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 729, 726, 729, 711, 1094, 1111, 563, 715, 644, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 719, 720, 721, 722, 700, 724, 725, 726, 635, 728, 1244, 565, 742, 113, 744, 1288, 1289, 1290, 954, 702, 30, 31, 1288, 711, 1290, 1078, 735, 715, 4, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, -1, 5, 177, 7, 702, -1, -1, 11, 26, 27, -1, 29, 742, 31, 744, 67, 27, -1, 687, 30, 24, 73, 40, 75, 42, -1, 78, 743, 32, 47, 48, -1, 50, -1, 703, 704, -1, 55, -1, 57, 51, 52, 53, -1, 55, -1, 762, 65, 31, 67, -1, -1, -1, 105, 4, 73, -1, 40, 76, 42, -1, 79, 45, 81, -1, -1, 77, 78, -1, 738, 739, -1, -1, 912, 913, 25, 26, 60, 96, 29, 98, 31, 49, 31, 67, 33, 34, 105, 55, -1, 73, -1, 42, 76, 105, 62, -1, 47, 48, 66, 50, -1, -1, -1, 694, -1, 1028, 57, 947, 948, -1, 761, -1, 952, 423, 424, 4, 67, -1, 67, -1, 27, 105, 73, 433, 31, 435, 436, -1, 79, -1, 81, -1, 442, 443, -1, 42, 446, 26, -1, -1, 29, -1, 31, -1, 51, 96, -1, 98, 55, -1, -1, 40, 743, -1, 105, -1, 105, -1, 47, 48, 67, 50, 1010, 1011, -1, -1, 73, -1, 57, -1, -1, 762, 1101, -1, 81, -1, 27, -1, 67, 30, -1, 1021, 1022, -1, 73, -1, 22, 76, -1, 1028, 79, -1, -1, -1, -1, -1, -1, -1, 105, -1, 51, 52, 53, 39, -1, -1, -1, 96, 1028, 98, -1, -1, -1, 49, -1, -1, 105, -1, 1058, 1059, 1060, 1061, 1062, 1063, 75, 61, 62, 78, -1, -1, 66, -1, -1, 69, -1, -1, -1, -1, 1078, 75, -1, -1, 912, 913, 1084, -1, -1, -1, 1088, -1, -1, 1091, -1, 1101, 105, 1102, 1103, -1, -1, 1099, -1, -1, -1, 573, -1, -1, 576, 577, -1, -1, 580, 1142, -1, 583, -1, -1, 586, -1, -1, 589, -1, -1, 592, 934, 935, 595, -1, -1, 598, -1, -1, 601, -1, -1, 604, 1142, -1, 607, -1, -1, 610, -1, -1, 613, 614, 615, 616, 1102, 1103, 619, -1, -1, 622, -1, 1154, 1244, -1, 27, -1, 1159, 30, 31, -1, -1, -1, -1, -1, -1, 638, 1102, 1103, -1, 42, 1106, 1107, -1, -1, -1, -1, -1, -1, 51, 52, 53, -1, 55, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, -1, 67, -1, 669, 670, 671, 1291, 1210, 1211, -1, -1, -1, 1141, 1142, 680, 1102, 1103, -1, -1, 1106, 1107, -1, -1, -1, 1220, -1, -1, 693, -1, -1, -1, -1, 1058, 1059, 1060, 1061, 1062, 1063, -1, 105, 1244, -1, 708, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1141, 1142, -1, 1208, -1, 1210, 1211, 1288, 1289, 1010, 1011, -1, -1, 1263, 1264, 1265, 1266, -1, -1, -1, 740, 741, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, 1093, 1291, 1095, 1096, 1097, -1, -1, -1, -1, -1, -1, -1, -1, 765, -1, -1, 768, 769, 770, -1, -1, -1, -1, -1, -1, -1, -1, 779, -1, -1, -1, -1, -1, -1, 1207, 1208, 1209, 1210, 1211, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 805, 806, -1, -1, 809, -1, 1092, -1, 1094, 814, 815, 816, -1, -1, -1, -1, 821, -1, -1, -1, -1, -1, -1, 828, -1, -1, -1, -1, 833, -1, -1, -1, -1, -1, -1, 840, 841, 842, 843, 844, 845, 846, -1, -1, 849, -1, -1, -1, -1, 854, 855, 856, 857, 858, -1, 1220, -1, -1, 863, 864, -1, -1, 867, -1, -1, 870, -1, -1, -1, -1, 875, 876, -1, -1, 879, -1, -1, -1, -1, 884, -1, -1, -1, -1, 889, 890, 891, 892, 893, 894, 895, -1, -1, -1, -1, 900, -1, -1, -1, -1, -1, -1, 907, 908, 909, 910, 911, -1, -1, -1, -1, -1, -1, 918, 919, 920, 921, 284, -1, -1, -1, 926, 927, 928, 929, 930, 293, -1, -1, -1, 297, -1, 299, 4, 301, -1, 303, -1, -1, -1, 307, -1, -1, -1, -1, 312, -1, -1, -1, -1, -1, -1, 319, -1, 25, 26, 323, -1, 29, -1, 31, 328, -1, -1, -1, 332, -1, -1, -1, -1, 337, 42, 339, -1, -1, 342, 47, 48, -1, 50, 347, -1, -1, -1, 351, -1, 57, 354, -1, 356, -1, -1, -1, -1, 361, -1, 67, -1, 365, -1, -1, -1, 73, -1, 371, -1, -1, 374, 79, -1, 81, 378, -1, -1, 92, -1, -1, 384, -1, -1, 4, 388, -1, -1, 1029, 96, -1, 98, -1, -1, -1, -1, -1, 1038, 105, 1040, 1041, -1, -1, 1044, -1, -1, 26, 27, -1, 29, -1, 31, 1053, 1054, -1, -1, -1, -1, -1, -1, 40, -1, 42, 1064, -1, -1, 46, 47, 48, -1, 50, -1, 52, 53, -1, 55, 150, 57, 58, -1, -1, 155, 1083, -1, 1085, -1, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 76, 77, -1, 79, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, 98, -1, -1, -1, 4, -1, -1, 105, -1, -1, -1, -1, -1, -1, 1133, -1, -1, -1, -1, -1, 1139, -1, -1, -1, -1, 25, 26, 27, -1, 29, 30, 31, -1, 1152, -1, -1, 1155, -1, -1, 1158, -1, 1160, 42, -1, 1163, -1, -1, 47, 48, -1, 50, 51, -1, -1, -1, -1, 1175, 1176, 1177, 1178, 1179, 1180, -1, -1, -1, 1184, -1, 67, -1, 261, -1, -1, 1191, 73, -1, -1, 268, -1, -1, -1, -1, 81, -1, -1, -1, 277, 278, -1, -1, 281, 282, -1, -1, -1, -1, -1, -1, -1, 98, 1218, -1, -1, -1, -1, -1, 105, -1, -1, -1, 1228, -1, -1, -1, -1, 1233, -1, -1, 309, -1, -1, -1, -1, -1, -1, 316, 317, -1, 4, -1, 321, 1249, -1, -1, 325, -1, -1, -1, -1, -1, 331, -1, -1, 334, 335, -1, -1, -1, -1, -1, 26, 1269, -1, 29, 1272, 31, -1, 1275, 349, -1, 1278, -1, 353, -1, 40, -1, 42, 358, 359, -1, -1, 47, 48, -1, 50, -1, 367, 368, 369, 55, -1, 1299, -1, -1, -1, 376, 1304, -1, -1, 1307, -1, 67, -1, -1, -1, 386, -1, 73, -1, -1, 76, 392, -1, 79, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, 426, 427, -1, 429, -1, 431, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 451, -1, -1, -1, -1, -1, -1, -1, 459, 749, 20, 21, 22, 23, 24, -1, -1, 27, 28, -1, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, -1, 41, 42, 43, 44, -1, 46, -1, 489, 49, -1, 51, 52, 53, -1, 55, 56, -1, 58, 59, -1, 61, 62, 63, 64, 65, 66, 67, 4, 69, 70, 71, -1, 73, 4, 75, 76, 77, 78, -1, 80, 81, 82, 83, -1, -1, -1, -1, -1, -1, 26, -1, -1, 29, -1, 31, 26, 97, -1, 29, -1, -1, 102, -1, 4, -1, 42, -1, -1, -1, 40, 47, 48, -1, 50, -1, -1, 47, 48, -1, 50, -1, -1, -1, -1, 55, 26, 568, -1, 29, -1, 67, -1, -1, -1, -1, -1, 73, -1, -1, 40, -1, -1, 79, -1, 81, 76, 47, 48, 79, 50, -1, -1, -1, -1, 55, 4, -1, -1, -1, -1, -1, 98, -1, -1, -1, -1, -1, 98, 105, -1, -1, -1, 21, -1, 105, 76, -1, 26, 79, -1, 29, -1, -1, -1, -1, -1, 35, 36, 630, 38, -1, 40, 41, -1, -1, -1, -1, 98, 47, 48, -1, 50, -1, -1, 105, -1, 27, -1, 57, 30, 31, -1, -1, 944, -1, -1, -1, -1, -1, -1, -1, 42, -1, 72, -1, -1, -1, 76, -1, -1, 79, 52, 53, -1, 55, -1, -1, 58, -1, -1, 682, -1, 684, -1, -1, -1, 67, -1, -1, 98, -1, -1, 73, -1, 75, -1, -1, 78, -1, -1, 81, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, 746, 747, 10, 11, -1, -1, -1, -1, -1, -1, -1, 757, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, 932, 933, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1034, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1048, -1, -1, -1, 1052, -1, -1, -1, -1, 1057, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1076, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, 11, -1, 1112, -1, -1, -1, -1, -1, 1118, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, -1, -1, -1, -1, 91, -1, -1, -1, -1, 96, 97, 98, -1, -1, -1, -1, -1, -1, 105, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1250, -1, -1, 1253, 4, 1255, -1, 1257, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, 9, 10, 11, 12, -1, -1, -1, 16, 17, 18, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, 8, -1, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 4, -1, -1, -1, -1, -1, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 114, 120, 124, 419, 441, 0, 5, 7, 54, 74, 418, 20, 21, 22, 23, 24, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 43, 44, 46, 51, 52, 53, 56, 58, 59, 61, 63, 64, 65, 67, 69, 71, 73, 77, 78, 80, 82, 83, 97, 102, 130, 140, 142, 144, 147, 149, 151, 153, 170, 176, 190, 202, 214, 222, 227, 229, 238, 241, 243, 245, 247, 339, 342, 345, 347, 350, 353, 359, 362, 430, 431, 432, 433, 434, 435, 436, 437, 438, 418, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 420, 402, 402, 75, 194, 76, 192, 42, 183, 49, 55, 62, 66, 204, 209, 224, 356, 440, 81, 335, 70, 157, 4, 25, 26, 29, 40, 45, 47, 48, 50, 57, 60, 79, 96, 98, 249, 254, 257, 261, 264, 267, 273, 277, 279, 283, 299, 304, 305, 307, 308, 310, 439, 407, 420, 419, 4, 8, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 115, 116, 119, 395, 425, 426, 427, 428, 123, 395, 169, 395, 11, 116, 189, 397, 428, 429, 141, 395, 88, 93, 116, 338, 340, 9, 11, 12, 16, 17, 18, 116, 148, 422, 424, 425, 246, 422, 150, 422, 242, 422, 240, 422, 17, 116, 201, 203, 390, 11, 116, 361, 363, 396, 425, 88, 93, 116, 341, 343, 94, 116, 349, 351, 390, 18, 116, 346, 348, 390, 391, 129, 422, 92, 95, 116, 352, 354, 146, 422, 116, 226, 371, 372, 373, 116, 237, 239, 391, 116, 143, 394, 428, 344, 422, 152, 422, 88, 93, 116, 228, 230, 12, 116, 139, 160, 85, 87, 90, 116, 175, 177, 116, 358, 360, 369, 396, 244, 422, 16, 17, 18, 116, 221, 223, 392, 393, 213, 422, 403, 418, 429, 420, 402, 420, 402, 420, 402, 420, 420, 208, 420, 420, 402, 420, 402, 420, 402, 420, 420, 420, 420, 420, 419, 420, 420, 420, 420, 419, 420, 420, 420, 104, 104, 402, 104, 106, 417, 8, 408, 424, 419, 104, 419, 104, 104, 106, 171, 104, 106, 398, 399, 401, 419, 419, 104, 419, 419, 398, 398, 423, 398, 398, 398, 398, 398, 419, 398, 364, 419, 419, 398, 419, 398, 419, 398, 419, 398, 419, 419, 398, 398, 398, 107, 374, 375, 14, 377, 378, 398, 419, 398, 419, 398, 398, 419, 419, 398, 161, 398, 419, 419, 419, 398, 398, 419, 370, 398, 398, 419, 398, 404, 405, 419, 195, 397, 191, 395, 182, 422, 205, 422, 355, 422, 210, 422, 365, 422, 334, 422, 155, 160, 276, 395, 272, 395, 266, 395, 253, 395, 248, 395, 258, 395, 260, 395, 263, 395, 309, 395, 282, 397, 298, 395, 278, 395, 402, 402, 419, 419, 419, 419, 117, 402, 402, 402, 402, 402, 402, 419, 419, 396, 376, 107, 379, 419, 368, 104, 106, 410, 406, 422, 104, 106, 196, 104, 104, 106, 184, 104, 106, 206, 104, 106, 357, 104, 106, 211, 104, 106, 225, 104, 106, 336, 104, 106, 158, 104, 106, 280, 104, 106, 274, 104, 106, 268, 104, 106, 255, 104, 106, 250, 104, 104, 104, 104, 106, 311, 104, 106, 284, 104, 106, 302, 280, 306, 306, 416, 409, 103, 121, 122, 125, 126, 83, 173, 105, 400, 144, 382, 374, 378, 380, 396, 107, 366, 419, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 105, 192, 249, 252, 254, 257, 261, 264, 267, 277, 279, 283, 356, 105, 105, 396, 103, 419, 131, 82, 128, 130, 144, 131, 128, 142, 420, 105, 402, 105, 108, 381, 382, 396, 411, 24, 32, 197, 198, 215, 217, 231, 233, 193, 105, 207, 207, 212, 207, 337, 159, 281, 275, 269, 256, 251, 259, 262, 265, 312, 285, 303, 402, 402, 402, 402, 419, 407, 419, 8, 43, 44, 132, 136, 145, 420, 145, 402, 88, 93, 116, 172, 174, 5, 421, 375, 54, 105, 403, 412, 414, 415, 427, 420, 420, 105, 190, 199, 200, 202, 204, 209, 224, 227, 229, 402, 232, 105, 151, 153, 176, 194, 245, 247, 105, 151, 153, 241, 243, 105, 105, 151, 153, 214, 241, 243, 105, 105, 151, 153, 105, 151, 153, 105, 151, 153, 176, 183, 335, 339, 342, 356, 105, 151, 153, 176, 183, 252, 335, 105, 151, 153, 176, 183, 247, 254, 257, 261, 264, 267, 270, 271, 273, 277, 279, 335, 339, 342, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 345, 356, 105, 151, 153, 176, 192, 249, 252, 299, 310, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 342, 356, 105, 151, 153, 176, 183, 194, 245, 247, 335, 339, 347, 350, 353, 356, 105, 151, 153, 176, 183, 192, 249, 252, 299, 310, 335, 339, 347, 350, 353, 356, 359, 362, 105, 151, 153, 176, 183, 192, 249, 252, 356, 21, 68, 105, 151, 153, 176, 183, 288, 293, 335, 105, 151, 153, 176, 183, 192, 249, 305, 308, 417, 8, 118, 420, 420, 402, 402, 147, 149, 151, 153, 154, 156, 127, 422, 154, 419, 419, 398, 383, 396, 419, 407, 407, 234, 395, 218, 422, 402, 194, 402, 402, 402, 216, 233, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 402, 420, 420, 402, 402, 402, 402, 402, 402, 402, 402, 402, 419, 419, 133, 395, 135, 395, 162, 163, 157, 398, 162, 109, 421, 104, 106, 413, 413, 104, 106, 235, 104, 106, 219, 217, 116, 291, 292, 369, 116, 286, 287, 369, 104, 104, 106, 137, 105, 21, 35, 36, 38, 41, 72, 164, 166, 179, 186, 192, 249, 252, 296, 301, 310, 314, 402, 105, 110, 419, 402, 402, 402, 402, 104, 419, 104, 106, 289, 419, 402, 402, 419, 420, 420, 420, 420, 420, 420, 402, 419, 421, 416, 236, 220, 402, 402, 134, 138, 116, 294, 295, 366, 367, 165, 395, 116, 313, 316, 367, 178, 395, 185, 395, 300, 395, 85, 384, 389, 105, 105, 151, 153, 176, 183, 238, 105, 151, 153, 176, 183, 222, 297, 290, 105, 140, 144, 151, 153, 105, 140, 151, 153, 104, 368, 419, 104, 106, 167, 104, 419, 104, 106, 180, 104, 106, 187, 302, 421, 421, 402, 402, 105, 151, 153, 176, 183, 252, 273, 299, 310, 335, 105, 151, 153, 183, 247, 339, 342, 345, 347, 350, 356, 402, 402, 402, 402, 402, 111, 107, 402, 402, 402, 402, 402, 402, 402, 402, 297, 168, 315, 181, 188, 421, 421, 105, 105, 151, 153, 170, 176, 37, 105, 151, 153, 105, 151, 153, 176, 183, 105, 151, 153, 176, 183, 190, 112, 14, 385, 386, 402, 420, 402, 402, 421, 387, 84, 86, 89, 91, 317, 318, 319, 321, 322, 323, 326, 327, 330, 331, 107, 386, 396, 402, 419, 419, 419, 419, 421, 388, 104, 106, 320, 104, 106, 324, 104, 106, 328, 104, 106, 332, 421, 402, 402, 402, 402, 107, 105, 325, 329, 333, 421, 105, 245, 247, 339, 342, 347, 350, 356, 359, 105, 245, 247, 356, 359, 105, 194, 245, 247, 339, 342, 347, 350, 396, 402, 402, 402 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 113, 114, 114, 114, 115, 116, 117, 118, 117, 119, 120, 121, 122, 122, 122, 122, 123, 124, 125, 126, 126, 126, 127, 128, 129, 130, 131, 131, 131, 132, 133, 134, 134, 134, 134, 134, 135, 136, 137, 137, 138, 138, 138, 138, 139, 140, 141, 142, 143, 144, 145, 145, 145, 145, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 156, 157, 158, 158, 159, 159, 159, 161, 160, 160, 162, 163, 163, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 165, 166, 167, 167, 168, 168, 168, 168, 168, 169, 170, 171, 171, 172, 173, 173, 174, 174, 174, 175, 176, 177, 177, 177, 177, 178, 179, 180, 180, 181, 181, 181, 181, 181, 182, 183, 184, 184, 185, 186, 187, 187, 188, 188, 188, 188, 188, 188, 189, 190, 191, 192, 193, 193, 193, 193, 193, 193, 193, 194, 195, 196, 196, 197, 197, 197, 198, 198, 198, 198, 198, 198, 198, 198, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, 206, 207, 207, 207, 207, 207, 208, 209, 210, 211, 211, 212, 212, 212, 212, 212, 212, 213, 214, 215, 216, 216, 217, 218, 219, 219, 220, 220, 220, 220, 220, 220, 221, 222, 223, 223, 224, 225, 225, 226, 227, 228, 229, 230, 230, 230, 231, 232, 232, 233, 234, 235, 235, 236, 236, 236, 236, 236, 236, 237, 238, 239, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 252, 252, 252, 253, 254, 255, 255, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 257, 258, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 260, 261, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 263, 264, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 266, 267, 268, 268, 269, 269, 269, 269, 269, 269, 269, 269, 269, 269, 270, 270, 271, 271, 271, 271, 271, 271, 271, 272, 273, 274, 274, 275, 275, 275, 275, 275, 275, 275, 276, 277, 278, 279, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 283, 284, 284, 285, 285, 285, 285, 285, 285, 285, 285, 286, 286, 287, 288, 289, 289, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 290, 291, 291, 292, 293, 294, 294, 295, 296, 297, 297, 297, 297, 297, 297, 297, 297, 297, 297, 298, 299, 300, 301, 302, 302, 303, 303, 303, 303, 303, 303, 303, 303, 303, 304, 305, 306, 306, 306, 306, 306, 307, 308, 309, 310, 311, 311, 312, 312, 312, 312, 312, 312, 312, 312, 312, 313, 314, 315, 315, 315, 315, 316, 316, 317, 317, 318, 319, 320, 320, 321, 321, 321, 322, 323, 324, 324, 325, 325, 325, 325, 325, 325, 325, 325, 325, 326, 327, 328, 328, 329, 329, 329, 329, 329, 330, 331, 332, 332, 333, 333, 333, 333, 333, 333, 333, 333, 334, 335, 336, 336, 337, 337, 337, 338, 339, 340, 340, 340, 341, 342, 343, 343, 343, 344, 345, 346, 347, 348, 348, 349, 350, 351, 351, 351, 352, 353, 354, 354, 354, 355, 356, 357, 357, 358, 359, 360, 360, 361, 362, 364, 363, 363, 365, 366, 367, 368, 368, 370, 369, 372, 371, 373, 371, 371, 374, 375, 376, 376, 377, 378, 379, 379, 380, 381, 381, 382, 382, 383, 384, 385, 386, 387, 387, 388, 388, 389, 390, 391, 391, 392, 392, 393, 393, 394, 394, 395, 395, 396, 396, 397, 397, 397, 398, 398, 399, 400, 401, 402, 402, 402, 403, 404, 405, 406, 406, 407, 407, 408, 408, 408, 409, 409, 410, 410, 411, 411, 412, 412, 412, 413, 413, 414, 415, 416, 416, 417, 417, 418, 418, 419, 419, 420, 421, 421, 423, 422, 422, 424, 424, 424, 424, 424, 424, 424, 425, 425, 425, 426, 426, 426, 426, 426, 426, 426, 426, 426, 426, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 438, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 439, 440, 440, 440, 440, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 1, 3, 0, 0, 6, 1, 13, 1, 0, 2, 2, 2, 1, 13, 1, 0, 2, 3, 1, 4, 1, 4, 0, 3, 3, 7, 1, 0, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 2, 1, 4, 1, 7, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 4, 1, 4, 1, 4, 1, 1, 0, 3, 4, 1, 4, 0, 2, 2, 0, 3, 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 4, 1, 0, 4, 2, 2, 1, 1, 4, 2, 2, 2, 1, 1, 4, 1, 4, 0, 3, 2, 2, 2, 1, 4, 1, 3, 1, 4, 1, 4, 0, 2, 3, 2, 2, 2, 1, 4, 1, 7, 0, 3, 2, 2, 2, 2, 2, 4, 1, 1, 4, 1, 1, 1, 0, 2, 2, 2, 3, 3, 2, 3, 3, 2, 0, 1, 4, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 1, 4, 1, 1, 4, 0, 2, 2, 2, 2, 2, 1, 4, 3, 0, 3, 4, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 4, 1, 4, 1, 4, 1, 4, 2, 2, 1, 2, 0, 2, 5, 1, 1, 4, 0, 3, 2, 2, 2, 2, 1, 4, 2, 1, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 0, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 1, 0, 3, 3, 3, 2, 3, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 7, 0, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 1, 4, 1, 4, 1, 4, 0, 3, 3, 3, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 2, 1, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 7, 2, 1, 1, 7, 0, 3, 3, 2, 2, 2, 3, 3, 3, 3, 1, 4, 1, 4, 1, 4, 0, 3, 2, 2, 2, 3, 3, 3, 3, 2, 5, 0, 3, 3, 3, 3, 2, 5, 1, 4, 1, 4, 0, 3, 3, 2, 2, 2, 3, 3, 3, 1, 7, 0, 2, 2, 5, 2, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 3, 1, 4, 0, 2, 3, 2, 2, 2, 2, 2, 2, 1, 3, 1, 4, 0, 2, 3, 2, 2, 1, 3, 1, 4, 0, 3, 2, 2, 2, 2, 2, 2, 1, 4, 1, 4, 0, 2, 2, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 2, 1, 1, 4, 2, 2, 1, 1, 4, 2, 2, 1, 1, 4, 1, 4, 1, 4, 2, 1, 1, 4, 0, 3, 1, 1, 2, 2, 0, 2, 0, 3, 0, 2, 0, 2, 1, 3, 2, 0, 2, 3, 2, 0, 2, 2, 0, 2, 0, 5, 5, 5, 4, 4, 0, 2, 0, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 2, 4, 1, 1, 1, 0, 2, 2, 3, 2, 1, 0, 1, 0, 2, 0, 2, 3, 0, 5, 1, 4, 0, 3, 1, 3, 3, 1, 4, 1, 1, 0, 4, 2, 5, 1, 1, 0, 2, 2, 0, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 4, 4, 4, 4, 4 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, scanner, param, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (0) #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K]) /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Print *YYLOCP on YYO. Private, do not rely on its existence. */ YY_ATTRIBUTE_UNUSED static int yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp) { int res = 0; int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0; if (0 <= yylocp->first_line) { res += YYFPRINTF (yyo, "%d", yylocp->first_line); if (0 <= yylocp->first_column) res += YYFPRINTF (yyo, ".%d", yylocp->first_column); } if (0 <= yylocp->last_line) { if (yylocp->first_line < yylocp->last_line) { res += YYFPRINTF (yyo, "-%d", yylocp->last_line); if (0 <= end_col) res += YYFPRINTF (yyo, ".%d", end_col); } else if (0 <= end_col && yylocp->first_column < end_col) res += YYFPRINTF (yyo, "-%d", end_col); } return res; } # define YY_LOCATION_PRINT(File, Loc) \ yy_location_print_ (File, &(Loc)) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, scanner, param); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*-----------------------------------. | Print this symbol's value on YYO. | `-----------------------------------*/ static void yy_symbol_value_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { FILE *yyoutput = yyo; YYUSE (yyoutput); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyo, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*---------------------------. | Print this symbol on YYO. | `---------------------------*/ static void yy_symbol_print (FILE *yyo, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, void *scanner, struct yang_parameter *param) { YYFPRINTF (yyo, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); YY_LOCATION_PRINT (yyo, *yylocationp); YYFPRINTF (yyo, ": "); yy_symbol_value_print (yyo, yytype, yyvaluep, yylocationp, scanner, param); YYFPRINTF (yyo, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, void *scanner, struct yang_parameter *param) { unsigned long yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , scanner, param); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, yylsp, Rule, scanner, param); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return (YYSIZE_T) (yystpcpy (yyres, yystr) - yyres); } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: /* Avoid compiler warnings. */ YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, void *scanner, struct yang_parameter *param) { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (scanner); YYUSE (param); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 115: /* tmp_string */ { free((((*yyvaluep).p_str)) ? *((*yyvaluep).p_str) : NULL); } break; case 210: /* pattern_arg_str */ { free(((*yyvaluep).str)); } break; case 399: /* semicolom */ { free(((*yyvaluep).str)); } break; case 401: /* curly_bracket_open */ { free(((*yyvaluep).str)); } break; case 405: /* string_opt_part1 */ { free(((*yyvaluep).str)); } break; case 430: /* type_ext_alloc */ { yang_type_free(param->module->ctx, ((*yyvaluep).v)); } break; case 431: /* typedef_ext_alloc */ { yang_type_free(param->module->ctx, &((struct lys_tpdf *)((*yyvaluep).v))->type); } break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++c; YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)]; } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...) { free(*param->value); *param->value = NULL; if (yylloc->first_line != -1) { if (*param->data_node && (*param->data_node) == (*param->actual_node)) { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner)); } else { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); } } }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_1360_2
crossvul-cpp_data_bad_349_7
/* * sc.c: General functions * * Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #ifdef ENABLE_OPENSSL #include <openssl/crypto.h> /* for OPENSSL_cleanse */ #endif #include "internal.h" #ifdef PACKAGE_VERSION static const char *sc_version = PACKAGE_VERSION; #else static const char *sc_version = "(undef)"; #endif const char *sc_get_version(void) { return sc_version; } int sc_hex_to_bin(const char *in, u8 *out, size_t *outlen) { int err = SC_SUCCESS; size_t left, count = 0, in_len; if (in == NULL || out == NULL || outlen == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } left = *outlen; in_len = strlen(in); while (*in != '\0') { int byte = 0, nybbles = 2; while (nybbles-- && *in && *in != ':' && *in != ' ') { char c; byte <<= 4; c = *in++; if ('0' <= c && c <= '9') c -= '0'; else if ('a' <= c && c <= 'f') c = c - 'a' + 10; else if ('A' <= c && c <= 'F') c = c - 'A' + 10; else { err = SC_ERROR_INVALID_ARGUMENTS; goto out; } byte |= c; } /* Detect premature end of string before byte is complete */ if (in_len > 1 && *in == '\0' && nybbles >= 0) { err = SC_ERROR_INVALID_ARGUMENTS; break; } if (*in == ':' || *in == ' ') in++; if (left <= 0) { err = SC_ERROR_BUFFER_TOO_SMALL; break; } out[count++] = (u8) byte; left--; } out: *outlen = count; return err; } int sc_bin_to_hex(const u8 *in, size_t in_len, char *out, size_t out_len, int in_sep) { unsigned int n, sep_len; char *pos, *end, sep; sep = (char)in_sep; sep_len = sep > 0 ? 1 : 0; pos = out; end = out + out_len; for (n = 0; n < in_len; n++) { if (pos + 3 + sep_len >= end) return SC_ERROR_BUFFER_TOO_SMALL; if (n && sep_len) *pos++ = sep; sprintf(pos, "%02x", in[n]); pos += 2; } *pos = '\0'; return SC_SUCCESS; } /* * Right trim all non-printable characters */ size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } u8 *ulong2bebytes(u8 *buf, unsigned long x) { if (buf != NULL) { buf[3] = (u8) (x & 0xff); buf[2] = (u8) ((x >> 8) & 0xff); buf[1] = (u8) ((x >> 16) & 0xff); buf[0] = (u8) ((x >> 24) & 0xff); } return buf; } u8 *ushort2bebytes(u8 *buf, unsigned short x) { if (buf != NULL) { buf[1] = (u8) (x & 0xff); buf[0] = (u8) ((x >> 8) & 0xff); } return buf; } unsigned long bebytes2ulong(const u8 *buf) { if (buf == NULL) return 0UL; return (unsigned long) (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]); } unsigned short bebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short) (buf[0] << 8 | buf[1]); } unsigned short lebytes2ushort(const u8 *buf) { if (buf == NULL) return 0U; return (unsigned short)buf[1] << 8 | (unsigned short)buf[0]; } void sc_init_oid(struct sc_object_id *oid) { int ii; if (!oid) return; for (ii=0; ii<SC_MAX_OBJECT_ID_OCTETS; ii++) oid->value[ii] = -1; } int sc_format_oid(struct sc_object_id *oid, const char *in) { int ii, ret = SC_ERROR_INVALID_ARGUMENTS; const char *p; char *q; if (oid == NULL || in == NULL) return SC_ERROR_INVALID_ARGUMENTS; sc_init_oid(oid); p = in; for (ii=0; ii < SC_MAX_OBJECT_ID_OCTETS; ii++) { oid->value[ii] = strtol(p, &q, 10); if (!*q) break; if (!(q[0] == '.' && isdigit(q[1]))) goto out; p = q + 1; } if (!sc_valid_oid(oid)) goto out; ret = SC_SUCCESS; out: if (ret) sc_init_oid(oid); return ret; } int sc_compare_oid(const struct sc_object_id *oid1, const struct sc_object_id *oid2) { int i; if (oid1 == NULL || oid2 == NULL) { return SC_ERROR_INVALID_ARGUMENTS; } for (i = 0; i < SC_MAX_OBJECT_ID_OCTETS; i++) { if (oid1->value[i] != oid2->value[i]) return 0; if (oid1->value[i] == -1) break; } return 1; } int sc_valid_oid(const struct sc_object_id *oid) { int ii; if (!oid) return 0; if (oid->value[0] == -1 || oid->value[1] == -1) return 0; if (oid->value[0] > 2 || oid->value[1] > 39) return 0; for (ii=0;ii<SC_MAX_OBJECT_ID_OCTETS;ii++) if (oid->value[ii]) break; if (ii==SC_MAX_OBJECT_ID_OCTETS) return 0; return 1; } int sc_detect_card_presence(sc_reader_t *reader) { int r; LOG_FUNC_CALLED(reader->ctx); if (reader->ops->detect_card_presence == NULL) LOG_FUNC_RETURN(reader->ctx, SC_ERROR_NOT_SUPPORTED); r = reader->ops->detect_card_presence(reader); LOG_FUNC_RETURN(reader->ctx, r); } int sc_path_set(sc_path_t *path, int type, const u8 *id, size_t id_len, int idx, int count) { if (path == NULL || id == NULL || id_len == 0 || id_len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(path, 0, sizeof(*path)); memcpy(path->value, id, id_len); path->len = id_len; path->type = type; path->index = idx; path->count = count; return SC_SUCCESS; } void sc_format_path(const char *str, sc_path_t *path) { int type = SC_PATH_TYPE_PATH; if (path) { memset(path, 0, sizeof(*path)); if (*str == 'i' || *str == 'I') { type = SC_PATH_TYPE_FILE_ID; str++; } path->len = sizeof(path->value); if (sc_hex_to_bin(str, path->value, &path->len) >= 0) { path->type = type; } path->count = -1; } } int sc_append_path(sc_path_t *dest, const sc_path_t *src) { return sc_concatenate_path(dest, dest, src); } int sc_append_path_id(sc_path_t *dest, const u8 *id, size_t idlen) { if (dest->len + idlen > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memcpy(dest->value + dest->len, id, idlen); dest->len += idlen; return SC_SUCCESS; } int sc_append_file_id(sc_path_t *dest, unsigned int fid) { u8 id[2] = { fid >> 8, fid & 0xff }; return sc_append_path_id(dest, id, 2); } int sc_concatenate_path(sc_path_t *d, const sc_path_t *p1, const sc_path_t *p2) { sc_path_t tpath; if (d == NULL || p1 == NULL || p2 == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (p1->type == SC_PATH_TYPE_DF_NAME || p2->type == SC_PATH_TYPE_DF_NAME) /* we do not support concatenation of AIDs at the moment */ return SC_ERROR_NOT_SUPPORTED; if (p1->len + p2->len > SC_MAX_PATH_SIZE) return SC_ERROR_INVALID_ARGUMENTS; memset(&tpath, 0, sizeof(sc_path_t)); memcpy(tpath.value, p1->value, p1->len); memcpy(tpath.value + p1->len, p2->value, p2->len); tpath.len = p1->len + p2->len; tpath.type = SC_PATH_TYPE_PATH; /* use 'index' and 'count' entry of the second path object */ tpath.index = p2->index; tpath.count = p2->count; /* the result is currently always as path */ tpath.type = SC_PATH_TYPE_PATH; *d = tpath; return SC_SUCCESS; } const char *sc_print_path(const sc_path_t *path) { static char buffer[SC_MAX_PATH_STRING_SIZE + SC_MAX_AID_STRING_SIZE]; if (sc_path_print(buffer, sizeof(buffer), path) != SC_SUCCESS) buffer[0] = '\0'; return buffer; } int sc_path_print(char *buf, size_t buflen, const sc_path_t *path) { size_t i; if (buf == NULL || path == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (buflen < path->len * 2 + path->aid.len * 2 + 1) return SC_ERROR_BUFFER_TOO_SMALL; buf[0] = '\0'; if (path->aid.len) { for (i = 0; i < path->aid.len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->aid.value[i]); snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); } for (i = 0; i < path->len; i++) snprintf(buf + strlen(buf), buflen - strlen(buf), "%02x", path->value[i]); if (!path->aid.len && path->type == SC_PATH_TYPE_DF_NAME) snprintf(buf + strlen(buf), buflen - strlen(buf), "::"); return SC_SUCCESS; } int sc_compare_path(const sc_path_t *path1, const sc_path_t *path2) { return path1->len == path2->len && !memcmp(path1->value, path2->value, path1->len); } int sc_compare_path_prefix(const sc_path_t *prefix, const sc_path_t *path) { sc_path_t tpath; if (prefix->len > path->len) return 0; tpath = *path; tpath.len = prefix->len; return sc_compare_path(&tpath, prefix); } const sc_path_t *sc_get_mf_path(void) { static const sc_path_t mf_path = { {0x3f, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 2, 0, 0, SC_PATH_TYPE_PATH, {{0},0} }; return &mf_path; } int sc_file_add_acl_entry(sc_file_t *file, unsigned int operation, unsigned int method, unsigned long key_ref) { sc_acl_entry_t *p, *_new; if (file == NULL || operation >= SC_MAX_AC_OPS) { return SC_ERROR_INVALID_ARGUMENTS; } switch (method) { case SC_AC_NEVER: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 1; return SC_SUCCESS; case SC_AC_NONE: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 2; return SC_SUCCESS; case SC_AC_UNKNOWN: sc_file_clear_acl_entries(file, operation); file->acl[operation] = (sc_acl_entry_t *) 3; return SC_SUCCESS; default: /* NONE and UNKNOWN get zapped when a new AC is added. * If the ACL is NEVER, additional entries will be * dropped silently. */ if (file->acl[operation] == (sc_acl_entry_t *) 1) return SC_SUCCESS; if (file->acl[operation] == (sc_acl_entry_t *) 2 || file->acl[operation] == (sc_acl_entry_t *) 3) file->acl[operation] = NULL; } /* If the entry is already present (e.g. due to the mapping) * of the card's AC with OpenSC's), don't add it again. */ for (p = file->acl[operation]; p != NULL; p = p->next) { if ((p->method == method) && (p->key_ref == key_ref)) return SC_SUCCESS; } _new = malloc(sizeof(sc_acl_entry_t)); if (_new == NULL) return SC_ERROR_OUT_OF_MEMORY; _new->method = method; _new->key_ref = key_ref; _new->next = NULL; p = file->acl[operation]; if (p == NULL) { file->acl[operation] = _new; return SC_SUCCESS; } while (p->next != NULL) p = p->next; p->next = _new; return SC_SUCCESS; } const sc_acl_entry_t * sc_file_get_acl_entry(const sc_file_t *file, unsigned int operation) { sc_acl_entry_t *p; static const sc_acl_entry_t e_never = { SC_AC_NEVER, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_none = { SC_AC_NONE, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; static const sc_acl_entry_t e_unknown = { SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE, {{0, 0, 0, {0}}}, NULL }; if (file == NULL || operation >= SC_MAX_AC_OPS) { return NULL; } p = file->acl[operation]; if (p == (sc_acl_entry_t *) 1) return &e_never; if (p == (sc_acl_entry_t *) 2) return &e_none; if (p == (sc_acl_entry_t *) 3) return &e_unknown; return file->acl[operation]; } void sc_file_clear_acl_entries(sc_file_t *file, unsigned int operation) { sc_acl_entry_t *e; if (file == NULL || operation >= SC_MAX_AC_OPS) { return; } e = file->acl[operation]; if (e == (sc_acl_entry_t *) 1 || e == (sc_acl_entry_t *) 2 || e == (sc_acl_entry_t *) 3) { file->acl[operation] = NULL; return; } while (e != NULL) { sc_acl_entry_t *tmp = e->next; free(e); e = tmp; } file->acl[operation] = NULL; } sc_file_t * sc_file_new(void) { sc_file_t *file = (sc_file_t *)calloc(1, sizeof(sc_file_t)); if (file == NULL) return NULL; file->magic = SC_FILE_MAGIC; return file; } void sc_file_free(sc_file_t *file) { unsigned int i; if (file == NULL || !sc_file_valid(file)) return; file->magic = 0; for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_clear_acl_entries(file, i); if (file->sec_attr) free(file->sec_attr); if (file->prop_attr) free(file->prop_attr); if (file->type_attr) free(file->type_attr); if (file->encoded_content) free(file->encoded_content); free(file); } void sc_file_dup(sc_file_t **dest, const sc_file_t *src) { sc_file_t *newf; const sc_acl_entry_t *e; unsigned int op; *dest = NULL; if (!sc_file_valid(src)) return; newf = sc_file_new(); if (newf == NULL) return; *dest = newf; memcpy(&newf->path, &src->path, sizeof(struct sc_path)); memcpy(&newf->name, &src->name, sizeof(src->name)); newf->namelen = src->namelen; newf->type = src->type; newf->shareable = src->shareable; newf->ef_structure = src->ef_structure; newf->size = src->size; newf->id = src->id; newf->status = src->status; for (op = 0; op < SC_MAX_AC_OPS; op++) { newf->acl[op] = NULL; e = sc_file_get_acl_entry(src, op); if (e != NULL) { if (sc_file_add_acl_entry(newf, op, e->method, e->key_ref) < 0) goto err; } } newf->record_length = src->record_length; newf->record_count = src->record_count; if (sc_file_set_sec_attr(newf, src->sec_attr, src->sec_attr_len) < 0) goto err; if (sc_file_set_prop_attr(newf, src->prop_attr, src->prop_attr_len) < 0) goto err; if (sc_file_set_type_attr(newf, src->type_attr, src->type_attr_len) < 0) goto err; if (sc_file_set_content(newf, src->encoded_content, src->encoded_content_len) < 0) goto err; return; err: sc_file_free(newf); *dest = NULL; } int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr, size_t sec_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (sec_attr == NULL) { if (file->sec_attr != NULL) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return 0; } tmp = (u8 *) realloc(file->sec_attr, sec_attr_len); if (!tmp) { if (file->sec_attr) free(file->sec_attr); file->sec_attr = NULL; file->sec_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->sec_attr = tmp; memcpy(file->sec_attr, sec_attr, sec_attr_len); file->sec_attr_len = sec_attr_len; return 0; } int sc_file_set_prop_attr(sc_file_t *file, const u8 *prop_attr, size_t prop_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (prop_attr == NULL) { if (file->prop_attr != NULL) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->prop_attr, prop_attr_len); if (!tmp) { if (file->prop_attr) free(file->prop_attr); file->prop_attr = NULL; file->prop_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->prop_attr = tmp; memcpy(file->prop_attr, prop_attr, prop_attr_len); file->prop_attr_len = prop_attr_len; return SC_SUCCESS; } int sc_file_set_type_attr(sc_file_t *file, const u8 *type_attr, size_t type_attr_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (type_attr == NULL) { if (file->type_attr != NULL) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->type_attr, type_attr_len); if (!tmp) { if (file->type_attr) free(file->type_attr); file->type_attr = NULL; file->type_attr_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->type_attr = tmp; memcpy(file->type_attr, type_attr, type_attr_len); file->type_attr_len = type_attr_len; return SC_SUCCESS; } int sc_file_set_content(sc_file_t *file, const u8 *content, size_t content_len) { u8 *tmp; if (!sc_file_valid(file)) { return SC_ERROR_INVALID_ARGUMENTS; } if (content == NULL) { if (file->encoded_content != NULL) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_SUCCESS; } tmp = (u8 *) realloc(file->encoded_content, content_len); if (!tmp) { if (file->encoded_content) free(file->encoded_content); file->encoded_content = NULL; file->encoded_content_len = 0; return SC_ERROR_OUT_OF_MEMORY; } file->encoded_content = tmp; memcpy(file->encoded_content, content, content_len); file->encoded_content_len = content_len; return SC_SUCCESS; } int sc_file_valid(const sc_file_t *file) { if (file == NULL) return 0; return file->magic == SC_FILE_MAGIC; } int _sc_parse_atr(sc_reader_t *reader) { u8 *p = reader->atr.value; int atr_len = (int) reader->atr.len; int n_hist, x; int tx[4] = {-1, -1, -1, -1}; int i, FI, DI; const int Fi_table[] = { 372, 372, 558, 744, 1116, 1488, 1860, -1, -1, 512, 768, 1024, 1536, 2048, -1, -1 }; const int f_table[] = { 40, 50, 60, 80, 120, 160, 200, -1, -1, 50, 75, 100, 150, 200, -1, -1 }; const int Di_table[] = { -1, 1, 2, 4, 8, 16, 32, -1, 12, 20, -1, -1, -1, -1, -1, -1 }; reader->atr_info.hist_bytes_len = 0; reader->atr_info.hist_bytes = NULL; if (atr_len == 0) { sc_log(reader->ctx, "empty ATR - card not present?\n"); return SC_ERROR_INTERNAL; } if (p[0] != 0x3B && p[0] != 0x3F) { sc_log(reader->ctx, "invalid sync byte in ATR: 0x%02X\n", p[0]); return SC_ERROR_INTERNAL; } n_hist = p[1] & 0x0F; x = p[1] >> 4; p += 2; atr_len -= 2; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } if (tx[0] >= 0) { reader->atr_info.FI = FI = tx[0] >> 4; reader->atr_info.DI = DI = tx[0] & 0x0F; reader->atr_info.Fi = Fi_table[FI]; reader->atr_info.f = f_table[FI]; reader->atr_info.Di = Di_table[DI]; } else { reader->atr_info.Fi = -1; reader->atr_info.f = -1; reader->atr_info.Di = -1; } if (tx[2] >= 0) reader->atr_info.N = tx[3]; else reader->atr_info.N = -1; while (tx[3] > 0 && tx[3] & 0xF0 && atr_len > 0) { x = tx[3] >> 4; for (i = 0; i < 4 && atr_len > 0; i++) { if (x & (1 << i)) { tx[i] = *p; p++; atr_len--; } else tx[i] = -1; } } if (atr_len <= 0) return SC_SUCCESS; if (n_hist > atr_len) n_hist = atr_len; reader->atr_info.hist_bytes_len = n_hist; reader->atr_info.hist_bytes = p; return SC_SUCCESS; } void sc_mem_clear(void *ptr, size_t len) { if (len > 0) { #ifdef ENABLE_OPENSSL OPENSSL_cleanse(ptr, len); #else memset(ptr, 0, len); #endif } } int sc_mem_reverse(unsigned char *buf, size_t len) { unsigned char ch; size_t ii; if (!buf || !len) return SC_ERROR_INVALID_ARGUMENTS; for (ii = 0; ii < len / 2; ii++) { ch = *(buf + ii); *(buf + ii) = *(buf + len - 1 - ii); *(buf + len - 1 - ii) = ch; } return SC_SUCCESS; } static int sc_remote_apdu_allocate(struct sc_remote_data *rdata, struct sc_remote_apdu **new_rapdu) { struct sc_remote_apdu *rapdu = NULL, *rr; if (!rdata) return SC_ERROR_INVALID_ARGUMENTS; rapdu = calloc(1, sizeof(struct sc_remote_apdu)); if (rapdu == NULL) return SC_ERROR_OUT_OF_MEMORY; rapdu->apdu.data = &rapdu->sbuf[0]; rapdu->apdu.resp = &rapdu->rbuf[0]; rapdu->apdu.resplen = sizeof(rapdu->rbuf); if (new_rapdu) *new_rapdu = rapdu; if (rdata->data == NULL) { rdata->data = rapdu; rdata->length = 1; return SC_SUCCESS; } for (rr = rdata->data; rr->next; rr = rr->next) ; rr->next = rapdu; rdata->length++; return SC_SUCCESS; } static void sc_remote_apdu_free (struct sc_remote_data *rdata) { struct sc_remote_apdu *rapdu = NULL; if (!rdata) return; rapdu = rdata->data; while(rapdu) { struct sc_remote_apdu *rr = rapdu->next; free(rapdu); rapdu = rr; } } void sc_remote_data_init(struct sc_remote_data *rdata) { if (!rdata) return; memset(rdata, 0, sizeof(struct sc_remote_data)); rdata->alloc = sc_remote_apdu_allocate; rdata->free = sc_remote_apdu_free; } static unsigned long sc_CRC_tab32[256]; static int sc_CRC_tab32_initialized = 0; unsigned sc_crc32(const unsigned char *value, size_t len) { size_t ii, jj; unsigned long crc; unsigned long index, long_c; if (!sc_CRC_tab32_initialized) { for (ii=0; ii<256; ii++) { crc = (unsigned long) ii; for (jj=0; jj<8; jj++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ 0xEDB88320l; else crc = crc >> 1; } sc_CRC_tab32[ii] = crc; } sc_CRC_tab32_initialized = 1; } crc = 0xffffffffL; for (ii=0; ii<len; ii++) { long_c = 0x000000ffL & (unsigned long) (*(value + ii)); index = crc ^ long_c; crc = (crc >> 8) ^ sc_CRC_tab32[ index & 0xff ]; } crc ^= 0xffffffff; return crc%0xffff; } const u8 *sc_compacttlv_find_tag(const u8 *buf, size_t len, u8 tag, size_t *outlen) { if (buf != NULL) { size_t idx; u8 plain_tag = tag & 0xF0; size_t expected_len = tag & 0x0F; for (idx = 0; idx < len; idx++) { if ((buf[idx] & 0xF0) == plain_tag && idx + expected_len < len && (expected_len == 0 || expected_len == (buf[idx] & 0x0F))) { if (outlen != NULL) *outlen = buf[idx] & 0x0F; return buf + (idx + 1); } idx += (buf[idx] & 0x0F); } } return NULL; } /**************************** mutex functions ************************/ int sc_mutex_create(const sc_context_t *ctx, void **mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->create_mutex != NULL) return ctx->thread_ctx->create_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_lock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->lock_mutex != NULL) return ctx->thread_ctx->lock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_unlock(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->unlock_mutex != NULL) return ctx->thread_ctx->unlock_mutex(mutex); else return SC_SUCCESS; } int sc_mutex_destroy(const sc_context_t *ctx, void *mutex) { if (ctx == NULL) return SC_ERROR_INVALID_ARGUMENTS; if (ctx->thread_ctx != NULL && ctx->thread_ctx->destroy_mutex != NULL) return ctx->thread_ctx->destroy_mutex(mutex); else return SC_SUCCESS; } unsigned long sc_thread_id(const sc_context_t *ctx) { if (ctx == NULL || ctx->thread_ctx == NULL || ctx->thread_ctx->thread_id == NULL) return 0UL; else return ctx->thread_ctx->thread_id(); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_349_7
crossvul-cpp_data_bad_2579_1
/* #ident "@(#)gss_seal.c 1.10 95/08/07 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_complete_auth_token */ #include "mglueP.h" #include <stdio.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> #include <errno.h> OM_uint32 KRB5_CALLCONV gss_complete_auth_token (OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech != NULL) { if (mech->gss_complete_auth_token != NULL) { status = mech->gss_complete_auth_token(minor_status, ctx->internal_ctx_id, input_message_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_COMPLETE; } else status = GSS_S_BAD_MECH; return status; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_1
crossvul-cpp_data_bad_347_3
/* * card-tcos.c: Support for TCOS cards * * Copyright (C) 2011 Peter Koch <pk@opensc-project.org> * Copyright (C) 2002 g10 Code GmbH * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <ctype.h> #include <time.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static struct sc_atr_table tcos_atrs[] = { /* Infineon SLE44 */ { "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66S */ { "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX320P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX322P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Philips P5CT072 */ { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, /* Philips P5CT080 */ { "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_card_operations tcos_ops; static struct sc_card_driver tcos_drv = { "TCOS 3.0", "tcos", &tcos_ops, NULL, 0, NULL }; static const struct sc_card_operations *iso_ops = NULL; typedef struct tcos_data_st { unsigned int pad_flags; unsigned int next_sign; } tcos_data; static int tcos_finish(sc_card_t *card) { free(card->drv_data); return 0; } static int tcos_match_card(sc_card_t *card) { int i; i = _sc_match_atr(card, tcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int tcos_init(sc_card_t *card) { unsigned long flags; tcos_data *data = malloc(sizeof(tcos_data)); if (!data) return SC_ERROR_OUT_OF_MEMORY; card->name = "TCOS"; card->drv_data = (void *)data; card->cla = 0x00; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_PAD_PKCS1; flags |= SC_ALGORITHM_RSA_HASH_NONE; _sc_card_add_rsa_alg(card, 512, flags, 0); _sc_card_add_rsa_alg(card, 768, flags, 0); _sc_card_add_rsa_alg(card, 1024, flags, 0); if (card->type == SC_CARD_TYPE_TCOS_V3) { card->caps |= SC_CARD_CAP_APDU_EXT; _sc_card_add_rsa_alg(card, 1280, flags, 0); _sc_card_add_rsa_alg(card, 1536, flags, 0); _sc_card_add_rsa_alg(card, 1792, flags, 0); _sc_card_add_rsa_alg(card, 2048, flags, 0); } return 0; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static int tcos_construct_fci(const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; size_t n; /* FIXME: possible buffer overflow */ *p++ = 0x6F; /* FCI */ p++; /* File size */ buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x81, buf, 2, p, 16, &p); /* File descriptor */ n = 0; buf[n] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_WORKING_EF: break; case SC_FILE_TYPE_DF: buf[0] |= 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } buf[n++] |= file->ef_structure & 7; if ( (file->ef_structure & 7) > 1) { /* record structured file */ buf[n++] = 0x41; /* indicate 3rd byte */ buf[n++] = file->record_length; } sc_asn1_put_tag(0x82, buf, n, p, 8, &p); /* File identifier */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, 16, &p); /* Directory name */ if (file->type == SC_FILE_TYPE_DF) { if (file->namelen) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, 16, &p); } else { /* TCOS needs one, so we use a faked one */ snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu", (unsigned long) time (NULL)); sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p); } } /* File descriptor extension */ if (file->prop_attr_len && file->prop_attr) { n = file->prop_attr_len; memcpy(buf, file->prop_attr, n); } else { n = 0; buf[n++] = 0x01; /* not invalidated, permanent */ if (file->type == SC_FILE_TYPE_WORKING_EF) buf[n++] = 0x00; /* generic data file */ } sc_asn1_put_tag(0x85, buf, n, p, 16, &p); /* Security attributes */ if (file->sec_attr_len && file->sec_attr) { memcpy(buf, file->sec_attr, file->sec_attr_len); n = file->sec_attr_len; } else { /* no attributes given - fall back to default one */ memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */ memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */ memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */ memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/ n = 24; } sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p); /* fixup length of FCI */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int tcos_create_file(sc_card_t *card, sc_file_t *file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; len = SC_MAX_APDU_BUFFER_SIZE; r = tcos_construct_fci(file, sbuf, &len); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "tcos_construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.cla |= 0x80; /* this is an proprietary extension */ apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static unsigned int map_operations (int commandbyte ) { unsigned int op = (unsigned int)-1; switch ( (commandbyte & 0xfe) ) { case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break; case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break; case 0xe0: /* create */ op = SC_AC_OP_CREATE; break; case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break; case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break; case 0x82: /* external auth */ op = SC_AC_OP_READ; break; case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break; case 0x88: /* internal auth */ op = SC_AC_OP_READ; break; case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break; case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break; case 0xb0: /* read binary */ op = SC_AC_OP_READ; break; case 0xb2: /* read record */ op = SC_AC_OP_READ; break; case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break; case 0xa4: /* select */ op = SC_AC_OP_SELECT; break; case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break; case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break; case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break; case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break; case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break; case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break; } return op; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static void parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { unsigned int op; /* list directory is not covered by ACLs - so always add an entry */ sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES, SC_AC_NONE, SC_AC_KEY_REF_NONE); /* FIXME: check for what LOCK is used */ sc_file_add_acl_entry (file, SC_AC_OP_LOCK, SC_AC_NONE, SC_AC_KEY_REF_NONE); for (; len >= 6; len -= 6, buf += 6) { /* FIXME: temporary hacks */ if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) /* select */ sc_file_add_acl_entry (file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) /*read*/ sc_file_add_acl_entry (file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) /*upd*/ sc_file_add_acl_entry (file, SC_AC_OP_UPDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */ sc_file_add_acl_entry (file, SC_AC_OP_WRITE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_CREATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else { /* the first byte tells use the command or the command group. We have to mask bit 0 because this one distinguish between AND/OR combination of PINs*/ op = map_operations (buf[0]); if (op == (unsigned int)-1) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown security command byte %02x\n", buf[0]); continue; } if (!buf[1]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_CHV, buf[1]); if (!buf[2] && !buf[3]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_TERM, (buf[2]<<8)|buf[3]); } } } static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1; int r, count = 0; assert(card != NULL); ctx = card->ctx; for (p1=1; p1<=2; p1++) { sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n", apdu.resplen / 2, p1 == 1 ? "DF" : "EF"); memcpy(buf, apdu.resp, apdu.resplen); buf += apdu.resplen; buflen -= apdu.resplen; count += apdu.resplen; } return count; } static int tcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r; u8 sbuf[2]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File type has to be SC_PATH_TYPE_FILE_ID\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } sbuf[0] = path->value[0]; sbuf[1] = path->value[1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_context_t *ctx; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p; int r, default_key, tcos3; tcos_data *data; assert(card != NULL && env != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)){ SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "No Key-Reference in SecEnvironment\n"); else sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n", env->key_ref[0], env->key_ref_len); /* Key-Reference 0x80 ?? */ default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n", tcos3, !!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); data->pad_flags = env->algorithm_flags; data->next_sign = default_key; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8); p = sbuf; *p++=0x80; *p++=0x01; *p++=tcos3 ? 0x0A : 0x10; if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { *p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } apdu.data = sbuf; apdu.lc = apdu.datalen = (p - sbuf); r=sc_transmit_apdu(card, &apdu); if (r) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Detected Signature-Only key\n"); if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS; } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_restore_security_env(sc_card_t *card, int se_num) { return 0; } static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { size_t i, dlen=datalen; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int tcos3, r; assert(card != NULL && data != NULL && out != NULL); tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); if (datalen > 255) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); if(((tcos_data *)card->drv_data)->next_sign){ if(datalen>48){ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Data to be signed is too long (TCOS supports max. 48 bytes)\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A); memcpy(sbuf, data, datalen); dlen=datalen; } else { int keylen= tcos3 ? 256 : 128; sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = tcos3 ? 256 : 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) { int keylen=128; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); } if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len = apdu.resplen>outlen ? outlen : apdu.resplen; memcpy(out, apdu.resp, len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL); sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "TCOS3:%d PKCS1:%d\n",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){ offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset; offset=(offset<len-1) ? offset+1 : 0; } memcpy(out, apdu.resp+offset, len-offset); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the NullPIN method will be activated, otherwise the permanent operation will be done on the active file. */ static int tcos_setperm(sc_card_t *card, int enable_nullpin) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 0; apdu.datalen = 0; apdu.data = NULL; r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; if (!serial) return SC_ERROR_INVALID_ARGUMENTS; /* see if we have cached serial number */ if (card->serialnr.len) { memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } card->serialnr.len = sizeof card->serialnr.value; r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0); if (r < 0) { card->serialnr.len = 0; return r; } /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_TCOS_SETPERM: return tcos_setperm(card, !!ptr); case SC_CARDCTL_GET_SERIALNR: return tcos_get_serialnr(card, (sc_serial_number_t *)ptr); } return SC_ERROR_NOT_SUPPORTED; } struct sc_card_driver * sc_get_tcos_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; tcos_ops = *iso_drv->ops; tcos_ops.match_card = tcos_match_card; tcos_ops.init = tcos_init; tcos_ops.finish = tcos_finish; tcos_ops.create_file = tcos_create_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.select_file = tcos_select_file; tcos_ops.list_files = tcos_list_files; tcos_ops.delete_file = tcos_delete_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.compute_signature = tcos_compute_signature; tcos_ops.decipher = tcos_decipher; tcos_ops.restore_security_env = tcos_restore_security_env; tcos_ops.card_ctl = tcos_card_ctl; return &tcos_drv; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_347_3
crossvul-cpp_data_bad_2579_3
/* #pragma ident "@(#)g_delete_sec_context.c 1.11 97/11/09 SMI" */ /* * Copyright 1996 by Sun Microsystems, Inc. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appears in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation, and that the name of Sun Microsystems not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * glue routine for gss_delete_sec_context */ #include "mglueP.h" #include <stdio.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif static OM_uint32 val_del_sec_ctx_args( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { /* Initialize outputs. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } /* Validate arguments. */ if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); if (context_handle == NULL || *context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_WRITE | GSS_S_NO_CONTEXT); return (GSS_S_COMPLETE); } OM_uint32 KRB5_CALLCONV gss_delete_sec_context (minor_status, context_handle, output_token) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_buffer_t output_token; { OM_uint32 status; gss_union_ctx_id_t ctx; status = val_del_sec_ctx_args(minor_status, context_handle, output_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) *context_handle; if (GSSINT_CHK_LOOP(ctx)) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); status = gssint_delete_internal_sec_context(minor_status, ctx->mech_type, &ctx->internal_ctx_id, output_token); if (status) return status; /* now free up the space for the union context structure */ free(ctx->mech_type->elements); free(ctx->mech_type); free(*context_handle); *context_handle = GSS_C_NO_CONTEXT; return (GSS_S_COMPLETE); }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_2579_3
crossvul-cpp_data_bad_3906_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Drawing Orders * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "window.h" #include <winpr/wtypes.h> #include <winpr/crt.h> #include <freerdp/api.h> #include <freerdp/log.h> #include <freerdp/graphics.h> #include <freerdp/codec/bitmap.h> #include <freerdp/gdi/gdi.h> #include "orders.h" #include "../cache/glyph.h" #include "../cache/bitmap.h" #include "../cache/brush.h" #include "../cache/cache.h" #define TAG FREERDP_TAG("core.orders") const BYTE PRIMARY_DRAWING_ORDER_FIELD_BYTES[] = { DSTBLT_ORDER_FIELD_BYTES, PATBLT_ORDER_FIELD_BYTES, SCRBLT_ORDER_FIELD_BYTES, 0, 0, 0, 0, DRAW_NINE_GRID_ORDER_FIELD_BYTES, MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES, LINE_TO_ORDER_FIELD_BYTES, OPAQUE_RECT_ORDER_FIELD_BYTES, SAVE_BITMAP_ORDER_FIELD_BYTES, 0, MEMBLT_ORDER_FIELD_BYTES, MEM3BLT_ORDER_FIELD_BYTES, MULTI_DSTBLT_ORDER_FIELD_BYTES, MULTI_PATBLT_ORDER_FIELD_BYTES, MULTI_SCRBLT_ORDER_FIELD_BYTES, MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES, FAST_INDEX_ORDER_FIELD_BYTES, POLYGON_SC_ORDER_FIELD_BYTES, POLYGON_CB_ORDER_FIELD_BYTES, POLYLINE_ORDER_FIELD_BYTES, 0, FAST_GLYPH_ORDER_FIELD_BYTES, ELLIPSE_SC_ORDER_FIELD_BYTES, ELLIPSE_CB_ORDER_FIELD_BYTES, GLYPH_INDEX_ORDER_FIELD_BYTES }; #define PRIMARY_DRAWING_ORDER_COUNT (ARRAYSIZE(PRIMARY_DRAWING_ORDER_FIELD_BYTES)) static const BYTE CBR2_BPP[] = { 0, 0, 0, 8, 16, 24, 32 }; static const BYTE BPP_CBR2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; static const BYTE CBR23_BPP[] = { 0, 0, 0, 8, 16, 24, 32 }; static const BYTE BPP_CBR23[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; static const BYTE BMF_BPP[] = { 0, 1, 0, 8, 16, 24, 32, 0 }; static const BYTE BPP_BMF[] = { 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName, BOOL condition) { if (!condition) { if (settings->AllowUnanouncedOrdersFromServer) { WLog_Print(log, WLOG_WARN, "%s - SERVER BUG: The support for this feature was not announced!", orderName); return TRUE; } else { WLog_Print(log, WLOG_ERROR, "%s - SERVER BUG: The support for this feature was not announced! Use " "/relax-order-checks to ignore", orderName); return FALSE; } } return TRUE; } static BOOL check_alt_order_supported(wLog* log, rdpSettings* settings, BYTE orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: case ORDER_TYPE_SWITCH_SURFACE: condition = settings->OffscreenSupportLevel != 0; break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: condition = settings->DrawNineGridEnabled; break; case ORDER_TYPE_FRAME_MARKER: condition = settings->FrameMarkerCommandEnabled; break; case ORDER_TYPE_GDIPLUS_FIRST: case ORDER_TYPE_GDIPLUS_NEXT: case ORDER_TYPE_GDIPLUS_END: case ORDER_TYPE_GDIPLUS_CACHE_FIRST: case ORDER_TYPE_GDIPLUS_CACHE_NEXT: case ORDER_TYPE_GDIPLUS_CACHE_END: condition = settings->DrawGdiPlusCacheEnabled; break; case ORDER_TYPE_WINDOW: condition = settings->RemoteWndSupportLevel != WINDOW_LEVEL_NOT_SUPPORTED; break; case ORDER_TYPE_STREAM_BITMAP_FIRST: case ORDER_TYPE_STREAM_BITMAP_NEXT: case ORDER_TYPE_COMPDESK_FIRST: condition = TRUE; break; default: WLog_Print(log, WLOG_WARN, "%s - Alternate Secondary Drawing Order UNKNOWN", orderName); condition = FALSE; break; } return check_order_activated(log, settings, orderName, condition); } static BOOL check_secondary_order_supported(wLog* log, rdpSettings* settings, BYTE orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: condition = settings->BitmapCacheEnabled; break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: condition = settings->BitmapCacheEnabled; break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: condition = settings->BitmapCacheV3Enabled; break; case ORDER_TYPE_CACHE_COLOR_TABLE: condition = (settings->OrderSupport[NEG_MEMBLT_INDEX] || settings->OrderSupport[NEG_MEM3BLT_INDEX]); break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: case GLYPH_SUPPORT_ENCODE: condition = TRUE; break; case GLYPH_SUPPORT_NONE: default: condition = FALSE; break; } } break; case ORDER_TYPE_CACHE_BRUSH: condition = TRUE; break; default: WLog_Print(log, WLOG_WARN, "SECONDARY ORDER %s not supported", orderName); break; } return check_order_activated(log, settings, orderName, condition); } static BOOL check_primary_order_supported(wLog* log, rdpSettings* settings, UINT32 orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_DSTBLT: condition = settings->OrderSupport[NEG_DSTBLT_INDEX]; break; case ORDER_TYPE_SCRBLT: condition = settings->OrderSupport[NEG_SCRBLT_INDEX]; break; case ORDER_TYPE_DRAW_NINE_GRID: condition = settings->OrderSupport[NEG_DRAWNINEGRID_INDEX]; break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: condition = settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX]; break; case ORDER_TYPE_LINE_TO: condition = settings->OrderSupport[NEG_LINETO_INDEX]; break; /* [MS-RDPEGDI] 2.2.2.2.1.1.2.5 OpaqueRect (OPAQUERECT_ORDER) * suggests that PatBlt and OpaqueRect imply each other. */ case ORDER_TYPE_PATBLT: case ORDER_TYPE_OPAQUE_RECT: condition = settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] || settings->OrderSupport[NEG_PATBLT_INDEX]; break; case ORDER_TYPE_SAVE_BITMAP: condition = settings->OrderSupport[NEG_SAVEBITMAP_INDEX]; break; case ORDER_TYPE_MEMBLT: condition = settings->OrderSupport[NEG_MEMBLT_INDEX]; break; case ORDER_TYPE_MEM3BLT: condition = settings->OrderSupport[NEG_MEM3BLT_INDEX]; break; case ORDER_TYPE_MULTI_DSTBLT: condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX]; break; case ORDER_TYPE_MULTI_PATBLT: condition = settings->OrderSupport[NEG_MULTIPATBLT_INDEX]; break; case ORDER_TYPE_MULTI_SCRBLT: condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX]; break; case ORDER_TYPE_MULTI_OPAQUE_RECT: condition = settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX]; break; case ORDER_TYPE_FAST_INDEX: condition = settings->OrderSupport[NEG_FAST_INDEX_INDEX]; break; case ORDER_TYPE_POLYGON_SC: condition = settings->OrderSupport[NEG_POLYGON_SC_INDEX]; break; case ORDER_TYPE_POLYGON_CB: condition = settings->OrderSupport[NEG_POLYGON_CB_INDEX]; break; case ORDER_TYPE_POLYLINE: condition = settings->OrderSupport[NEG_POLYLINE_INDEX]; break; case ORDER_TYPE_FAST_GLYPH: condition = settings->OrderSupport[NEG_FAST_GLYPH_INDEX]; break; case ORDER_TYPE_ELLIPSE_SC: condition = settings->OrderSupport[NEG_ELLIPSE_SC_INDEX]; break; case ORDER_TYPE_ELLIPSE_CB: condition = settings->OrderSupport[NEG_ELLIPSE_CB_INDEX]; break; case ORDER_TYPE_GLYPH_INDEX: condition = settings->OrderSupport[NEG_GLYPH_INDEX_INDEX]; break; default: WLog_Print(log, WLOG_WARN, "%s Primary Drawing Order not supported", orderName); break; } return check_order_activated(log, settings, orderName, condition); } static const char* primary_order_string(UINT32 orderType) { const char* orders[] = { "[0x%02" PRIx8 "] DstBlt", "[0x%02" PRIx8 "] PatBlt", "[0x%02" PRIx8 "] ScrBlt", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] DrawNineGrid", "[0x%02" PRIx8 "] MultiDrawNineGrid", "[0x%02" PRIx8 "] LineTo", "[0x%02" PRIx8 "] OpaqueRect", "[0x%02" PRIx8 "] SaveBitmap", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] MemBlt", "[0x%02" PRIx8 "] Mem3Blt", "[0x%02" PRIx8 "] MultiDstBlt", "[0x%02" PRIx8 "] MultiPatBlt", "[0x%02" PRIx8 "] MultiScrBlt", "[0x%02" PRIx8 "] MultiOpaqueRect", "[0x%02" PRIx8 "] FastIndex", "[0x%02" PRIx8 "] PolygonSC", "[0x%02" PRIx8 "] PolygonCB", "[0x%02" PRIx8 "] Polyline", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] FastGlyph", "[0x%02" PRIx8 "] EllipseSC", "[0x%02" PRIx8 "] EllipseCB", "[0x%02" PRIx8 "] GlyphIndex" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static const char* secondary_order_string(UINT32 orderType) { const char* orders[] = { "[0x%02" PRIx8 "] Cache Bitmap", "[0x%02" PRIx8 "] Cache Color Table", "[0x%02" PRIx8 "] Cache Bitmap (Compressed)", "[0x%02" PRIx8 "] Cache Glyph", "[0x%02" PRIx8 "] Cache Bitmap V2", "[0x%02" PRIx8 "] Cache Bitmap V2 (Compressed)", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] Cache Brush", "[0x%02" PRIx8 "] Cache Bitmap V3" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static const char* altsec_order_string(BYTE orderType) { const char* orders[] = { "[0x%02" PRIx8 "] Switch Surface", "[0x%02" PRIx8 "] Create Offscreen Bitmap", "[0x%02" PRIx8 "] Stream Bitmap First", "[0x%02" PRIx8 "] Stream Bitmap Next", "[0x%02" PRIx8 "] Create NineGrid Bitmap", "[0x%02" PRIx8 "] Draw GDI+ First", "[0x%02" PRIx8 "] Draw GDI+ Next", "[0x%02" PRIx8 "] Draw GDI+ End", "[0x%02" PRIx8 "] Draw GDI+ Cache First", "[0x%02" PRIx8 "] Draw GDI+ Cache Next", "[0x%02" PRIx8 "] Draw GDI+ Cache End", "[0x%02" PRIx8 "] Windowing", "[0x%02" PRIx8 "] Desktop Composition", "[0x%02" PRIx8 "] Frame Marker" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static INLINE BOOL update_read_coord(wStream* s, INT32* coord, BOOL delta) { INT8 lsi8; INT16 lsi16; if (delta) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_INT8(s, lsi8); *coord += lsi8; } else { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_INT16(s, lsi16); *coord = lsi16; } return TRUE; } static INLINE BOOL update_write_coord(wStream* s, INT32 coord) { Stream_Write_UINT16(s, coord); return TRUE; } static INLINE BOOL update_read_color(wStream* s, UINT32* color) { BYTE byte; if (Stream_GetRemainingLength(s) < 3) return FALSE; *color = 0; Stream_Read_UINT8(s, byte); *color = (UINT32)byte; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 8) & 0xFF00; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 16) & 0xFF0000; return TRUE; } static INLINE BOOL update_write_color(wStream* s, UINT32 color) { BYTE byte; byte = (color & 0xFF); Stream_Write_UINT8(s, byte); byte = ((color >> 8) & 0xFF); Stream_Write_UINT8(s, byte); byte = ((color >> 16) & 0xFF); Stream_Write_UINT8(s, byte); return TRUE; } static INLINE BOOL update_read_colorref(wStream* s, UINT32* color) { BYTE byte; if (Stream_GetRemainingLength(s) < 4) return FALSE; *color = 0; Stream_Read_UINT8(s, byte); *color = byte; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 8); Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 16); Stream_Seek_UINT8(s); return TRUE; } static INLINE BOOL update_read_color_quad(wStream* s, UINT32* color) { return update_read_colorref(s, color); } static INLINE void update_write_color_quad(wStream* s, UINT32 color) { BYTE byte; byte = (color >> 16) & 0xFF; Stream_Write_UINT8(s, byte); byte = (color >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = color & 0xFF; Stream_Write_UINT8(s, byte); } static INLINE BOOL update_read_2byte_unsigned(wStream* s, UINT32* value) { BYTE byte; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) return FALSE; *value = (byte & 0x7F) << 8; Stream_Read_UINT8(s, byte); *value |= byte; } else { *value = (byte & 0x7F); } return TRUE; } static INLINE BOOL update_write_2byte_unsigned(wStream* s, UINT32 value) { BYTE byte; if (value > 0x7FFF) return FALSE; if (value >= 0x7F) { byte = ((value & 0x7F00) >> 8); Stream_Write_UINT8(s, byte | 0x80); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else { byte = (value & 0x7F); Stream_Write_UINT8(s, byte); } return TRUE; } static INLINE BOOL update_read_2byte_signed(wStream* s, INT32* value) { BYTE byte; BOOL negative; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); negative = (byte & 0x40) ? TRUE : FALSE; *value = (byte & 0x3F); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } if (negative) *value *= -1; return TRUE; } static INLINE BOOL update_write_2byte_signed(wStream* s, INT32 value) { BYTE byte; BOOL negative = FALSE; if (value < 0) { negative = TRUE; value *= -1; } if (value > 0x3FFF) return FALSE; if (value >= 0x3F) { byte = ((value & 0x3F00) >> 8); if (negative) byte |= 0x40; Stream_Write_UINT8(s, byte | 0x80); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else { byte = (value & 0x3F); if (negative) byte |= 0x40; Stream_Write_UINT8(s, byte); } return TRUE; } static INLINE BOOL update_read_4byte_unsigned(wStream* s, UINT32* value) { BYTE byte; BYTE count; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); count = (byte & 0xC0) >> 6; if (Stream_GetRemainingLength(s) < count) return FALSE; switch (count) { case 0: *value = (byte & 0x3F); break; case 1: *value = (byte & 0x3F) << 8; Stream_Read_UINT8(s, byte); *value |= byte; break; case 2: *value = (byte & 0x3F) << 16; Stream_Read_UINT8(s, byte); *value |= (byte << 8); Stream_Read_UINT8(s, byte); *value |= byte; break; case 3: *value = (byte & 0x3F) << 24; Stream_Read_UINT8(s, byte); *value |= (byte << 16); Stream_Read_UINT8(s, byte); *value |= (byte << 8); Stream_Read_UINT8(s, byte); *value |= byte; break; default: break; } return TRUE; } static INLINE BOOL update_write_4byte_unsigned(wStream* s, UINT32 value) { BYTE byte; if (value <= 0x3F) { Stream_Write_UINT8(s, value); } else if (value <= 0x3FFF) { byte = (value >> 8) & 0x3F; Stream_Write_UINT8(s, byte | 0x40); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else if (value <= 0x3FFFFF) { byte = (value >> 16) & 0x3F; Stream_Write_UINT8(s, byte | 0x80); byte = (value >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else if (value <= 0x3FFFFFFF) { byte = (value >> 24) & 0x3F; Stream_Write_UINT8(s, byte | 0xC0); byte = (value >> 16) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else return FALSE; return TRUE; } static INLINE BOOL update_read_delta(wStream* s, INT32* value) { BYTE byte; if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, byte); if (byte & 0x40) *value = (byte | ~0x3F); else *value = (byte & 0x3F); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } return TRUE; } #if 0 static INLINE void update_read_glyph_delta(wStream* s, UINT16* value) { BYTE byte; Stream_Read_UINT8(s, byte); if (byte == 0x80) Stream_Read_UINT16(s, *value); else *value = (byte & 0x3F); } static INLINE void update_seek_glyph_delta(wStream* s) { BYTE byte; Stream_Read_UINT8(s, byte); if (byte & 0x80) Stream_Seek_UINT8(s); } #endif static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) { if (fieldFlags & ORDER_FIELD_01) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->x); } if (fieldFlags & ORDER_FIELD_02) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->y); } if (fieldFlags & ORDER_FIELD_03) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->style); } if (fieldFlags & ORDER_FIELD_04) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->hatch); } if (brush->style & CACHED_BRUSH) { brush->index = brush->hatch; brush->bpp = BMF_BPP[brush->style & 0x07]; if (brush->bpp == 0) brush->bpp = 1; } if (fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 7) return FALSE; brush->data = (BYTE*)brush->p8x8; Stream_Read_UINT8(s, brush->data[7]); Stream_Read_UINT8(s, brush->data[6]); Stream_Read_UINT8(s, brush->data[5]); Stream_Read_UINT8(s, brush->data[4]); Stream_Read_UINT8(s, brush->data[3]); Stream_Read_UINT8(s, brush->data[2]); Stream_Read_UINT8(s, brush->data[1]); brush->data[0] = brush->hatch; } return TRUE; } static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) { if (fieldFlags & ORDER_FIELD_01) { Stream_Write_UINT8(s, brush->x); } if (fieldFlags & ORDER_FIELD_02) { Stream_Write_UINT8(s, brush->y); } if (fieldFlags & ORDER_FIELD_03) { Stream_Write_UINT8(s, brush->style); } if (brush->style & CACHED_BRUSH) { brush->hatch = brush->index; brush->bpp = BMF_BPP[brush->style & 0x07]; if (brush->bpp == 0) brush->bpp = 1; } if (fieldFlags & ORDER_FIELD_04) { Stream_Write_UINT8(s, brush->hatch); } if (fieldFlags & ORDER_FIELD_05) { brush->data = (BYTE*)brush->p8x8; Stream_Write_UINT8(s, brush->data[7]); Stream_Write_UINT8(s, brush->data[6]); Stream_Write_UINT8(s, brush->data[5]); Stream_Write_UINT8(s, brush->data[4]); Stream_Write_UINT8(s, brush->data[3]); Stream_Write_UINT8(s, brush->data[2]); Stream_Write_UINT8(s, brush->data[1]); brush->data[0] = brush->hatch; } return TRUE; } static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32 number) { UINT32 i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; if (number > 45) number = 45; zeroBitsSize = ((number + 1) / 2); if (Stream_GetRemainingLength(s) < zeroBitsSize) return FALSE; Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(rectangles, sizeof(DELTA_RECT) * number); for (i = 0; i < number; i++) { if (i % 2 == 0) flags = zeroBits[i / 2]; if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left)) return FALSE; if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top)) return FALSE; if (~flags & 0x20) { if (!update_read_delta(s, &rectangles[i].width)) return FALSE; } else if (i > 0) rectangles[i].width = rectangles[i - 1].width; else rectangles[i].width = 0; if (~flags & 0x10) { if (!update_read_delta(s, &rectangles[i].height)) return FALSE; } else if (i > 0) rectangles[i].height = rectangles[i - 1].height; else rectangles[i].height = 0; if (i > 0) { rectangles[i].left += rectangles[i - 1].left; rectangles[i].top += rectangles[i - 1].top; } flags <<= 4; } return TRUE; } static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int number, INT16 x, INT16 y) { int i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; zeroBitsSize = ((number + 3) / 4); if (Stream_GetRemainingLength(s) < zeroBitsSize) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %" PRIu32 "", zeroBitsSize); return FALSE; } Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(points, sizeof(DELTA_POINT) * number); for (i = 0; i < number; i++) { if (i % 4 == 0) flags = zeroBits[i / 4]; if ((~flags & 0x80) && !update_read_delta(s, &points[i].x)) { WLog_ERR(TAG, "update_read_delta(x) failed"); return FALSE; } if ((~flags & 0x40) && !update_read_delta(s, &points[i].y)) { WLog_ERR(TAG, "update_read_delta(y) failed"); return FALSE; } flags <<= 2; } return TRUE; } #define ORDER_FIELD_BYTE(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 1) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT8(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_2BYTE(NO, TARGET1, TARGET2) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 2) \ { \ WLog_ERR(TAG, "error reading %s or %s", #TARGET1, #TARGET2); \ return FALSE; \ } \ Stream_Read_UINT8(s, TARGET1); \ Stream_Read_UINT8(s, TARGET2); \ } \ } while (0) #define ORDER_FIELD_UINT16(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 2) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT16(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_UINT32(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 4) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT32(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_COORD(NO, TARGET) \ do \ { \ if ((orderInfo->fieldFlags & (1 << (NO - 1))) && \ !update_read_coord(s, &TARGET, orderInfo->deltaCoordinates)) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ } while (0) static INLINE BOOL ORDER_FIELD_COLOR(const ORDER_INFO* orderInfo, wStream* s, UINT32 NO, UINT32* TARGET) { if (!TARGET || !orderInfo) return FALSE; if ((orderInfo->fieldFlags & (1 << (NO - 1))) && !update_read_color(s, TARGET)) return FALSE; return TRUE; } static INLINE BOOL FIELD_SKIP_BUFFER16(wStream* s, UINT32 TARGET_LEN) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, TARGET_LEN); if (!Stream_SafeSeek(s, TARGET_LEN)) { WLog_ERR(TAG, "error skipping %" PRIu32 " bytes", TARGET_LEN); return FALSE; } return TRUE; } /* Primary Drawing Orders */ static BOOL update_read_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, DSTBLT_ORDER* dstblt) { ORDER_FIELD_COORD(1, dstblt->nLeftRect); ORDER_FIELD_COORD(2, dstblt->nTopRect); ORDER_FIELD_COORD(3, dstblt->nWidth); ORDER_FIELD_COORD(4, dstblt->nHeight); ORDER_FIELD_BYTE(5, dstblt->bRop); return TRUE; } int update_approximate_dstblt_order(ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt) { return 32; } BOOL update_write_dstblt_order(wStream* s, ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_dstblt_order(orderInfo, dstblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, dstblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, dstblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, dstblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, dstblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, dstblt->bRop); return TRUE; } static BOOL update_read_patblt_order(wStream* s, const ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { ORDER_FIELD_COORD(1, patblt->nLeftRect); ORDER_FIELD_COORD(2, patblt->nTopRect); ORDER_FIELD_COORD(3, patblt->nWidth); ORDER_FIELD_COORD(4, patblt->nHeight); ORDER_FIELD_BYTE(5, patblt->bRop); ORDER_FIELD_COLOR(orderInfo, s, 6, &patblt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 7, &patblt->foreColor); return update_read_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7); } int update_approximate_patblt_order(ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { return 32; } BOOL update_write_patblt_order(wStream* s, ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_patblt_order(orderInfo, patblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, patblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, patblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, patblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, patblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, patblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, patblt->backColor); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_color(s, patblt->foreColor); orderInfo->fieldFlags |= ORDER_FIELD_08; orderInfo->fieldFlags |= ORDER_FIELD_09; orderInfo->fieldFlags |= ORDER_FIELD_10; orderInfo->fieldFlags |= ORDER_FIELD_11; orderInfo->fieldFlags |= ORDER_FIELD_12; update_write_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7); return TRUE; } static BOOL update_read_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, SCRBLT_ORDER* scrblt) { ORDER_FIELD_COORD(1, scrblt->nLeftRect); ORDER_FIELD_COORD(2, scrblt->nTopRect); ORDER_FIELD_COORD(3, scrblt->nWidth); ORDER_FIELD_COORD(4, scrblt->nHeight); ORDER_FIELD_BYTE(5, scrblt->bRop); ORDER_FIELD_COORD(6, scrblt->nXSrc); ORDER_FIELD_COORD(7, scrblt->nYSrc); return TRUE; } int update_approximate_scrblt_order(ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt) { return 32; } BOOL update_write_scrblt_order(wStream* s, ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_scrblt_order(orderInfo, scrblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, scrblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, scrblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, scrblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, scrblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, scrblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_coord(s, scrblt->nXSrc); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_coord(s, scrblt->nYSrc); return TRUE; } static BOOL update_read_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, OPAQUE_RECT_ORDER* opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, opaque_rect->nTopRect); ORDER_FIELD_COORD(3, opaque_rect->nWidth); ORDER_FIELD_COORD(4, opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } return TRUE; } int update_approximate_opaque_rect_order(ORDER_INFO* orderInfo, const OPAQUE_RECT_ORDER* opaque_rect) { return 32; } BOOL update_write_opaque_rect_order(wStream* s, ORDER_INFO* orderInfo, const OPAQUE_RECT_ORDER* opaque_rect) { BYTE byte; int inf = update_approximate_opaque_rect_order(orderInfo, opaque_rect); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; // TODO: Color format conversion orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, opaque_rect->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, opaque_rect->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, opaque_rect->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, opaque_rect->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; byte = opaque_rect->color & 0x000000FF; Stream_Write_UINT8(s, byte); orderInfo->fieldFlags |= ORDER_FIELD_06; byte = (opaque_rect->color & 0x0000FF00) >> 8; Stream_Write_UINT8(s, byte); orderInfo->fieldFlags |= ORDER_FIELD_07; byte = (opaque_rect->color & 0x00FF0000) >> 16; Stream_Write_UINT8(s, byte); return TRUE; } static BOOL update_read_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo, DRAW_NINE_GRID_ORDER* draw_nine_grid) { ORDER_FIELD_COORD(1, draw_nine_grid->srcLeft); ORDER_FIELD_COORD(2, draw_nine_grid->srcTop); ORDER_FIELD_COORD(3, draw_nine_grid->srcRight); ORDER_FIELD_COORD(4, draw_nine_grid->srcBottom); ORDER_FIELD_UINT16(5, draw_nine_grid->bitmapId); return TRUE; } static BOOL update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DSTBLT_ORDER* multi_dstblt) { ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect); ORDER_FIELD_COORD(2, multi_dstblt->nTopRect); ORDER_FIELD_COORD(3, multi_dstblt->nWidth); ORDER_FIELD_COORD(4, multi_dstblt->nHeight); ORDER_FIELD_BYTE(5, multi_dstblt->bRop); ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_dstblt->cbData); return update_read_delta_rects(s, multi_dstblt->rectangles, multi_dstblt->numRectangles); } return TRUE; } static BOOL update_read_multi_patblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_PATBLT_ORDER* multi_patblt) { ORDER_FIELD_COORD(1, multi_patblt->nLeftRect); ORDER_FIELD_COORD(2, multi_patblt->nTopRect); ORDER_FIELD_COORD(3, multi_patblt->nWidth); ORDER_FIELD_COORD(4, multi_patblt->nHeight); ORDER_FIELD_BYTE(5, multi_patblt->bRop); ORDER_FIELD_COLOR(orderInfo, s, 6, &multi_patblt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 7, &multi_patblt->foreColor); if (!update_read_brush(s, &multi_patblt->brush, orderInfo->fieldFlags >> 7)) return FALSE; ORDER_FIELD_BYTE(13, multi_patblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_14) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_patblt->cbData); if (!update_read_delta_rects(s, multi_patblt->rectangles, multi_patblt->numRectangles)) return FALSE; } return TRUE; } static BOOL update_read_multi_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_SCRBLT_ORDER* multi_scrblt) { ORDER_FIELD_COORD(1, multi_scrblt->nLeftRect); ORDER_FIELD_COORD(2, multi_scrblt->nTopRect); ORDER_FIELD_COORD(3, multi_scrblt->nWidth); ORDER_FIELD_COORD(4, multi_scrblt->nHeight); ORDER_FIELD_BYTE(5, multi_scrblt->bRop); ORDER_FIELD_COORD(6, multi_scrblt->nXSrc); ORDER_FIELD_COORD(7, multi_scrblt->nYSrc); ORDER_FIELD_BYTE(8, multi_scrblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_scrblt->cbData); return update_read_delta_rects(s, multi_scrblt->rectangles, multi_scrblt->numRectangles); } return TRUE; } static BOOL update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect); ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth); ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_opaque_rect->cbData); return update_read_delta_rects(s, multi_opaque_rect->rectangles, multi_opaque_rect->numRectangles); } return TRUE; } static BOOL update_read_multi_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DRAW_NINE_GRID_ORDER* multi_draw_nine_grid) { ORDER_FIELD_COORD(1, multi_draw_nine_grid->srcLeft); ORDER_FIELD_COORD(2, multi_draw_nine_grid->srcTop); ORDER_FIELD_COORD(3, multi_draw_nine_grid->srcRight); ORDER_FIELD_COORD(4, multi_draw_nine_grid->srcBottom); ORDER_FIELD_UINT16(5, multi_draw_nine_grid->bitmapId); ORDER_FIELD_BYTE(6, multi_draw_nine_grid->nDeltaEntries); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_draw_nine_grid->cbData); return update_read_delta_rects(s, multi_draw_nine_grid->rectangles, multi_draw_nine_grid->nDeltaEntries); } return TRUE; } static BOOL update_read_line_to_order(wStream* s, const ORDER_INFO* orderInfo, LINE_TO_ORDER* line_to) { ORDER_FIELD_UINT16(1, line_to->backMode); ORDER_FIELD_COORD(2, line_to->nXStart); ORDER_FIELD_COORD(3, line_to->nYStart); ORDER_FIELD_COORD(4, line_to->nXEnd); ORDER_FIELD_COORD(5, line_to->nYEnd); ORDER_FIELD_COLOR(orderInfo, s, 6, &line_to->backColor); ORDER_FIELD_BYTE(7, line_to->bRop2); ORDER_FIELD_BYTE(8, line_to->penStyle); ORDER_FIELD_BYTE(9, line_to->penWidth); ORDER_FIELD_COLOR(orderInfo, s, 10, &line_to->penColor); return TRUE; } int update_approximate_line_to_order(ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to) { return 32; } BOOL update_write_line_to_order(wStream* s, ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_line_to_order(orderInfo, line_to))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT16(s, line_to->backMode); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, line_to->nXStart); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, line_to->nYStart); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, line_to->nXEnd); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_coord(s, line_to->nYEnd); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, line_to->backColor); orderInfo->fieldFlags |= ORDER_FIELD_07; Stream_Write_UINT8(s, line_to->bRop2); orderInfo->fieldFlags |= ORDER_FIELD_08; Stream_Write_UINT8(s, line_to->penStyle); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT8(s, line_to->penWidth); orderInfo->fieldFlags |= ORDER_FIELD_10; update_write_color(s, line_to->penColor); return TRUE; } static BOOL update_read_polyline_order(wStream* s, const ORDER_INFO* orderInfo, POLYLINE_ORDER* polyline) { UINT16 word; UINT32 new_num = polyline->numDeltaEntries; ORDER_FIELD_COORD(1, polyline->xStart); ORDER_FIELD_COORD(2, polyline->yStart); ORDER_FIELD_BYTE(3, polyline->bRop2); ORDER_FIELD_UINT16(4, word); ORDER_FIELD_COLOR(orderInfo, s, 5, &polyline->penColor); ORDER_FIELD_BYTE(6, new_num); if (orderInfo->fieldFlags & ORDER_FIELD_07) { DELTA_POINT* new_points; if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, polyline->cbData); new_points = (DELTA_POINT*)realloc(polyline->points, sizeof(DELTA_POINT) * new_num); if (!new_points) { WLog_ERR(TAG, "realloc(%" PRIu32 ") failed", new_num); return FALSE; } polyline->points = new_points; polyline->numDeltaEntries = new_num; return update_read_delta_points(s, polyline->points, polyline->numDeltaEntries, polyline->xStart, polyline->yStart); } return TRUE; } static BOOL update_read_memblt_order(wStream* s, const ORDER_INFO* orderInfo, MEMBLT_ORDER* memblt) { if (!s || !orderInfo || !memblt) return FALSE; ORDER_FIELD_UINT16(1, memblt->cacheId); ORDER_FIELD_COORD(2, memblt->nLeftRect); ORDER_FIELD_COORD(3, memblt->nTopRect); ORDER_FIELD_COORD(4, memblt->nWidth); ORDER_FIELD_COORD(5, memblt->nHeight); ORDER_FIELD_BYTE(6, memblt->bRop); ORDER_FIELD_COORD(7, memblt->nXSrc); ORDER_FIELD_COORD(8, memblt->nYSrc); ORDER_FIELD_UINT16(9, memblt->cacheIndex); memblt->colorIndex = (memblt->cacheId >> 8); memblt->cacheId = (memblt->cacheId & 0xFF); memblt->bitmap = NULL; return TRUE; } int update_approximate_memblt_order(ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt) { return 64; } BOOL update_write_memblt_order(wStream* s, ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt) { UINT16 cacheId; if (!Stream_EnsureRemainingCapacity(s, update_approximate_memblt_order(orderInfo, memblt))) return FALSE; cacheId = (memblt->cacheId & 0xFF) | ((memblt->colorIndex & 0xFF) << 8); orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT16(s, cacheId); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, memblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, memblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, memblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_coord(s, memblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_06; Stream_Write_UINT8(s, memblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_coord(s, memblt->nXSrc); orderInfo->fieldFlags |= ORDER_FIELD_08; update_write_coord(s, memblt->nYSrc); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT16(s, memblt->cacheIndex); return TRUE; } static BOOL update_read_mem3blt_order(wStream* s, const ORDER_INFO* orderInfo, MEM3BLT_ORDER* mem3blt) { ORDER_FIELD_UINT16(1, mem3blt->cacheId); ORDER_FIELD_COORD(2, mem3blt->nLeftRect); ORDER_FIELD_COORD(3, mem3blt->nTopRect); ORDER_FIELD_COORD(4, mem3blt->nWidth); ORDER_FIELD_COORD(5, mem3blt->nHeight); ORDER_FIELD_BYTE(6, mem3blt->bRop); ORDER_FIELD_COORD(7, mem3blt->nXSrc); ORDER_FIELD_COORD(8, mem3blt->nYSrc); ORDER_FIELD_COLOR(orderInfo, s, 9, &mem3blt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 10, &mem3blt->foreColor); if (!update_read_brush(s, &mem3blt->brush, orderInfo->fieldFlags >> 10)) return FALSE; ORDER_FIELD_UINT16(16, mem3blt->cacheIndex); mem3blt->colorIndex = (mem3blt->cacheId >> 8); mem3blt->cacheId = (mem3blt->cacheId & 0xFF); mem3blt->bitmap = NULL; return TRUE; } static BOOL update_read_save_bitmap_order(wStream* s, const ORDER_INFO* orderInfo, SAVE_BITMAP_ORDER* save_bitmap) { ORDER_FIELD_UINT32(1, save_bitmap->savedBitmapPosition); ORDER_FIELD_COORD(2, save_bitmap->nLeftRect); ORDER_FIELD_COORD(3, save_bitmap->nTopRect); ORDER_FIELD_COORD(4, save_bitmap->nRightRect); ORDER_FIELD_COORD(5, save_bitmap->nBottomRect); ORDER_FIELD_BYTE(6, save_bitmap->operation); return TRUE; } static BOOL update_read_glyph_index_order(wStream* s, const ORDER_INFO* orderInfo, GLYPH_INDEX_ORDER* glyph_index) { ORDER_FIELD_BYTE(1, glyph_index->cacheId); ORDER_FIELD_BYTE(2, glyph_index->flAccel); ORDER_FIELD_BYTE(3, glyph_index->ulCharInc); ORDER_FIELD_BYTE(4, glyph_index->fOpRedundant); ORDER_FIELD_COLOR(orderInfo, s, 5, &glyph_index->backColor); ORDER_FIELD_COLOR(orderInfo, s, 6, &glyph_index->foreColor); ORDER_FIELD_UINT16(7, glyph_index->bkLeft); ORDER_FIELD_UINT16(8, glyph_index->bkTop); ORDER_FIELD_UINT16(9, glyph_index->bkRight); ORDER_FIELD_UINT16(10, glyph_index->bkBottom); ORDER_FIELD_UINT16(11, glyph_index->opLeft); ORDER_FIELD_UINT16(12, glyph_index->opTop); ORDER_FIELD_UINT16(13, glyph_index->opRight); ORDER_FIELD_UINT16(14, glyph_index->opBottom); if (!update_read_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14)) return FALSE; ORDER_FIELD_UINT16(20, glyph_index->x); ORDER_FIELD_UINT16(21, glyph_index->y); if (orderInfo->fieldFlags & ORDER_FIELD_22) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, glyph_index->cbData); if (Stream_GetRemainingLength(s) < glyph_index->cbData) return FALSE; CopyMemory(glyph_index->data, Stream_Pointer(s), glyph_index->cbData); Stream_Seek(s, glyph_index->cbData); } return TRUE; } int update_approximate_glyph_index_order(ORDER_INFO* orderInfo, const GLYPH_INDEX_ORDER* glyph_index) { return 64; } BOOL update_write_glyph_index_order(wStream* s, ORDER_INFO* orderInfo, GLYPH_INDEX_ORDER* glyph_index) { int inf = update_approximate_glyph_index_order(orderInfo, glyph_index); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT8(s, glyph_index->cacheId); orderInfo->fieldFlags |= ORDER_FIELD_02; Stream_Write_UINT8(s, glyph_index->flAccel); orderInfo->fieldFlags |= ORDER_FIELD_03; Stream_Write_UINT8(s, glyph_index->ulCharInc); orderInfo->fieldFlags |= ORDER_FIELD_04; Stream_Write_UINT8(s, glyph_index->fOpRedundant); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_color(s, glyph_index->backColor); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, glyph_index->foreColor); orderInfo->fieldFlags |= ORDER_FIELD_07; Stream_Write_UINT16(s, glyph_index->bkLeft); orderInfo->fieldFlags |= ORDER_FIELD_08; Stream_Write_UINT16(s, glyph_index->bkTop); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT16(s, glyph_index->bkRight); orderInfo->fieldFlags |= ORDER_FIELD_10; Stream_Write_UINT16(s, glyph_index->bkBottom); orderInfo->fieldFlags |= ORDER_FIELD_11; Stream_Write_UINT16(s, glyph_index->opLeft); orderInfo->fieldFlags |= ORDER_FIELD_12; Stream_Write_UINT16(s, glyph_index->opTop); orderInfo->fieldFlags |= ORDER_FIELD_13; Stream_Write_UINT16(s, glyph_index->opRight); orderInfo->fieldFlags |= ORDER_FIELD_14; Stream_Write_UINT16(s, glyph_index->opBottom); orderInfo->fieldFlags |= ORDER_FIELD_15; orderInfo->fieldFlags |= ORDER_FIELD_16; orderInfo->fieldFlags |= ORDER_FIELD_17; orderInfo->fieldFlags |= ORDER_FIELD_18; orderInfo->fieldFlags |= ORDER_FIELD_19; update_write_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14); orderInfo->fieldFlags |= ORDER_FIELD_20; Stream_Write_UINT16(s, glyph_index->x); orderInfo->fieldFlags |= ORDER_FIELD_21; Stream_Write_UINT16(s, glyph_index->y); orderInfo->fieldFlags |= ORDER_FIELD_22; Stream_Write_UINT8(s, glyph_index->cbData); Stream_Write(s, glyph_index->data, glyph_index->cbData); return TRUE; } static BOOL update_read_fast_index_order(wStream* s, const ORDER_INFO* orderInfo, FAST_INDEX_ORDER* fast_index) { ORDER_FIELD_BYTE(1, fast_index->cacheId); ORDER_FIELD_2BYTE(2, fast_index->ulCharInc, fast_index->flAccel); ORDER_FIELD_COLOR(orderInfo, s, 3, &fast_index->backColor); ORDER_FIELD_COLOR(orderInfo, s, 4, &fast_index->foreColor); ORDER_FIELD_COORD(5, fast_index->bkLeft); ORDER_FIELD_COORD(6, fast_index->bkTop); ORDER_FIELD_COORD(7, fast_index->bkRight); ORDER_FIELD_COORD(8, fast_index->bkBottom); ORDER_FIELD_COORD(9, fast_index->opLeft); ORDER_FIELD_COORD(10, fast_index->opTop); ORDER_FIELD_COORD(11, fast_index->opRight); ORDER_FIELD_COORD(12, fast_index->opBottom); ORDER_FIELD_COORD(13, fast_index->x); ORDER_FIELD_COORD(14, fast_index->y); if (orderInfo->fieldFlags & ORDER_FIELD_15) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, fast_index->cbData); if (Stream_GetRemainingLength(s) < fast_index->cbData) return FALSE; CopyMemory(fast_index->data, Stream_Pointer(s), fast_index->cbData); Stream_Seek(s, fast_index->cbData); } return TRUE; } static BOOL update_read_fast_glyph_order(wStream* s, const ORDER_INFO* orderInfo, FAST_GLYPH_ORDER* fastGlyph) { BYTE* phold; GLYPH_DATA_V2* glyph = &fastGlyph->glyphData; ORDER_FIELD_BYTE(1, fastGlyph->cacheId); ORDER_FIELD_2BYTE(2, fastGlyph->ulCharInc, fastGlyph->flAccel); ORDER_FIELD_COLOR(orderInfo, s, 3, &fastGlyph->backColor); ORDER_FIELD_COLOR(orderInfo, s, 4, &fastGlyph->foreColor); ORDER_FIELD_COORD(5, fastGlyph->bkLeft); ORDER_FIELD_COORD(6, fastGlyph->bkTop); ORDER_FIELD_COORD(7, fastGlyph->bkRight); ORDER_FIELD_COORD(8, fastGlyph->bkBottom); ORDER_FIELD_COORD(9, fastGlyph->opLeft); ORDER_FIELD_COORD(10, fastGlyph->opTop); ORDER_FIELD_COORD(11, fastGlyph->opRight); ORDER_FIELD_COORD(12, fastGlyph->opBottom); ORDER_FIELD_COORD(13, fastGlyph->x); ORDER_FIELD_COORD(14, fastGlyph->y); if (orderInfo->fieldFlags & ORDER_FIELD_15) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, fastGlyph->cbData); if (Stream_GetRemainingLength(s) < fastGlyph->cbData) return FALSE; CopyMemory(fastGlyph->data, Stream_Pointer(s), fastGlyph->cbData); phold = Stream_Pointer(s); if (!Stream_SafeSeek(s, 1)) return FALSE; if (fastGlyph->cbData > 1) { UINT32 new_cb; /* parse optional glyph data */ glyph->cacheIndex = fastGlyph->data[0]; if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) || !update_read_2byte_unsigned(s, &glyph->cx) || !update_read_2byte_unsigned(s, &glyph->cy)) return FALSE; glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; new_cb = ((glyph->cx + 7) / 8) * glyph->cy; new_cb += ((new_cb % 4) > 0) ? 4 - (new_cb % 4) : 0; if (Stream_GetRemainingLength(s) < new_cb) return FALSE; if (new_cb) { BYTE* new_aj; new_aj = (BYTE*)realloc(glyph->aj, new_cb); if (!new_aj) return FALSE; glyph->aj = new_aj; glyph->cb = new_cb; Stream_Read(s, glyph->aj, glyph->cb); } } Stream_SetPointer(s, phold + fastGlyph->cbData); } return TRUE; } static BOOL update_read_polygon_sc_order(wStream* s, const ORDER_INFO* orderInfo, POLYGON_SC_ORDER* polygon_sc) { UINT32 num = polygon_sc->numPoints; ORDER_FIELD_COORD(1, polygon_sc->xStart); ORDER_FIELD_COORD(2, polygon_sc->yStart); ORDER_FIELD_BYTE(3, polygon_sc->bRop2); ORDER_FIELD_BYTE(4, polygon_sc->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_sc->brushColor); ORDER_FIELD_BYTE(6, num); if (orderInfo->fieldFlags & ORDER_FIELD_07) { DELTA_POINT* newpoints; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, polygon_sc->cbData); newpoints = (DELTA_POINT*)realloc(polygon_sc->points, sizeof(DELTA_POINT) * num); if (!newpoints) return FALSE; polygon_sc->points = newpoints; polygon_sc->numPoints = num; return update_read_delta_points(s, polygon_sc->points, polygon_sc->numPoints, polygon_sc->xStart, polygon_sc->yStart); } return TRUE; } static BOOL update_read_polygon_cb_order(wStream* s, const ORDER_INFO* orderInfo, POLYGON_CB_ORDER* polygon_cb) { UINT32 num = polygon_cb->numPoints; ORDER_FIELD_COORD(1, polygon_cb->xStart); ORDER_FIELD_COORD(2, polygon_cb->yStart); ORDER_FIELD_BYTE(3, polygon_cb->bRop2); ORDER_FIELD_BYTE(4, polygon_cb->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_cb->backColor); ORDER_FIELD_COLOR(orderInfo, s, 6, &polygon_cb->foreColor); if (!update_read_brush(s, &polygon_cb->brush, orderInfo->fieldFlags >> 6)) return FALSE; ORDER_FIELD_BYTE(12, num); if (orderInfo->fieldFlags & ORDER_FIELD_13) { DELTA_POINT* newpoints; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, polygon_cb->cbData); newpoints = (DELTA_POINT*)realloc(polygon_cb->points, sizeof(DELTA_POINT) * num); if (!newpoints) return FALSE; polygon_cb->points = newpoints; polygon_cb->numPoints = num; if (!update_read_delta_points(s, polygon_cb->points, polygon_cb->numPoints, polygon_cb->xStart, polygon_cb->yStart)) return FALSE; } polygon_cb->backMode = (polygon_cb->bRop2 & 0x80) ? BACKMODE_TRANSPARENT : BACKMODE_OPAQUE; polygon_cb->bRop2 = (polygon_cb->bRop2 & 0x1F); return TRUE; } static BOOL update_read_ellipse_sc_order(wStream* s, const ORDER_INFO* orderInfo, ELLIPSE_SC_ORDER* ellipse_sc) { ORDER_FIELD_COORD(1, ellipse_sc->leftRect); ORDER_FIELD_COORD(2, ellipse_sc->topRect); ORDER_FIELD_COORD(3, ellipse_sc->rightRect); ORDER_FIELD_COORD(4, ellipse_sc->bottomRect); ORDER_FIELD_BYTE(5, ellipse_sc->bRop2); ORDER_FIELD_BYTE(6, ellipse_sc->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_sc->color); return TRUE; } static BOOL update_read_ellipse_cb_order(wStream* s, const ORDER_INFO* orderInfo, ELLIPSE_CB_ORDER* ellipse_cb) { ORDER_FIELD_COORD(1, ellipse_cb->leftRect); ORDER_FIELD_COORD(2, ellipse_cb->topRect); ORDER_FIELD_COORD(3, ellipse_cb->rightRect); ORDER_FIELD_COORD(4, ellipse_cb->bottomRect); ORDER_FIELD_BYTE(5, ellipse_cb->bRop2); ORDER_FIELD_BYTE(6, ellipse_cb->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_cb->backColor); ORDER_FIELD_COLOR(orderInfo, s, 8, &ellipse_cb->foreColor); return update_read_brush(s, &ellipse_cb->brush, orderInfo->fieldFlags >> 8); } /* Secondary Drawing Orders */ static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { CACHE_BITMAP_ORDER* cache_bitmap; if (!update || !s) return NULL; cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER)); if (!cache_bitmap) goto fail; if (Stream_GetRemainingLength(s) < 9) goto fail; Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "", cache_bitmap->bitmapBpp); goto fail; } Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ if (compressed) { if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0) { BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ cache_bitmap->bitmapLength -= 8; } } if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength) goto fail; cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength); if (!cache_bitmap->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength); cache_bitmap->compressed = compressed; return cache_bitmap; fail: free_cache_bitmap_order(update->context, cache_bitmap); return NULL; } int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, UINT16* flags) { return 64 + cache_bitmap->bitmapLength; } BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, UINT16* flags) { UINT32 bitmapLength = cache_bitmap->bitmapLength; int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; *flags = NO_BITMAP_COMPRESSION_HDR; if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) bitmapLength += 8; Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */ Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ if (compressed) { if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) { BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ bitmapLength -= 8; } Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); } else { Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); } return TRUE; } static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { BYTE bitsPerPixelId; CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; if (!update || !s) return NULL; cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); if (!cache_bitmap_v2) goto fail; cache_bitmap_v2->cacheId = flags & 0x0003; cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; bitsPerPixelId = (flags & 0x0078) >> 3; cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId]; if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ goto fail; cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth; } else { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ goto fail; } if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */ goto fail; if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } } if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength) goto fail; if (cache_bitmap_v2->bitmapLength == 0) goto fail; cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength); if (!cache_bitmap_v2->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); cache_bitmap_v2->compressed = compressed; return cache_bitmap_v2; fail: free_cache_bitmap_v2_order(update->context, cache_bitmap_v2); return NULL; } int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, BOOL compressed, UINT16* flags) { return 64 + cache_bitmap_v2->bitmapLength; } BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, BOOL compressed, UINT16* flags) { BYTE bitsPerPixelId; if (!Stream_EnsureRemainingCapacity( s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags))) return FALSE; bitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp]; *flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) | ((cache_bitmap_v2->flags << 7) & 0xFF80); if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { Stream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ return FALSE; } else { if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ return FALSE; } if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */ return FALSE; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength)) return FALSE; Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); } else { if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength)) return FALSE; Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); } cache_bitmap_v2->compressed = compressed; return TRUE; } static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s, UINT16 flags) { BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; UINT32 new_len; BYTE* new_data; CACHE_BITMAP_V3_ORDER* cache_bitmap_v3; if (!update || !s) return NULL; cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER)); if (!cache_bitmap_v3) goto fail; cache_bitmap_v3->cacheId = flags & 0x00000003; cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7; bitsPerPixelId = (flags & 0x00000078) >> 3; cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId]; if (Stream_GetRemainingLength(s) < 21) goto fail; Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ bitmapData = &cache_bitmap_v3->bitmapData; Stream_Read_UINT8(s, bitmapData->bpp); if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp); goto fail; } Stream_Seek_UINT8(s); /* reserved1 (1 byte) */ Stream_Seek_UINT8(s); /* reserved2 (1 byte) */ Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Read_UINT32(s, new_len); /* length (4 bytes) */ if (Stream_GetRemainingLength(s) < new_len) goto fail; new_data = (BYTE*)realloc(bitmapData->data, new_len); if (!new_data) goto fail; bitmapData->data = new_data; bitmapData->length = new_len; Stream_Read(s, bitmapData->data, bitmapData->length); return cache_bitmap_v3; fail: free_cache_bitmap_v3_order(update->context, cache_bitmap_v3); return NULL; } int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags) { BITMAP_DATA_EX* bitmapData = &cache_bitmap_v3->bitmapData; return 64 + bitmapData->length; } BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags) { BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; if (!Stream_EnsureRemainingCapacity( s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags))) return FALSE; bitmapData = &cache_bitmap_v3->bitmapData; bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp]; *flags = (cache_bitmap_v3->cacheId & 0x00000003) | ((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078); Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ Stream_Write_UINT8(s, bitmapData->bpp); Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */ Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */ Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */ Stream_Write(s, bitmapData->data, bitmapData->length); return TRUE; } static CACHE_COLOR_TABLE_ORDER* update_read_cache_color_table_order(rdpUpdate* update, wStream* s, UINT16 flags) { int i; UINT32* colorTable; CACHE_COLOR_TABLE_ORDER* cache_color_table = calloc(1, sizeof(CACHE_COLOR_TABLE_ORDER)); if (!cache_color_table) goto fail; if (Stream_GetRemainingLength(s) < 3) goto fail; Stream_Read_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */ Stream_Read_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */ if (cache_color_table->numberColors != 256) { /* This field MUST be set to 256 */ goto fail; } if (Stream_GetRemainingLength(s) < cache_color_table->numberColors * 4) goto fail; colorTable = (UINT32*)&cache_color_table->colorTable; for (i = 0; i < (int)cache_color_table->numberColors; i++) update_read_color_quad(s, &colorTable[i]); return cache_color_table; fail: free_cache_color_table_order(update->context, cache_color_table); return NULL; } int update_approximate_cache_color_table_order(const CACHE_COLOR_TABLE_ORDER* cache_color_table, UINT16* flags) { return 16 + (256 * 4); } BOOL update_write_cache_color_table_order(wStream* s, const CACHE_COLOR_TABLE_ORDER* cache_color_table, UINT16* flags) { int i, inf; UINT32* colorTable; if (cache_color_table->numberColors != 256) return FALSE; inf = update_approximate_cache_color_table_order(cache_color_table, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */ Stream_Write_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */ colorTable = (UINT32*)&cache_color_table->colorTable; for (i = 0; i < (int)cache_color_table->numberColors; i++) { update_write_color_quad(s, colorTable[i]); } return TRUE; } static CACHE_GLYPH_ORDER* update_read_cache_glyph_order(rdpUpdate* update, wStream* s, UINT16 flags) { UINT32 i; CACHE_GLYPH_ORDER* cache_glyph_order = calloc(1, sizeof(CACHE_GLYPH_ORDER)); if (!cache_glyph_order || !update || !s) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT8(s, cache_glyph_order->cacheId); /* cacheId (1 byte) */ Stream_Read_UINT8(s, cache_glyph_order->cGlyphs); /* cGlyphs (1 byte) */ for (i = 0; i < cache_glyph_order->cGlyphs; i++) { GLYPH_DATA* glyph = &cache_glyph_order->glyphData[i]; if (Stream_GetRemainingLength(s) < 10) goto fail; Stream_Read_UINT16(s, glyph->cacheIndex); Stream_Read_INT16(s, glyph->x); Stream_Read_INT16(s, glyph->y); Stream_Read_UINT16(s, glyph->cx); Stream_Read_UINT16(s, glyph->cy); glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; if (Stream_GetRemainingLength(s) < glyph->cb) goto fail; glyph->aj = (BYTE*)malloc(glyph->cb); if (!glyph->aj) goto fail; Stream_Read(s, glyph->aj, glyph->cb); } if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_order->cGlyphs > 0)) { cache_glyph_order->unicodeCharacters = calloc(cache_glyph_order->cGlyphs, sizeof(WCHAR)); if (!cache_glyph_order->unicodeCharacters) goto fail; if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_order->cGlyphs) goto fail; Stream_Read_UTF16_String(s, cache_glyph_order->unicodeCharacters, cache_glyph_order->cGlyphs); } return cache_glyph_order; fail: free_cache_glyph_order(update->context, cache_glyph_order); return NULL; } int update_approximate_cache_glyph_order(const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags) { return 2 + cache_glyph->cGlyphs * 32; } BOOL update_write_cache_glyph_order(wStream* s, const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags) { int i, inf; INT16 lsi16; const GLYPH_DATA* glyph; inf = update_approximate_cache_glyph_order(cache_glyph, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT8(s, cache_glyph->cacheId); /* cacheId (1 byte) */ Stream_Write_UINT8(s, cache_glyph->cGlyphs); /* cGlyphs (1 byte) */ for (i = 0; i < (int)cache_glyph->cGlyphs; i++) { UINT32 cb; glyph = &cache_glyph->glyphData[i]; Stream_Write_UINT16(s, glyph->cacheIndex); /* cacheIndex (2 bytes) */ lsi16 = glyph->x; Stream_Write_UINT16(s, lsi16); /* x (2 bytes) */ lsi16 = glyph->y; Stream_Write_UINT16(s, lsi16); /* y (2 bytes) */ Stream_Write_UINT16(s, glyph->cx); /* cx (2 bytes) */ Stream_Write_UINT16(s, glyph->cy); /* cy (2 bytes) */ cb = ((glyph->cx + 7) / 8) * glyph->cy; cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0; Stream_Write(s, glyph->aj, cb); } if (*flags & CG_GLYPH_UNICODE_PRESENT) { Stream_Zero(s, cache_glyph->cGlyphs * 2); } return TRUE; } static CACHE_GLYPH_V2_ORDER* update_read_cache_glyph_v2_order(rdpUpdate* update, wStream* s, UINT16 flags) { UINT32 i; CACHE_GLYPH_V2_ORDER* cache_glyph_v2 = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER)); if (!cache_glyph_v2) goto fail; cache_glyph_v2->cacheId = (flags & 0x000F); cache_glyph_v2->flags = (flags & 0x00F0) >> 4; cache_glyph_v2->cGlyphs = (flags & 0xFF00) >> 8; for (i = 0; i < cache_glyph_v2->cGlyphs; i++) { GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i]; if (Stream_GetRemainingLength(s) < 1) goto fail; Stream_Read_UINT8(s, glyph->cacheIndex); if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) || !update_read_2byte_unsigned(s, &glyph->cx) || !update_read_2byte_unsigned(s, &glyph->cy)) { goto fail; } glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; if (Stream_GetRemainingLength(s) < glyph->cb) goto fail; glyph->aj = (BYTE*)malloc(glyph->cb); if (!glyph->aj) goto fail; Stream_Read(s, glyph->aj, glyph->cb); } if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_v2->cGlyphs > 0)) { cache_glyph_v2->unicodeCharacters = calloc(cache_glyph_v2->cGlyphs, sizeof(WCHAR)); if (!cache_glyph_v2->unicodeCharacters) goto fail; if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_v2->cGlyphs) goto fail; Stream_Read_UTF16_String(s, cache_glyph_v2->unicodeCharacters, cache_glyph_v2->cGlyphs); } return cache_glyph_v2; fail: free_cache_glyph_v2_order(update->context, cache_glyph_v2); return NULL; } int update_approximate_cache_glyph_v2_order(const CACHE_GLYPH_V2_ORDER* cache_glyph_v2, UINT16* flags) { return 8 + cache_glyph_v2->cGlyphs * 32; } BOOL update_write_cache_glyph_v2_order(wStream* s, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2, UINT16* flags) { UINT32 i, inf; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; *flags = (cache_glyph_v2->cacheId & 0x000F) | ((cache_glyph_v2->flags & 0x000F) << 4) | ((cache_glyph_v2->cGlyphs & 0x00FF) << 8); for (i = 0; i < cache_glyph_v2->cGlyphs; i++) { UINT32 cb; const GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i]; Stream_Write_UINT8(s, glyph->cacheIndex); if (!update_write_2byte_signed(s, glyph->x) || !update_write_2byte_signed(s, glyph->y) || !update_write_2byte_unsigned(s, glyph->cx) || !update_write_2byte_unsigned(s, glyph->cy)) { return FALSE; } cb = ((glyph->cx + 7) / 8) * glyph->cy; cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0; Stream_Write(s, glyph->aj, cb); } if (*flags & CG_GLYPH_UNICODE_PRESENT) { Stream_Zero(s, cache_glyph_v2->cGlyphs * 2); } return TRUE; } static BOOL update_decompress_brush(wStream* s, BYTE* output, BYTE bpp) { int index; int x, y, k; BYTE byte = 0; BYTE* palette; int bytesPerPixel; palette = Stream_Pointer(s) + 16; bytesPerPixel = ((bpp + 1) / 8); if (Stream_GetRemainingLength(s) < 16) // 64 / 4 return FALSE; for (y = 7; y >= 0; y--) { for (x = 0; x < 8; x++) { if ((x % 4) == 0) Stream_Read_UINT8(s, byte); index = ((byte >> ((3 - (x % 4)) * 2)) & 0x03); for (k = 0; k < bytesPerPixel; k++) { output[((y * 8 + x) * bytesPerPixel) + k] = palette[(index * bytesPerPixel) + k]; } } } return TRUE; } static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp) { return FALSE; } static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags) { int i; BYTE iBitmapFormat; BOOL compressed = FALSE; CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER)); if (!cache_brush) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ if (iBitmapFormat > ARRAYSIZE(BMF_BPP)) goto fail; cache_brush->bpp = BMF_BPP[iBitmapFormat]; Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Read_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_Print(update->log, WLOG_ERROR, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); goto fail; } /* rows are encoded in reverse order */ if (Stream_GetRemainingLength(s) < 8) goto fail; for (i = 7; i >= 0; i--) { Stream_Read_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_decompress_brush(s, cache_brush->data, cache_brush->bpp)) goto fail; } else { /* uncompressed brush */ UINT32 scanline = (cache_brush->bpp / 8) * 8; if (Stream_GetRemainingLength(s) < scanline * 8) goto fail; for (i = 7; i >= 0; i--) { Stream_Read(s, &cache_brush->data[i * scanline], scanline); } } } } return cache_brush; fail: free_cache_brush_order(update->context, cache_brush); return NULL; } int update_approximate_cache_brush_order(const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { return 64; } BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { int i; BYTE iBitmapFormat; BOOL compressed = FALSE; if (!Stream_EnsureRemainingCapacity(s, update_approximate_cache_brush_order(cache_brush, flags))) return FALSE; iBitmapFormat = BPP_BMF[cache_brush->bpp]; Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); return FALSE; } for (i = 7; i >= 0; i--) { Stream_Write_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp)) return FALSE; } else { /* uncompressed brush */ int scanline = (cache_brush->bpp / 8) * 8; for (i = 7; i >= 0; i--) { Stream_Write(s, &cache_brush->data[i * scanline], scanline); } } } } return TRUE; } /* Alternate Secondary Drawing Orders */ static BOOL update_read_create_offscreen_bitmap_order(wStream* s, CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { UINT16 flags; BOOL deleteListPresent; OFFSCREEN_DELETE_LIST* deleteList; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT16(s, flags); /* flags (2 bytes) */ create_offscreen_bitmap->id = flags & 0x7FFF; deleteListPresent = (flags & 0x8000) ? TRUE : FALSE; Stream_Read_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */ Stream_Read_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */ deleteList = &(create_offscreen_bitmap->deleteList); if (deleteListPresent) { UINT32 i; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, deleteList->cIndices); if (deleteList->cIndices > deleteList->sIndices) { UINT16* new_indices; new_indices = (UINT16*)realloc(deleteList->indices, deleteList->cIndices * 2); if (!new_indices) return FALSE; deleteList->sIndices = deleteList->cIndices; deleteList->indices = new_indices; } if (Stream_GetRemainingLength(s) < 2 * deleteList->cIndices) return FALSE; for (i = 0; i < deleteList->cIndices; i++) { Stream_Read_UINT16(s, deleteList->indices[i]); } } else { deleteList->cIndices = 0; } return TRUE; } int update_approximate_create_offscreen_bitmap_order( const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { const OFFSCREEN_DELETE_LIST* deleteList = &(create_offscreen_bitmap->deleteList); return 32 + deleteList->cIndices * 2; } BOOL update_write_create_offscreen_bitmap_order( wStream* s, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { UINT16 flags; BOOL deleteListPresent; const OFFSCREEN_DELETE_LIST* deleteList; if (!Stream_EnsureRemainingCapacity( s, update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap))) return FALSE; deleteList = &(create_offscreen_bitmap->deleteList); flags = create_offscreen_bitmap->id & 0x7FFF; deleteListPresent = (deleteList->cIndices > 0) ? TRUE : FALSE; if (deleteListPresent) flags |= 0x8000; Stream_Write_UINT16(s, flags); /* flags (2 bytes) */ Stream_Write_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */ Stream_Write_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */ if (deleteListPresent) { int i; Stream_Write_UINT16(s, deleteList->cIndices); for (i = 0; i < (int)deleteList->cIndices; i++) { Stream_Write_UINT16(s, deleteList->indices[i]); } } return TRUE; } static BOOL update_read_switch_surface_order(wStream* s, SWITCH_SURFACE_ORDER* switch_surface) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */ return TRUE; } int update_approximate_switch_surface_order(const SWITCH_SURFACE_ORDER* switch_surface) { return 2; } BOOL update_write_switch_surface_order(wStream* s, const SWITCH_SURFACE_ORDER* switch_surface) { int inf = update_approximate_switch_surface_order(switch_surface); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */ return TRUE; } static BOOL update_read_create_nine_grid_bitmap_order(wStream* s, CREATE_NINE_GRID_BITMAP_ORDER* create_nine_grid_bitmap) { NINE_GRID_BITMAP_INFO* nineGridInfo; if (Stream_GetRemainingLength(s) < 19) return FALSE; Stream_Read_UINT8(s, create_nine_grid_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ if ((create_nine_grid_bitmap->bitmapBpp < 1) || (create_nine_grid_bitmap->bitmapBpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", create_nine_grid_bitmap->bitmapBpp); return FALSE; } Stream_Read_UINT16(s, create_nine_grid_bitmap->bitmapId); /* bitmapId (2 bytes) */ nineGridInfo = &(create_nine_grid_bitmap->nineGridInfo); Stream_Read_UINT32(s, nineGridInfo->flFlags); /* flFlags (4 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulLeftWidth); /* ulLeftWidth (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulRightWidth); /* ulRightWidth (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulTopHeight); /* ulTopHeight (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulBottomHeight); /* ulBottomHeight (2 bytes) */ update_read_colorref(s, &nineGridInfo->crTransparent); /* crTransparent (4 bytes) */ return TRUE; } static BOOL update_read_frame_marker_order(wStream* s, FRAME_MARKER_ORDER* frame_marker) { if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, frame_marker->action); /* action (4 bytes) */ return TRUE; } static BOOL update_read_stream_bitmap_first_order(wStream* s, STREAM_BITMAP_FIRST_ORDER* stream_bitmap_first) { if (Stream_GetRemainingLength(s) < 10) // 8 + 2 at least return FALSE; Stream_Read_UINT8(s, stream_bitmap_first->bitmapFlags); /* bitmapFlags (1 byte) */ Stream_Read_UINT8(s, stream_bitmap_first->bitmapBpp); /* bitmapBpp (1 byte) */ if ((stream_bitmap_first->bitmapBpp < 1) || (stream_bitmap_first->bitmapBpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", stream_bitmap_first->bitmapBpp); return FALSE; } Stream_Read_UINT16(s, stream_bitmap_first->bitmapType); /* bitmapType (2 bytes) */ Stream_Read_UINT16(s, stream_bitmap_first->bitmapWidth); /* bitmapWidth (2 bytes) */ Stream_Read_UINT16(s, stream_bitmap_first->bitmapHeight); /* bitmapHeigth (2 bytes) */ if (stream_bitmap_first->bitmapFlags & STREAM_BITMAP_V2) { if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, stream_bitmap_first->bitmapSize); /* bitmapSize (4 bytes) */ } else { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, stream_bitmap_first->bitmapSize); /* bitmapSize (2 bytes) */ } FIELD_SKIP_BUFFER16( s, stream_bitmap_first->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */ return TRUE; } static BOOL update_read_stream_bitmap_next_order(wStream* s, STREAM_BITMAP_NEXT_ORDER* stream_bitmap_next) { if (Stream_GetRemainingLength(s) < 5) return FALSE; Stream_Read_UINT8(s, stream_bitmap_next->bitmapFlags); /* bitmapFlags (1 byte) */ Stream_Read_UINT16(s, stream_bitmap_next->bitmapType); /* bitmapType (2 bytes) */ FIELD_SKIP_BUFFER16( s, stream_bitmap_next->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */ return TRUE; } static BOOL update_read_draw_gdiplus_first_order(wStream* s, DRAW_GDIPLUS_FIRST_ORDER* draw_gdiplus_first) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_first->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalSize); /* cbTotalSize (4 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_first->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_next_order(wStream* s, DRAW_GDIPLUS_NEXT_ORDER* draw_gdiplus_next) { if (Stream_GetRemainingLength(s) < 3) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ FIELD_SKIP_BUFFER16(s, draw_gdiplus_next->cbSize); /* cbSize(2 bytes) + emfRecords */ return TRUE; } static BOOL update_read_draw_gdiplus_end_order(wStream* s, DRAW_GDIPLUS_END_ORDER* draw_gdiplus_end) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_end->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalSize); /* cbTotalSize (4 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_end->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_cache_first_order(wStream* s, DRAW_GDIPLUS_CACHE_FIRST_ORDER* draw_gdiplus_cache_first) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_first->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_cache_first->cbTotalSize); /* cbTotalSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_cache_first->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_cache_next_order(wStream* s, DRAW_GDIPLUS_CACHE_NEXT_ORDER* draw_gdiplus_cache_next) { if (Stream_GetRemainingLength(s) < 7) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_next->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheIndex); /* cacheIndex (2 bytes) */ FIELD_SKIP_BUFFER16(s, draw_gdiplus_cache_next->cbSize); /* cbSize(2 bytes) + emfRecords */ return TRUE; } static BOOL update_read_draw_gdiplus_cache_end_order(wStream* s, DRAW_GDIPLUS_CACHE_END_ORDER* draw_gdiplus_cache_end) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_end->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_cache_end->cbTotalSize); /* cbTotalSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_cache_end->cbSize); /* emfRecords */ } static BOOL update_read_field_flags(wStream* s, UINT32* fieldFlags, BYTE flags, BYTE fieldBytes) { int i; BYTE byte; if (flags & ORDER_ZERO_FIELD_BYTE_BIT0) fieldBytes--; if (flags & ORDER_ZERO_FIELD_BYTE_BIT1) { if (fieldBytes > 1) fieldBytes -= 2; else fieldBytes = 0; } if (Stream_GetRemainingLength(s) < fieldBytes) return FALSE; *fieldFlags = 0; for (i = 0; i < fieldBytes; i++) { Stream_Read_UINT8(s, byte); *fieldFlags |= byte << (i * 8); } return TRUE; } BOOL update_write_field_flags(wStream* s, UINT32 fieldFlags, BYTE flags, BYTE fieldBytes) { BYTE byte; if (fieldBytes == 1) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); } else if (fieldBytes == 2) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 8) & 0xFF; Stream_Write_UINT8(s, byte); } else if (fieldBytes == 3) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 16) & 0xFF; Stream_Write_UINT8(s, byte); } else { return FALSE; } return TRUE; } static BOOL update_read_bounds(wStream* s, rdpBounds* bounds) { BYTE flags; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, flags); /* field flags */ if (flags & BOUND_LEFT) { if (!update_read_coord(s, &bounds->left, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_LEFT) { if (!update_read_coord(s, &bounds->left, TRUE)) return FALSE; } if (flags & BOUND_TOP) { if (!update_read_coord(s, &bounds->top, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_TOP) { if (!update_read_coord(s, &bounds->top, TRUE)) return FALSE; } if (flags & BOUND_RIGHT) { if (!update_read_coord(s, &bounds->right, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_RIGHT) { if (!update_read_coord(s, &bounds->right, TRUE)) return FALSE; } if (flags & BOUND_BOTTOM) { if (!update_read_coord(s, &bounds->bottom, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_BOTTOM) { if (!update_read_coord(s, &bounds->bottom, TRUE)) return FALSE; } return TRUE; } BOOL update_write_bounds(wStream* s, ORDER_INFO* orderInfo) { if (!(orderInfo->controlFlags & ORDER_BOUNDS)) return TRUE; if (orderInfo->controlFlags & ORDER_ZERO_BOUNDS_DELTAS) return TRUE; Stream_Write_UINT8(s, orderInfo->boundsFlags); /* field flags */ if (orderInfo->boundsFlags & BOUND_LEFT) { if (!update_write_coord(s, orderInfo->bounds.left)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_LEFT) { } if (orderInfo->boundsFlags & BOUND_TOP) { if (!update_write_coord(s, orderInfo->bounds.top)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_TOP) { } if (orderInfo->boundsFlags & BOUND_RIGHT) { if (!update_write_coord(s, orderInfo->bounds.right)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_RIGHT) { } if (orderInfo->boundsFlags & BOUND_BOTTOM) { if (!update_write_coord(s, orderInfo->bounds.bottom)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_BOTTOM) { } return TRUE; } static BOOL read_primary_order(wLog* log, const char* orderName, wStream* s, const ORDER_INFO* orderInfo, rdpPrimaryUpdate* primary) { BOOL rc = FALSE; if (!s || !orderInfo || !primary || !orderName) return FALSE; switch (orderInfo->orderType) { case ORDER_TYPE_DSTBLT: rc = update_read_dstblt_order(s, orderInfo, &(primary->dstblt)); break; case ORDER_TYPE_PATBLT: rc = update_read_patblt_order(s, orderInfo, &(primary->patblt)); break; case ORDER_TYPE_SCRBLT: rc = update_read_scrblt_order(s, orderInfo, &(primary->scrblt)); break; case ORDER_TYPE_OPAQUE_RECT: rc = update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect)); break; case ORDER_TYPE_DRAW_NINE_GRID: rc = update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid)); break; case ORDER_TYPE_MULTI_DSTBLT: rc = update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt)); break; case ORDER_TYPE_MULTI_PATBLT: rc = update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt)); break; case ORDER_TYPE_MULTI_SCRBLT: rc = update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt)); break; case ORDER_TYPE_MULTI_OPAQUE_RECT: rc = update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect)); break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: rc = update_read_multi_draw_nine_grid_order(s, orderInfo, &(primary->multi_draw_nine_grid)); break; case ORDER_TYPE_LINE_TO: rc = update_read_line_to_order(s, orderInfo, &(primary->line_to)); break; case ORDER_TYPE_POLYLINE: rc = update_read_polyline_order(s, orderInfo, &(primary->polyline)); break; case ORDER_TYPE_MEMBLT: rc = update_read_memblt_order(s, orderInfo, &(primary->memblt)); break; case ORDER_TYPE_MEM3BLT: rc = update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt)); break; case ORDER_TYPE_SAVE_BITMAP: rc = update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap)); break; case ORDER_TYPE_GLYPH_INDEX: rc = update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index)); break; case ORDER_TYPE_FAST_INDEX: rc = update_read_fast_index_order(s, orderInfo, &(primary->fast_index)); break; case ORDER_TYPE_FAST_GLYPH: rc = update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph)); break; case ORDER_TYPE_POLYGON_SC: rc = update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc)); break; case ORDER_TYPE_POLYGON_CB: rc = update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb)); break; case ORDER_TYPE_ELLIPSE_SC: rc = update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc)); break; case ORDER_TYPE_ELLIPSE_CB: rc = update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb)); break; default: WLog_Print(log, WLOG_WARN, "Primary Drawing Order %s not supported, ignoring", orderName); rc = TRUE; break; } if (!rc) { WLog_Print(log, WLOG_ERROR, "%s - update_read_dstblt_order() failed", orderName); return FALSE; } return TRUE; } static BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; rdpContext* context = update->context; rdpPrimaryUpdate* primary = update->primary; ORDER_INFO* orderInfo = &(primary->order_info); rdpSettings* settings = context->settings; const char* orderName; if (flags & ORDER_TYPE_CHANGE) { if (Stream_GetRemainingLength(s) < 1) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ } orderName = primary_order_string(orderInfo->orderType); if (!check_primary_order_supported(update->log, settings, orderInfo->orderType, orderName)) return FALSE; if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType])) { WLog_Print(update->log, WLOG_ERROR, "update_read_field_flags() failed"); return FALSE; } if (flags & ORDER_BOUNDS) { if (!(flags & ORDER_ZERO_BOUNDS_DELTAS)) { if (!update_read_bounds(s, &orderInfo->bounds)) { WLog_Print(update->log, WLOG_ERROR, "update_read_bounds() failed"); return FALSE; } } rc = IFCALLRESULT(FALSE, update->SetBounds, context, &orderInfo->bounds); if (!rc) return FALSE; } orderInfo->deltaCoordinates = (flags & ORDER_DELTA_COORDINATES) ? TRUE : FALSE; if (!read_primary_order(update->log, orderName, s, orderInfo, primary)) return FALSE; switch (orderInfo->orderType) { case ORDER_TYPE_DSTBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->dstblt.bRop), gdi_rop3_code(primary->dstblt.bRop)); rc = IFCALLRESULT(FALSE, primary->DstBlt, context, &primary->dstblt); } break; case ORDER_TYPE_PATBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->patblt.bRop), gdi_rop3_code(primary->patblt.bRop)); rc = IFCALLRESULT(FALSE, primary->PatBlt, context, &primary->patblt); } break; case ORDER_TYPE_SCRBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->scrblt.bRop), gdi_rop3_code(primary->scrblt.bRop)); rc = IFCALLRESULT(FALSE, primary->ScrBlt, context, &primary->scrblt); } break; case ORDER_TYPE_OPAQUE_RECT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->OpaqueRect, context, &primary->opaque_rect); } break; case ORDER_TYPE_DRAW_NINE_GRID: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->DrawNineGrid, context, &primary->draw_nine_grid); } break; case ORDER_TYPE_MULTI_DSTBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_dstblt.bRop), gdi_rop3_code(primary->multi_dstblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiDstBlt, context, &primary->multi_dstblt); } break; case ORDER_TYPE_MULTI_PATBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_patblt.bRop), gdi_rop3_code(primary->multi_patblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiPatBlt, context, &primary->multi_patblt); } break; case ORDER_TYPE_MULTI_SCRBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_scrblt.bRop), gdi_rop3_code(primary->multi_scrblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiScrBlt, context, &primary->multi_scrblt); } break; case ORDER_TYPE_MULTI_OPAQUE_RECT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->MultiOpaqueRect, context, &primary->multi_opaque_rect); } break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->MultiDrawNineGrid, context, &primary->multi_draw_nine_grid); } break; case ORDER_TYPE_LINE_TO: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->LineTo, context, &primary->line_to); } break; case ORDER_TYPE_POLYLINE: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->Polyline, context, &primary->polyline); } break; case ORDER_TYPE_MEMBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->memblt.bRop), gdi_rop3_code(primary->memblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MemBlt, context, &primary->memblt); } break; case ORDER_TYPE_MEM3BLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->mem3blt.bRop), gdi_rop3_code(primary->mem3blt.bRop)); rc = IFCALLRESULT(FALSE, primary->Mem3Blt, context, &primary->mem3blt); } break; case ORDER_TYPE_SAVE_BITMAP: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->SaveBitmap, context, &primary->save_bitmap); } break; case ORDER_TYPE_GLYPH_INDEX: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->GlyphIndex, context, &primary->glyph_index); } break; case ORDER_TYPE_FAST_INDEX: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->FastIndex, context, &primary->fast_index); } break; case ORDER_TYPE_FAST_GLYPH: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->FastGlyph, context, &primary->fast_glyph); } break; case ORDER_TYPE_POLYGON_SC: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->PolygonSC, context, &primary->polygon_sc); } break; case ORDER_TYPE_POLYGON_CB: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->PolygonCB, context, &primary->polygon_cb); } break; case ORDER_TYPE_ELLIPSE_SC: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->EllipseSC, context, &primary->ellipse_sc); } break; case ORDER_TYPE_ELLIPSE_CB: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->EllipseCB, context, &primary->ellipse_cb); } break; default: WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s not supported", orderName); break; } if (!rc) { WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s failed", orderName); return FALSE; } if (flags & ORDER_BOUNDS) { rc = IFCALLRESULT(FALSE, update->SetBounds, context, NULL); } return rc; } static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; BYTE* next; BYTE orderType; UINT16 extraFlags; UINT16 orderLength; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpSecondaryUpdate* secondary = update->secondary; const char* name; if (Stream_GetRemainingLength(s) < 5) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5"); return FALSE; } Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */ next = Stream_Pointer(s) + ((INT16)orderLength) + 7; name = secondary_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name); if (!check_secondary_order_supported(update->log, settings, orderType, name)) return FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: { const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED); CACHE_BITMAP_ORDER* order = update_read_cache_bitmap_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order); free_cache_bitmap_order(context, order); } } break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: { const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2); CACHE_BITMAP_V2_ORDER* order = update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order); free_cache_bitmap_v2_order(context, order); } } break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: { CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order); free_cache_bitmap_v3_order(context, order); } } break; case ORDER_TYPE_CACHE_COLOR_TABLE: { CACHE_COLOR_TABLE_ORDER* order = update_read_cache_color_table_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order); free_cache_color_table_order(context, order); } } break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: { CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order); free_cache_glyph_order(context, order); } } break; case GLYPH_SUPPORT_ENCODE: { CACHE_GLYPH_V2_ORDER* order = update_read_cache_glyph_v2_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order); free_cache_glyph_v2_order(context, order); } } break; case GLYPH_SUPPORT_NONE: default: break; } } break; case ORDER_TYPE_CACHE_BRUSH: /* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */ { CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order); free_cache_brush_order(context, order); } } break; default: WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name); break; } if (!rc) { WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name); } Stream_SetPointer(s, next); return rc; } static BOOL read_altsec_order(wStream* s, BYTE orderType, rdpAltSecUpdate* altsec) { BOOL rc = FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: rc = update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: rc = update_read_switch_surface_order(s, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: rc = update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: rc = update_read_frame_marker_order(s, &(altsec->frame_marker)); break; case ORDER_TYPE_STREAM_BITMAP_FIRST: rc = update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: rc = update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: rc = update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: rc = update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: rc = update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: rc = update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: rc = update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: rc = update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end)); break; case ORDER_TYPE_WINDOW: /* This order is handled elsewhere. */ rc = TRUE; break; case ORDER_TYPE_COMPDESK_FIRST: rc = TRUE; break; default: break; } return rc; } static BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags) { BYTE orderType = flags >>= 2; /* orderType is in higher 6 bits of flags field */ BOOL rc = FALSE; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpAltSecUpdate* altsec = update->altsec; const char* orderName = altsec_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Alternate Secondary Drawing Order %s", orderName); if (!check_alt_order_supported(update->log, settings, orderType, orderName)) return FALSE; if (!read_altsec_order(s, orderType, altsec)) return FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: IFCALLRET(altsec->CreateOffscreenBitmap, rc, context, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: IFCALLRET(altsec->SwitchSurface, rc, context, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: IFCALLRET(altsec->CreateNineGridBitmap, rc, context, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: IFCALLRET(altsec->FrameMarker, rc, context, &(altsec->frame_marker)); break; case ORDER_TYPE_STREAM_BITMAP_FIRST: IFCALLRET(altsec->StreamBitmapFirst, rc, context, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: IFCALLRET(altsec->StreamBitmapNext, rc, context, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: IFCALLRET(altsec->DrawGdiPlusFirst, rc, context, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: IFCALLRET(altsec->DrawGdiPlusNext, rc, context, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: IFCALLRET(altsec->DrawGdiPlusEnd, rc, context, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: IFCALLRET(altsec->DrawGdiPlusCacheFirst, rc, context, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: IFCALLRET(altsec->DrawGdiPlusCacheNext, rc, context, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: IFCALLRET(altsec->DrawGdiPlusCacheEnd, rc, context, &(altsec->draw_gdiplus_cache_end)); break; case ORDER_TYPE_WINDOW: rc = update_recv_altsec_window_order(update, s); break; case ORDER_TYPE_COMPDESK_FIRST: rc = TRUE; break; default: break; } if (!rc) { WLog_Print(update->log, WLOG_WARN, "Alternate Secondary Drawing Order %s failed", orderName); } return rc; } BOOL update_recv_order(rdpUpdate* update, wStream* s) { BOOL rc; BYTE controlFlags; if (Stream_GetRemainingLength(s) < 1) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */ if (!(controlFlags & ORDER_STANDARD)) rc = update_recv_altsec_order(update, s, controlFlags); else if (controlFlags & ORDER_SECONDARY) rc = update_recv_secondary_order(update, s, controlFlags); else rc = update_recv_primary_order(update, s, controlFlags); if (!rc) WLog_Print(update->log, WLOG_ERROR, "order flags %02" PRIx8 " failed", controlFlags); return rc; }
./CrossVul/dataset_final_sorted/CWE-415/c/bad_3906_0
crossvul-cpp_data_bad_3180_0
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2001, 2004 * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2001-2003 Intel Corp. * Copyright (c) 2001-2002 Nokia, Inc. * Copyright (c) 2001 La Monte H.P. Yarroll * * This file is part of the SCTP kernel implementation * * These functions interface with the sockets layer to implement the * SCTP Extensions for the Sockets API. * * Note that the descriptions from the specification are USER level * functions--this file is the functions which populate the struct proto * for SCTP which is the BOTTOM of the sockets interface. * * This SCTP implementation is free software; * you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This SCTP implementation is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied * ************************ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU CC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <linux-sctp@vger.kernel.org> * * Written or modified by: * La Monte H.P. Yarroll <piggy@acm.org> * Narasimha Budihal <narsi@refcode.org> * Karl Knutson <karl@athena.chicago.il.us> * Jon Grimm <jgrimm@us.ibm.com> * Xingang Guo <xingang.guo@intel.com> * Daisy Chang <daisyc@us.ibm.com> * Sridhar Samudrala <samudrala@us.ibm.com> * Inaky Perez-Gonzalez <inaky.gonzalez@intel.com> * Ardelle Fan <ardelle.fan@intel.com> * Ryan Layer <rmlayer@us.ibm.com> * Anup Pemmaiah <pemmaiah@cc.usu.edu> * Kevin Gao <kevin.gao@intel.com> */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <crypto/hash.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/wait.h> #include <linux/time.h> #include <linux/ip.h> #include <linux/capability.h> #include <linux/fcntl.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/file.h> #include <linux/compat.h> #include <net/ip.h> #include <net/icmp.h> #include <net/route.h> #include <net/ipv6.h> #include <net/inet_common.h> #include <net/busy_poll.h> #include <linux/socket.h> /* for sa_family_t */ #include <linux/export.h> #include <net/sock.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> /* Forward declarations for internal helper functions. */ static int sctp_writeable(struct sock *sk); static void sctp_wfree(struct sk_buff *skb); static int sctp_wait_for_sndbuf(struct sctp_association *, long *timeo_p, size_t msg_len); static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p); static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p); static int sctp_wait_for_accept(struct sock *sk, long timeo); static void sctp_wait_for_close(struct sock *sk, long timeo); static void sctp_destruct_sock(struct sock *sk); static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt, union sctp_addr *addr, int len); static int sctp_bindx_add(struct sock *, struct sockaddr *, int); static int sctp_bindx_rem(struct sock *, struct sockaddr *, int); static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int); static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int); static int sctp_send_asconf(struct sctp_association *asoc, struct sctp_chunk *chunk); static int sctp_do_bind(struct sock *, union sctp_addr *, int); static int sctp_autobind(struct sock *sk); static void sctp_sock_migrate(struct sock *, struct sock *, struct sctp_association *, sctp_socket_type_t); static int sctp_memory_pressure; static atomic_long_t sctp_memory_allocated; struct percpu_counter sctp_sockets_allocated; static void sctp_enter_memory_pressure(struct sock *sk) { sctp_memory_pressure = 1; } /* Get the sndbuf space available at the time on the association. */ static inline int sctp_wspace(struct sctp_association *asoc) { int amt; if (asoc->ep->sndbuf_policy) amt = asoc->sndbuf_used; else amt = sk_wmem_alloc_get(asoc->base.sk); if (amt >= asoc->base.sk->sk_sndbuf) { if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK) amt = 0; else { amt = sk_stream_wspace(asoc->base.sk); if (amt < 0) amt = 0; } } else { amt = asoc->base.sk->sk_sndbuf - amt; } return amt; } /* Increment the used sndbuf space count of the corresponding association by * the size of the outgoing data chunk. * Also, set the skb destructor for sndbuf accounting later. * * Since it is always 1-1 between chunk and skb, and also a new skb is always * allocated for chunk bundling in sctp_packet_transmit(), we can use the * destructor in the data chunk skb for the purpose of the sndbuf space * tracking. */ static inline void sctp_set_owner_w(struct sctp_chunk *chunk) { struct sctp_association *asoc = chunk->asoc; struct sock *sk = asoc->base.sk; /* The sndbuf space is tracked per association. */ sctp_association_hold(asoc); skb_set_owner_w(chunk->skb, sk); chunk->skb->destructor = sctp_wfree; /* Save the chunk pointer in skb for sctp_wfree to use later. */ skb_shinfo(chunk->skb)->destructor_arg = chunk; asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) + sizeof(struct sk_buff) + sizeof(struct sctp_chunk); atomic_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc); sk->sk_wmem_queued += chunk->skb->truesize; sk_mem_charge(sk, chunk->skb->truesize); } /* Verify that this is a valid address. */ static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr, int len) { struct sctp_af *af; /* Verify basic sockaddr. */ af = sctp_sockaddr_af(sctp_sk(sk), addr, len); if (!af) return -EINVAL; /* Is this a valid SCTP address? */ if (!af->addr_valid(addr, sctp_sk(sk), NULL)) return -EINVAL; if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr))) return -EINVAL; return 0; } /* Look up the association by its id. If this is not a UDP-style * socket, the ID field is always ignored. */ struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id) { struct sctp_association *asoc = NULL; /* If this is not a UDP-style socket, assoc id should be ignored. */ if (!sctp_style(sk, UDP)) { /* Return NULL if the socket state is not ESTABLISHED. It * could be a TCP-style listening socket or a socket which * hasn't yet called connect() to establish an association. */ if (!sctp_sstate(sk, ESTABLISHED) && !sctp_sstate(sk, CLOSING)) return NULL; /* Get the first and the only association from the list. */ if (!list_empty(&sctp_sk(sk)->ep->asocs)) asoc = list_entry(sctp_sk(sk)->ep->asocs.next, struct sctp_association, asocs); return asoc; } /* Otherwise this is a UDP-style socket. */ if (!id || (id == (sctp_assoc_t)-1)) return NULL; spin_lock_bh(&sctp_assocs_id_lock); asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id); spin_unlock_bh(&sctp_assocs_id_lock); if (!asoc || (asoc->base.sk != sk) || asoc->base.dead) return NULL; return asoc; } /* Look up the transport from an address and an assoc id. If both address and * id are specified, the associations matching the address and the id should be * the same. */ static struct sctp_transport *sctp_addr_id2transport(struct sock *sk, struct sockaddr_storage *addr, sctp_assoc_t id) { struct sctp_association *addr_asoc = NULL, *id_asoc = NULL; struct sctp_af *af = sctp_get_af_specific(addr->ss_family); union sctp_addr *laddr = (union sctp_addr *)addr; struct sctp_transport *transport; if (!af || sctp_verify_addr(sk, laddr, af->sockaddr_len)) return NULL; addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep, laddr, &transport); if (!addr_asoc) return NULL; id_asoc = sctp_id2assoc(sk, id); if (id_asoc && (id_asoc != addr_asoc)) return NULL; sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk), (union sctp_addr *)addr); return transport; } /* API 3.1.2 bind() - UDP Style Syntax * The syntax of bind() is, * * ret = bind(int sd, struct sockaddr *addr, int addrlen); * * sd - the socket descriptor returned by socket(). * addr - the address structure (struct sockaddr_in or struct * sockaddr_in6 [RFC 2553]), * addr_len - the size of the address structure. */ static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len) { int retval = 0; lock_sock(sk); pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk, addr, addr_len); /* Disallow binding twice. */ if (!sctp_sk(sk)->ep->base.bind_addr.port) retval = sctp_do_bind(sk, (union sctp_addr *)addr, addr_len); else retval = -EINVAL; release_sock(sk); return retval; } static long sctp_get_port_local(struct sock *, union sctp_addr *); /* Verify this is a valid sockaddr. */ static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt, union sctp_addr *addr, int len) { struct sctp_af *af; /* Check minimum size. */ if (len < sizeof (struct sockaddr)) return NULL; /* V4 mapped address are really of AF_INET family */ if (addr->sa.sa_family == AF_INET6 && ipv6_addr_v4mapped(&addr->v6.sin6_addr)) { if (!opt->pf->af_supported(AF_INET, opt)) return NULL; } else { /* Does this PF support this AF? */ if (!opt->pf->af_supported(addr->sa.sa_family, opt)) return NULL; } /* If we get this far, af is valid. */ af = sctp_get_af_specific(addr->sa.sa_family); if (len < af->sockaddr_len) return NULL; return af; } /* Bind a local address either to an endpoint or to an association. */ static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len) { struct net *net = sock_net(sk); struct sctp_sock *sp = sctp_sk(sk); struct sctp_endpoint *ep = sp->ep; struct sctp_bind_addr *bp = &ep->base.bind_addr; struct sctp_af *af; unsigned short snum; int ret = 0; /* Common sockaddr verification. */ af = sctp_sockaddr_af(sp, addr, len); if (!af) { pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n", __func__, sk, addr, len); return -EINVAL; } snum = ntohs(addr->v4.sin_port); pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n", __func__, sk, &addr->sa, bp->port, snum, len); /* PF specific bind() address verification. */ if (!sp->pf->bind_verify(sp, addr)) return -EADDRNOTAVAIL; /* We must either be unbound, or bind to the same port. * It's OK to allow 0 ports if we are already bound. * We'll just inhert an already bound port in this case */ if (bp->port) { if (!snum) snum = bp->port; else if (snum != bp->port) { pr_debug("%s: new port %d doesn't match existing port " "%d\n", __func__, snum, bp->port); return -EINVAL; } } if (snum && snum < inet_prot_sock(net) && !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) return -EACCES; /* See if the address matches any of the addresses we may have * already bound before checking against other endpoints. */ if (sctp_bind_addr_match(bp, addr, sp)) return -EINVAL; /* Make sure we are allowed to bind here. * The function sctp_get_port_local() does duplicate address * detection. */ addr->v4.sin_port = htons(snum); if ((ret = sctp_get_port_local(sk, addr))) { return -EADDRINUSE; } /* Refresh ephemeral port. */ if (!bp->port) bp->port = inet_sk(sk)->inet_num; /* Add the address to the bind address list. * Use GFP_ATOMIC since BHs will be disabled. */ ret = sctp_add_bind_addr(bp, addr, af->sockaddr_len, SCTP_ADDR_SRC, GFP_ATOMIC); /* Copy back into socket for getsockname() use. */ if (!ret) { inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num); sp->pf->to_sk_saddr(addr, sk); } return ret; } /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks * * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged * at any one time. If a sender, after sending an ASCONF chunk, decides * it needs to transfer another ASCONF Chunk, it MUST wait until the * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a * subsequent ASCONF. Note this restriction binds each side, so at any * time two ASCONF may be in-transit on any given association (one sent * from each endpoint). */ static int sctp_send_asconf(struct sctp_association *asoc, struct sctp_chunk *chunk) { struct net *net = sock_net(asoc->base.sk); int retval = 0; /* If there is an outstanding ASCONF chunk, queue it for later * transmission. */ if (asoc->addip_last_asconf) { list_add_tail(&chunk->list, &asoc->addip_chunk_list); goto out; } /* Hold the chunk until an ASCONF_ACK is received. */ sctp_chunk_hold(chunk); retval = sctp_primitive_ASCONF(net, asoc, chunk); if (retval) sctp_chunk_free(chunk); else asoc->addip_last_asconf = chunk; out: return retval; } /* Add a list of addresses as bind addresses to local endpoint or * association. * * Basically run through each address specified in the addrs/addrcnt * array/length pair, determine if it is IPv6 or IPv4 and call * sctp_do_bind() on it. * * If any of them fails, then the operation will be reversed and the * ones that were added will be removed. * * Only sctp_setsockopt_bindx() is supposed to call this function. */ static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt) { int cnt; int retval = 0; void *addr_buf; struct sockaddr *sa_addr; struct sctp_af *af; pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk, addrs, addrcnt); addr_buf = addrs; for (cnt = 0; cnt < addrcnt; cnt++) { /* The list may contain either IPv4 or IPv6 address; * determine the address length for walking thru the list. */ sa_addr = addr_buf; af = sctp_get_af_specific(sa_addr->sa_family); if (!af) { retval = -EINVAL; goto err_bindx_add; } retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr, af->sockaddr_len); addr_buf += af->sockaddr_len; err_bindx_add: if (retval < 0) { /* Failed. Cleanup the ones that have been added */ if (cnt > 0) sctp_bindx_rem(sk, addrs, cnt); return retval; } } return retval; } /* Send an ASCONF chunk with Add IP address parameters to all the peers of the * associations that are part of the endpoint indicating that a list of local * addresses are added to the endpoint. * * If any of the addresses is already in the bind address list of the * association, we do not send the chunk for that association. But it will not * affect other associations. * * Only sctp_setsockopt_bindx() is supposed to call this function. */ static int sctp_send_asconf_add_ip(struct sock *sk, struct sockaddr *addrs, int addrcnt) { struct net *net = sock_net(sk); struct sctp_sock *sp; struct sctp_endpoint *ep; struct sctp_association *asoc; struct sctp_bind_addr *bp; struct sctp_chunk *chunk; struct sctp_sockaddr_entry *laddr; union sctp_addr *addr; union sctp_addr saveaddr; void *addr_buf; struct sctp_af *af; struct list_head *p; int i; int retval = 0; if (!net->sctp.addip_enable) return retval; sp = sctp_sk(sk); ep = sp->ep; pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk, addrs, addrcnt); list_for_each_entry(asoc, &ep->asocs, asocs) { if (!asoc->peer.asconf_capable) continue; if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP) continue; if (!sctp_state(asoc, ESTABLISHED)) continue; /* Check if any address in the packed array of addresses is * in the bind address list of the association. If so, * do not send the asconf chunk to its peer, but continue with * other associations. */ addr_buf = addrs; for (i = 0; i < addrcnt; i++) { addr = addr_buf; af = sctp_get_af_specific(addr->v4.sin_family); if (!af) { retval = -EINVAL; goto out; } if (sctp_assoc_lookup_laddr(asoc, addr)) break; addr_buf += af->sockaddr_len; } if (i < addrcnt) continue; /* Use the first valid address in bind addr list of * association as Address Parameter of ASCONF CHUNK. */ bp = &asoc->base.bind_addr; p = bp->address_list.next; laddr = list_entry(p, struct sctp_sockaddr_entry, list); chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs, addrcnt, SCTP_PARAM_ADD_IP); if (!chunk) { retval = -ENOMEM; goto out; } /* Add the new addresses to the bind address list with * use_as_src set to 0. */ addr_buf = addrs; for (i = 0; i < addrcnt; i++) { addr = addr_buf; af = sctp_get_af_specific(addr->v4.sin_family); memcpy(&saveaddr, addr, af->sockaddr_len); retval = sctp_add_bind_addr(bp, &saveaddr, sizeof(saveaddr), SCTP_ADDR_NEW, GFP_ATOMIC); addr_buf += af->sockaddr_len; } if (asoc->src_out_of_asoc_ok) { struct sctp_transport *trans; list_for_each_entry(trans, &asoc->peer.transport_addr_list, transports) { /* Clear the source and route cache */ sctp_transport_dst_release(trans); trans->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380)); trans->ssthresh = asoc->peer.i.a_rwnd; trans->rto = asoc->rto_initial; sctp_max_rto(asoc, trans); trans->rtt = trans->srtt = trans->rttvar = 0; sctp_transport_route(trans, NULL, sctp_sk(asoc->base.sk)); } } retval = sctp_send_asconf(asoc, chunk); } out: return retval; } /* Remove a list of addresses from bind addresses list. Do not remove the * last address. * * Basically run through each address specified in the addrs/addrcnt * array/length pair, determine if it is IPv6 or IPv4 and call * sctp_del_bind() on it. * * If any of them fails, then the operation will be reversed and the * ones that were removed will be added back. * * At least one address has to be left; if only one address is * available, the operation will return -EBUSY. * * Only sctp_setsockopt_bindx() is supposed to call this function. */ static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_endpoint *ep = sp->ep; int cnt; struct sctp_bind_addr *bp = &ep->base.bind_addr; int retval = 0; void *addr_buf; union sctp_addr *sa_addr; struct sctp_af *af; pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk, addrs, addrcnt); addr_buf = addrs; for (cnt = 0; cnt < addrcnt; cnt++) { /* If the bind address list is empty or if there is only one * bind address, there is nothing more to be removed (we need * at least one address here). */ if (list_empty(&bp->address_list) || (sctp_list_single_entry(&bp->address_list))) { retval = -EBUSY; goto err_bindx_rem; } sa_addr = addr_buf; af = sctp_get_af_specific(sa_addr->sa.sa_family); if (!af) { retval = -EINVAL; goto err_bindx_rem; } if (!af->addr_valid(sa_addr, sp, NULL)) { retval = -EADDRNOTAVAIL; goto err_bindx_rem; } if (sa_addr->v4.sin_port && sa_addr->v4.sin_port != htons(bp->port)) { retval = -EINVAL; goto err_bindx_rem; } if (!sa_addr->v4.sin_port) sa_addr->v4.sin_port = htons(bp->port); /* FIXME - There is probably a need to check if sk->sk_saddr and * sk->sk_rcv_addr are currently set to one of the addresses to * be removed. This is something which needs to be looked into * when we are fixing the outstanding issues with multi-homing * socket routing and failover schemes. Refer to comments in * sctp_do_bind(). -daisy */ retval = sctp_del_bind_addr(bp, sa_addr); addr_buf += af->sockaddr_len; err_bindx_rem: if (retval < 0) { /* Failed. Add the ones that has been removed back */ if (cnt > 0) sctp_bindx_add(sk, addrs, cnt); return retval; } } return retval; } /* Send an ASCONF chunk with Delete IP address parameters to all the peers of * the associations that are part of the endpoint indicating that a list of * local addresses are removed from the endpoint. * * If any of the addresses is already in the bind address list of the * association, we do not send the chunk for that association. But it will not * affect other associations. * * Only sctp_setsockopt_bindx() is supposed to call this function. */ static int sctp_send_asconf_del_ip(struct sock *sk, struct sockaddr *addrs, int addrcnt) { struct net *net = sock_net(sk); struct sctp_sock *sp; struct sctp_endpoint *ep; struct sctp_association *asoc; struct sctp_transport *transport; struct sctp_bind_addr *bp; struct sctp_chunk *chunk; union sctp_addr *laddr; void *addr_buf; struct sctp_af *af; struct sctp_sockaddr_entry *saddr; int i; int retval = 0; int stored = 0; chunk = NULL; if (!net->sctp.addip_enable) return retval; sp = sctp_sk(sk); ep = sp->ep; pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk, addrs, addrcnt); list_for_each_entry(asoc, &ep->asocs, asocs) { if (!asoc->peer.asconf_capable) continue; if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP) continue; if (!sctp_state(asoc, ESTABLISHED)) continue; /* Check if any address in the packed array of addresses is * not present in the bind address list of the association. * If so, do not send the asconf chunk to its peer, but * continue with other associations. */ addr_buf = addrs; for (i = 0; i < addrcnt; i++) { laddr = addr_buf; af = sctp_get_af_specific(laddr->v4.sin_family); if (!af) { retval = -EINVAL; goto out; } if (!sctp_assoc_lookup_laddr(asoc, laddr)) break; addr_buf += af->sockaddr_len; } if (i < addrcnt) continue; /* Find one address in the association's bind address list * that is not in the packed array of addresses. This is to * make sure that we do not delete all the addresses in the * association. */ bp = &asoc->base.bind_addr; laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs, addrcnt, sp); if ((laddr == NULL) && (addrcnt == 1)) { if (asoc->asconf_addr_del_pending) continue; asoc->asconf_addr_del_pending = kzalloc(sizeof(union sctp_addr), GFP_ATOMIC); if (asoc->asconf_addr_del_pending == NULL) { retval = -ENOMEM; goto out; } asoc->asconf_addr_del_pending->sa.sa_family = addrs->sa_family; asoc->asconf_addr_del_pending->v4.sin_port = htons(bp->port); if (addrs->sa_family == AF_INET) { struct sockaddr_in *sin; sin = (struct sockaddr_in *)addrs; asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr; } else if (addrs->sa_family == AF_INET6) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)addrs; asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr; } pr_debug("%s: keep the last address asoc:%p %pISc at %p\n", __func__, asoc, &asoc->asconf_addr_del_pending->sa, asoc->asconf_addr_del_pending); asoc->src_out_of_asoc_ok = 1; stored = 1; goto skip_mkasconf; } if (laddr == NULL) return -EINVAL; /* We do not need RCU protection throughout this loop * because this is done under a socket lock from the * setsockopt call. */ chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt, SCTP_PARAM_DEL_IP); if (!chunk) { retval = -ENOMEM; goto out; } skip_mkasconf: /* Reset use_as_src flag for the addresses in the bind address * list that are to be deleted. */ addr_buf = addrs; for (i = 0; i < addrcnt; i++) { laddr = addr_buf; af = sctp_get_af_specific(laddr->v4.sin_family); list_for_each_entry(saddr, &bp->address_list, list) { if (sctp_cmp_addr_exact(&saddr->a, laddr)) saddr->state = SCTP_ADDR_DEL; } addr_buf += af->sockaddr_len; } /* Update the route and saddr entries for all the transports * as some of the addresses in the bind address list are * about to be deleted and cannot be used as source addresses. */ list_for_each_entry(transport, &asoc->peer.transport_addr_list, transports) { sctp_transport_dst_release(transport); sctp_transport_route(transport, NULL, sctp_sk(asoc->base.sk)); } if (stored) /* We don't need to transmit ASCONF */ continue; retval = sctp_send_asconf(asoc, chunk); } out: return retval; } /* set addr events to assocs in the endpoint. ep and addr_wq must be locked */ int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw) { struct sock *sk = sctp_opt2sk(sp); union sctp_addr *addr; struct sctp_af *af; /* It is safe to write port space in caller. */ addr = &addrw->a; addr->v4.sin_port = htons(sp->ep->base.bind_addr.port); af = sctp_get_af_specific(addr->sa.sa_family); if (!af) return -EINVAL; if (sctp_verify_addr(sk, addr, af->sockaddr_len)) return -EINVAL; if (addrw->state == SCTP_ADDR_NEW) return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1); else return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1); } /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt() * * API 8.1 * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt, * int flags); * * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses. * If the sd is an IPv6 socket, the addresses passed can either be IPv4 * or IPv6 addresses. * * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see * Section 3.1.2 for this usage. * * addrs is a pointer to an array of one or more socket addresses. Each * address is contained in its appropriate structure (i.e. struct * sockaddr_in or struct sockaddr_in6) the family of the address type * must be used to distinguish the address length (note that this * representation is termed a "packed array" of addresses). The caller * specifies the number of addresses in the array with addrcnt. * * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns * -1, and sets errno to the appropriate error code. * * For SCTP, the port given in each socket address must be the same, or * sctp_bindx() will fail, setting errno to EINVAL. * * The flags parameter is formed from the bitwise OR of zero or more of * the following currently defined flags: * * SCTP_BINDX_ADD_ADDR * * SCTP_BINDX_REM_ADDR * * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given * addresses from the association. The two flags are mutually exclusive; * if both are given, sctp_bindx() will fail with EINVAL. A caller may * not remove all addresses from an association; sctp_bindx() will * reject such an attempt with EINVAL. * * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate * additional addresses with an endpoint after calling bind(). Or use * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening * socket is associated with so that no new association accepted will be * associated with those addresses. If the endpoint supports dynamic * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a * endpoint to send the appropriate message to the peer to change the * peers address lists. * * Adding and removing addresses from a connected association is * optional functionality. Implementations that do not support this * functionality should return EOPNOTSUPP. * * Basically do nothing but copying the addresses from user to kernel * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk. * This is used for tunneling the sctp_bindx() request through sctp_setsockopt() * from userspace. * * We don't use copy_from_user() for optimization: we first do the * sanity checks (buffer size -fast- and access check-healthy * pointer); if all of those succeed, then we can alloc the memory * (expensive operation) needed to copy the data to kernel. Then we do * the copying without checking the user space area * (__copy_from_user()). * * On exit there is no need to do sockfd_put(), sys_setsockopt() does * it. * * sk The sk of the socket * addrs The pointer to the addresses in user land * addrssize Size of the addrs buffer * op Operation to perform (add or remove, see the flags of * sctp_bindx) * * Returns 0 if ok, <0 errno code on error. */ static int sctp_setsockopt_bindx(struct sock *sk, struct sockaddr __user *addrs, int addrs_size, int op) { struct sockaddr *kaddrs; int err; int addrcnt = 0; int walk_size = 0; struct sockaddr *sa_addr; void *addr_buf; struct sctp_af *af; pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n", __func__, sk, addrs, addrs_size, op); if (unlikely(addrs_size <= 0)) return -EINVAL; /* Check the user passed a healthy pointer. */ if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size))) return -EFAULT; /* Alloc space for the address array in kernel memory. */ kaddrs = kmalloc(addrs_size, GFP_USER | __GFP_NOWARN); if (unlikely(!kaddrs)) return -ENOMEM; if (__copy_from_user(kaddrs, addrs, addrs_size)) { kfree(kaddrs); return -EFAULT; } /* Walk through the addrs buffer and count the number of addresses. */ addr_buf = kaddrs; while (walk_size < addrs_size) { if (walk_size + sizeof(sa_family_t) > addrs_size) { kfree(kaddrs); return -EINVAL; } sa_addr = addr_buf; af = sctp_get_af_specific(sa_addr->sa_family); /* If the address family is not supported or if this address * causes the address buffer to overflow return EINVAL. */ if (!af || (walk_size + af->sockaddr_len) > addrs_size) { kfree(kaddrs); return -EINVAL; } addrcnt++; addr_buf += af->sockaddr_len; walk_size += af->sockaddr_len; } /* Do the work. */ switch (op) { case SCTP_BINDX_ADD_ADDR: err = sctp_bindx_add(sk, kaddrs, addrcnt); if (err) goto out; err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt); break; case SCTP_BINDX_REM_ADDR: err = sctp_bindx_rem(sk, kaddrs, addrcnt); if (err) goto out; err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt); break; default: err = -EINVAL; break; } out: kfree(kaddrs); return err; } /* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size) * * Common routine for handling connect() and sctp_connectx(). * Connect will come in with just a single address. */ static int __sctp_connect(struct sock *sk, struct sockaddr *kaddrs, int addrs_size, sctp_assoc_t *assoc_id) { struct net *net = sock_net(sk); struct sctp_sock *sp; struct sctp_endpoint *ep; struct sctp_association *asoc = NULL; struct sctp_association *asoc2; struct sctp_transport *transport; union sctp_addr to; sctp_scope_t scope; long timeo; int err = 0; int addrcnt = 0; int walk_size = 0; union sctp_addr *sa_addr = NULL; void *addr_buf; unsigned short port; unsigned int f_flags = 0; sp = sctp_sk(sk); ep = sp->ep; /* connect() cannot be done on a socket that is already in ESTABLISHED * state - UDP-style peeled off socket or a TCP-style socket that * is already connected. * It cannot be done even on a TCP-style listening socket. */ if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) || (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) { err = -EISCONN; goto out_free; } /* Walk through the addrs buffer and count the number of addresses. */ addr_buf = kaddrs; while (walk_size < addrs_size) { struct sctp_af *af; if (walk_size + sizeof(sa_family_t) > addrs_size) { err = -EINVAL; goto out_free; } sa_addr = addr_buf; af = sctp_get_af_specific(sa_addr->sa.sa_family); /* If the address family is not supported or if this address * causes the address buffer to overflow return EINVAL. */ if (!af || (walk_size + af->sockaddr_len) > addrs_size) { err = -EINVAL; goto out_free; } port = ntohs(sa_addr->v4.sin_port); /* Save current address so we can work with it */ memcpy(&to, sa_addr, af->sockaddr_len); err = sctp_verify_addr(sk, &to, af->sockaddr_len); if (err) goto out_free; /* Make sure the destination port is correctly set * in all addresses. */ if (asoc && asoc->peer.port && asoc->peer.port != port) { err = -EINVAL; goto out_free; } /* Check if there already is a matching association on the * endpoint (other than the one created here). */ asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport); if (asoc2 && asoc2 != asoc) { if (asoc2->state >= SCTP_STATE_ESTABLISHED) err = -EISCONN; else err = -EALREADY; goto out_free; } /* If we could not find a matching association on the endpoint, * make sure that there is no peeled-off association matching * the peer address even on another socket. */ if (sctp_endpoint_is_peeled_off(ep, &to)) { err = -EADDRNOTAVAIL; goto out_free; } if (!asoc) { /* If a bind() or sctp_bindx() is not called prior to * an sctp_connectx() call, the system picks an * ephemeral port and will choose an address set * equivalent to binding with a wildcard address. */ if (!ep->base.bind_addr.port) { if (sctp_autobind(sk)) { err = -EAGAIN; goto out_free; } } else { /* * If an unprivileged user inherits a 1-many * style socket with open associations on a * privileged port, it MAY be permitted to * accept new associations, but it SHOULD NOT * be permitted to open new associations. */ if (ep->base.bind_addr.port < inet_prot_sock(net) && !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) { err = -EACCES; goto out_free; } } scope = sctp_scope(&to); asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL); if (!asoc) { err = -ENOMEM; goto out_free; } err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL); if (err < 0) { goto out_free; } } /* Prime the peer's transport structures. */ transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN); if (!transport) { err = -ENOMEM; goto out_free; } addrcnt++; addr_buf += af->sockaddr_len; walk_size += af->sockaddr_len; } /* In case the user of sctp_connectx() wants an association * id back, assign one now. */ if (assoc_id) { err = sctp_assoc_set_id(asoc, GFP_KERNEL); if (err < 0) goto out_free; } err = sctp_primitive_ASSOCIATE(net, asoc, NULL); if (err < 0) { goto out_free; } /* Initialize sk's dport and daddr for getpeername() */ inet_sk(sk)->inet_dport = htons(asoc->peer.port); sp->pf->to_sk_daddr(sa_addr, sk); sk->sk_err = 0; /* in-kernel sockets don't generally have a file allocated to them * if all they do is call sock_create_kern(). */ if (sk->sk_socket->file) f_flags = sk->sk_socket->file->f_flags; timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK); if (assoc_id) *assoc_id = asoc->assoc_id; err = sctp_wait_for_connect(asoc, &timeo); /* Note: the asoc may be freed after the return of * sctp_wait_for_connect. */ /* Don't free association on exit. */ asoc = NULL; out_free: pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n", __func__, asoc, kaddrs, err); if (asoc) { /* sctp_primitive_ASSOCIATE may have added this association * To the hash table, try to unhash it, just in case, its a noop * if it wasn't hashed so we're safe */ sctp_association_free(asoc); } return err; } /* Helper for tunneling sctp_connectx() requests through sctp_setsockopt() * * API 8.9 * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt, * sctp_assoc_t *asoc); * * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses. * If the sd is an IPv6 socket, the addresses passed can either be IPv4 * or IPv6 addresses. * * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see * Section 3.1.2 for this usage. * * addrs is a pointer to an array of one or more socket addresses. Each * address is contained in its appropriate structure (i.e. struct * sockaddr_in or struct sockaddr_in6) the family of the address type * must be used to distengish the address length (note that this * representation is termed a "packed array" of addresses). The caller * specifies the number of addresses in the array with addrcnt. * * On success, sctp_connectx() returns 0. It also sets the assoc_id to * the association id of the new association. On failure, sctp_connectx() * returns -1, and sets errno to the appropriate error code. The assoc_id * is not touched by the kernel. * * For SCTP, the port given in each socket address must be the same, or * sctp_connectx() will fail, setting errno to EINVAL. * * An application can use sctp_connectx to initiate an association with * an endpoint that is multi-homed. Much like sctp_bindx() this call * allows a caller to specify multiple addresses at which a peer can be * reached. The way the SCTP stack uses the list of addresses to set up * the association is implementation dependent. This function only * specifies that the stack will try to make use of all the addresses in * the list when needed. * * Note that the list of addresses passed in is only used for setting up * the association. It does not necessarily equal the set of addresses * the peer uses for the resulting association. If the caller wants to * find out the set of peer addresses, it must use sctp_getpaddrs() to * retrieve them after the association has been set up. * * Basically do nothing but copying the addresses from user to kernel * land and invoking either sctp_connectx(). This is used for tunneling * the sctp_connectx() request through sctp_setsockopt() from userspace. * * We don't use copy_from_user() for optimization: we first do the * sanity checks (buffer size -fast- and access check-healthy * pointer); if all of those succeed, then we can alloc the memory * (expensive operation) needed to copy the data to kernel. Then we do * the copying without checking the user space area * (__copy_from_user()). * * On exit there is no need to do sockfd_put(), sys_setsockopt() does * it. * * sk The sk of the socket * addrs The pointer to the addresses in user land * addrssize Size of the addrs buffer * * Returns >=0 if ok, <0 errno code on error. */ static int __sctp_setsockopt_connectx(struct sock *sk, struct sockaddr __user *addrs, int addrs_size, sctp_assoc_t *assoc_id) { struct sockaddr *kaddrs; gfp_t gfp = GFP_KERNEL; int err = 0; pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n", __func__, sk, addrs, addrs_size); if (unlikely(addrs_size <= 0)) return -EINVAL; /* Check the user passed a healthy pointer. */ if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size))) return -EFAULT; /* Alloc space for the address array in kernel memory. */ if (sk->sk_socket->file) gfp = GFP_USER | __GFP_NOWARN; kaddrs = kmalloc(addrs_size, gfp); if (unlikely(!kaddrs)) return -ENOMEM; if (__copy_from_user(kaddrs, addrs, addrs_size)) { err = -EFAULT; } else { err = __sctp_connect(sk, kaddrs, addrs_size, assoc_id); } kfree(kaddrs); return err; } /* * This is an older interface. It's kept for backward compatibility * to the option that doesn't provide association id. */ static int sctp_setsockopt_connectx_old(struct sock *sk, struct sockaddr __user *addrs, int addrs_size) { return __sctp_setsockopt_connectx(sk, addrs, addrs_size, NULL); } /* * New interface for the API. The since the API is done with a socket * option, to make it simple we feed back the association id is as a return * indication to the call. Error is always negative and association id is * always positive. */ static int sctp_setsockopt_connectx(struct sock *sk, struct sockaddr __user *addrs, int addrs_size) { sctp_assoc_t assoc_id = 0; int err = 0; err = __sctp_setsockopt_connectx(sk, addrs, addrs_size, &assoc_id); if (err) return err; else return assoc_id; } /* * New (hopefully final) interface for the API. * We use the sctp_getaddrs_old structure so that use-space library * can avoid any unnecessary allocations. The only different part * is that we store the actual length of the address buffer into the * addrs_num structure member. That way we can re-use the existing * code. */ #ifdef CONFIG_COMPAT struct compat_sctp_getaddrs_old { sctp_assoc_t assoc_id; s32 addr_num; compat_uptr_t addrs; /* struct sockaddr * */ }; #endif static int sctp_getsockopt_connectx3(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_getaddrs_old param; sctp_assoc_t assoc_id = 0; int err = 0; #ifdef CONFIG_COMPAT if (in_compat_syscall()) { struct compat_sctp_getaddrs_old param32; if (len < sizeof(param32)) return -EINVAL; if (copy_from_user(&param32, optval, sizeof(param32))) return -EFAULT; param.assoc_id = param32.assoc_id; param.addr_num = param32.addr_num; param.addrs = compat_ptr(param32.addrs); } else #endif { if (len < sizeof(param)) return -EINVAL; if (copy_from_user(&param, optval, sizeof(param))) return -EFAULT; } err = __sctp_setsockopt_connectx(sk, (struct sockaddr __user *) param.addrs, param.addr_num, &assoc_id); if (err == 0 || err == -EINPROGRESS) { if (copy_to_user(optval, &assoc_id, sizeof(assoc_id))) return -EFAULT; if (put_user(sizeof(assoc_id), optlen)) return -EFAULT; } return err; } /* API 3.1.4 close() - UDP Style Syntax * Applications use close() to perform graceful shutdown (as described in * Section 10.1 of [SCTP]) on ALL the associations currently represented * by a UDP-style socket. * * The syntax is * * ret = close(int sd); * * sd - the socket descriptor of the associations to be closed. * * To gracefully shutdown a specific association represented by the * UDP-style socket, an application should use the sendmsg() call, * passing no user data, but including the appropriate flag in the * ancillary data (see Section xxxx). * * If sd in the close() call is a branched-off socket representing only * one association, the shutdown is performed on that association only. * * 4.1.6 close() - TCP Style Syntax * * Applications use close() to gracefully close down an association. * * The syntax is: * * int close(int sd); * * sd - the socket descriptor of the association to be closed. * * After an application calls close() on a socket descriptor, no further * socket operations will succeed on that descriptor. * * API 7.1.4 SO_LINGER * * An application using the TCP-style socket can use this option to * perform the SCTP ABORT primitive. The linger option structure is: * * struct linger { * int l_onoff; // option on/off * int l_linger; // linger time * }; * * To enable the option, set l_onoff to 1. If the l_linger value is set * to 0, calling close() is the same as the ABORT primitive. If the * value is set to a negative value, the setsockopt() call will return * an error. If the value is set to a positive value linger_time, the * close() can be blocked for at most linger_time ms. If the graceful * shutdown phase does not finish during this period, close() will * return but the graceful shutdown phase continues in the system. */ static void sctp_close(struct sock *sk, long timeout) { struct net *net = sock_net(sk); struct sctp_endpoint *ep; struct sctp_association *asoc; struct list_head *pos, *temp; unsigned int data_was_unread; pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout); lock_sock(sk); sk->sk_shutdown = SHUTDOWN_MASK; sk->sk_state = SCTP_SS_CLOSING; ep = sctp_sk(sk)->ep; /* Clean up any skbs sitting on the receive queue. */ data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue); data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby); /* Walk all associations on an endpoint. */ list_for_each_safe(pos, temp, &ep->asocs) { asoc = list_entry(pos, struct sctp_association, asocs); if (sctp_style(sk, TCP)) { /* A closed association can still be in the list if * it belongs to a TCP-style listening socket that is * not yet accepted. If so, free it. If not, send an * ABORT or SHUTDOWN based on the linger options. */ if (sctp_state(asoc, CLOSED)) { sctp_association_free(asoc); continue; } } if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) || !skb_queue_empty(&asoc->ulpq.reasm) || (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) { struct sctp_chunk *chunk; chunk = sctp_make_abort_user(asoc, NULL, 0); sctp_primitive_ABORT(net, asoc, chunk); } else sctp_primitive_SHUTDOWN(net, asoc, NULL); } /* On a TCP-style socket, block for at most linger_time if set. */ if (sctp_style(sk, TCP) && timeout) sctp_wait_for_close(sk, timeout); /* This will run the backlog queue. */ release_sock(sk); /* Supposedly, no process has access to the socket, but * the net layers still may. * Also, sctp_destroy_sock() needs to be called with addr_wq_lock * held and that should be grabbed before socket lock. */ spin_lock_bh(&net->sctp.addr_wq_lock); bh_lock_sock(sk); /* Hold the sock, since sk_common_release() will put sock_put() * and we have just a little more cleanup. */ sock_hold(sk); sk_common_release(sk); bh_unlock_sock(sk); spin_unlock_bh(&net->sctp.addr_wq_lock); sock_put(sk); SCTP_DBG_OBJCNT_DEC(sock); } /* Handle EPIPE error. */ static int sctp_error(struct sock *sk, int flags, int err) { if (err == -EPIPE) err = sock_error(sk) ? : -EPIPE; if (err == -EPIPE && !(flags & MSG_NOSIGNAL)) send_sig(SIGPIPE, current, 0); return err; } /* API 3.1.3 sendmsg() - UDP Style Syntax * * An application uses sendmsg() and recvmsg() calls to transmit data to * and receive data from its peer. * * ssize_t sendmsg(int socket, const struct msghdr *message, * int flags); * * socket - the socket descriptor of the endpoint. * message - pointer to the msghdr structure which contains a single * user message and possibly some ancillary data. * * See Section 5 for complete description of the data * structures. * * flags - flags sent or received with the user message, see Section * 5 for complete description of the flags. * * Note: This function could use a rewrite especially when explicit * connect support comes in. */ /* BUG: We do not implement the equivalent of sk_stream_wait_memory(). */ static int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *); static int sctp_sendmsg(struct sock *sk, struct msghdr *msg, size_t msg_len) { struct net *net = sock_net(sk); struct sctp_sock *sp; struct sctp_endpoint *ep; struct sctp_association *new_asoc = NULL, *asoc = NULL; struct sctp_transport *transport, *chunk_tp; struct sctp_chunk *chunk; union sctp_addr to; struct sockaddr *msg_name = NULL; struct sctp_sndrcvinfo default_sinfo; struct sctp_sndrcvinfo *sinfo; struct sctp_initmsg *sinit; sctp_assoc_t associd = 0; sctp_cmsgs_t cmsgs = { NULL }; sctp_scope_t scope; bool fill_sinfo_ttl = false, wait_connect = false; struct sctp_datamsg *datamsg; int msg_flags = msg->msg_flags; __u16 sinfo_flags = 0; long timeo; int err; err = 0; sp = sctp_sk(sk); ep = sp->ep; pr_debug("%s: sk:%p, msg:%p, msg_len:%zu ep:%p\n", __func__, sk, msg, msg_len, ep); /* We cannot send a message over a TCP-style listening socket. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) { err = -EPIPE; goto out_nounlock; } /* Parse out the SCTP CMSGs. */ err = sctp_msghdr_parse(msg, &cmsgs); if (err) { pr_debug("%s: msghdr parse err:%x\n", __func__, err); goto out_nounlock; } /* Fetch the destination address for this packet. This * address only selects the association--it is not necessarily * the address we will send to. * For a peeled-off socket, msg_name is ignored. */ if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) { int msg_namelen = msg->msg_namelen; err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name, msg_namelen); if (err) return err; if (msg_namelen > sizeof(to)) msg_namelen = sizeof(to); memcpy(&to, msg->msg_name, msg_namelen); msg_name = msg->msg_name; } sinit = cmsgs.init; if (cmsgs.sinfo != NULL) { memset(&default_sinfo, 0, sizeof(default_sinfo)); default_sinfo.sinfo_stream = cmsgs.sinfo->snd_sid; default_sinfo.sinfo_flags = cmsgs.sinfo->snd_flags; default_sinfo.sinfo_ppid = cmsgs.sinfo->snd_ppid; default_sinfo.sinfo_context = cmsgs.sinfo->snd_context; default_sinfo.sinfo_assoc_id = cmsgs.sinfo->snd_assoc_id; sinfo = &default_sinfo; fill_sinfo_ttl = true; } else { sinfo = cmsgs.srinfo; } /* Did the user specify SNDINFO/SNDRCVINFO? */ if (sinfo) { sinfo_flags = sinfo->sinfo_flags; associd = sinfo->sinfo_assoc_id; } pr_debug("%s: msg_len:%zu, sinfo_flags:0x%x\n", __func__, msg_len, sinfo_flags); /* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */ if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) { err = -EINVAL; goto out_nounlock; } /* If SCTP_EOF is set, no data can be sent. Disallow sending zero * length messages when SCTP_EOF|SCTP_ABORT is not set. * If SCTP_ABORT is set, the message length could be non zero with * the msg_iov set to the user abort reason. */ if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) || (!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) { err = -EINVAL; goto out_nounlock; } /* If SCTP_ADDR_OVER is set, there must be an address * specified in msg_name. */ if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) { err = -EINVAL; goto out_nounlock; } transport = NULL; pr_debug("%s: about to look up association\n", __func__); lock_sock(sk); /* If a msg_name has been specified, assume this is to be used. */ if (msg_name) { /* Look for a matching association on the endpoint. */ asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport); /* If we could not find a matching association on the * endpoint, make sure that it is not a TCP-style * socket that already has an association or there is * no peeled-off association on another socket. */ if (!asoc && ((sctp_style(sk, TCP) && (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING))) || sctp_endpoint_is_peeled_off(ep, &to))) { err = -EADDRNOTAVAIL; goto out_unlock; } } else { asoc = sctp_id2assoc(sk, associd); if (!asoc) { err = -EPIPE; goto out_unlock; } } if (asoc) { pr_debug("%s: just looked up association:%p\n", __func__, asoc); /* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED * socket that has an association in CLOSED state. This can * happen when an accepted socket has an association that is * already CLOSED. */ if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) { err = -EPIPE; goto out_unlock; } if (sinfo_flags & SCTP_EOF) { pr_debug("%s: shutting down association:%p\n", __func__, asoc); sctp_primitive_SHUTDOWN(net, asoc, NULL); err = 0; goto out_unlock; } if (sinfo_flags & SCTP_ABORT) { chunk = sctp_make_abort_user(asoc, msg, msg_len); if (!chunk) { err = -ENOMEM; goto out_unlock; } pr_debug("%s: aborting association:%p\n", __func__, asoc); sctp_primitive_ABORT(net, asoc, chunk); err = 0; goto out_unlock; } } /* Do we need to create the association? */ if (!asoc) { pr_debug("%s: there is no association yet\n", __func__); if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) { err = -EINVAL; goto out_unlock; } /* Check for invalid stream against the stream counts, * either the default or the user specified stream counts. */ if (sinfo) { if (!sinit || !sinit->sinit_num_ostreams) { /* Check against the defaults. */ if (sinfo->sinfo_stream >= sp->initmsg.sinit_num_ostreams) { err = -EINVAL; goto out_unlock; } } else { /* Check against the requested. */ if (sinfo->sinfo_stream >= sinit->sinit_num_ostreams) { err = -EINVAL; goto out_unlock; } } } /* * API 3.1.2 bind() - UDP Style Syntax * If a bind() or sctp_bindx() is not called prior to a * sendmsg() call that initiates a new association, the * system picks an ephemeral port and will choose an address * set equivalent to binding with a wildcard address. */ if (!ep->base.bind_addr.port) { if (sctp_autobind(sk)) { err = -EAGAIN; goto out_unlock; } } else { /* * If an unprivileged user inherits a one-to-many * style socket with open associations on a privileged * port, it MAY be permitted to accept new associations, * but it SHOULD NOT be permitted to open new * associations. */ if (ep->base.bind_addr.port < inet_prot_sock(net) && !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) { err = -EACCES; goto out_unlock; } } scope = sctp_scope(&to); new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL); if (!new_asoc) { err = -ENOMEM; goto out_unlock; } asoc = new_asoc; err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL); if (err < 0) { err = -ENOMEM; goto out_free; } /* If the SCTP_INIT ancillary data is specified, set all * the association init values accordingly. */ if (sinit) { if (sinit->sinit_num_ostreams) { asoc->c.sinit_num_ostreams = sinit->sinit_num_ostreams; } if (sinit->sinit_max_instreams) { asoc->c.sinit_max_instreams = sinit->sinit_max_instreams; } if (sinit->sinit_max_attempts) { asoc->max_init_attempts = sinit->sinit_max_attempts; } if (sinit->sinit_max_init_timeo) { asoc->max_init_timeo = msecs_to_jiffies(sinit->sinit_max_init_timeo); } } /* Prime the peer's transport structures. */ transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN); if (!transport) { err = -ENOMEM; goto out_free; } } /* ASSERT: we have a valid association at this point. */ pr_debug("%s: we have a valid association\n", __func__); if (!sinfo) { /* If the user didn't specify SNDINFO/SNDRCVINFO, make up * one with some defaults. */ memset(&default_sinfo, 0, sizeof(default_sinfo)); default_sinfo.sinfo_stream = asoc->default_stream; default_sinfo.sinfo_flags = asoc->default_flags; default_sinfo.sinfo_ppid = asoc->default_ppid; default_sinfo.sinfo_context = asoc->default_context; default_sinfo.sinfo_timetolive = asoc->default_timetolive; default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc); sinfo = &default_sinfo; } else if (fill_sinfo_ttl) { /* In case SNDINFO was specified, we still need to fill * it with a default ttl from the assoc here. */ sinfo->sinfo_timetolive = asoc->default_timetolive; } /* API 7.1.7, the sndbuf size per association bounds the * maximum size of data that can be sent in a single send call. */ if (msg_len > sk->sk_sndbuf) { err = -EMSGSIZE; goto out_free; } if (asoc->pmtu_pending) sctp_assoc_pending_pmtu(sk, asoc); /* If fragmentation is disabled and the message length exceeds the * association fragmentation point, return EMSGSIZE. The I-D * does not specify what this error is, but this looks like * a great fit. */ if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) { err = -EMSGSIZE; goto out_free; } /* Check for invalid stream. */ if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) { err = -EINVAL; goto out_free; } if (sctp_wspace(asoc) < msg_len) sctp_prsctp_prune(asoc, sinfo, msg_len - sctp_wspace(asoc)); timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); if (!sctp_wspace(asoc)) { err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len); if (err) goto out_free; } /* If an address is passed with the sendto/sendmsg call, it is used * to override the primary destination address in the TCP model, or * when SCTP_ADDR_OVER flag is set in the UDP model. */ if ((sctp_style(sk, TCP) && msg_name) || (sinfo_flags & SCTP_ADDR_OVER)) { chunk_tp = sctp_assoc_lookup_paddr(asoc, &to); if (!chunk_tp) { err = -EINVAL; goto out_free; } } else chunk_tp = NULL; /* Auto-connect, if we aren't connected already. */ if (sctp_state(asoc, CLOSED)) { err = sctp_primitive_ASSOCIATE(net, asoc, NULL); if (err < 0) goto out_free; wait_connect = true; pr_debug("%s: we associated primitively\n", __func__); } /* Break the message into multiple chunks of maximum size. */ datamsg = sctp_datamsg_from_user(asoc, sinfo, &msg->msg_iter); if (IS_ERR(datamsg)) { err = PTR_ERR(datamsg); goto out_free; } datamsg->force_delay = !!(msg->msg_flags & MSG_MORE); /* Now send the (possibly) fragmented message. */ list_for_each_entry(chunk, &datamsg->chunks, frag_list) { sctp_chunk_hold(chunk); /* Do accounting for the write space. */ sctp_set_owner_w(chunk); chunk->transport = chunk_tp; } /* Send it to the lower layers. Note: all chunks * must either fail or succeed. The lower layer * works that way today. Keep it that way or this * breaks. */ err = sctp_primitive_SEND(net, asoc, datamsg); /* Did the lower layer accept the chunk? */ if (err) { sctp_datamsg_free(datamsg); goto out_free; } pr_debug("%s: we sent primitively\n", __func__); sctp_datamsg_put(datamsg); err = msg_len; if (unlikely(wait_connect)) { timeo = sock_sndtimeo(sk, msg_flags & MSG_DONTWAIT); sctp_wait_for_connect(asoc, &timeo); } /* If we are already past ASSOCIATE, the lower * layers are responsible for association cleanup. */ goto out_unlock; out_free: if (new_asoc) sctp_association_free(asoc); out_unlock: release_sock(sk); out_nounlock: return sctp_error(sk, msg_flags, err); #if 0 do_sock_err: if (msg_len) err = msg_len; else err = sock_error(sk); goto out; do_interrupted: if (msg_len) err = msg_len; goto out; #endif /* 0 */ } /* This is an extended version of skb_pull() that removes the data from the * start of a skb even when data is spread across the list of skb's in the * frag_list. len specifies the total amount of data that needs to be removed. * when 'len' bytes could be removed from the skb, it returns 0. * If 'len' exceeds the total skb length, it returns the no. of bytes that * could not be removed. */ static int sctp_skb_pull(struct sk_buff *skb, int len) { struct sk_buff *list; int skb_len = skb_headlen(skb); int rlen; if (len <= skb_len) { __skb_pull(skb, len); return 0; } len -= skb_len; __skb_pull(skb, skb_len); skb_walk_frags(skb, list) { rlen = sctp_skb_pull(list, len); skb->len -= (len-rlen); skb->data_len -= (len-rlen); if (!rlen) return 0; len = rlen; } return len; } /* API 3.1.3 recvmsg() - UDP Style Syntax * * ssize_t recvmsg(int socket, struct msghdr *message, * int flags); * * socket - the socket descriptor of the endpoint. * message - pointer to the msghdr structure which contains a single * user message and possibly some ancillary data. * * See Section 5 for complete description of the data * structures. * * flags - flags sent or received with the user message, see Section * 5 for complete description of the flags. */ static int sctp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct sctp_ulpevent *event = NULL; struct sctp_sock *sp = sctp_sk(sk); struct sk_buff *skb, *head_skb; int copied; int err = 0; int skb_len; pr_debug("%s: sk:%p, msghdr:%p, len:%zd, noblock:%d, flags:0x%x, " "addr_len:%p)\n", __func__, sk, msg, len, noblock, flags, addr_len); lock_sock(sk); if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED) && !sctp_sstate(sk, CLOSING) && !sctp_sstate(sk, CLOSED)) { err = -ENOTCONN; goto out; } skb = sctp_skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; /* Get the total length of the skb including any skb's in the * frag_list. */ skb_len = skb->len; copied = skb_len; if (copied > len) copied = len; err = skb_copy_datagram_msg(skb, 0, msg, copied); event = sctp_skb2event(skb); if (err) goto out_free; if (event->chunk && event->chunk->head_skb) head_skb = event->chunk->head_skb; else head_skb = skb; sock_recv_ts_and_drops(msg, sk, head_skb); if (sctp_ulpevent_is_notification(event)) { msg->msg_flags |= MSG_NOTIFICATION; sp->pf->event_msgname(event, msg->msg_name, addr_len); } else { sp->pf->skb_msgname(head_skb, msg->msg_name, addr_len); } /* Check if we allow SCTP_NXTINFO. */ if (sp->recvnxtinfo) sctp_ulpevent_read_nxtinfo(event, msg, sk); /* Check if we allow SCTP_RCVINFO. */ if (sp->recvrcvinfo) sctp_ulpevent_read_rcvinfo(event, msg); /* Check if we allow SCTP_SNDRCVINFO. */ if (sp->subscribe.sctp_data_io_event) sctp_ulpevent_read_sndrcvinfo(event, msg); err = copied; /* If skb's length exceeds the user's buffer, update the skb and * push it back to the receive_queue so that the next call to * recvmsg() will return the remaining data. Don't set MSG_EOR. */ if (skb_len > copied) { msg->msg_flags &= ~MSG_EOR; if (flags & MSG_PEEK) goto out_free; sctp_skb_pull(skb, copied); skb_queue_head(&sk->sk_receive_queue, skb); /* When only partial message is copied to the user, increase * rwnd by that amount. If all the data in the skb is read, * rwnd is updated when the event is freed. */ if (!sctp_ulpevent_is_notification(event)) sctp_assoc_rwnd_increase(event->asoc, copied); goto out; } else if ((event->msg_flags & MSG_NOTIFICATION) || (event->msg_flags & MSG_EOR)) msg->msg_flags |= MSG_EOR; else msg->msg_flags &= ~MSG_EOR; out_free: if (flags & MSG_PEEK) { /* Release the skb reference acquired after peeking the skb in * sctp_skb_recv_datagram(). */ kfree_skb(skb); } else { /* Free the event which includes releasing the reference to * the owner of the skb, freeing the skb and updating the * rwnd. */ sctp_ulpevent_free(event); } out: release_sock(sk); return err; } /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS) * * This option is a on/off flag. If enabled no SCTP message * fragmentation will be performed. Instead if a message being sent * exceeds the current PMTU size, the message will NOT be sent and * instead a error will be indicated to the user. */ static int sctp_setsockopt_disable_fragments(struct sock *sk, char __user *optval, unsigned int optlen) { int val; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1; return 0; } static int sctp_setsockopt_events(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_association *asoc; struct sctp_ulpevent *event; if (optlen > sizeof(struct sctp_event_subscribe)) return -EINVAL; if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen)) return -EFAULT; /* At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT, * if there is no data to be sent or retransmit, the stack will * immediately send up this notification. */ if (sctp_ulpevent_type_enabled(SCTP_SENDER_DRY_EVENT, &sctp_sk(sk)->subscribe)) { asoc = sctp_id2assoc(sk, 0); if (asoc && sctp_outq_is_empty(&asoc->outqueue)) { event = sctp_ulpevent_make_sender_dry_event(asoc, GFP_ATOMIC); if (!event) return -ENOMEM; sctp_ulpq_tail_event(&asoc->ulpq, event); } } return 0; } /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE) * * This socket option is applicable to the UDP-style socket only. When * set it will cause associations that are idle for more than the * specified number of seconds to automatically close. An association * being idle is defined an association that has NOT sent or received * user data. The special value of '0' indicates that no automatic * close of any associations should be performed. The option expects an * integer defining the number of seconds of idle time before an * association is closed. */ static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_sock *sp = sctp_sk(sk); struct net *net = sock_net(sk); /* Applicable to UDP-style socket only */ if (sctp_style(sk, TCP)) return -EOPNOTSUPP; if (optlen != sizeof(int)) return -EINVAL; if (copy_from_user(&sp->autoclose, optval, optlen)) return -EFAULT; if (sp->autoclose > net->sctp.max_autoclose) sp->autoclose = net->sctp.max_autoclose; return 0; } /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS) * * Applications can enable or disable heartbeats for any peer address of * an association, modify an address's heartbeat interval, force a * heartbeat to be sent immediately, and adjust the address's maximum * number of retransmissions sent before an address is considered * unreachable. The following structure is used to access and modify an * address's parameters: * * struct sctp_paddrparams { * sctp_assoc_t spp_assoc_id; * struct sockaddr_storage spp_address; * uint32_t spp_hbinterval; * uint16_t spp_pathmaxrxt; * uint32_t spp_pathmtu; * uint32_t spp_sackdelay; * uint32_t spp_flags; * }; * * spp_assoc_id - (one-to-many style socket) This is filled in the * application, and identifies the association for * this query. * spp_address - This specifies which address is of interest. * spp_hbinterval - This contains the value of the heartbeat interval, * in milliseconds. If a value of zero * is present in this field then no changes are to * be made to this parameter. * spp_pathmaxrxt - This contains the maximum number of * retransmissions before this address shall be * considered unreachable. If a value of zero * is present in this field then no changes are to * be made to this parameter. * spp_pathmtu - When Path MTU discovery is disabled the value * specified here will be the "fixed" path mtu. * Note that if the spp_address field is empty * then all associations on this address will * have this fixed path mtu set upon them. * * spp_sackdelay - When delayed sack is enabled, this value specifies * the number of milliseconds that sacks will be delayed * for. This value will apply to all addresses of an * association if the spp_address field is empty. Note * also, that if delayed sack is enabled and this * value is set to 0, no change is made to the last * recorded delayed sack timer value. * * spp_flags - These flags are used to control various features * on an association. The flag field may contain * zero or more of the following options. * * SPP_HB_ENABLE - Enable heartbeats on the * specified address. Note that if the address * field is empty all addresses for the association * have heartbeats enabled upon them. * * SPP_HB_DISABLE - Disable heartbeats on the * speicifed address. Note that if the address * field is empty all addresses for the association * will have their heartbeats disabled. Note also * that SPP_HB_ENABLE and SPP_HB_DISABLE are * mutually exclusive, only one of these two should * be specified. Enabling both fields will have * undetermined results. * * SPP_HB_DEMAND - Request a user initiated heartbeat * to be made immediately. * * SPP_HB_TIME_IS_ZERO - Specify's that the time for * heartbeat delayis to be set to the value of 0 * milliseconds. * * SPP_PMTUD_ENABLE - This field will enable PMTU * discovery upon the specified address. Note that * if the address feild is empty then all addresses * on the association are effected. * * SPP_PMTUD_DISABLE - This field will disable PMTU * discovery upon the specified address. Note that * if the address feild is empty then all addresses * on the association are effected. Not also that * SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually * exclusive. Enabling both will have undetermined * results. * * SPP_SACKDELAY_ENABLE - Setting this flag turns * on delayed sack. The time specified in spp_sackdelay * is used to specify the sack delay for this address. Note * that if spp_address is empty then all addresses will * enable delayed sack and take on the sack delay * value specified in spp_sackdelay. * SPP_SACKDELAY_DISABLE - Setting this flag turns * off delayed sack. If the spp_address field is blank then * delayed sack is disabled for the entire association. Note * also that this field is mutually exclusive to * SPP_SACKDELAY_ENABLE, setting both will have undefined * results. */ static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params, struct sctp_transport *trans, struct sctp_association *asoc, struct sctp_sock *sp, int hb_change, int pmtud_change, int sackdelay_change) { int error; if (params->spp_flags & SPP_HB_DEMAND && trans) { struct net *net = sock_net(trans->asoc->base.sk); error = sctp_primitive_REQUESTHEARTBEAT(net, trans->asoc, trans); if (error) return error; } /* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of * this field is ignored. Note also that a value of zero indicates * the current setting should be left unchanged. */ if (params->spp_flags & SPP_HB_ENABLE) { /* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is * set. This lets us use 0 value when this flag * is set. */ if (params->spp_flags & SPP_HB_TIME_IS_ZERO) params->spp_hbinterval = 0; if (params->spp_hbinterval || (params->spp_flags & SPP_HB_TIME_IS_ZERO)) { if (trans) { trans->hbinterval = msecs_to_jiffies(params->spp_hbinterval); } else if (asoc) { asoc->hbinterval = msecs_to_jiffies(params->spp_hbinterval); } else { sp->hbinterval = params->spp_hbinterval; } } } if (hb_change) { if (trans) { trans->param_flags = (trans->param_flags & ~SPP_HB) | hb_change; } else if (asoc) { asoc->param_flags = (asoc->param_flags & ~SPP_HB) | hb_change; } else { sp->param_flags = (sp->param_flags & ~SPP_HB) | hb_change; } } /* When Path MTU discovery is disabled the value specified here will * be the "fixed" path mtu (i.e. the value of the spp_flags field must * include the flag SPP_PMTUD_DISABLE for this field to have any * effect). */ if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) { if (trans) { trans->pathmtu = params->spp_pathmtu; sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc); } else if (asoc) { asoc->pathmtu = params->spp_pathmtu; } else { sp->pathmtu = params->spp_pathmtu; } } if (pmtud_change) { if (trans) { int update = (trans->param_flags & SPP_PMTUD_DISABLE) && (params->spp_flags & SPP_PMTUD_ENABLE); trans->param_flags = (trans->param_flags & ~SPP_PMTUD) | pmtud_change; if (update) { sctp_transport_pmtu(trans, sctp_opt2sk(sp)); sctp_assoc_sync_pmtu(sctp_opt2sk(sp), asoc); } } else if (asoc) { asoc->param_flags = (asoc->param_flags & ~SPP_PMTUD) | pmtud_change; } else { sp->param_flags = (sp->param_flags & ~SPP_PMTUD) | pmtud_change; } } /* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the * value of this field is ignored. Note also that a value of zero * indicates the current setting should be left unchanged. */ if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) { if (trans) { trans->sackdelay = msecs_to_jiffies(params->spp_sackdelay); } else if (asoc) { asoc->sackdelay = msecs_to_jiffies(params->spp_sackdelay); } else { sp->sackdelay = params->spp_sackdelay; } } if (sackdelay_change) { if (trans) { trans->param_flags = (trans->param_flags & ~SPP_SACKDELAY) | sackdelay_change; } else if (asoc) { asoc->param_flags = (asoc->param_flags & ~SPP_SACKDELAY) | sackdelay_change; } else { sp->param_flags = (sp->param_flags & ~SPP_SACKDELAY) | sackdelay_change; } } /* Note that a value of zero indicates the current setting should be left unchanged. */ if (params->spp_pathmaxrxt) { if (trans) { trans->pathmaxrxt = params->spp_pathmaxrxt; } else if (asoc) { asoc->pathmaxrxt = params->spp_pathmaxrxt; } else { sp->pathmaxrxt = params->spp_pathmaxrxt; } } return 0; } static int sctp_setsockopt_peer_addr_params(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_paddrparams params; struct sctp_transport *trans = NULL; struct sctp_association *asoc = NULL; struct sctp_sock *sp = sctp_sk(sk); int error; int hb_change, pmtud_change, sackdelay_change; if (optlen != sizeof(struct sctp_paddrparams)) return -EINVAL; if (copy_from_user(&params, optval, optlen)) return -EFAULT; /* Validate flags and value parameters. */ hb_change = params.spp_flags & SPP_HB; pmtud_change = params.spp_flags & SPP_PMTUD; sackdelay_change = params.spp_flags & SPP_SACKDELAY; if (hb_change == SPP_HB || pmtud_change == SPP_PMTUD || sackdelay_change == SPP_SACKDELAY || params.spp_sackdelay > 500 || (params.spp_pathmtu && params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT)) return -EINVAL; /* If an address other than INADDR_ANY is specified, and * no transport is found, then the request is invalid. */ if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) { trans = sctp_addr_id2transport(sk, &params.spp_address, params.spp_assoc_id); if (!trans) return -EINVAL; } /* Get association, if assoc_id != 0 and the socket is a one * to many style socket, and an association was not found, then * the id was invalid. */ asoc = sctp_id2assoc(sk, params.spp_assoc_id); if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) return -EINVAL; /* Heartbeat demand can only be sent on a transport or * association, but not a socket. */ if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc) return -EINVAL; /* Process parameters. */ error = sctp_apply_peer_addr_params(&params, trans, asoc, sp, hb_change, pmtud_change, sackdelay_change); if (error) return error; /* If changes are for association, also apply parameters to each * transport. */ if (!trans && asoc) { list_for_each_entry(trans, &asoc->peer.transport_addr_list, transports) { sctp_apply_peer_addr_params(&params, trans, asoc, sp, hb_change, pmtud_change, sackdelay_change); } } return 0; } static inline __u32 sctp_spp_sackdelay_enable(__u32 param_flags) { return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_ENABLE; } static inline __u32 sctp_spp_sackdelay_disable(__u32 param_flags) { return (param_flags & ~SPP_SACKDELAY) | SPP_SACKDELAY_DISABLE; } /* * 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK) * * This option will effect the way delayed acks are performed. This * option allows you to get or set the delayed ack time, in * milliseconds. It also allows changing the delayed ack frequency. * Changing the frequency to 1 disables the delayed sack algorithm. If * the assoc_id is 0, then this sets or gets the endpoints default * values. If the assoc_id field is non-zero, then the set or get * effects the specified association for the one to many model (the * assoc_id field is ignored by the one to one model). Note that if * sack_delay or sack_freq are 0 when setting this option, then the * current values will remain unchanged. * * struct sctp_sack_info { * sctp_assoc_t sack_assoc_id; * uint32_t sack_delay; * uint32_t sack_freq; * }; * * sack_assoc_id - This parameter, indicates which association the user * is performing an action upon. Note that if this field's value is * zero then the endpoints default value is changed (effecting future * associations only). * * sack_delay - This parameter contains the number of milliseconds that * the user is requesting the delayed ACK timer be set to. Note that * this value is defined in the standard to be between 200 and 500 * milliseconds. * * sack_freq - This parameter contains the number of packets that must * be received before a sack is sent without waiting for the delay * timer to expire. The default value for this is 2, setting this * value to 1 will disable the delayed sack algorithm. */ static int sctp_setsockopt_delayed_ack(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_sack_info params; struct sctp_transport *trans = NULL; struct sctp_association *asoc = NULL; struct sctp_sock *sp = sctp_sk(sk); if (optlen == sizeof(struct sctp_sack_info)) { if (copy_from_user(&params, optval, optlen)) return -EFAULT; if (params.sack_delay == 0 && params.sack_freq == 0) return 0; } else if (optlen == sizeof(struct sctp_assoc_value)) { pr_warn_ratelimited(DEPRECATED "%s (pid %d) " "Use of struct sctp_assoc_value in delayed_ack socket option.\n" "Use struct sctp_sack_info instead\n", current->comm, task_pid_nr(current)); if (copy_from_user(&params, optval, optlen)) return -EFAULT; if (params.sack_delay == 0) params.sack_freq = 1; else params.sack_freq = 0; } else return -EINVAL; /* Validate value parameter. */ if (params.sack_delay > 500) return -EINVAL; /* Get association, if sack_assoc_id != 0 and the socket is a one * to many style socket, and an association was not found, then * the id was invalid. */ asoc = sctp_id2assoc(sk, params.sack_assoc_id); if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (params.sack_delay) { if (asoc) { asoc->sackdelay = msecs_to_jiffies(params.sack_delay); asoc->param_flags = sctp_spp_sackdelay_enable(asoc->param_flags); } else { sp->sackdelay = params.sack_delay; sp->param_flags = sctp_spp_sackdelay_enable(sp->param_flags); } } if (params.sack_freq == 1) { if (asoc) { asoc->param_flags = sctp_spp_sackdelay_disable(asoc->param_flags); } else { sp->param_flags = sctp_spp_sackdelay_disable(sp->param_flags); } } else if (params.sack_freq > 1) { if (asoc) { asoc->sackfreq = params.sack_freq; asoc->param_flags = sctp_spp_sackdelay_enable(asoc->param_flags); } else { sp->sackfreq = params.sack_freq; sp->param_flags = sctp_spp_sackdelay_enable(sp->param_flags); } } /* If change is for association, also apply to each transport. */ if (asoc) { list_for_each_entry(trans, &asoc->peer.transport_addr_list, transports) { if (params.sack_delay) { trans->sackdelay = msecs_to_jiffies(params.sack_delay); trans->param_flags = sctp_spp_sackdelay_enable(trans->param_flags); } if (params.sack_freq == 1) { trans->param_flags = sctp_spp_sackdelay_disable(trans->param_flags); } else if (params.sack_freq > 1) { trans->sackfreq = params.sack_freq; trans->param_flags = sctp_spp_sackdelay_enable(trans->param_flags); } } } return 0; } /* 7.1.3 Initialization Parameters (SCTP_INITMSG) * * Applications can specify protocol parameters for the default association * initialization. The option name argument to setsockopt() and getsockopt() * is SCTP_INITMSG. * * Setting initialization parameters is effective only on an unconnected * socket (for UDP-style sockets only future associations are effected * by the change). With TCP-style sockets, this option is inherited by * sockets derived from a listener socket. */ static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_initmsg sinit; struct sctp_sock *sp = sctp_sk(sk); if (optlen != sizeof(struct sctp_initmsg)) return -EINVAL; if (copy_from_user(&sinit, optval, optlen)) return -EFAULT; if (sinit.sinit_num_ostreams) sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams; if (sinit.sinit_max_instreams) sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams; if (sinit.sinit_max_attempts) sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts; if (sinit.sinit_max_init_timeo) sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo; return 0; } /* * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM) * * Applications that wish to use the sendto() system call may wish to * specify a default set of parameters that would normally be supplied * through the inclusion of ancillary data. This socket option allows * such an application to set the default sctp_sndrcvinfo structure. * The application that wishes to use this socket option simply passes * in to this call the sctp_sndrcvinfo structure defined in Section * 5.2.2) The input parameters accepted by this call include * sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context, * sinfo_timetolive. The user must provide the sinfo_assoc_id field in * to this call if the caller is using the UDP model. */ static int sctp_setsockopt_default_send_param(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_association *asoc; struct sctp_sndrcvinfo info; if (optlen != sizeof(info)) return -EINVAL; if (copy_from_user(&info, optval, optlen)) return -EFAULT; if (info.sinfo_flags & ~(SCTP_UNORDERED | SCTP_ADDR_OVER | SCTP_ABORT | SCTP_EOF)) return -EINVAL; asoc = sctp_id2assoc(sk, info.sinfo_assoc_id); if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) { asoc->default_stream = info.sinfo_stream; asoc->default_flags = info.sinfo_flags; asoc->default_ppid = info.sinfo_ppid; asoc->default_context = info.sinfo_context; asoc->default_timetolive = info.sinfo_timetolive; } else { sp->default_stream = info.sinfo_stream; sp->default_flags = info.sinfo_flags; sp->default_ppid = info.sinfo_ppid; sp->default_context = info.sinfo_context; sp->default_timetolive = info.sinfo_timetolive; } return 0; } /* RFC6458, Section 8.1.31. Set/get Default Send Parameters * (SCTP_DEFAULT_SNDINFO) */ static int sctp_setsockopt_default_sndinfo(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_association *asoc; struct sctp_sndinfo info; if (optlen != sizeof(info)) return -EINVAL; if (copy_from_user(&info, optval, optlen)) return -EFAULT; if (info.snd_flags & ~(SCTP_UNORDERED | SCTP_ADDR_OVER | SCTP_ABORT | SCTP_EOF)) return -EINVAL; asoc = sctp_id2assoc(sk, info.snd_assoc_id); if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) { asoc->default_stream = info.snd_sid; asoc->default_flags = info.snd_flags; asoc->default_ppid = info.snd_ppid; asoc->default_context = info.snd_context; } else { sp->default_stream = info.snd_sid; sp->default_flags = info.snd_flags; sp->default_ppid = info.snd_ppid; sp->default_context = info.snd_context; } return 0; } /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR) * * Requests that the local SCTP stack use the enclosed peer address as * the association primary. The enclosed address must be one of the * association peer's addresses. */ static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_prim prim; struct sctp_transport *trans; if (optlen != sizeof(struct sctp_prim)) return -EINVAL; if (copy_from_user(&prim, optval, sizeof(struct sctp_prim))) return -EFAULT; trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id); if (!trans) return -EINVAL; sctp_assoc_set_primary(trans->asoc, trans); return 0; } /* * 7.1.5 SCTP_NODELAY * * Turn on/off any Nagle-like algorithm. This means that packets are * generally sent as soon as possible and no unnecessary delays are * introduced, at the cost of more packets in the network. Expects an * integer boolean flag. */ static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval, unsigned int optlen) { int val; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1; return 0; } /* * * 7.1.1 SCTP_RTOINFO * * The protocol parameters used to initialize and bound retransmission * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access * and modify these parameters. * All parameters are time values, in milliseconds. A value of 0, when * modifying the parameters, indicates that the current value should not * be changed. * */ static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_rtoinfo rtoinfo; struct sctp_association *asoc; unsigned long rto_min, rto_max; struct sctp_sock *sp = sctp_sk(sk); if (optlen != sizeof (struct sctp_rtoinfo)) return -EINVAL; if (copy_from_user(&rtoinfo, optval, optlen)) return -EFAULT; asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id); /* Set the values to the specific association */ if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP)) return -EINVAL; rto_max = rtoinfo.srto_max; rto_min = rtoinfo.srto_min; if (rto_max) rto_max = asoc ? msecs_to_jiffies(rto_max) : rto_max; else rto_max = asoc ? asoc->rto_max : sp->rtoinfo.srto_max; if (rto_min) rto_min = asoc ? msecs_to_jiffies(rto_min) : rto_min; else rto_min = asoc ? asoc->rto_min : sp->rtoinfo.srto_min; if (rto_min > rto_max) return -EINVAL; if (asoc) { if (rtoinfo.srto_initial != 0) asoc->rto_initial = msecs_to_jiffies(rtoinfo.srto_initial); asoc->rto_max = rto_max; asoc->rto_min = rto_min; } else { /* If there is no association or the association-id = 0 * set the values to the endpoint. */ if (rtoinfo.srto_initial != 0) sp->rtoinfo.srto_initial = rtoinfo.srto_initial; sp->rtoinfo.srto_max = rto_max; sp->rtoinfo.srto_min = rto_min; } return 0; } /* * * 7.1.2 SCTP_ASSOCINFO * * This option is used to tune the maximum retransmission attempts * of the association. * Returns an error if the new association retransmission value is * greater than the sum of the retransmission value of the peer. * See [SCTP] for more information. * */ static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_assocparams assocparams; struct sctp_association *asoc; if (optlen != sizeof(struct sctp_assocparams)) return -EINVAL; if (copy_from_user(&assocparams, optval, optlen)) return -EFAULT; asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id); if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP)) return -EINVAL; /* Set the values to the specific association */ if (asoc) { if (assocparams.sasoc_asocmaxrxt != 0) { __u32 path_sum = 0; int paths = 0; struct sctp_transport *peer_addr; list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list, transports) { path_sum += peer_addr->pathmaxrxt; paths++; } /* Only validate asocmaxrxt if we have more than * one path/transport. We do this because path * retransmissions are only counted when we have more * then one path. */ if (paths > 1 && assocparams.sasoc_asocmaxrxt > path_sum) return -EINVAL; asoc->max_retrans = assocparams.sasoc_asocmaxrxt; } if (assocparams.sasoc_cookie_life != 0) asoc->cookie_life = ms_to_ktime(assocparams.sasoc_cookie_life); } else { /* Set the values to the endpoint */ struct sctp_sock *sp = sctp_sk(sk); if (assocparams.sasoc_asocmaxrxt != 0) sp->assocparams.sasoc_asocmaxrxt = assocparams.sasoc_asocmaxrxt; if (assocparams.sasoc_cookie_life != 0) sp->assocparams.sasoc_cookie_life = assocparams.sasoc_cookie_life; } return 0; } /* * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR) * * This socket option is a boolean flag which turns on or off mapped V4 * addresses. If this option is turned on and the socket is type * PF_INET6, then IPv4 addresses will be mapped to V6 representation. * If this option is turned off, then no mapping will be done of V4 * addresses and a user will receive both PF_INET6 and PF_INET type * addresses on the socket. */ static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, unsigned int optlen) { int val; struct sctp_sock *sp = sctp_sk(sk); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; if (val) sp->v4mapped = 1; else sp->v4mapped = 0; return 0; } /* * 8.1.16. Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG) * This option will get or set the maximum size to put in any outgoing * SCTP DATA chunk. If a message is larger than this size it will be * fragmented by SCTP into the specified size. Note that the underlying * SCTP implementation may fragment into smaller sized chunks when the * PMTU of the underlying association is smaller than the value set by * the user. The default value for this option is '0' which indicates * the user is NOT limiting fragmentation and only the PMTU will effect * SCTP's choice of DATA chunk size. Note also that values set larger * than the maximum size of an IP datagram will effectively let SCTP * control fragmentation (i.e. the same as setting this option to 0). * * The following structure is used to access and modify this parameter: * * struct sctp_assoc_value { * sctp_assoc_t assoc_id; * uint32_t assoc_value; * }; * * assoc_id: This parameter is ignored for one-to-one style sockets. * For one-to-many style sockets this parameter indicates which * association the user is performing an action upon. Note that if * this field's value is zero then the endpoints default value is * changed (effecting future associations only). * assoc_value: This parameter specifies the maximum size in bytes. */ static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_assoc_value params; struct sctp_association *asoc; struct sctp_sock *sp = sctp_sk(sk); int val; if (optlen == sizeof(int)) { pr_warn_ratelimited(DEPRECATED "%s (pid %d) " "Use of int in maxseg socket option.\n" "Use struct sctp_assoc_value instead\n", current->comm, task_pid_nr(current)); if (copy_from_user(&val, optval, optlen)) return -EFAULT; params.assoc_id = 0; } else if (optlen == sizeof(struct sctp_assoc_value)) { if (copy_from_user(&params, optval, optlen)) return -EFAULT; val = params.assoc_value; } else return -EINVAL; if ((val != 0) && ((val < 8) || (val > SCTP_MAX_CHUNK_LEN))) return -EINVAL; asoc = sctp_id2assoc(sk, params.assoc_id); if (!asoc && params.assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) { if (val == 0) { val = asoc->pathmtu; val -= sp->pf->af->net_header_len; val -= sizeof(struct sctphdr) + sizeof(struct sctp_data_chunk); } asoc->user_frag = val; asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu); } else { sp->user_frag = val; } return 0; } /* * 7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR) * * Requests that the peer mark the enclosed address as the association * primary. The enclosed address must be one of the association's * locally bound addresses. The following structure is used to make a * set primary request: */ static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval, unsigned int optlen) { struct net *net = sock_net(sk); struct sctp_sock *sp; struct sctp_association *asoc = NULL; struct sctp_setpeerprim prim; struct sctp_chunk *chunk; struct sctp_af *af; int err; sp = sctp_sk(sk); if (!net->sctp.addip_enable) return -EPERM; if (optlen != sizeof(struct sctp_setpeerprim)) return -EINVAL; if (copy_from_user(&prim, optval, optlen)) return -EFAULT; asoc = sctp_id2assoc(sk, prim.sspp_assoc_id); if (!asoc) return -EINVAL; if (!asoc->peer.asconf_capable) return -EPERM; if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY) return -EPERM; if (!sctp_state(asoc, ESTABLISHED)) return -ENOTCONN; af = sctp_get_af_specific(prim.sspp_addr.ss_family); if (!af) return -EINVAL; if (!af->addr_valid((union sctp_addr *)&prim.sspp_addr, sp, NULL)) return -EADDRNOTAVAIL; if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr)) return -EADDRNOTAVAIL; /* Create an ASCONF chunk with SET_PRIMARY parameter */ chunk = sctp_make_asconf_set_prim(asoc, (union sctp_addr *)&prim.sspp_addr); if (!chunk) return -ENOMEM; err = sctp_send_asconf(asoc, chunk); pr_debug("%s: we set peer primary addr primitively\n", __func__); return err; } static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_setadaptation adaptation; if (optlen != sizeof(struct sctp_setadaptation)) return -EINVAL; if (copy_from_user(&adaptation, optval, optlen)) return -EFAULT; sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind; return 0; } /* * 7.1.29. Set or Get the default context (SCTP_CONTEXT) * * The context field in the sctp_sndrcvinfo structure is normally only * used when a failed message is retrieved holding the value that was * sent down on the actual send call. This option allows the setting of * a default context on an association basis that will be received on * reading messages from the peer. This is especially helpful in the * one-2-many model for an application to keep some reference to an * internal state machine that is processing messages on the * association. Note that the setting of this value only effects * received messages from the peer and does not effect the value that is * saved with outbound messages. */ static int sctp_setsockopt_context(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_assoc_value params; struct sctp_sock *sp; struct sctp_association *asoc; if (optlen != sizeof(struct sctp_assoc_value)) return -EINVAL; if (copy_from_user(&params, optval, optlen)) return -EFAULT; sp = sctp_sk(sk); if (params.assoc_id != 0) { asoc = sctp_id2assoc(sk, params.assoc_id); if (!asoc) return -EINVAL; asoc->default_rcv_context = params.assoc_value; } else { sp->default_rcv_context = params.assoc_value; } return 0; } /* * 7.1.24. Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE) * * This options will at a minimum specify if the implementation is doing * fragmented interleave. Fragmented interleave, for a one to many * socket, is when subsequent calls to receive a message may return * parts of messages from different associations. Some implementations * may allow you to turn this value on or off. If so, when turned off, * no fragment interleave will occur (which will cause a head of line * blocking amongst multiple associations sharing the same one to many * socket). When this option is turned on, then each receive call may * come from a different association (thus the user must receive data * with the extended calls (e.g. sctp_recvmsg) to keep track of which * association each receive belongs to. * * This option takes a boolean value. A non-zero value indicates that * fragmented interleave is on. A value of zero indicates that * fragmented interleave is off. * * Note that it is important that an implementation that allows this * option to be turned on, have it off by default. Otherwise an unaware * application using the one to many model may become confused and act * incorrectly. */ static int sctp_setsockopt_fragment_interleave(struct sock *sk, char __user *optval, unsigned int optlen) { int val; if (optlen != sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1; return 0; } /* * 8.1.21. Set or Get the SCTP Partial Delivery Point * (SCTP_PARTIAL_DELIVERY_POINT) * * This option will set or get the SCTP partial delivery point. This * point is the size of a message where the partial delivery API will be * invoked to help free up rwnd space for the peer. Setting this to a * lower value will cause partial deliveries to happen more often. The * calls argument is an integer that sets or gets the partial delivery * point. Note also that the call will fail if the user attempts to set * this value larger than the socket receive buffer size. * * Note that any single message having a length smaller than or equal to * the SCTP partial delivery point will be delivered in one single read * call as long as the user provided buffer is large enough to hold the * message. */ static int sctp_setsockopt_partial_delivery_point(struct sock *sk, char __user *optval, unsigned int optlen) { u32 val; if (optlen != sizeof(u32)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; /* Note: We double the receive buffer from what the user sets * it to be, also initial rwnd is based on rcvbuf/2. */ if (val > (sk->sk_rcvbuf >> 1)) return -EINVAL; sctp_sk(sk)->pd_point = val; return 0; /* is this the right error code? */ } /* * 7.1.28. Set or Get the maximum burst (SCTP_MAX_BURST) * * This option will allow a user to change the maximum burst of packets * that can be emitted by this association. Note that the default value * is 4, and some implementations may restrict this setting so that it * can only be lowered. * * NOTE: This text doesn't seem right. Do this on a socket basis with * future associations inheriting the socket value. */ static int sctp_setsockopt_maxburst(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_assoc_value params; struct sctp_sock *sp; struct sctp_association *asoc; int val; int assoc_id = 0; if (optlen == sizeof(int)) { pr_warn_ratelimited(DEPRECATED "%s (pid %d) " "Use of int in max_burst socket option deprecated.\n" "Use struct sctp_assoc_value instead\n", current->comm, task_pid_nr(current)); if (copy_from_user(&val, optval, optlen)) return -EFAULT; } else if (optlen == sizeof(struct sctp_assoc_value)) { if (copy_from_user(&params, optval, optlen)) return -EFAULT; val = params.assoc_value; assoc_id = params.assoc_id; } else return -EINVAL; sp = sctp_sk(sk); if (assoc_id != 0) { asoc = sctp_id2assoc(sk, assoc_id); if (!asoc) return -EINVAL; asoc->max_burst = val; } else sp->max_burst = val; return 0; } /* * 7.1.18. Add a chunk that must be authenticated (SCTP_AUTH_CHUNK) * * This set option adds a chunk type that the user is requesting to be * received only in an authenticated way. Changes to the list of chunks * will only effect future associations on the socket. */ static int sctp_setsockopt_auth_chunk(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authchunk val; if (!ep->auth_enable) return -EACCES; if (optlen != sizeof(struct sctp_authchunk)) return -EINVAL; if (copy_from_user(&val, optval, optlen)) return -EFAULT; switch (val.sauth_chunk) { case SCTP_CID_INIT: case SCTP_CID_INIT_ACK: case SCTP_CID_SHUTDOWN_COMPLETE: case SCTP_CID_AUTH: return -EINVAL; } /* add this chunk id to the endpoint */ return sctp_auth_ep_add_chunkid(ep, val.sauth_chunk); } /* * 7.1.19. Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT) * * This option gets or sets the list of HMAC algorithms that the local * endpoint requires the peer to use. */ static int sctp_setsockopt_hmac_ident(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_hmacalgo *hmacs; u32 idents; int err; if (!ep->auth_enable) return -EACCES; if (optlen < sizeof(struct sctp_hmacalgo)) return -EINVAL; hmacs = memdup_user(optval, optlen); if (IS_ERR(hmacs)) return PTR_ERR(hmacs); idents = hmacs->shmac_num_idents; if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS || (idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo))) { err = -EINVAL; goto out; } err = sctp_auth_ep_set_hmacs(ep, hmacs); out: kfree(hmacs); return err; } /* * 7.1.20. Set a shared key (SCTP_AUTH_KEY) * * This option will set a shared secret key which is used to build an * association shared key. */ static int sctp_setsockopt_auth_key(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authkey *authkey; struct sctp_association *asoc; int ret; if (!ep->auth_enable) return -EACCES; if (optlen <= sizeof(struct sctp_authkey)) return -EINVAL; authkey = memdup_user(optval, optlen); if (IS_ERR(authkey)) return PTR_ERR(authkey); if (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) { ret = -EINVAL; goto out; } asoc = sctp_id2assoc(sk, authkey->sca_assoc_id); if (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) { ret = -EINVAL; goto out; } ret = sctp_auth_set_key(ep, asoc, authkey); out: kzfree(authkey); return ret; } /* * 7.1.21. Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY) * * This option will get or set the active shared key to be used to build * the association shared key. */ static int sctp_setsockopt_active_key(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authkeyid val; struct sctp_association *asoc; if (!ep->auth_enable) return -EACCES; if (optlen != sizeof(struct sctp_authkeyid)) return -EINVAL; if (copy_from_user(&val, optval, optlen)) return -EFAULT; asoc = sctp_id2assoc(sk, val.scact_assoc_id); if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP)) return -EINVAL; return sctp_auth_set_active_key(ep, asoc, val.scact_keynumber); } /* * 7.1.22. Delete a shared key (SCTP_AUTH_DELETE_KEY) * * This set option will delete a shared secret key from use. */ static int sctp_setsockopt_del_key(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authkeyid val; struct sctp_association *asoc; if (!ep->auth_enable) return -EACCES; if (optlen != sizeof(struct sctp_authkeyid)) return -EINVAL; if (copy_from_user(&val, optval, optlen)) return -EFAULT; asoc = sctp_id2assoc(sk, val.scact_assoc_id); if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP)) return -EINVAL; return sctp_auth_del_key_id(ep, asoc, val.scact_keynumber); } /* * 8.1.23 SCTP_AUTO_ASCONF * * This option will enable or disable the use of the automatic generation of * ASCONF chunks to add and delete addresses to an existing association. Note * that this option has two caveats namely: a) it only affects sockets that * are bound to all addresses available to the SCTP stack, and b) the system * administrator may have an overriding control that turns the ASCONF feature * off no matter what setting the socket option may have. * This option expects an integer boolean flag, where a non-zero value turns on * the option, and a zero value turns off the option. * Note. In this implementation, socket operation overrides default parameter * being set by sysctl as well as FreeBSD implementation */ static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval, unsigned int optlen) { int val; struct sctp_sock *sp = sctp_sk(sk); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; if (!sctp_is_ep_boundall(sk) && val) return -EINVAL; if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf)) return 0; spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock); if (val == 0 && sp->do_auto_asconf) { list_del(&sp->auto_asconf_list); sp->do_auto_asconf = 0; } else if (val && !sp->do_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &sock_net(sk)->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock); return 0; } /* * SCTP_PEER_ADDR_THLDS * * This option allows us to alter the partially failed threshold for one or all * transports in an association. See Section 6.1 of: * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt */ static int sctp_setsockopt_paddr_thresholds(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_paddrthlds val; struct sctp_transport *trans; struct sctp_association *asoc; if (optlen < sizeof(struct sctp_paddrthlds)) return -EINVAL; if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, sizeof(struct sctp_paddrthlds))) return -EFAULT; if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) { asoc = sctp_id2assoc(sk, val.spt_assoc_id); if (!asoc) return -ENOENT; list_for_each_entry(trans, &asoc->peer.transport_addr_list, transports) { if (val.spt_pathmaxrxt) trans->pathmaxrxt = val.spt_pathmaxrxt; trans->pf_retrans = val.spt_pathpfthld; } if (val.spt_pathmaxrxt) asoc->pathmaxrxt = val.spt_pathmaxrxt; asoc->pf_retrans = val.spt_pathpfthld; } else { trans = sctp_addr_id2transport(sk, &val.spt_address, val.spt_assoc_id); if (!trans) return -ENOENT; if (val.spt_pathmaxrxt) trans->pathmaxrxt = val.spt_pathmaxrxt; trans->pf_retrans = val.spt_pathpfthld; } return 0; } static int sctp_setsockopt_recvrcvinfo(struct sock *sk, char __user *optval, unsigned int optlen) { int val; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *) optval)) return -EFAULT; sctp_sk(sk)->recvrcvinfo = (val == 0) ? 0 : 1; return 0; } static int sctp_setsockopt_recvnxtinfo(struct sock *sk, char __user *optval, unsigned int optlen) { int val; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *) optval)) return -EFAULT; sctp_sk(sk)->recvnxtinfo = (val == 0) ? 0 : 1; return 0; } static int sctp_setsockopt_pr_supported(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_assoc_value params; struct sctp_association *asoc; int retval = -EINVAL; if (optlen != sizeof(params)) goto out; if (copy_from_user(&params, optval, optlen)) { retval = -EFAULT; goto out; } asoc = sctp_id2assoc(sk, params.assoc_id); if (asoc) { asoc->prsctp_enable = !!params.assoc_value; } else if (!params.assoc_id) { struct sctp_sock *sp = sctp_sk(sk); sp->ep->prsctp_enable = !!params.assoc_value; } else { goto out; } retval = 0; out: return retval; } static int sctp_setsockopt_default_prinfo(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_default_prinfo info; struct sctp_association *asoc; int retval = -EINVAL; if (optlen != sizeof(info)) goto out; if (copy_from_user(&info, optval, sizeof(info))) { retval = -EFAULT; goto out; } if (info.pr_policy & ~SCTP_PR_SCTP_MASK) goto out; if (info.pr_policy == SCTP_PR_SCTP_NONE) info.pr_value = 0; asoc = sctp_id2assoc(sk, info.pr_assoc_id); if (asoc) { SCTP_PR_SET_POLICY(asoc->default_flags, info.pr_policy); asoc->default_timetolive = info.pr_value; } else if (!info.pr_assoc_id) { struct sctp_sock *sp = sctp_sk(sk); SCTP_PR_SET_POLICY(sp->default_flags, info.pr_policy); sp->default_timetolive = info.pr_value; } else { goto out; } retval = 0; out: return retval; } static int sctp_setsockopt_enable_strreset(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_assoc_value params; struct sctp_association *asoc; int retval = -EINVAL; if (optlen != sizeof(params)) goto out; if (copy_from_user(&params, optval, optlen)) { retval = -EFAULT; goto out; } if (params.assoc_value & (~SCTP_ENABLE_STRRESET_MASK)) goto out; asoc = sctp_id2assoc(sk, params.assoc_id); if (asoc) { asoc->strreset_enable = params.assoc_value; } else if (!params.assoc_id) { struct sctp_sock *sp = sctp_sk(sk); sp->ep->strreset_enable = params.assoc_value; } else { goto out; } retval = 0; out: return retval; } static int sctp_setsockopt_reset_streams(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_reset_streams *params; struct sctp_association *asoc; int retval = -EINVAL; if (optlen < sizeof(struct sctp_reset_streams)) return -EINVAL; params = memdup_user(optval, optlen); if (IS_ERR(params)) return PTR_ERR(params); asoc = sctp_id2assoc(sk, params->srs_assoc_id); if (!asoc) goto out; retval = sctp_send_reset_streams(asoc, params); out: kfree(params); return retval; } static int sctp_setsockopt_reset_assoc(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_association *asoc; sctp_assoc_t associd; int retval = -EINVAL; if (optlen != sizeof(associd)) goto out; if (copy_from_user(&associd, optval, optlen)) { retval = -EFAULT; goto out; } asoc = sctp_id2assoc(sk, associd); if (!asoc) goto out; retval = sctp_send_reset_assoc(asoc); out: return retval; } static int sctp_setsockopt_add_streams(struct sock *sk, char __user *optval, unsigned int optlen) { struct sctp_association *asoc; struct sctp_add_streams params; int retval = -EINVAL; if (optlen != sizeof(params)) goto out; if (copy_from_user(&params, optval, optlen)) { retval = -EFAULT; goto out; } asoc = sctp_id2assoc(sk, params.sas_assoc_id); if (!asoc) goto out; retval = sctp_send_add_streams(asoc, &params); out: return retval; } /* API 6.2 setsockopt(), getsockopt() * * Applications use setsockopt() and getsockopt() to set or retrieve * socket options. Socket options are used to change the default * behavior of sockets calls. They are described in Section 7. * * The syntax is: * * ret = getsockopt(int sd, int level, int optname, void __user *optval, * int __user *optlen); * ret = setsockopt(int sd, int level, int optname, const void __user *optval, * int optlen); * * sd - the socket descript. * level - set to IPPROTO_SCTP for all SCTP options. * optname - the option name. * optval - the buffer to store the value of the option. * optlen - the size of the buffer. */ static int sctp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { int retval = 0; pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname); /* I can hardly begin to describe how wrong this is. This is * so broken as to be worse than useless. The API draft * REALLY is NOT helpful here... I am not convinced that the * semantics of setsockopt() with a level OTHER THAN SOL_SCTP * are at all well-founded. */ if (level != SOL_SCTP) { struct sctp_af *af = sctp_sk(sk)->pf->af; retval = af->setsockopt(sk, level, optname, optval, optlen); goto out_nounlock; } lock_sock(sk); switch (optname) { case SCTP_SOCKOPT_BINDX_ADD: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, optlen, SCTP_BINDX_ADD_ADDR); break; case SCTP_SOCKOPT_BINDX_REM: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, optlen, SCTP_BINDX_REM_ADDR); break; case SCTP_SOCKOPT_CONNECTX_OLD: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_connectx_old(sk, (struct sockaddr __user *)optval, optlen); break; case SCTP_SOCKOPT_CONNECTX: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_connectx(sk, (struct sockaddr __user *)optval, optlen); break; case SCTP_DISABLE_FRAGMENTS: retval = sctp_setsockopt_disable_fragments(sk, optval, optlen); break; case SCTP_EVENTS: retval = sctp_setsockopt_events(sk, optval, optlen); break; case SCTP_AUTOCLOSE: retval = sctp_setsockopt_autoclose(sk, optval, optlen); break; case SCTP_PEER_ADDR_PARAMS: retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen); break; case SCTP_DELAYED_SACK: retval = sctp_setsockopt_delayed_ack(sk, optval, optlen); break; case SCTP_PARTIAL_DELIVERY_POINT: retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen); break; case SCTP_INITMSG: retval = sctp_setsockopt_initmsg(sk, optval, optlen); break; case SCTP_DEFAULT_SEND_PARAM: retval = sctp_setsockopt_default_send_param(sk, optval, optlen); break; case SCTP_DEFAULT_SNDINFO: retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen); break; case SCTP_PRIMARY_ADDR: retval = sctp_setsockopt_primary_addr(sk, optval, optlen); break; case SCTP_SET_PEER_PRIMARY_ADDR: retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen); break; case SCTP_NODELAY: retval = sctp_setsockopt_nodelay(sk, optval, optlen); break; case SCTP_RTOINFO: retval = sctp_setsockopt_rtoinfo(sk, optval, optlen); break; case SCTP_ASSOCINFO: retval = sctp_setsockopt_associnfo(sk, optval, optlen); break; case SCTP_I_WANT_MAPPED_V4_ADDR: retval = sctp_setsockopt_mappedv4(sk, optval, optlen); break; case SCTP_MAXSEG: retval = sctp_setsockopt_maxseg(sk, optval, optlen); break; case SCTP_ADAPTATION_LAYER: retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen); break; case SCTP_CONTEXT: retval = sctp_setsockopt_context(sk, optval, optlen); break; case SCTP_FRAGMENT_INTERLEAVE: retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen); break; case SCTP_MAX_BURST: retval = sctp_setsockopt_maxburst(sk, optval, optlen); break; case SCTP_AUTH_CHUNK: retval = sctp_setsockopt_auth_chunk(sk, optval, optlen); break; case SCTP_HMAC_IDENT: retval = sctp_setsockopt_hmac_ident(sk, optval, optlen); break; case SCTP_AUTH_KEY: retval = sctp_setsockopt_auth_key(sk, optval, optlen); break; case SCTP_AUTH_ACTIVE_KEY: retval = sctp_setsockopt_active_key(sk, optval, optlen); break; case SCTP_AUTH_DELETE_KEY: retval = sctp_setsockopt_del_key(sk, optval, optlen); break; case SCTP_AUTO_ASCONF: retval = sctp_setsockopt_auto_asconf(sk, optval, optlen); break; case SCTP_PEER_ADDR_THLDS: retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen); break; case SCTP_RECVRCVINFO: retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen); break; case SCTP_RECVNXTINFO: retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen); break; case SCTP_PR_SUPPORTED: retval = sctp_setsockopt_pr_supported(sk, optval, optlen); break; case SCTP_DEFAULT_PRINFO: retval = sctp_setsockopt_default_prinfo(sk, optval, optlen); break; case SCTP_ENABLE_STREAM_RESET: retval = sctp_setsockopt_enable_strreset(sk, optval, optlen); break; case SCTP_RESET_STREAMS: retval = sctp_setsockopt_reset_streams(sk, optval, optlen); break; case SCTP_RESET_ASSOC: retval = sctp_setsockopt_reset_assoc(sk, optval, optlen); break; case SCTP_ADD_STREAMS: retval = sctp_setsockopt_add_streams(sk, optval, optlen); break; default: retval = -ENOPROTOOPT; break; } release_sock(sk); out_nounlock: return retval; } /* API 3.1.6 connect() - UDP Style Syntax * * An application may use the connect() call in the UDP model to initiate an * association without sending data. * * The syntax is: * * ret = connect(int sd, const struct sockaddr *nam, socklen_t len); * * sd: the socket descriptor to have a new association added to. * * nam: the address structure (either struct sockaddr_in or struct * sockaddr_in6 defined in RFC2553 [7]). * * len: the size of the address. */ static int sctp_connect(struct sock *sk, struct sockaddr *addr, int addr_len) { int err = 0; struct sctp_af *af; lock_sock(sk); pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk, addr, addr_len); /* Validate addr_len before calling common connect/connectx routine. */ af = sctp_get_af_specific(addr->sa_family); if (!af || addr_len < af->sockaddr_len) { err = -EINVAL; } else { /* Pass correct addr len to common routine (so it knows there * is only one address being passed. */ err = __sctp_connect(sk, addr, af->sockaddr_len, NULL); } release_sock(sk); return err; } /* FIXME: Write comments. */ static int sctp_disconnect(struct sock *sk, int flags) { return -EOPNOTSUPP; /* STUB */ } /* 4.1.4 accept() - TCP Style Syntax * * Applications use accept() call to remove an established SCTP * association from the accept queue of the endpoint. A new socket * descriptor will be returned from accept() to represent the newly * formed association. */ static struct sock *sctp_accept(struct sock *sk, int flags, int *err) { struct sctp_sock *sp; struct sctp_endpoint *ep; struct sock *newsk = NULL; struct sctp_association *asoc; long timeo; int error = 0; lock_sock(sk); sp = sctp_sk(sk); ep = sp->ep; if (!sctp_style(sk, TCP)) { error = -EOPNOTSUPP; goto out; } if (!sctp_sstate(sk, LISTENING)) { error = -EINVAL; goto out; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); error = sctp_wait_for_accept(sk, timeo); if (error) goto out; /* We treat the list of associations on the endpoint as the accept * queue and pick the first association on the list. */ asoc = list_entry(ep->asocs.next, struct sctp_association, asocs); newsk = sp->pf->create_accept_sk(sk, asoc); if (!newsk) { error = -ENOMEM; goto out; } /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP); out: release_sock(sk); *err = error; return newsk; } /* The SCTP ioctl handler. */ static int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg) { int rc = -ENOTCONN; lock_sock(sk); /* * SEQPACKET-style sockets in LISTENING state are valid, for * SCTP, so only discard TCP-style sockets in LISTENING state. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) goto out; switch (cmd) { case SIOCINQ: { struct sk_buff *skb; unsigned int amount = 0; skb = skb_peek(&sk->sk_receive_queue); if (skb != NULL) { /* * We will only return the amount of this packet since * that is all that will be read. */ amount = skb->len; } rc = put_user(amount, (int __user *)arg); break; } default: rc = -ENOIOCTLCMD; break; } out: release_sock(sk); return rc; } /* This is the function which gets called during socket creation to * initialized the SCTP-specific portion of the sock. * The sock structure should already be zero-filled memory. */ static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } sk->sk_gso_type = SKB_GSO_SCTP; /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); /* Nothing can fail after this block, otherwise * sctp_destroy_sock() will be called without addr_wq_lock held */ if (net->sctp.default_auto_asconf) { spin_lock(&sock_net(sk)->sctp.addr_wq_lock); list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; spin_unlock(&sock_net(sk)->sctp.addr_wq_lock); } else { sp->do_auto_asconf = 0; } local_bh_enable(); return 0; } /* Cleanup any SCTP per socket resources. Must be called with * sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true */ static void sctp_destroy_sock(struct sock *sk) { struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); /* Release our hold on the endpoint. */ sp = sctp_sk(sk); /* This could happen during socket init, thus we bail out * early, since the rest of the below is not setup either. */ if (sp->ep == NULL) return; if (sp->do_auto_asconf) { sp->do_auto_asconf = 0; list_del(&sp->auto_asconf_list); } sctp_endpoint_free(sp->ep); local_bh_disable(); percpu_counter_dec(&sctp_sockets_allocated); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); local_bh_enable(); } /* Triggered when there are no references on the socket anymore */ static void sctp_destruct_sock(struct sock *sk) { struct sctp_sock *sp = sctp_sk(sk); /* Free up the HMAC transform. */ crypto_free_shash(sp->hmac); inet_sock_destruct(sk); } /* API 4.1.7 shutdown() - TCP Style Syntax * int shutdown(int socket, int how); * * sd - the socket descriptor of the association to be closed. * how - Specifies the type of shutdown. The values are * as follows: * SHUT_RD * Disables further receive operations. No SCTP * protocol action is taken. * SHUT_WR * Disables further send operations, and initiates * the SCTP shutdown sequence. * SHUT_RDWR * Disables further send and receive operations * and initiates the SCTP shutdown sequence. */ static void sctp_shutdown(struct sock *sk, int how) { struct net *net = sock_net(sk); struct sctp_endpoint *ep; if (!sctp_style(sk, TCP)) return; ep = sctp_sk(sk)->ep; if (how & SEND_SHUTDOWN && !list_empty(&ep->asocs)) { struct sctp_association *asoc; sk->sk_state = SCTP_SS_CLOSING; asoc = list_entry(ep->asocs.next, struct sctp_association, asocs); sctp_primitive_SHUTDOWN(net, asoc, NULL); } } int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc, struct sctp_info *info) { struct sctp_transport *prim; struct list_head *pos; int mask; memset(info, 0, sizeof(*info)); if (!asoc) { struct sctp_sock *sp = sctp_sk(sk); info->sctpi_s_autoclose = sp->autoclose; info->sctpi_s_adaptation_ind = sp->adaptation_ind; info->sctpi_s_pd_point = sp->pd_point; info->sctpi_s_nodelay = sp->nodelay; info->sctpi_s_disable_fragments = sp->disable_fragments; info->sctpi_s_v4mapped = sp->v4mapped; info->sctpi_s_frag_interleave = sp->frag_interleave; info->sctpi_s_type = sp->type; return 0; } info->sctpi_tag = asoc->c.my_vtag; info->sctpi_state = asoc->state; info->sctpi_rwnd = asoc->a_rwnd; info->sctpi_unackdata = asoc->unack_data; info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map); info->sctpi_instrms = asoc->c.sinit_max_instreams; info->sctpi_outstrms = asoc->c.sinit_num_ostreams; list_for_each(pos, &asoc->base.inqueue.in_chunk_list) info->sctpi_inqueue++; list_for_each(pos, &asoc->outqueue.out_chunk_list) info->sctpi_outqueue++; info->sctpi_overall_error = asoc->overall_error_count; info->sctpi_max_burst = asoc->max_burst; info->sctpi_maxseg = asoc->frag_point; info->sctpi_peer_rwnd = asoc->peer.rwnd; info->sctpi_peer_tag = asoc->c.peer_vtag; mask = asoc->peer.ecn_capable << 1; mask = (mask | asoc->peer.ipv4_address) << 1; mask = (mask | asoc->peer.ipv6_address) << 1; mask = (mask | asoc->peer.hostname_address) << 1; mask = (mask | asoc->peer.asconf_capable) << 1; mask = (mask | asoc->peer.prsctp_capable) << 1; mask = (mask | asoc->peer.auth_capable); info->sctpi_peer_capable = mask; mask = asoc->peer.sack_needed << 1; mask = (mask | asoc->peer.sack_generation) << 1; mask = (mask | asoc->peer.zero_window_announced); info->sctpi_peer_sack = mask; info->sctpi_isacks = asoc->stats.isacks; info->sctpi_osacks = asoc->stats.osacks; info->sctpi_opackets = asoc->stats.opackets; info->sctpi_ipackets = asoc->stats.ipackets; info->sctpi_rtxchunks = asoc->stats.rtxchunks; info->sctpi_outofseqtsns = asoc->stats.outofseqtsns; info->sctpi_idupchunks = asoc->stats.idupchunks; info->sctpi_gapcnt = asoc->stats.gapcnt; info->sctpi_ouodchunks = asoc->stats.ouodchunks; info->sctpi_iuodchunks = asoc->stats.iuodchunks; info->sctpi_oodchunks = asoc->stats.oodchunks; info->sctpi_iodchunks = asoc->stats.iodchunks; info->sctpi_octrlchunks = asoc->stats.octrlchunks; info->sctpi_ictrlchunks = asoc->stats.ictrlchunks; prim = asoc->peer.primary_path; memcpy(&info->sctpi_p_address, &prim->ipaddr, sizeof(struct sockaddr_storage)); info->sctpi_p_state = prim->state; info->sctpi_p_cwnd = prim->cwnd; info->sctpi_p_srtt = prim->srtt; info->sctpi_p_rto = jiffies_to_msecs(prim->rto); info->sctpi_p_hbinterval = prim->hbinterval; info->sctpi_p_pathmaxrxt = prim->pathmaxrxt; info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay); info->sctpi_p_ssthresh = prim->ssthresh; info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked; info->sctpi_p_flight_size = prim->flight_size; info->sctpi_p_error = prim->error_count; return 0; } EXPORT_SYMBOL_GPL(sctp_get_sctp_info); /* use callback to avoid exporting the core structure */ int sctp_transport_walk_start(struct rhashtable_iter *iter) { int err; rhltable_walk_enter(&sctp_transport_hashtable, iter); err = rhashtable_walk_start(iter); if (err && err != -EAGAIN) { rhashtable_walk_stop(iter); rhashtable_walk_exit(iter); return err; } return 0; } void sctp_transport_walk_stop(struct rhashtable_iter *iter) { rhashtable_walk_stop(iter); rhashtable_walk_exit(iter); } struct sctp_transport *sctp_transport_get_next(struct net *net, struct rhashtable_iter *iter) { struct sctp_transport *t; t = rhashtable_walk_next(iter); for (; t; t = rhashtable_walk_next(iter)) { if (IS_ERR(t)) { if (PTR_ERR(t) == -EAGAIN) continue; break; } if (net_eq(sock_net(t->asoc->base.sk), net) && t->asoc->peer.primary_path == t) break; } return t; } struct sctp_transport *sctp_transport_get_idx(struct net *net, struct rhashtable_iter *iter, int pos) { void *obj = SEQ_START_TOKEN; while (pos && (obj = sctp_transport_get_next(net, iter)) && !IS_ERR(obj)) pos--; return obj; } int sctp_for_each_endpoint(int (*cb)(struct sctp_endpoint *, void *), void *p) { int err = 0; int hash = 0; struct sctp_ep_common *epb; struct sctp_hashbucket *head; for (head = sctp_ep_hashtable; hash < sctp_ep_hashsize; hash++, head++) { read_lock(&head->lock); sctp_for_each_hentry(epb, &head->chain) { err = cb(sctp_ep(epb), p); if (err) break; } read_unlock(&head->lock); } return err; } EXPORT_SYMBOL_GPL(sctp_for_each_endpoint); int sctp_transport_lookup_process(int (*cb)(struct sctp_transport *, void *), struct net *net, const union sctp_addr *laddr, const union sctp_addr *paddr, void *p) { struct sctp_transport *transport; int err; rcu_read_lock(); transport = sctp_addrs_lookup_transport(net, laddr, paddr); rcu_read_unlock(); if (!transport) return -ENOENT; err = cb(transport, p); sctp_transport_put(transport); return err; } EXPORT_SYMBOL_GPL(sctp_transport_lookup_process); int sctp_for_each_transport(int (*cb)(struct sctp_transport *, void *), struct net *net, int pos, void *p) { struct rhashtable_iter hti; void *obj; int err; err = sctp_transport_walk_start(&hti); if (err) return err; sctp_transport_get_idx(net, &hti, pos); obj = sctp_transport_get_next(net, &hti); for (; obj && !IS_ERR(obj); obj = sctp_transport_get_next(net, &hti)) { struct sctp_transport *transport = obj; if (!sctp_transport_hold(transport)) continue; err = cb(transport, p); sctp_transport_put(transport); if (err) break; } sctp_transport_walk_stop(&hti); return err; } EXPORT_SYMBOL_GPL(sctp_for_each_transport); /* 7.2.1 Association Status (SCTP_STATUS) * Applications can retrieve current status information about an * association, including association state, peer receiver window size, * number of unacked data chunks, and number of data chunks pending * receipt. This information is read-only. */ static int sctp_getsockopt_sctp_status(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_status status; struct sctp_association *asoc = NULL; struct sctp_transport *transport; sctp_assoc_t associd; int retval = 0; if (len < sizeof(status)) { retval = -EINVAL; goto out; } len = sizeof(status); if (copy_from_user(&status, optval, len)) { retval = -EFAULT; goto out; } associd = status.sstat_assoc_id; asoc = sctp_id2assoc(sk, associd); if (!asoc) { retval = -EINVAL; goto out; } transport = asoc->peer.primary_path; status.sstat_assoc_id = sctp_assoc2id(asoc); status.sstat_state = sctp_assoc_to_state(asoc); status.sstat_rwnd = asoc->peer.rwnd; status.sstat_unackdata = asoc->unack_data; status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map); status.sstat_instrms = asoc->c.sinit_max_instreams; status.sstat_outstrms = asoc->c.sinit_num_ostreams; status.sstat_fragmentation_point = asoc->frag_point; status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc); memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr, transport->af_specific->sockaddr_len); /* Map ipv4 address into v4-mapped-on-v6 address. */ sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk), (union sctp_addr *)&status.sstat_primary.spinfo_address); status.sstat_primary.spinfo_state = transport->state; status.sstat_primary.spinfo_cwnd = transport->cwnd; status.sstat_primary.spinfo_srtt = transport->srtt; status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto); status.sstat_primary.spinfo_mtu = transport->pathmtu; if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN) status.sstat_primary.spinfo_state = SCTP_ACTIVE; if (put_user(len, optlen)) { retval = -EFAULT; goto out; } pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n", __func__, len, status.sstat_state, status.sstat_rwnd, status.sstat_assoc_id); if (copy_to_user(optval, &status, len)) { retval = -EFAULT; goto out; } out: return retval; } /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO) * * Applications can retrieve information about a specific peer address * of an association, including its reachability state, congestion * window, and retransmission timer values. This information is * read-only. */ static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_paddrinfo pinfo; struct sctp_transport *transport; int retval = 0; if (len < sizeof(pinfo)) { retval = -EINVAL; goto out; } len = sizeof(pinfo); if (copy_from_user(&pinfo, optval, len)) { retval = -EFAULT; goto out; } transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address, pinfo.spinfo_assoc_id); if (!transport) return -EINVAL; pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc); pinfo.spinfo_state = transport->state; pinfo.spinfo_cwnd = transport->cwnd; pinfo.spinfo_srtt = transport->srtt; pinfo.spinfo_rto = jiffies_to_msecs(transport->rto); pinfo.spinfo_mtu = transport->pathmtu; if (pinfo.spinfo_state == SCTP_UNKNOWN) pinfo.spinfo_state = SCTP_ACTIVE; if (put_user(len, optlen)) { retval = -EFAULT; goto out; } if (copy_to_user(optval, &pinfo, len)) { retval = -EFAULT; goto out; } out: return retval; } /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS) * * This option is a on/off flag. If enabled no SCTP message * fragmentation will be performed. Instead if a message being sent * exceeds the current PMTU size, the message will NOT be sent and * instead a error will be indicated to the user. */ static int sctp_getsockopt_disable_fragments(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); val = (sctp_sk(sk)->disable_fragments == 1); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS) * * This socket option is used to specify various notifications and * ancillary data the user wishes to receive. */ static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval, int __user *optlen) { if (len == 0) return -EINVAL; if (len > sizeof(struct sctp_event_subscribe)) len = sizeof(struct sctp_event_subscribe); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len)) return -EFAULT; return 0; } /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE) * * This socket option is applicable to the UDP-style socket only. When * set it will cause associations that are idle for more than the * specified number of seconds to automatically close. An association * being idle is defined an association that has NOT sent or received * user data. The special value of '0' indicates that no automatic * close of any associations should be performed. The option expects an * integer defining the number of seconds of idle time before an * association is closed. */ static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen) { /* Applicable to UDP-style socket only */ if (sctp_style(sk, TCP)) return -EOPNOTSUPP; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int))) return -EFAULT; return 0; } /* Helper routine to branch off an association to a new socket. */ int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; if (!asoc) return -EINVAL; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; } EXPORT_SYMBOL(sctp_do_peeloff); static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen) { sctp_peeloff_arg_t peeloff; struct socket *newsock; struct file *newfile; int retval = 0; if (len < sizeof(sctp_peeloff_arg_t)) return -EINVAL; len = sizeof(sctp_peeloff_arg_t); if (copy_from_user(&peeloff, optval, len)) return -EFAULT; retval = sctp_do_peeloff(sk, peeloff.associd, &newsock); if (retval < 0) goto out; /* Map the socket to an unused fd that can be returned to the user. */ retval = get_unused_fd_flags(0); if (retval < 0) { sock_release(newsock); goto out; } newfile = sock_alloc_file(newsock, 0, NULL); if (IS_ERR(newfile)) { put_unused_fd(retval); sock_release(newsock); return PTR_ERR(newfile); } pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk, retval); /* Return the fd mapped to the new socket. */ if (put_user(len, optlen)) { fput(newfile); put_unused_fd(retval); return -EFAULT; } peeloff.sd = retval; if (copy_to_user(optval, &peeloff, len)) { fput(newfile); put_unused_fd(retval); return -EFAULT; } fd_install(retval, newfile); out: return retval; } /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS) * * Applications can enable or disable heartbeats for any peer address of * an association, modify an address's heartbeat interval, force a * heartbeat to be sent immediately, and adjust the address's maximum * number of retransmissions sent before an address is considered * unreachable. The following structure is used to access and modify an * address's parameters: * * struct sctp_paddrparams { * sctp_assoc_t spp_assoc_id; * struct sockaddr_storage spp_address; * uint32_t spp_hbinterval; * uint16_t spp_pathmaxrxt; * uint32_t spp_pathmtu; * uint32_t spp_sackdelay; * uint32_t spp_flags; * }; * * spp_assoc_id - (one-to-many style socket) This is filled in the * application, and identifies the association for * this query. * spp_address - This specifies which address is of interest. * spp_hbinterval - This contains the value of the heartbeat interval, * in milliseconds. If a value of zero * is present in this field then no changes are to * be made to this parameter. * spp_pathmaxrxt - This contains the maximum number of * retransmissions before this address shall be * considered unreachable. If a value of zero * is present in this field then no changes are to * be made to this parameter. * spp_pathmtu - When Path MTU discovery is disabled the value * specified here will be the "fixed" path mtu. * Note that if the spp_address field is empty * then all associations on this address will * have this fixed path mtu set upon them. * * spp_sackdelay - When delayed sack is enabled, this value specifies * the number of milliseconds that sacks will be delayed * for. This value will apply to all addresses of an * association if the spp_address field is empty. Note * also, that if delayed sack is enabled and this * value is set to 0, no change is made to the last * recorded delayed sack timer value. * * spp_flags - These flags are used to control various features * on an association. The flag field may contain * zero or more of the following options. * * SPP_HB_ENABLE - Enable heartbeats on the * specified address. Note that if the address * field is empty all addresses for the association * have heartbeats enabled upon them. * * SPP_HB_DISABLE - Disable heartbeats on the * speicifed address. Note that if the address * field is empty all addresses for the association * will have their heartbeats disabled. Note also * that SPP_HB_ENABLE and SPP_HB_DISABLE are * mutually exclusive, only one of these two should * be specified. Enabling both fields will have * undetermined results. * * SPP_HB_DEMAND - Request a user initiated heartbeat * to be made immediately. * * SPP_PMTUD_ENABLE - This field will enable PMTU * discovery upon the specified address. Note that * if the address feild is empty then all addresses * on the association are effected. * * SPP_PMTUD_DISABLE - This field will disable PMTU * discovery upon the specified address. Note that * if the address feild is empty then all addresses * on the association are effected. Not also that * SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually * exclusive. Enabling both will have undetermined * results. * * SPP_SACKDELAY_ENABLE - Setting this flag turns * on delayed sack. The time specified in spp_sackdelay * is used to specify the sack delay for this address. Note * that if spp_address is empty then all addresses will * enable delayed sack and take on the sack delay * value specified in spp_sackdelay. * SPP_SACKDELAY_DISABLE - Setting this flag turns * off delayed sack. If the spp_address field is blank then * delayed sack is disabled for the entire association. Note * also that this field is mutually exclusive to * SPP_SACKDELAY_ENABLE, setting both will have undefined * results. */ static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_paddrparams params; struct sctp_transport *trans = NULL; struct sctp_association *asoc = NULL; struct sctp_sock *sp = sctp_sk(sk); if (len < sizeof(struct sctp_paddrparams)) return -EINVAL; len = sizeof(struct sctp_paddrparams); if (copy_from_user(&params, optval, len)) return -EFAULT; /* If an address other than INADDR_ANY is specified, and * no transport is found, then the request is invalid. */ if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) { trans = sctp_addr_id2transport(sk, &params.spp_address, params.spp_assoc_id); if (!trans) { pr_debug("%s: failed no transport\n", __func__); return -EINVAL; } } /* Get association, if assoc_id != 0 and the socket is a one * to many style socket, and an association was not found, then * the id was invalid. */ asoc = sctp_id2assoc(sk, params.spp_assoc_id); if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) { pr_debug("%s: failed no association\n", __func__); return -EINVAL; } if (trans) { /* Fetch transport values. */ params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval); params.spp_pathmtu = trans->pathmtu; params.spp_pathmaxrxt = trans->pathmaxrxt; params.spp_sackdelay = jiffies_to_msecs(trans->sackdelay); /*draft-11 doesn't say what to return in spp_flags*/ params.spp_flags = trans->param_flags; } else if (asoc) { /* Fetch association values. */ params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval); params.spp_pathmtu = asoc->pathmtu; params.spp_pathmaxrxt = asoc->pathmaxrxt; params.spp_sackdelay = jiffies_to_msecs(asoc->sackdelay); /*draft-11 doesn't say what to return in spp_flags*/ params.spp_flags = asoc->param_flags; } else { /* Fetch socket values. */ params.spp_hbinterval = sp->hbinterval; params.spp_pathmtu = sp->pathmtu; params.spp_sackdelay = sp->sackdelay; params.spp_pathmaxrxt = sp->pathmaxrxt; /*draft-11 doesn't say what to return in spp_flags*/ params.spp_flags = sp->param_flags; } if (copy_to_user(optval, &params, len)) return -EFAULT; if (put_user(len, optlen)) return -EFAULT; return 0; } /* * 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK) * * This option will effect the way delayed acks are performed. This * option allows you to get or set the delayed ack time, in * milliseconds. It also allows changing the delayed ack frequency. * Changing the frequency to 1 disables the delayed sack algorithm. If * the assoc_id is 0, then this sets or gets the endpoints default * values. If the assoc_id field is non-zero, then the set or get * effects the specified association for the one to many model (the * assoc_id field is ignored by the one to one model). Note that if * sack_delay or sack_freq are 0 when setting this option, then the * current values will remain unchanged. * * struct sctp_sack_info { * sctp_assoc_t sack_assoc_id; * uint32_t sack_delay; * uint32_t sack_freq; * }; * * sack_assoc_id - This parameter, indicates which association the user * is performing an action upon. Note that if this field's value is * zero then the endpoints default value is changed (effecting future * associations only). * * sack_delay - This parameter contains the number of milliseconds that * the user is requesting the delayed ACK timer be set to. Note that * this value is defined in the standard to be between 200 and 500 * milliseconds. * * sack_freq - This parameter contains the number of packets that must * be received before a sack is sent without waiting for the delay * timer to expire. The default value for this is 2, setting this * value to 1 will disable the delayed sack algorithm. */ static int sctp_getsockopt_delayed_ack(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_sack_info params; struct sctp_association *asoc = NULL; struct sctp_sock *sp = sctp_sk(sk); if (len >= sizeof(struct sctp_sack_info)) { len = sizeof(struct sctp_sack_info); if (copy_from_user(&params, optval, len)) return -EFAULT; } else if (len == sizeof(struct sctp_assoc_value)) { pr_warn_ratelimited(DEPRECATED "%s (pid %d) " "Use of struct sctp_assoc_value in delayed_ack socket option.\n" "Use struct sctp_sack_info instead\n", current->comm, task_pid_nr(current)); if (copy_from_user(&params, optval, len)) return -EFAULT; } else return -EINVAL; /* Get association, if sack_assoc_id != 0 and the socket is a one * to many style socket, and an association was not found, then * the id was invalid. */ asoc = sctp_id2assoc(sk, params.sack_assoc_id); if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) { /* Fetch association values. */ if (asoc->param_flags & SPP_SACKDELAY_ENABLE) { params.sack_delay = jiffies_to_msecs( asoc->sackdelay); params.sack_freq = asoc->sackfreq; } else { params.sack_delay = 0; params.sack_freq = 1; } } else { /* Fetch socket values. */ if (sp->param_flags & SPP_SACKDELAY_ENABLE) { params.sack_delay = sp->sackdelay; params.sack_freq = sp->sackfreq; } else { params.sack_delay = 0; params.sack_freq = 1; } } if (copy_to_user(optval, &params, len)) return -EFAULT; if (put_user(len, optlen)) return -EFAULT; return 0; } /* 7.1.3 Initialization Parameters (SCTP_INITMSG) * * Applications can specify protocol parameters for the default association * initialization. The option name argument to setsockopt() and getsockopt() * is SCTP_INITMSG. * * Setting initialization parameters is effective only on an unconnected * socket (for UDP-style sockets only future associations are effected * by the change). With TCP-style sockets, this option is inherited by * sockets derived from a listener socket. */ static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen) { if (len < sizeof(struct sctp_initmsg)) return -EINVAL; len = sizeof(struct sctp_initmsg); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len)) return -EFAULT; return 0; } static int sctp_getsockopt_peer_addrs(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_association *asoc; int cnt = 0; struct sctp_getaddrs getaddrs; struct sctp_transport *from; void __user *to; union sctp_addr temp; struct sctp_sock *sp = sctp_sk(sk); int addrlen; size_t space_left; int bytes_copied; if (len < sizeof(struct sctp_getaddrs)) return -EINVAL; if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs))) return -EFAULT; /* For UDP-style sockets, id specifies the association to query. */ asoc = sctp_id2assoc(sk, getaddrs.assoc_id); if (!asoc) return -EINVAL; to = optval + offsetof(struct sctp_getaddrs, addrs); space_left = len - offsetof(struct sctp_getaddrs, addrs); list_for_each_entry(from, &asoc->peer.transport_addr_list, transports) { memcpy(&temp, &from->ipaddr, sizeof(temp)); addrlen = sctp_get_pf_specific(sk->sk_family) ->addr_to_user(sp, &temp); if (space_left < addrlen) return -ENOMEM; if (copy_to_user(to, &temp, addrlen)) return -EFAULT; to += addrlen; cnt++; space_left -= addrlen; } if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) return -EFAULT; bytes_copied = ((char __user *)to) - optval; if (put_user(bytes_copied, optlen)) return -EFAULT; return 0; } static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to, size_t space_left, int *bytes_copied) { struct sctp_sockaddr_entry *addr; union sctp_addr temp; int cnt = 0; int addrlen; struct net *net = sock_net(sk); rcu_read_lock(); list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) { if (!addr->valid) continue; if ((PF_INET == sk->sk_family) && (AF_INET6 == addr->a.sa.sa_family)) continue; if ((PF_INET6 == sk->sk_family) && inet_v6_ipv6only(sk) && (AF_INET == addr->a.sa.sa_family)) continue; memcpy(&temp, &addr->a, sizeof(temp)); if (!temp.v4.sin_port) temp.v4.sin_port = htons(port); addrlen = sctp_get_pf_specific(sk->sk_family) ->addr_to_user(sctp_sk(sk), &temp); if (space_left < addrlen) { cnt = -ENOMEM; break; } memcpy(to, &temp, addrlen); to += addrlen; cnt++; space_left -= addrlen; *bytes_copied += addrlen; } rcu_read_unlock(); return cnt; } static int sctp_getsockopt_local_addrs(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_bind_addr *bp; struct sctp_association *asoc; int cnt = 0; struct sctp_getaddrs getaddrs; struct sctp_sockaddr_entry *addr; void __user *to; union sctp_addr temp; struct sctp_sock *sp = sctp_sk(sk); int addrlen; int err = 0; size_t space_left; int bytes_copied = 0; void *addrs; void *buf; if (len < sizeof(struct sctp_getaddrs)) return -EINVAL; if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs))) return -EFAULT; /* * For UDP-style sockets, id specifies the association to query. * If the id field is set to the value '0' then the locally bound * addresses are returned without regard to any particular * association. */ if (0 == getaddrs.assoc_id) { bp = &sctp_sk(sk)->ep->base.bind_addr; } else { asoc = sctp_id2assoc(sk, getaddrs.assoc_id); if (!asoc) return -EINVAL; bp = &asoc->base.bind_addr; } to = optval + offsetof(struct sctp_getaddrs, addrs); space_left = len - offsetof(struct sctp_getaddrs, addrs); addrs = kmalloc(space_left, GFP_USER | __GFP_NOWARN); if (!addrs) return -ENOMEM; /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid * addresses from the global local address list. */ if (sctp_list_single_entry(&bp->address_list)) { addr = list_entry(bp->address_list.next, struct sctp_sockaddr_entry, list); if (sctp_is_any(sk, &addr->a)) { cnt = sctp_copy_laddrs(sk, bp->port, addrs, space_left, &bytes_copied); if (cnt < 0) { err = cnt; goto out; } goto copy_getaddrs; } } buf = addrs; /* Protection on the bound address list is not needed since * in the socket option context we hold a socket lock and * thus the bound address list can't change. */ list_for_each_entry(addr, &bp->address_list, list) { memcpy(&temp, &addr->a, sizeof(temp)); addrlen = sctp_get_pf_specific(sk->sk_family) ->addr_to_user(sp, &temp); if (space_left < addrlen) { err = -ENOMEM; /*fixme: right error?*/ goto out; } memcpy(buf, &temp, addrlen); buf += addrlen; bytes_copied += addrlen; cnt++; space_left -= addrlen; } copy_getaddrs: if (copy_to_user(to, addrs, bytes_copied)) { err = -EFAULT; goto out; } if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) { err = -EFAULT; goto out; } if (put_user(bytes_copied, optlen)) err = -EFAULT; out: kfree(addrs); return err; } /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR) * * Requests that the local SCTP stack use the enclosed peer address as * the association primary. The enclosed address must be one of the * association peer's addresses. */ static int sctp_getsockopt_primary_addr(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_prim prim; struct sctp_association *asoc; struct sctp_sock *sp = sctp_sk(sk); if (len < sizeof(struct sctp_prim)) return -EINVAL; len = sizeof(struct sctp_prim); if (copy_from_user(&prim, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, prim.ssp_assoc_id); if (!asoc) return -EINVAL; if (!asoc->peer.primary_path) return -ENOTCONN; memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr, asoc->peer.primary_path->af_specific->sockaddr_len); sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp, (union sctp_addr *)&prim.ssp_addr); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &prim, len)) return -EFAULT; return 0; } /* * 7.1.11 Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER) * * Requests that the local endpoint set the specified Adaptation Layer * Indication parameter for all future INIT and INIT-ACK exchanges. */ static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_setadaptation adaptation; if (len < sizeof(struct sctp_setadaptation)) return -EINVAL; len = sizeof(struct sctp_setadaptation); adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &adaptation, len)) return -EFAULT; return 0; } /* * * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM) * * Applications that wish to use the sendto() system call may wish to * specify a default set of parameters that would normally be supplied * through the inclusion of ancillary data. This socket option allows * such an application to set the default sctp_sndrcvinfo structure. * The application that wishes to use this socket option simply passes * in to this call the sctp_sndrcvinfo structure defined in Section * 5.2.2) The input parameters accepted by this call include * sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context, * sinfo_timetolive. The user must provide the sinfo_assoc_id field in * to this call if the caller is using the UDP model. * * For getsockopt, it get the default sctp_sndrcvinfo structure. */ static int sctp_getsockopt_default_send_param(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_association *asoc; struct sctp_sndrcvinfo info; if (len < sizeof(info)) return -EINVAL; len = sizeof(info); if (copy_from_user(&info, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, info.sinfo_assoc_id); if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) { info.sinfo_stream = asoc->default_stream; info.sinfo_flags = asoc->default_flags; info.sinfo_ppid = asoc->default_ppid; info.sinfo_context = asoc->default_context; info.sinfo_timetolive = asoc->default_timetolive; } else { info.sinfo_stream = sp->default_stream; info.sinfo_flags = sp->default_flags; info.sinfo_ppid = sp->default_ppid; info.sinfo_context = sp->default_context; info.sinfo_timetolive = sp->default_timetolive; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } /* RFC6458, Section 8.1.31. Set/get Default Send Parameters * (SCTP_DEFAULT_SNDINFO) */ static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_association *asoc; struct sctp_sndinfo info; if (len < sizeof(info)) return -EINVAL; len = sizeof(info); if (copy_from_user(&info, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, info.snd_assoc_id); if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) { info.snd_sid = asoc->default_stream; info.snd_flags = asoc->default_flags; info.snd_ppid = asoc->default_ppid; info.snd_context = asoc->default_context; } else { info.snd_sid = sp->default_stream; info.snd_flags = sp->default_flags; info.snd_ppid = sp->default_ppid; info.snd_context = sp->default_context; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } /* * * 7.1.5 SCTP_NODELAY * * Turn on/off any Nagle-like algorithm. This means that packets are * generally sent as soon as possible and no unnecessary delays are * introduced, at the cost of more packets in the network. Expects an * integer boolean flag. */ static int sctp_getsockopt_nodelay(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); val = (sctp_sk(sk)->nodelay == 1); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * * 7.1.1 SCTP_RTOINFO * * The protocol parameters used to initialize and bound retransmission * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access * and modify these parameters. * All parameters are time values, in milliseconds. A value of 0, when * modifying the parameters, indicates that the current value should not * be changed. * */ static int sctp_getsockopt_rtoinfo(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_rtoinfo rtoinfo; struct sctp_association *asoc; if (len < sizeof (struct sctp_rtoinfo)) return -EINVAL; len = sizeof(struct sctp_rtoinfo); if (copy_from_user(&rtoinfo, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id); if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP)) return -EINVAL; /* Values corresponding to the specific association. */ if (asoc) { rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial); rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max); rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min); } else { /* Values corresponding to the endpoint. */ struct sctp_sock *sp = sctp_sk(sk); rtoinfo.srto_initial = sp->rtoinfo.srto_initial; rtoinfo.srto_max = sp->rtoinfo.srto_max; rtoinfo.srto_min = sp->rtoinfo.srto_min; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &rtoinfo, len)) return -EFAULT; return 0; } /* * * 7.1.2 SCTP_ASSOCINFO * * This option is used to tune the maximum retransmission attempts * of the association. * Returns an error if the new association retransmission value is * greater than the sum of the retransmission value of the peer. * See [SCTP] for more information. * */ static int sctp_getsockopt_associnfo(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assocparams assocparams; struct sctp_association *asoc; struct list_head *pos; int cnt = 0; if (len < sizeof (struct sctp_assocparams)) return -EINVAL; len = sizeof(struct sctp_assocparams); if (copy_from_user(&assocparams, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id); if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP)) return -EINVAL; /* Values correspoinding to the specific association */ if (asoc) { assocparams.sasoc_asocmaxrxt = asoc->max_retrans; assocparams.sasoc_peer_rwnd = asoc->peer.rwnd; assocparams.sasoc_local_rwnd = asoc->a_rwnd; assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life); list_for_each(pos, &asoc->peer.transport_addr_list) { cnt++; } assocparams.sasoc_number_peer_destinations = cnt; } else { /* Values corresponding to the endpoint */ struct sctp_sock *sp = sctp_sk(sk); assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt; assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd; assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd; assocparams.sasoc_cookie_life = sp->assocparams.sasoc_cookie_life; assocparams.sasoc_number_peer_destinations = sp->assocparams. sasoc_number_peer_destinations; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &assocparams, len)) return -EFAULT; return 0; } /* * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR) * * This socket option is a boolean flag which turns on or off mapped V4 * addresses. If this option is turned on and the socket is type * PF_INET6, then IPv4 addresses will be mapped to V6 representation. * If this option is turned off, then no mapping will be done of V4 * addresses and a user will receive both PF_INET6 and PF_INET type * addresses on the socket. */ static int sctp_getsockopt_mappedv4(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val; struct sctp_sock *sp = sctp_sk(sk); if (len < sizeof(int)) return -EINVAL; len = sizeof(int); val = sp->v4mapped; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * 7.1.29. Set or Get the default context (SCTP_CONTEXT) * (chapter and verse is quoted at sctp_setsockopt_context()) */ static int sctp_getsockopt_context(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_value params; struct sctp_sock *sp; struct sctp_association *asoc; if (len < sizeof(struct sctp_assoc_value)) return -EINVAL; len = sizeof(struct sctp_assoc_value); if (copy_from_user(&params, optval, len)) return -EFAULT; sp = sctp_sk(sk); if (params.assoc_id != 0) { asoc = sctp_id2assoc(sk, params.assoc_id); if (!asoc) return -EINVAL; params.assoc_value = asoc->default_rcv_context; } else { params.assoc_value = sp->default_rcv_context; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &params, len)) return -EFAULT; return 0; } /* * 8.1.16. Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG) * This option will get or set the maximum size to put in any outgoing * SCTP DATA chunk. If a message is larger than this size it will be * fragmented by SCTP into the specified size. Note that the underlying * SCTP implementation may fragment into smaller sized chunks when the * PMTU of the underlying association is smaller than the value set by * the user. The default value for this option is '0' which indicates * the user is NOT limiting fragmentation and only the PMTU will effect * SCTP's choice of DATA chunk size. Note also that values set larger * than the maximum size of an IP datagram will effectively let SCTP * control fragmentation (i.e. the same as setting this option to 0). * * The following structure is used to access and modify this parameter: * * struct sctp_assoc_value { * sctp_assoc_t assoc_id; * uint32_t assoc_value; * }; * * assoc_id: This parameter is ignored for one-to-one style sockets. * For one-to-many style sockets this parameter indicates which * association the user is performing an action upon. Note that if * this field's value is zero then the endpoints default value is * changed (effecting future associations only). * assoc_value: This parameter specifies the maximum size in bytes. */ static int sctp_getsockopt_maxseg(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_value params; struct sctp_association *asoc; if (len == sizeof(int)) { pr_warn_ratelimited(DEPRECATED "%s (pid %d) " "Use of int in maxseg socket option.\n" "Use struct sctp_assoc_value instead\n", current->comm, task_pid_nr(current)); params.assoc_id = 0; } else if (len >= sizeof(struct sctp_assoc_value)) { len = sizeof(struct sctp_assoc_value); if (copy_from_user(&params, optval, sizeof(params))) return -EFAULT; } else return -EINVAL; asoc = sctp_id2assoc(sk, params.assoc_id); if (!asoc && params.assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) params.assoc_value = asoc->frag_point; else params.assoc_value = sctp_sk(sk)->user_frag; if (put_user(len, optlen)) return -EFAULT; if (len == sizeof(int)) { if (copy_to_user(optval, &params.assoc_value, len)) return -EFAULT; } else { if (copy_to_user(optval, &params, len)) return -EFAULT; } return 0; } /* * 7.1.24. Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE) * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave()) */ static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); val = sctp_sk(sk)->frag_interleave; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * 7.1.25. Set or Get the sctp partial delivery point * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point()) */ static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len, char __user *optval, int __user *optlen) { u32 val; if (len < sizeof(u32)) return -EINVAL; len = sizeof(u32); val = sctp_sk(sk)->pd_point; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * 7.1.28. Set or Get the maximum burst (SCTP_MAX_BURST) * (chapter and verse is quoted at sctp_setsockopt_maxburst()) */ static int sctp_getsockopt_maxburst(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_value params; struct sctp_sock *sp; struct sctp_association *asoc; if (len == sizeof(int)) { pr_warn_ratelimited(DEPRECATED "%s (pid %d) " "Use of int in max_burst socket option.\n" "Use struct sctp_assoc_value instead\n", current->comm, task_pid_nr(current)); params.assoc_id = 0; } else if (len >= sizeof(struct sctp_assoc_value)) { len = sizeof(struct sctp_assoc_value); if (copy_from_user(&params, optval, len)) return -EFAULT; } else return -EINVAL; sp = sctp_sk(sk); if (params.assoc_id != 0) { asoc = sctp_id2assoc(sk, params.assoc_id); if (!asoc) return -EINVAL; params.assoc_value = asoc->max_burst; } else params.assoc_value = sp->max_burst; if (len == sizeof(int)) { if (copy_to_user(optval, &params.assoc_value, len)) return -EFAULT; } else { if (copy_to_user(optval, &params, len)) return -EFAULT; } return 0; } static int sctp_getsockopt_hmac_ident(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_hmacalgo __user *p = (void __user *)optval; struct sctp_hmac_algo_param *hmacs; __u16 data_len = 0; u32 num_idents; int i; if (!ep->auth_enable) return -EACCES; hmacs = ep->auth_hmacs_list; data_len = ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t); if (len < sizeof(struct sctp_hmacalgo) + data_len) return -EINVAL; len = sizeof(struct sctp_hmacalgo) + data_len; num_idents = data_len / sizeof(u16); if (put_user(len, optlen)) return -EFAULT; if (put_user(num_idents, &p->shmac_num_idents)) return -EFAULT; for (i = 0; i < num_idents; i++) { __u16 hmacid = ntohs(hmacs->hmac_ids[i]); if (copy_to_user(&p->shmac_idents[i], &hmacid, sizeof(__u16))) return -EFAULT; } return 0; } static int sctp_getsockopt_active_key(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authkeyid val; struct sctp_association *asoc; if (!ep->auth_enable) return -EACCES; if (len < sizeof(struct sctp_authkeyid)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid))) return -EFAULT; asoc = sctp_id2assoc(sk, val.scact_assoc_id); if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) val.scact_keynumber = asoc->active_key_id; else val.scact_keynumber = ep->active_key_id; len = sizeof(struct sctp_authkeyid); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authchunks __user *p = (void __user *)optval; struct sctp_authchunks val; struct sctp_association *asoc; struct sctp_chunks_param *ch; u32 num_chunks = 0; char __user *to; if (!ep->auth_enable) return -EACCES; if (len < sizeof(struct sctp_authchunks)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks))) return -EFAULT; to = p->gauth_chunks; asoc = sctp_id2assoc(sk, val.gauth_assoc_id); if (!asoc) return -EINVAL; ch = asoc->peer.peer_chunks; if (!ch) goto num; /* See if the user provided enough room for all the data */ num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t); if (len < num_chunks) return -EINVAL; if (copy_to_user(to, ch->chunks, num_chunks)) return -EFAULT; num: len = sizeof(struct sctp_authchunks) + num_chunks; if (put_user(len, optlen)) return -EFAULT; if (put_user(num_chunks, &p->gauth_number_of_chunks)) return -EFAULT; return 0; } static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_endpoint *ep = sctp_sk(sk)->ep; struct sctp_authchunks __user *p = (void __user *)optval; struct sctp_authchunks val; struct sctp_association *asoc; struct sctp_chunks_param *ch; u32 num_chunks = 0; char __user *to; if (!ep->auth_enable) return -EACCES; if (len < sizeof(struct sctp_authchunks)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks))) return -EFAULT; to = p->gauth_chunks; asoc = sctp_id2assoc(sk, val.gauth_assoc_id); if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP)) return -EINVAL; if (asoc) ch = (struct sctp_chunks_param *)asoc->c.auth_chunks; else ch = ep->auth_chunk_list; if (!ch) goto num; num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t); if (len < sizeof(struct sctp_authchunks) + num_chunks) return -EINVAL; if (copy_to_user(to, ch->chunks, num_chunks)) return -EFAULT; num: len = sizeof(struct sctp_authchunks) + num_chunks; if (put_user(len, optlen)) return -EFAULT; if (put_user(num_chunks, &p->gauth_number_of_chunks)) return -EFAULT; return 0; } /* * 8.2.5. Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER) * This option gets the current number of associations that are attached * to a one-to-many style socket. The option value is an uint32_t. */ static int sctp_getsockopt_assoc_number(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_association *asoc; u32 val = 0; if (sctp_style(sk, TCP)) return -EOPNOTSUPP; if (len < sizeof(u32)) return -EINVAL; len = sizeof(u32); list_for_each_entry(asoc, &(sp->ep->asocs), asocs) { val++; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * 8.1.23 SCTP_AUTO_ASCONF * See the corresponding setsockopt entry as description */ static int sctp_getsockopt_auto_asconf(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val = 0; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk)) val = 1; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * 8.2.6. Get the Current Identifiers of Associations * (SCTP_GET_ASSOC_ID_LIST) * * This option gets the current list of SCTP association identifiers of * the SCTP associations handled by a one-to-many style socket. */ static int sctp_getsockopt_assoc_ids(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_association *asoc; struct sctp_assoc_ids *ids; u32 num = 0; if (sctp_style(sk, TCP)) return -EOPNOTSUPP; if (len < sizeof(struct sctp_assoc_ids)) return -EINVAL; list_for_each_entry(asoc, &(sp->ep->asocs), asocs) { num++; } if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num) return -EINVAL; len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num; ids = kmalloc(len, GFP_USER | __GFP_NOWARN); if (unlikely(!ids)) return -ENOMEM; ids->gaids_number_of_ids = num; num = 0; list_for_each_entry(asoc, &(sp->ep->asocs), asocs) { ids->gaids_assoc_id[num++] = asoc->assoc_id; } if (put_user(len, optlen) || copy_to_user(optval, ids, len)) { kfree(ids); return -EFAULT; } kfree(ids); return 0; } /* * SCTP_PEER_ADDR_THLDS * * This option allows us to fetch the partially failed threshold for one or all * transports in an association. See Section 6.1 of: * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt */ static int sctp_getsockopt_paddr_thresholds(struct sock *sk, char __user *optval, int len, int __user *optlen) { struct sctp_paddrthlds val; struct sctp_transport *trans; struct sctp_association *asoc; if (len < sizeof(struct sctp_paddrthlds)) return -EINVAL; len = sizeof(struct sctp_paddrthlds); if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len)) return -EFAULT; if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) { asoc = sctp_id2assoc(sk, val.spt_assoc_id); if (!asoc) return -ENOENT; val.spt_pathpfthld = asoc->pf_retrans; val.spt_pathmaxrxt = asoc->pathmaxrxt; } else { trans = sctp_addr_id2transport(sk, &val.spt_address, val.spt_assoc_id); if (!trans) return -ENOENT; val.spt_pathmaxrxt = trans->pathmaxrxt; val.spt_pathpfthld = trans->pf_retrans; } if (put_user(len, optlen) || copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* * SCTP_GET_ASSOC_STATS * * This option retrieves local per endpoint statistics. It is modeled * after OpenSolaris' implementation */ static int sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; if (put_user(len, optlen)) return -EFAULT; pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; } static int sctp_getsockopt_recvrcvinfo(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val = 0; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); if (sctp_sk(sk)->recvrcvinfo) val = 1; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } static int sctp_getsockopt_recvnxtinfo(struct sock *sk, int len, char __user *optval, int __user *optlen) { int val = 0; if (len < sizeof(int)) return -EINVAL; len = sizeof(int); if (sctp_sk(sk)->recvnxtinfo) val = 1; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } static int sctp_getsockopt_pr_supported(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_value params; struct sctp_association *asoc; int retval = -EFAULT; if (len < sizeof(params)) { retval = -EINVAL; goto out; } len = sizeof(params); if (copy_from_user(&params, optval, len)) goto out; asoc = sctp_id2assoc(sk, params.assoc_id); if (asoc) { params.assoc_value = asoc->prsctp_enable; } else if (!params.assoc_id) { struct sctp_sock *sp = sctp_sk(sk); params.assoc_value = sp->ep->prsctp_enable; } else { retval = -EINVAL; goto out; } if (put_user(len, optlen)) goto out; if (copy_to_user(optval, &params, len)) goto out; retval = 0; out: return retval; } static int sctp_getsockopt_default_prinfo(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_default_prinfo info; struct sctp_association *asoc; int retval = -EFAULT; if (len < sizeof(info)) { retval = -EINVAL; goto out; } len = sizeof(info); if (copy_from_user(&info, optval, len)) goto out; asoc = sctp_id2assoc(sk, info.pr_assoc_id); if (asoc) { info.pr_policy = SCTP_PR_POLICY(asoc->default_flags); info.pr_value = asoc->default_timetolive; } else if (!info.pr_assoc_id) { struct sctp_sock *sp = sctp_sk(sk); info.pr_policy = SCTP_PR_POLICY(sp->default_flags); info.pr_value = sp->default_timetolive; } else { retval = -EINVAL; goto out; } if (put_user(len, optlen)) goto out; if (copy_to_user(optval, &info, len)) goto out; retval = 0; out: return retval; } static int sctp_getsockopt_pr_assocstatus(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_prstatus params; struct sctp_association *asoc; int policy; int retval = -EINVAL; if (len < sizeof(params)) goto out; len = sizeof(params); if (copy_from_user(&params, optval, len)) { retval = -EFAULT; goto out; } policy = params.sprstat_policy; if (policy & ~SCTP_PR_SCTP_MASK) goto out; asoc = sctp_id2assoc(sk, params.sprstat_assoc_id); if (!asoc) goto out; if (policy == SCTP_PR_SCTP_NONE) { params.sprstat_abandoned_unsent = 0; params.sprstat_abandoned_sent = 0; for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) { params.sprstat_abandoned_unsent += asoc->abandoned_unsent[policy]; params.sprstat_abandoned_sent += asoc->abandoned_sent[policy]; } } else { params.sprstat_abandoned_unsent = asoc->abandoned_unsent[__SCTP_PR_INDEX(policy)]; params.sprstat_abandoned_sent = asoc->abandoned_sent[__SCTP_PR_INDEX(policy)]; } if (put_user(len, optlen)) { retval = -EFAULT; goto out; } if (copy_to_user(optval, &params, len)) { retval = -EFAULT; goto out; } retval = 0; out: return retval; } static int sctp_getsockopt_enable_strreset(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_value params; struct sctp_association *asoc; int retval = -EFAULT; if (len < sizeof(params)) { retval = -EINVAL; goto out; } len = sizeof(params); if (copy_from_user(&params, optval, len)) goto out; asoc = sctp_id2assoc(sk, params.assoc_id); if (asoc) { params.assoc_value = asoc->strreset_enable; } else if (!params.assoc_id) { struct sctp_sock *sp = sctp_sk(sk); params.assoc_value = sp->ep->strreset_enable; } else { retval = -EINVAL; goto out; } if (put_user(len, optlen)) goto out; if (copy_to_user(optval, &params, len)) goto out; retval = 0; out: return retval; } static int sctp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { int retval = 0; int len; pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname); /* I can hardly begin to describe how wrong this is. This is * so broken as to be worse than useless. The API draft * REALLY is NOT helpful here... I am not convinced that the * semantics of getsockopt() with a level OTHER THAN SOL_SCTP * are at all well-founded. */ if (level != SOL_SCTP) { struct sctp_af *af = sctp_sk(sk)->pf->af; retval = af->getsockopt(sk, level, optname, optval, optlen); return retval; } if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; lock_sock(sk); switch (optname) { case SCTP_STATUS: retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen); break; case SCTP_DISABLE_FRAGMENTS: retval = sctp_getsockopt_disable_fragments(sk, len, optval, optlen); break; case SCTP_EVENTS: retval = sctp_getsockopt_events(sk, len, optval, optlen); break; case SCTP_AUTOCLOSE: retval = sctp_getsockopt_autoclose(sk, len, optval, optlen); break; case SCTP_SOCKOPT_PEELOFF: retval = sctp_getsockopt_peeloff(sk, len, optval, optlen); break; case SCTP_PEER_ADDR_PARAMS: retval = sctp_getsockopt_peer_addr_params(sk, len, optval, optlen); break; case SCTP_DELAYED_SACK: retval = sctp_getsockopt_delayed_ack(sk, len, optval, optlen); break; case SCTP_INITMSG: retval = sctp_getsockopt_initmsg(sk, len, optval, optlen); break; case SCTP_GET_PEER_ADDRS: retval = sctp_getsockopt_peer_addrs(sk, len, optval, optlen); break; case SCTP_GET_LOCAL_ADDRS: retval = sctp_getsockopt_local_addrs(sk, len, optval, optlen); break; case SCTP_SOCKOPT_CONNECTX3: retval = sctp_getsockopt_connectx3(sk, len, optval, optlen); break; case SCTP_DEFAULT_SEND_PARAM: retval = sctp_getsockopt_default_send_param(sk, len, optval, optlen); break; case SCTP_DEFAULT_SNDINFO: retval = sctp_getsockopt_default_sndinfo(sk, len, optval, optlen); break; case SCTP_PRIMARY_ADDR: retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen); break; case SCTP_NODELAY: retval = sctp_getsockopt_nodelay(sk, len, optval, optlen); break; case SCTP_RTOINFO: retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen); break; case SCTP_ASSOCINFO: retval = sctp_getsockopt_associnfo(sk, len, optval, optlen); break; case SCTP_I_WANT_MAPPED_V4_ADDR: retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen); break; case SCTP_MAXSEG: retval = sctp_getsockopt_maxseg(sk, len, optval, optlen); break; case SCTP_GET_PEER_ADDR_INFO: retval = sctp_getsockopt_peer_addr_info(sk, len, optval, optlen); break; case SCTP_ADAPTATION_LAYER: retval = sctp_getsockopt_adaptation_layer(sk, len, optval, optlen); break; case SCTP_CONTEXT: retval = sctp_getsockopt_context(sk, len, optval, optlen); break; case SCTP_FRAGMENT_INTERLEAVE: retval = sctp_getsockopt_fragment_interleave(sk, len, optval, optlen); break; case SCTP_PARTIAL_DELIVERY_POINT: retval = sctp_getsockopt_partial_delivery_point(sk, len, optval, optlen); break; case SCTP_MAX_BURST: retval = sctp_getsockopt_maxburst(sk, len, optval, optlen); break; case SCTP_AUTH_KEY: case SCTP_AUTH_CHUNK: case SCTP_AUTH_DELETE_KEY: retval = -EOPNOTSUPP; break; case SCTP_HMAC_IDENT: retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen); break; case SCTP_AUTH_ACTIVE_KEY: retval = sctp_getsockopt_active_key(sk, len, optval, optlen); break; case SCTP_PEER_AUTH_CHUNKS: retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval, optlen); break; case SCTP_LOCAL_AUTH_CHUNKS: retval = sctp_getsockopt_local_auth_chunks(sk, len, optval, optlen); break; case SCTP_GET_ASSOC_NUMBER: retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen); break; case SCTP_GET_ASSOC_ID_LIST: retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen); break; case SCTP_AUTO_ASCONF: retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen); break; case SCTP_PEER_ADDR_THLDS: retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen); break; case SCTP_GET_ASSOC_STATS: retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen); break; case SCTP_RECVRCVINFO: retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen); break; case SCTP_RECVNXTINFO: retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen); break; case SCTP_PR_SUPPORTED: retval = sctp_getsockopt_pr_supported(sk, len, optval, optlen); break; case SCTP_DEFAULT_PRINFO: retval = sctp_getsockopt_default_prinfo(sk, len, optval, optlen); break; case SCTP_PR_ASSOC_STATUS: retval = sctp_getsockopt_pr_assocstatus(sk, len, optval, optlen); break; case SCTP_ENABLE_STREAM_RESET: retval = sctp_getsockopt_enable_strreset(sk, len, optval, optlen); break; default: retval = -ENOPROTOOPT; break; } release_sock(sk); return retval; } static int sctp_hash(struct sock *sk) { /* STUB */ return 0; } static void sctp_unhash(struct sock *sk) { /* STUB */ } /* Check if port is acceptable. Possibly find first available port. * * The port hash table (contained in the 'global' SCTP protocol storage * returned by struct sctp_protocol *sctp_get_protocol()). The hash * table is an array of 4096 lists (sctp_bind_hashbucket). Each * list (the list number is the port number hashed out, so as you * would expect from a hash function, all the ports in a given list have * such a number that hashes out to the same list number; you were * expecting that, right?); so each list has a set of ports, with a * link to the socket (struct sock) that uses it, the port number and * a fastreuse flag (FIXME: NPI ipg). */ static struct sctp_bind_bucket *sctp_bucket_create( struct sctp_bind_hashbucket *head, struct net *, unsigned short snum); static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr) { struct sctp_bind_hashbucket *head; /* hash list */ struct sctp_bind_bucket *pp; unsigned short snum; int ret; snum = ntohs(addr->v4.sin_port); pr_debug("%s: begins, snum:%d\n", __func__, snum); local_bh_disable(); if (snum == 0) { /* Search for an available port. */ int low, high, remaining, index; unsigned int rover; struct net *net = sock_net(sk); inet_get_local_port_range(net, &low, &high); remaining = (high - low) + 1; rover = prandom_u32() % remaining + low; do { rover++; if ((rover < low) || (rover > high)) rover = low; if (inet_is_local_reserved_port(net, rover)) continue; index = sctp_phashfn(sock_net(sk), rover); head = &sctp_port_hashtable[index]; spin_lock(&head->lock); sctp_for_each_hentry(pp, &head->chain) if ((pp->port == rover) && net_eq(sock_net(sk), pp->net)) goto next; break; next: spin_unlock(&head->lock); } while (--remaining > 0); /* Exhausted local port range during search? */ ret = 1; if (remaining <= 0) goto fail; /* OK, here is the one we will use. HEAD (the port * hash table list entry) is non-NULL and we hold it's * mutex. */ snum = rover; } else { /* We are given an specific port number; we verify * that it is not being used. If it is used, we will * exahust the search in the hash list corresponding * to the port number (snum) - we detect that with the * port iterator, pp being NULL. */ head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)]; spin_lock(&head->lock); sctp_for_each_hentry(pp, &head->chain) { if ((pp->port == snum) && net_eq(pp->net, sock_net(sk))) goto pp_found; } } pp = NULL; goto pp_not_found; pp_found: if (!hlist_empty(&pp->owner)) { /* We had a port hash table hit - there is an * available port (pp != NULL) and it is being * used by other socket (pp->owner not empty); that other * socket is going to be sk2. */ int reuse = sk->sk_reuse; struct sock *sk2; pr_debug("%s: found a possible match\n", __func__); if (pp->fastreuse && sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING) goto success; /* Run through the list of sockets bound to the port * (pp->port) [via the pointers bind_next and * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one, * we get the endpoint they describe and run through * the endpoint's list of IP (v4 or v6) addresses, * comparing each of the addresses with the address of * the socket sk. If we find a match, then that means * that this port/socket (sk) combination are already * in an endpoint. */ sk_for_each_bound(sk2, &pp->owner) { struct sctp_endpoint *ep2; ep2 = sctp_sk(sk2)->ep; if (sk == sk2 || (reuse && sk2->sk_reuse && sk2->sk_state != SCTP_SS_LISTENING)) continue; if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr, sctp_sk(sk2), sctp_sk(sk))) { ret = (long)sk2; goto fail_unlock; } } pr_debug("%s: found a match\n", __func__); } pp_not_found: /* If there was a hash table miss, create a new port. */ ret = 1; if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum))) goto fail_unlock; /* In either case (hit or miss), make sure fastreuse is 1 only * if sk->sk_reuse is too (that is, if the caller requested * SO_REUSEADDR on this socket -sk-). */ if (hlist_empty(&pp->owner)) { if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING) pp->fastreuse = 1; else pp->fastreuse = 0; } else if (pp->fastreuse && (!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING)) pp->fastreuse = 0; /* We are set, so fill up all the data in the hash table * entry, tie the socket list information with the rest of the * sockets FIXME: Blurry, NPI (ipg). */ success: if (!sctp_sk(sk)->bind_hash) { inet_sk(sk)->inet_num = snum; sk_add_bind_node(sk, &pp->owner); sctp_sk(sk)->bind_hash = pp; } ret = 0; fail_unlock: spin_unlock(&head->lock); fail: local_bh_enable(); return ret; } /* Assign a 'snum' port to the socket. If snum == 0, an ephemeral * port is requested. */ static int sctp_get_port(struct sock *sk, unsigned short snum) { union sctp_addr addr; struct sctp_af *af = sctp_sk(sk)->pf->af; /* Set up a dummy address struct from the sk. */ af->from_sk(&addr, sk); addr.v4.sin_port = htons(snum); /* Note: sk->sk_num gets filled in if ephemeral port request. */ return !!sctp_get_port_local(sk, &addr); } /* * Move a socket to LISTENING state. */ static int sctp_listen_start(struct sock *sk, int backlog) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_endpoint *ep = sp->ep; struct crypto_shash *tfm = NULL; char alg[32]; /* Allocate HMAC for generating cookie. */ if (!sp->hmac && sp->sctp_hmac_alg) { sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg); tfm = crypto_alloc_shash(alg, 0, 0); if (IS_ERR(tfm)) { net_info_ratelimited("failed to load transform for %s: %ld\n", sp->sctp_hmac_alg, PTR_ERR(tfm)); return -ENOSYS; } sctp_sk(sk)->hmac = tfm; } /* * If a bind() or sctp_bindx() is not called prior to a listen() * call that allows new associations to be accepted, the system * picks an ephemeral port and will choose an address set equivalent * to binding with a wildcard address. * * This is not currently spelled out in the SCTP sockets * extensions draft, but follows the practice as seen in TCP * sockets. * */ sk->sk_state = SCTP_SS_LISTENING; if (!ep->base.bind_addr.port) { if (sctp_autobind(sk)) return -EAGAIN; } else { if (sctp_get_port(sk, inet_sk(sk)->inet_num)) { sk->sk_state = SCTP_SS_CLOSED; return -EADDRINUSE; } } sk->sk_max_ack_backlog = backlog; sctp_hash_endpoint(ep); return 0; } /* * 4.1.3 / 5.1.3 listen() * * By default, new associations are not accepted for UDP style sockets. * An application uses listen() to mark a socket as being able to * accept new associations. * * On TCP style sockets, applications use listen() to ready the SCTP * endpoint for accepting inbound associations. * * On both types of endpoints a backlog of '0' disables listening. * * Move a socket to LISTENING state. */ int sctp_inet_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; struct sctp_endpoint *ep = sctp_sk(sk)->ep; int err = -EINVAL; if (unlikely(backlog < 0)) return err; lock_sock(sk); /* Peeled-off sockets are not allowed to listen(). */ if (sctp_style(sk, UDP_HIGH_BANDWIDTH)) goto out; if (sock->state != SS_UNCONNECTED) goto out; /* If backlog is zero, disable listening. */ if (!backlog) { if (sctp_sstate(sk, CLOSED)) goto out; err = 0; sctp_unhash_endpoint(ep); sk->sk_state = SCTP_SS_CLOSED; if (sk->sk_reuse) sctp_sk(sk)->bind_hash->fastreuse = 1; goto out; } /* If we are already listening, just update the backlog */ if (sctp_sstate(sk, LISTENING)) sk->sk_max_ack_backlog = backlog; else { err = sctp_listen_start(sk, backlog); if (err) goto out; } err = 0; out: release_sock(sk); return err; } /* * This function is done by modeling the current datagram_poll() and the * tcp_poll(). Note that, based on these implementations, we don't * lock the socket in this function, even though it seems that, * ideally, locking or some other mechanisms can be used to ensure * the integrity of the counters (sndbuf and wmem_alloc) used * in this place. We assume that we don't need locks either until proven * otherwise. * * Another thing to note is that we include the Async I/O support * here, again, by modeling the current TCP/UDP code. We don't have * a good way to test with it yet. */ unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct sctp_sock *sp = sctp_sk(sk); unsigned int mask; poll_wait(file, sk_sleep(sk), wait); sock_rps_record_flow(sk); /* A TCP-style listening socket becomes readable when the accept queue * is not empty. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) return (!list_empty(&sp->ep->asocs)) ? (POLLIN | POLLRDNORM) : 0; mask = 0; /* Is there any exceptional events? */ if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR | (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0); if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; /* Is it readable? Reconsider this code with TCP-style support. */ if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; /* The association is either gone or not ready. */ if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED)) return mask; /* Is it writable? */ if (sctp_writeable(sk)) { mask |= POLLOUT | POLLWRNORM; } else { sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); /* * Since the socket is not locked, the buffer * might be made available after the writeable check and * before the bit is set. This could cause a lost I/O * signal. tcp_poll() has a race breaker for this race * condition. Based on their implementation, we put * in the following code to cover it as well. */ if (sctp_writeable(sk)) mask |= POLLOUT | POLLWRNORM; } return mask; } /******************************************************************** * 2nd Level Abstractions ********************************************************************/ static struct sctp_bind_bucket *sctp_bucket_create( struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum) { struct sctp_bind_bucket *pp; pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC); if (pp) { SCTP_DBG_OBJCNT_INC(bind_bucket); pp->port = snum; pp->fastreuse = 0; INIT_HLIST_HEAD(&pp->owner); pp->net = net; hlist_add_head(&pp->node, &head->chain); } return pp; } /* Caller must hold hashbucket lock for this tb with local BH disabled */ static void sctp_bucket_destroy(struct sctp_bind_bucket *pp) { if (pp && hlist_empty(&pp->owner)) { __hlist_del(&pp->node); kmem_cache_free(sctp_bucket_cachep, pp); SCTP_DBG_OBJCNT_DEC(bind_bucket); } } /* Release this socket's reference to a local port. */ static inline void __sctp_put_port(struct sock *sk) { struct sctp_bind_hashbucket *head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), inet_sk(sk)->inet_num)]; struct sctp_bind_bucket *pp; spin_lock(&head->lock); pp = sctp_sk(sk)->bind_hash; __sk_del_bind_node(sk); sctp_sk(sk)->bind_hash = NULL; inet_sk(sk)->inet_num = 0; sctp_bucket_destroy(pp); spin_unlock(&head->lock); } void sctp_put_port(struct sock *sk) { local_bh_disable(); __sctp_put_port(sk); local_bh_enable(); } /* * The system picks an ephemeral port and choose an address set equivalent * to binding with a wildcard address. * One of those addresses will be the primary address for the association. * This automatically enables the multihoming capability of SCTP. */ static int sctp_autobind(struct sock *sk) { union sctp_addr autoaddr; struct sctp_af *af; __be16 port; /* Initialize a local sockaddr structure to INADDR_ANY. */ af = sctp_sk(sk)->pf->af; port = htons(inet_sk(sk)->inet_num); af->inaddr_any(&autoaddr, port); return sctp_do_bind(sk, &autoaddr, af->sockaddr_len); } /* Parse out IPPROTO_SCTP CMSG headers. Perform only minimal validation. * * From RFC 2292 * 4.2 The cmsghdr Structure * * * When ancillary data is sent or received, any number of ancillary data * objects can be specified by the msg_control and msg_controllen members of * the msghdr structure, because each object is preceded by * a cmsghdr structure defining the object's length (the cmsg_len member). * Historically Berkeley-derived implementations have passed only one object * at a time, but this API allows multiple objects to be * passed in a single call to sendmsg() or recvmsg(). The following example * shows two ancillary data objects in a control buffer. * * |<--------------------------- msg_controllen -------------------------->| * | | * * |<----- ancillary data object ----->|<----- ancillary data object ----->| * * |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->| * | | | * * |<---------- cmsg_len ---------->| |<--------- cmsg_len ----------->| | * * |<--------- CMSG_LEN() --------->| |<-------- CMSG_LEN() ---------->| | * | | | | | * * +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+ * |cmsg_|cmsg_|cmsg_|XX| |XX|cmsg_|cmsg_|cmsg_|XX| |XX| * * |len |level|type |XX|cmsg_data[]|XX|len |level|type |XX|cmsg_data[]|XX| * * +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+ * ^ * | * * msg_control * points here */ static int sctp_msghdr_parse(const struct msghdr *msg, sctp_cmsgs_t *cmsgs) { struct cmsghdr *cmsg; struct msghdr *my_msg = (struct msghdr *)msg; for_each_cmsghdr(cmsg, my_msg) { if (!CMSG_OK(my_msg, cmsg)) return -EINVAL; /* Should we parse this header or ignore? */ if (cmsg->cmsg_level != IPPROTO_SCTP) continue; /* Strictly check lengths following example in SCM code. */ switch (cmsg->cmsg_type) { case SCTP_INIT: /* SCTP Socket API Extension * 5.3.1 SCTP Initiation Structure (SCTP_INIT) * * This cmsghdr structure provides information for * initializing new SCTP associations with sendmsg(). * The SCTP_INITMSG socket option uses this same data * structure. This structure is not used for * recvmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ---------------------- * IPPROTO_SCTP SCTP_INIT struct sctp_initmsg */ if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg))) return -EINVAL; cmsgs->init = CMSG_DATA(cmsg); break; case SCTP_SNDRCV: /* SCTP Socket API Extension * 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV) * * This cmsghdr structure specifies SCTP options for * sendmsg() and describes SCTP header information * about a received message through recvmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ---------------------- * IPPROTO_SCTP SCTP_SNDRCV struct sctp_sndrcvinfo */ if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo))) return -EINVAL; cmsgs->srinfo = CMSG_DATA(cmsg); if (cmsgs->srinfo->sinfo_flags & ~(SCTP_UNORDERED | SCTP_ADDR_OVER | SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK | SCTP_ABORT | SCTP_EOF)) return -EINVAL; break; case SCTP_SNDINFO: /* SCTP Socket API Extension * 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO) * * This cmsghdr structure specifies SCTP options for * sendmsg(). This structure and SCTP_RCVINFO replaces * SCTP_SNDRCV which has been deprecated. * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ --------------------- * IPPROTO_SCTP SCTP_SNDINFO struct sctp_sndinfo */ if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo))) return -EINVAL; cmsgs->sinfo = CMSG_DATA(cmsg); if (cmsgs->sinfo->snd_flags & ~(SCTP_UNORDERED | SCTP_ADDR_OVER | SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK | SCTP_ABORT | SCTP_EOF)) return -EINVAL; break; default: return -EINVAL; } } return 0; } /* * Wait for a packet.. * Note: This function is the same function as in core/datagram.c * with a few modifications to make lksctp work. */ static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p) { int error; DEFINE_WAIT(wait); prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); /* Socket errors? */ error = sock_error(sk); if (error) goto out; if (!skb_queue_empty(&sk->sk_receive_queue)) goto ready; /* Socket shut down? */ if (sk->sk_shutdown & RCV_SHUTDOWN) goto out; /* Sequenced packets can come disconnected. If so we report the * problem. */ error = -ENOTCONN; /* Is there a good reason to think that we may receive some data? */ if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING)) goto out; /* Handle signals. */ if (signal_pending(current)) goto interrupted; /* Let another process have a go. Since we are going to sleep * anyway. Note: This may cause odd behaviors if the message * does not fit in the user's buffer, but this seems to be the * only way to honor MSG_DONTWAIT realistically. */ release_sock(sk); *timeo_p = schedule_timeout(*timeo_p); lock_sock(sk); ready: finish_wait(sk_sleep(sk), &wait); return 0; interrupted: error = sock_intr_errno(*timeo_p); out: finish_wait(sk_sleep(sk), &wait); *err = error; return error; } /* Receive a datagram. * Note: This is pretty much the same routine as in core/datagram.c * with a few changes to make lksctp work. */ struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags, int noblock, int *err) { int error; struct sk_buff *skb; long timeo; timeo = sock_rcvtimeo(sk, noblock); pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo, MAX_SCHEDULE_TIMEOUT); do { /* Again only user level code calls this function, * so nothing interrupt level * will suddenly eat the receive_queue. * * Look at current nfs client by the way... * However, this function was correct in any case. 8) */ if (flags & MSG_PEEK) { skb = skb_peek(&sk->sk_receive_queue); if (skb) atomic_inc(&skb->users); } else { skb = __skb_dequeue(&sk->sk_receive_queue); } if (skb) return skb; /* Caller is allowed not to check sk->sk_err before calling. */ error = sock_error(sk); if (error) goto no_packet; if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk_can_busy_loop(sk) && sk_busy_loop(sk, noblock)) continue; /* User doesn't want to wait. */ error = -EAGAIN; if (!timeo) goto no_packet; } while (sctp_wait_for_packet(sk, err, &timeo) == 0); return NULL; no_packet: *err = error; return NULL; } /* If sndbuf has changed, wake up per association sndbuf waiters. */ static void __sctp_write_space(struct sctp_association *asoc) { struct sock *sk = asoc->base.sk; if (sctp_wspace(asoc) <= 0) return; if (waitqueue_active(&asoc->wait)) wake_up_interruptible(&asoc->wait); if (sctp_writeable(sk)) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq) { if (waitqueue_active(&wq->wait)) wake_up_interruptible(&wq->wait); /* Note that we try to include the Async I/O support * here by modeling from the current TCP/UDP code. * We have not tested with it yet. */ if (!(sk->sk_shutdown & SEND_SHUTDOWN)) sock_wake_async(wq, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } } static void sctp_wake_up_waiters(struct sock *sk, struct sctp_association *asoc) { struct sctp_association *tmp = asoc; /* We do accounting for the sndbuf space per association, * so we only need to wake our own association. */ if (asoc->ep->sndbuf_policy) return __sctp_write_space(asoc); /* If association goes down and is just flushing its * outq, then just normally notify others. */ if (asoc->base.dead) return sctp_write_space(sk); /* Accounting for the sndbuf space is per socket, so we * need to wake up others, try to be fair and in case of * other associations, let them have a go first instead * of just doing a sctp_write_space() call. * * Note that we reach sctp_wake_up_waiters() only when * associations free up queued chunks, thus we are under * lock and the list of associations on a socket is * guaranteed not to change. */ for (tmp = list_next_entry(tmp, asocs); 1; tmp = list_next_entry(tmp, asocs)) { /* Manually skip the head element. */ if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs)) continue; /* Wake up association. */ __sctp_write_space(tmp); /* We've reached the end. */ if (tmp == asoc) break; } } /* Do accounting for the sndbuf space. * Decrement the used sndbuf space of the corresponding association by the * data size which was just transmitted(freed). */ static void sctp_wfree(struct sk_buff *skb) { struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg; struct sctp_association *asoc = chunk->asoc; struct sock *sk = asoc->base.sk; asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) + sizeof(struct sk_buff) + sizeof(struct sctp_chunk); atomic_sub(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc); /* * This undoes what is done via sctp_set_owner_w and sk_mem_charge */ sk->sk_wmem_queued -= skb->truesize; sk_mem_uncharge(sk, skb->truesize); sock_wfree(skb); sctp_wake_up_waiters(sk, asoc); sctp_association_put(asoc); } /* Do accounting for the receive space on the socket. * Accounting for the association is done in ulpevent.c * We set this as a destructor for the cloned data skbs so that * accounting is done at the correct time. */ void sctp_sock_rfree(struct sk_buff *skb) { struct sock *sk = skb->sk; struct sctp_ulpevent *event = sctp_skb2event(skb); atomic_sub(event->rmem_len, &sk->sk_rmem_alloc); /* * Mimic the behavior of sock_rfree */ sk_mem_uncharge(sk, event->rmem_len); } /* Helper function to wait for space in the sndbuf. */ static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, size_t msg_len) { struct sock *sk = asoc->base.sk; int err = 0; long current_timeo = *timeo_p; DEFINE_WAIT(wait); pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc, *timeo_p, msg_len); /* Increment the association's refcnt. */ sctp_association_hold(asoc); /* Wait on the association specific sndbuf space. */ for (;;) { prepare_to_wait_exclusive(&asoc->wait, &wait, TASK_INTERRUPTIBLE); if (!*timeo_p) goto do_nonblock; if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING || asoc->base.dead) goto do_error; if (signal_pending(current)) goto do_interrupted; if (msg_len <= sctp_wspace(asoc)) break; /* Let another process have a go. Since we are going * to sleep anyway. */ release_sock(sk); current_timeo = schedule_timeout(current_timeo); if (sk != asoc->base.sk) goto do_error; lock_sock(sk); *timeo_p = current_timeo; } out: finish_wait(&asoc->wait, &wait); /* Release the association's refcnt. */ sctp_association_put(asoc); return err; do_error: err = -EPIPE; goto out; do_interrupted: err = sock_intr_errno(*timeo_p); goto out; do_nonblock: err = -EAGAIN; goto out; } void sctp_data_ready(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (skwq_has_sleeper(wq)) wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLRDNORM | POLLRDBAND); sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); rcu_read_unlock(); } /* If socket sndbuf has changed, wake up all per association waiters. */ void sctp_write_space(struct sock *sk) { struct sctp_association *asoc; /* Wake up the tasks in each wait queue. */ list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) { __sctp_write_space(asoc); } } /* Is there any sndbuf space available on the socket? * * Note that sk_wmem_alloc is the sum of the send buffers on all of the * associations on the same socket. For a UDP-style socket with * multiple associations, it is possible for it to be "unwriteable" * prematurely. I assume that this is acceptable because * a premature "unwriteable" is better than an accidental "writeable" which * would cause an unwanted block under certain circumstances. For the 1-1 * UDP-style sockets or TCP-style sockets, this code should work. * - Daisy */ static int sctp_writeable(struct sock *sk) { int amt = 0; amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amt < 0) amt = 0; return amt; } /* Wait for an association to go into ESTABLISHED state. If timeout is 0, * returns immediately with EINPROGRESS. */ static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p) { struct sock *sk = asoc->base.sk; int err = 0; long current_timeo = *timeo_p; DEFINE_WAIT(wait); pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p); /* Increment the association's refcnt. */ sctp_association_hold(asoc); for (;;) { prepare_to_wait_exclusive(&asoc->wait, &wait, TASK_INTERRUPTIBLE); if (!*timeo_p) goto do_nonblock; if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING || asoc->base.dead) goto do_error; if (signal_pending(current)) goto do_interrupted; if (sctp_state(asoc, ESTABLISHED)) break; /* Let another process have a go. Since we are going * to sleep anyway. */ release_sock(sk); current_timeo = schedule_timeout(current_timeo); lock_sock(sk); *timeo_p = current_timeo; } out: finish_wait(&asoc->wait, &wait); /* Release the association's refcnt. */ sctp_association_put(asoc); return err; do_error: if (asoc->init_err_counter + 1 > asoc->max_init_attempts) err = -ETIMEDOUT; else err = -ECONNREFUSED; goto out; do_interrupted: err = sock_intr_errno(*timeo_p); goto out; do_nonblock: err = -EINPROGRESS; goto out; } static int sctp_wait_for_accept(struct sock *sk, long timeo) { struct sctp_endpoint *ep; int err = 0; DEFINE_WAIT(wait); ep = sctp_sk(sk)->ep; for (;;) { prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (list_empty(&ep->asocs)) { release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); } err = -EINVAL; if (!sctp_sstate(sk, LISTENING)) break; err = 0; if (!list_empty(&ep->asocs)) break; err = sock_intr_errno(timeo); if (signal_pending(current)) break; err = -EAGAIN; if (!timeo) break; } finish_wait(sk_sleep(sk), &wait); return err; } static void sctp_wait_for_close(struct sock *sk, long timeout) { DEFINE_WAIT(wait); do { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (list_empty(&sctp_sk(sk)->ep->asocs)) break; release_sock(sk); timeout = schedule_timeout(timeout); lock_sock(sk); } while (!signal_pending(current) && timeout); finish_wait(sk_sleep(sk), &wait); } static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk) { struct sk_buff *frag; if (!skb->data_len) goto done; /* Don't forget the fragments. */ skb_walk_frags(skb, frag) sctp_skb_set_owner_r_frag(frag, sk); done: sctp_skb_set_owner_r(skb, sk); } void sctp_copy_sock(struct sock *newsk, struct sock *sk, struct sctp_association *asoc) { struct inet_sock *inet = inet_sk(sk); struct inet_sock *newinet; newsk->sk_type = sk->sk_type; newsk->sk_bound_dev_if = sk->sk_bound_dev_if; newsk->sk_flags = sk->sk_flags; newsk->sk_tsflags = sk->sk_tsflags; newsk->sk_no_check_tx = sk->sk_no_check_tx; newsk->sk_no_check_rx = sk->sk_no_check_rx; newsk->sk_reuse = sk->sk_reuse; newsk->sk_shutdown = sk->sk_shutdown; newsk->sk_destruct = sctp_destruct_sock; newsk->sk_family = sk->sk_family; newsk->sk_protocol = IPPROTO_SCTP; newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv; newsk->sk_sndbuf = sk->sk_sndbuf; newsk->sk_rcvbuf = sk->sk_rcvbuf; newsk->sk_lingertime = sk->sk_lingertime; newsk->sk_rcvtimeo = sk->sk_rcvtimeo; newsk->sk_sndtimeo = sk->sk_sndtimeo; newsk->sk_rxhash = sk->sk_rxhash; newinet = inet_sk(newsk); /* Initialize sk's sport, dport, rcv_saddr and daddr for * getsockname() and getpeername() */ newinet->inet_sport = inet->inet_sport; newinet->inet_saddr = inet->inet_saddr; newinet->inet_rcv_saddr = inet->inet_rcv_saddr; newinet->inet_dport = htons(asoc->peer.port); newinet->pmtudisc = inet->pmtudisc; newinet->inet_id = asoc->next_tsn ^ jiffies; newinet->uc_ttl = inet->uc_ttl; newinet->mc_loop = 1; newinet->mc_ttl = 1; newinet->mc_index = 0; newinet->mc_list = NULL; if (newsk->sk_flags & SK_FLAGS_TIMESTAMP) net_enable_timestamp(); security_sk_clone(sk, newsk); } static inline void sctp_copy_descendant(struct sock *sk_to, const struct sock *sk_from) { int ancestor_size = sizeof(struct inet_sock) + sizeof(struct sctp_sock) - offsetof(struct sctp_sock, auto_asconf_list); if (sk_from->sk_family == PF_INET6) ancestor_size += sizeof(struct ipv6_pinfo); __inet_sk_copy_descendant(sk_to, sk_from, ancestor_size); } /* Populate the fields of the newsk from the oldsk and migrate the assoc * and its messages to the newsk. */ static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk, struct sctp_association *assoc, sctp_socket_type_t type) { struct sctp_sock *oldsp = sctp_sk(oldsk); struct sctp_sock *newsp = sctp_sk(newsk); struct sctp_bind_bucket *pp; /* hash list port iterator */ struct sctp_endpoint *newep = newsp->ep; struct sk_buff *skb, *tmp; struct sctp_ulpevent *event; struct sctp_bind_hashbucket *head; /* Migrate socket buffer sizes and all the socket level options to the * new socket. */ newsk->sk_sndbuf = oldsk->sk_sndbuf; newsk->sk_rcvbuf = oldsk->sk_rcvbuf; /* Brute force copy old sctp opt. */ sctp_copy_descendant(newsk, oldsk); /* Restore the ep value that was overwritten with the above structure * copy. */ newsp->ep = newep; newsp->hmac = NULL; /* Hook this new socket in to the bind_hash list. */ head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk), inet_sk(oldsk)->inet_num)]; spin_lock_bh(&head->lock); pp = sctp_sk(oldsk)->bind_hash; sk_add_bind_node(newsk, &pp->owner); sctp_sk(newsk)->bind_hash = pp; inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num; spin_unlock_bh(&head->lock); /* Copy the bind_addr list from the original endpoint to the new * endpoint so that we can handle restarts properly */ sctp_bind_addr_dup(&newsp->ep->base.bind_addr, &oldsp->ep->base.bind_addr, GFP_KERNEL); /* Move any messages in the old socket's receive queue that are for the * peeled off association to the new socket's receive queue. */ sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { __skb_unlink(skb, &oldsk->sk_receive_queue); __skb_queue_tail(&newsk->sk_receive_queue, skb); sctp_skb_set_owner_r_frag(skb, newsk); } } /* Clean up any messages pending delivery due to partial * delivery. Three cases: * 1) No partial deliver; no work. * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby. * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue. */ skb_queue_head_init(&newsp->pd_lobby); atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode); if (atomic_read(&sctp_sk(oldsk)->pd_mode)) { struct sk_buff_head *queue; /* Decide which queue to move pd_lobby skbs to. */ if (assoc->ulpq.pd_mode) { queue = &newsp->pd_lobby; } else queue = &newsk->sk_receive_queue; /* Walk through the pd_lobby, looking for skbs that * need moved to the new socket. */ sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) { event = sctp_skb2event(skb); if (event->asoc == assoc) { __skb_unlink(skb, &oldsp->pd_lobby); __skb_queue_tail(queue, skb); sctp_skb_set_owner_r_frag(skb, newsk); } } /* Clear up any skbs waiting for the partial * delivery to finish. */ if (assoc->ulpq.pd_mode) sctp_clear_pd(oldsk, NULL); } sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp) sctp_skb_set_owner_r_frag(skb, newsk); sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp) sctp_skb_set_owner_r_frag(skb, newsk); /* Set the type of socket to indicate that it is peeled off from the * original UDP-style socket or created with the accept() call on a * TCP-style socket.. */ newsp->type = type; /* Mark the new socket "in-use" by the user so that any packets * that may arrive on the association after we've moved it are * queued to the backlog. This prevents a potential race between * backlog processing on the old socket and new-packet processing * on the new socket. * * The caller has just allocated newsk so we can guarantee that other * paths won't try to lock it and then oldsk. */ lock_sock_nested(newsk, SINGLE_DEPTH_NESTING); sctp_assoc_migrate(assoc, newsk); /* If the association on the newsk is already closed before accept() * is called, set RCV_SHUTDOWN flag. */ if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) { newsk->sk_state = SCTP_SS_CLOSED; newsk->sk_shutdown |= RCV_SHUTDOWN; } else { newsk->sk_state = SCTP_SS_ESTABLISHED; } release_sock(newsk); } /* This proto struct describes the ULP interface for SCTP. */ struct proto sctp_prot = { .name = "SCTP", .owner = THIS_MODULE, .close = sctp_close, .connect = sctp_connect, .disconnect = sctp_disconnect, .accept = sctp_accept, .ioctl = sctp_ioctl, .init = sctp_init_sock, .destroy = sctp_destroy_sock, .shutdown = sctp_shutdown, .setsockopt = sctp_setsockopt, .getsockopt = sctp_getsockopt, .sendmsg = sctp_sendmsg, .recvmsg = sctp_recvmsg, .bind = sctp_bind, .backlog_rcv = sctp_backlog_rcv, .hash = sctp_hash, .unhash = sctp_unhash, .get_port = sctp_get_port, .obj_size = sizeof(struct sctp_sock), .sysctl_mem = sysctl_sctp_mem, .sysctl_rmem = sysctl_sctp_rmem, .sysctl_wmem = sysctl_sctp_wmem, .memory_pressure = &sctp_memory_pressure, .enter_memory_pressure = sctp_enter_memory_pressure, .memory_allocated = &sctp_memory_allocated, .sockets_allocated = &sctp_sockets_allocated, }; #if IS_ENABLED(CONFIG_IPV6) #include <net/transp_v6.h> static void sctp_v6_destroy_sock(struct sock *sk) { sctp_destroy_sock(sk); inet6_destroy_sock(sk); } struct proto sctpv6_prot = { .name = "SCTPv6", .owner = THIS_MODULE, .close = sctp_close, .connect = sctp_connect, .disconnect = sctp_disconnect, .accept = sctp_accept, .ioctl = sctp_ioctl, .init = sctp_init_sock, .destroy = sctp_v6_destroy_sock, .shutdown = sctp_shutdown, .setsockopt = sctp_setsockopt, .getsockopt = sctp_getsockopt, .sendmsg = sctp_sendmsg, .recvmsg = sctp_recvmsg, .bind = sctp_bind, .backlog_rcv = sctp_backlog_rcv, .hash = sctp_hash, .unhash = sctp_unhash, .get_port = sctp_get_port, .obj_size = sizeof(struct sctp6_sock), .sysctl_mem = sysctl_sctp_mem, .sysctl_rmem = sysctl_sctp_rmem, .sysctl_wmem = sysctl_sctp_wmem, .memory_pressure = &sctp_memory_pressure, .enter_memory_pressure = sctp_enter_memory_pressure, .memory_allocated = &sctp_memory_allocated, .sockets_allocated = &sctp_sockets_allocated, }; #endif /* IS_ENABLED(CONFIG_IPV6) */
./CrossVul/dataset_final_sorted/CWE-415/c/bad_3180_0
crossvul-cpp_data_good_1406_6
/** * Test that failure to convert to JPEG returns NULL * * We are creating an image, set its width to zero, and pass this image to * `gdImageJpegPtr()` which is supposed to fail, and as such should return NULL. * * See also <https://github.com/libgd/libgd/issues/381> */ #include "gd.h" #include "gdtest.h" int main() { gdImagePtr src, dst; int size; src = gdImageCreateTrueColor(1, 10); gdTestAssert(src != NULL); src->sx = 0; /* this hack forces gdImageJpegPtr() to fail */ dst = gdImageJpegPtr(src, &size, 0); gdTestAssert(dst == NULL); gdImageDestroy(src); return gdNumFailures(); }
./CrossVul/dataset_final_sorted/CWE-415/c/good_1406_6